Ejemplo n.º 1
0
        // http://thebuildingcoder.typepad.com/blog/2010/01/findreferencesbydirection.html#comment-4055509541
        /// <summary>
        /// Return reference to ceiling face to place
        /// lighting fixture above a given point.
        /// </summary>
        Reference GetCeilingReferenceAbove(
            View3D view,
            XYZ p)
        {
            ElementClassFilter filter = new ElementClassFilter(
                typeof(Ceiling));

            ReferenceIntersector refIntersector
                = new ReferenceIntersector(filter,
                                           FindReferenceTarget.Face, view);

            refIntersector.FindReferencesInRevitLinks = true;

            ReferenceWithContext rwc = refIntersector.FindNearest(
                p, XYZ.BasisZ);

            Reference r = (null == rwc)
        ? null
        : rwc.GetReference();

            if (null == r)
            {
                System.Windows.MessageBox.Show("no intersecting geometry");
            }
            return(r);
        }
Ejemplo n.º 2
0
        private void CreateInstancesAndSetLocations(List <XYZ> locations, Room room)
        {
            FilteredElementCollector collector     = new FilteredElementCollector(Doc);
            Func <View3D, bool>      isNotTemplate = v3 => !(v3.IsTemplate);
            View3D view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate);

            BoundingBoxXYZ box    = room.get_BoundingBox(view3D);
            XYZ            center = box.Min.Add(box.Max).Multiply(0.5);

            // Project in the negative Z direction down to the floor.
            XYZ rayDirection = new XYZ(0, 0, 1);

            ElementClassFilter filter = new ElementClassFilter(typeof(Floor));

            ReferenceIntersector refIntersector       = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);
            ReferenceWithContext referenceWithContext = refIntersector.FindNearest(center, rayDirection);

            Reference reference = referenceWithContext.GetReference();

            var el     = Doc.GetElement(reference);
            var ids    = string.Empty;
            var vector = new XYZ(1, 0, 0);

            for (int i = 0; i < locations.Count; i++)
            {
                var fi = App.ActiveUIDocument.Document.Create.NewFamilyInstance(reference, locations[i], vector, this.symbol);
                ids += fi.Id.IntegerValue.ToString() + ";";
            }
        }
Ejemplo n.º 3
0
        public static double Gethsfs(Document doc, Room piece, ElementCategoryFilter filtresol)
        {
            double hsfs = 0.00;

            // on verifie si sol au dessus de piece
            try
            {
                LocationPoint locpiece = piece.Location as LocationPoint;
                XYZ           ptpiece  = locpiece.Point;
                ptpiece = new XYZ(ptpiece.X, ptpiece.Y, ptpiece.Z + 0.05);
                XYZ vecteurpiece               = new XYZ(0, 0, 1);
                ReferenceIntersector refi      = new ReferenceIntersector(filtresol, FindReferenceTarget.Face, (View3D)doc.ActiveView);
                ReferenceWithContext refc      = refi.FindNearest(ptpiece, vecteurpiece);
                Reference            reference = refc.GetReference();
                XYZ intpoint = reference.GlobalPoint;
                hsfs = ptpiece.DistanceTo(intpoint);
                hsfs = UnitUtils.ConvertFromInternalUnits(hsfs, DisplayUnitType.DUT_METERS);
                hsfs = Math.Round(hsfs, 2);
                //MessageBox.Show(string.Format("hauteur sous dalle : {0}", hsfs));
            }
            catch (Exception)
            {
                //MessageBox.Show("pas de sol au dessus de la piece","erreur");
                hsfs = 0.00;
            }
            return(hsfs);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Gets the nearest planar face by ray that room cener point to element center point.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="elm"></param>
        /// <param name="room"></param>
        /// <param name="doc"></param>
        /// <param name="view"></param>
        /// <returns></returns>
        public static PlanarFace GetNearestPlanarFace <T>(this T elm, SpatialElement room, Document doc, View3D view) where T : Element
        {
            if (elm is null)
            {
                throw new ArgumentNullException(nameof(elm));
            }

            if (room is null)
            {
                throw new ArgumentNullException(nameof(room));
            }

            if (doc is null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (view is null)
            {
                throw new ArgumentNullException(nameof(view));
            }

            var elmCenter = elm.GetBoundingBox(doc).GetBoxCenter();

            var roomCenter = room.GetBoundingBox(doc).GetBoxCenter();

            var direction = (elmCenter - roomCenter).Normalize();

            var elmFilter = new ElementClassFilter(elm.GetType());

            var intersector = new ReferenceIntersector(elmFilter, FindReferenceTarget.Face, view);

            var context = intersector.FindNearest(roomCenter, direction);

            doc.AutoTransaction(() =>
            {
                doc.CreateModelCurve(Line.CreateBound(roomCenter, elmCenter), out _);
            });

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

            var reference = context.GetReference();

            var refElm = doc.GetElement(reference.ElementId);

            var face = refElm.GetGeometryObjectFromReference(reference) as Face;

            if (face is PlanarFace planarFace)
            {
                return(planarFace);
            }

            return(null);
        }
Ejemplo n.º 5
0
        private XYZ ProjectPoint(Document doc, Reference refFace, XYZ point, XYZ rayDirection)
        {
            View3D active3D = doc.ActiveView as View3D;

            ReferenceIntersector refIntersector = new ReferenceIntersector(refFace.ElementId, FindReferenceTarget.Face, active3D);

            ReferenceWithContext referenceWithContext = refIntersector.FindNearest(point, rayDirection);

            Reference reference = referenceWithContext.GetReference();

            XYZ intersection = reference.GlobalPoint;

            return(intersection);
        }
Ejemplo n.º 6
0
        public Result OLET(ElementSymbol elementSymbol)
        {
            try
            {
                //Get all pipe connectors
                var allConnectors = ch.GetALLConnectors(pif._doc);

                //Determine the branch1point of the olet which is the connection to the olet pipe
                XYZ bp1 = elementSymbol.Branch1Point.Xyz;
                XYZ cp  = elementSymbol.CentrePoint.Xyz;

                Pipe pipe1 = null;
                //Pipe pipe2 = null;

                pipe1 = ch.CreateDummyPipe(bp1, elementSymbol.CentrePoint.Xyz, elementSymbol.Branch1Point, elementSymbol);
                var c1 = ch.MatchConnector(bp1, pipe1);

                ////Determine the corresponding pipe connector to bp1
                //var c1 = (from Connector c in allConnectors where Util.IsEqual(bp1, c.Origin) select c).FirstOrDefault();
                ////Get the owner of the connector
                //var owner = c1.Owner;

                //Find the target pipe
                var filter               = new ElementClassFilter(typeof(Pipe));
                var view3D               = ch.Get3DView(pif._doc);
                var refIntersect         = new ReferenceIntersector(filter, FindReferenceTarget.Element, view3D);
                ReferenceWithContext rwc = refIntersect.FindNearest(c1.Origin, c1.CoordinateSystem.BasisZ);
                var refId             = rwc.GetReference().ElementId;
                var pipeToConnectInto = (MEPCurve)pif._doc.GetElement(refId);

                if (c1 != null)
                {
                    Element element = PCFImport.doc.Create.NewTakeoffFitting(c1, pipeToConnectInto);
                    if (pipe1 != null)
                    {
                        PCFImport.doc.Delete(pipe1.Id);
                    }
                    //if (pipe2 != null) PCFImport.doc.Delete(pipe2.Id);
                    elementSymbol.CreatedElement = element;
                    PCFImport.doc.Regenerate();
                    return(Result.Succeeded);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            //If this point is reached, something has failed
            return(Result.Failed);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var uiDoc = uiApp.ActiveUIDocument;
            var app   = uiApp.Application;
            var doc   = uiDoc.Document;

            // Start code here

            // Lay nhung doi tuong dang chon
            try
            {
                var refObject = uiDoc.Selection.PickObject(ObjectType.Element);
                var elementId = refObject.ElementId;
                var element   = doc.GetElement(elementId);

                //Bộ lọc các đối tượng cần tính toán giao điểm
                var filter = new ElementCategoryFilter(BuiltInCategory.OST_Floors);
                // là đối tượng hướng dẫn để tìm giao điểm
                var refInter = new ReferenceIntersector(filter, FindReferenceTarget.Face, (View3D)doc.ActiveView);

                // điểm cơ sở của vector bạn cần tính toán giao điểm.
                var basePoint = ((LocationPoint)element.Location).Point;
                // điểm chỉ hướng của vector bạn cần tính toán
                var ray = new XYZ(0, 0, 1);

                // trong trường hợp tia chỉ hướng là ngược hướng
                // với hướng mà lẽ ra theo hướng đó, vector mới cắt với mặt phẳng thì sẽ không trả về kế quả nào.
                var refContext = refInter.FindNearest(basePoint, ray);
                var intersectP = refContext.GetReference().GlobalPoint;

                var distacne = UnitUtils.ConvertFromInternalUnits(basePoint.DistanceTo(intersectP), DisplayUnitType.DUT_MILLIMETERS);
                // Lưu ý element location point không nhất thiết là điểm thấp nhất mà là điểm cơ sở của đối tượng
                TaskDialog.Show("Tinh Khoang cach", "Khoỏng cách từ chân cột đến mái là " + distacne);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 8
0
        internal IList <XYZ> ProjectSupportPointsOnRoof(XYZ currentPointOnRidge)
        {
            IList <XYZ> supportPoints = GetEavePointsOnSupports(currentPointOnRidge);

            //if (supportPoints.Count < 1 || supportPoints.Count > 2)
            //    throw new Exception("Invalid number of support points for the truss");

            IList <XYZ> resultingPoints = new List <XYZ>();

            ReferenceIntersector roofIntersector = new ReferenceIntersector(CurrentRoof.Id, FindReferenceTarget.Element, CurrentRoof.Document.ActiveView as View3D);

            foreach (XYZ currentSupportPoint in supportPoints)
            {
                XYZ originPoint = new XYZ(currentSupportPoint.X, currentSupportPoint.Y, GetCurrentRoofHeight() - 1);
                ReferenceWithContext roofIntersContext = roofIntersector.FindNearest(originPoint, XYZ.BasisZ);

                if (roofIntersContext == null)
                {
                    continue;
                }

                XYZ currentHitPoint = roofIntersContext.GetReference().GlobalPoint;
                resultingPoints.Add(currentHitPoint);
            }

            if (resultingPoints.Count == 1)
            {
                if (RoofLineType == RoofLineType.Ridge)
                {
                    if (Support.HasSameSlopes(CurrentRoof))
                    {
                        XYZ  ridgePointFlaten = new XYZ(currentPointOnRidge.X, currentPointOnRidge.Y, resultingPoints[0].Z);
                        Line CrossedRidgeLine = Line.CreateBound(resultingPoints[0], ridgePointFlaten);
                        XYZ  crossedDirection = CrossedRidgeLine.Direction;
                        XYZ  mirroredPoint    = resultingPoints[0].Add(crossedDirection.Multiply(CrossedRidgeLine.ApproximateLength * 2));
                        resultingPoints.Add(mirroredPoint);
                    }
                }
            }

            return(resultingPoints);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Find Elements Intersect By Ray
        /// </summary>
        /// <param name="element"></param>
        /// <param name="categories"></param>
        /// <param name="direction"></param>
        /// <returns></returns>
        public static Autodesk.Revit.DB.XYZ RayIntersect(this Autodesk.Revit.DB.Element element, List <string> categories, XYZ direction)
        {
            // Find a 3D view to use for the ReferenceIntersector constructor

            FilteredElementCollector collector     = new FilteredElementCollector(element.Document);
            Func <View3D, bool>      isNotTemplate = v3 => !(v3.IsTemplate);
            View3D view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate);

            // Use the center of the skylight bounding box as the start point.
            BoundingBoxXYZ box    = element.get_BoundingBox(view3D);
            XYZ            center = box.Min.Add(box.Max).Multiply(0.5);
            // Project in the negative Z direction down to the ceiling.
            ElementFilter        elementFilter  = element.Document.FiltersElementByCategory(categories);
            ReferenceIntersector refIntersector = new ReferenceIntersector(elementFilter, FindReferenceTarget.Face, view3D);

            refIntersector.FindReferencesInRevitLinks = true;
            ReferenceWithContext referenceWithContext = refIntersector.FindNearest(center, direction);
            Reference            reference            = referenceWithContext?.GetReference();

            return(reference?.GlobalPoint);
        }
Ejemplo n.º 10
0
        public void RoomCeilingHeight()
        {
            Document   doc   = this.ActiveUIDocument.Document;
            UIDocument uidoc = new UIDocument(doc);
//			RevitCommandId commandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Default3DView);
            //            if (this.CanPostCommand(commandId))
            //              this.PostCommand(commandId);

            // Prompt user to select a room
            Room          room      = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element)) as Room;
            LocationPoint roomPoint = room.Location as LocationPoint;

            //GeometryElement roomGeoElem = room.get_Geometry(new Options());
            //XYZ roomCent = roomGeoElem.Select(geo => geo as Solid).FirstOrDefault(sld => null != sld).ComputeCentroid();
            var view = new FilteredElementCollector(doc)
                       .OfClass(typeof(View3D)).OfType <View3D>()
                       .FirstOrDefault((View3D v) => v.Name.Contains("{3d"));
            var bic = BuiltInCategory.OST_Floors;


            ReferenceIntersector intersector = new ReferenceIntersector(
                new ElementCategoryFilter(bic),
                FindReferenceTarget.Element, view);

            // XYZ.BasisZ shoots the ray "up"
            ReferenceWithContext rwC = intersector.FindNearest(roomPoint.Point, XYZ.BasisZ * -1);

            // Report the data to the user. This information could also be used to set a "Ceiling Height" instance parameter
            if (rwC == null)
            {
                TaskDialog.Show(string.Format("{0}", view.Name), "no Floors found");
            }
            else
            {
                var rwD   = "View used to Project the Ray " + doc.GetElement(intersector.ViewId).Name;
                var rwPro = "Height is " + UnitUtils.ConvertFromInternalUnits(rwC.Proximity, DisplayUnitType.DUT_MILLIMETERS).ToString() + " mm";
                var rwEle = bic.ToString() + " id: " + rwC.GetReference().ElementId.ToString();
                TaskDialog.Show("Element ID", rwEle + "\n" + rwPro + "\n" + rwD);
            }
        }
        // finding building elevation
        public double FindBuildingElevation(ProcessPolygon polygon)
        {
            List <XYZ>           heights        = new List <XYZ>();
            ReferenceIntersector refIntersector = new ReferenceIntersector(this.TopographyID, FindReferenceTarget.Mesh, this.RayTracerView);
            int    counter = 0;
            double h       = 0;

            foreach (XYZ item in polygon.ProcessedPolygon)
            {
                ReferenceWithContext referenceWithContext = refIntersector.FindNearest(item, XYZ.BasisZ);
                if (referenceWithContext != null)
                {
                    counter++;
                    h += referenceWithContext.Proximity;
                }
                else
                {
                    return(-1);
                }
            }
            return(h / counter);
        }
Ejemplo n.º 12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            try
            {
                // pick object
                Reference pickedObj = uidoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
                if (pickedObj != null)
                {
                    //Retrieve Element
                    ElementId eleId = pickedObj.ElementId;
                    Element   ele   = doc.GetElement(eleId);

                    //Project Ray
                    LocationPoint locp = ele.Location as LocationPoint;
                    XYZ           p1   = locp.Point;

                    // Ray
                    XYZ rayd = new XYZ(0, 0, 1);
                    ElementCategoryFilter filter    = new ElementCategoryFilter(BuiltInCategory.OST_Roofs);
                    ReferenceIntersector  refi      = new ReferenceIntersector(filter, FindReferenceTarget.Face, (View3D)doc.ActiveView);
                    ReferenceWithContext  refc      = refi.FindNearest(p1, rayd);
                    Reference             reference = refc.GetReference();
                    XYZ    intpoing = reference.GlobalPoint;
                    Double dist     = p1.DistanceTo(intpoing);

                    TaskDialog.Show("Ray", string.Format("Distance to roof {0}", dist));
                }
                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 13
0
        //this method checks to see if a rectangular region has valid projection on the ground.
        private bool CanSubregionBeValid(BoundingBoxUV boundingBox)
        {
            List <XYZ> corners = new List <XYZ>();
            XYZ        Min     = new XYZ(boundingBox.Min.U, boundingBox.Min.V, 0);
            XYZ        Max     = new XYZ(boundingBox.Max.U, boundingBox.Max.V, 0);
            XYZ        p0      = new XYZ(boundingBox.Min.U, boundingBox.Max.V, 0);
            XYZ        p1      = new XYZ(boundingBox.Max.U, boundingBox.Min.V, 0);

            corners.Add(Min);
            corners.Add(Max);
            corners.Add(p0);
            corners.Add(p1);
            ReferenceIntersector refIntersector = new ReferenceIntersector(this.TopographySurfaceId, FindReferenceTarget.Mesh, this.RayTracerView);

            foreach (XYZ item in corners)
            {
                ReferenceWithContext referenceWithContext = refIntersector.FindNearest(item, XYZ.BasisZ);
                if (referenceWithContext == null)
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 14
0
        internal XYZ GetTrussTopPoint(XYZ currentPointOnRidge)
        {
            if (RoofLineType == RoofLineType.Ridge)
            {
                return(currentPointOnRidge);
            }

            //If the is not a Ridge this MUST be a SinglePanelRidge
            if (RoofLineType == RoofLineType.RidgeSinglePanel)
            {
                return(currentPointOnRidge);
            }

            Line currentRidgeLine = Curve.Clone() as Line;

            if (currentRidgeLine == null)
            {
                throw new Exception("The ridge is not a straight line!");
            }

            ModelCurveArrArray sketchModels = CurrentRoof.GetProfiles();
            double             minDist      = double.MaxValue;
            ModelCurve         targetEave   = null;
            XYZ projectedPoint = null;

            double currentRoofTotalHeight = GetCurrentRoofHeight();

            foreach (ModelCurveArray currentCurveArr in sketchModels)
            {
                foreach (ModelCurve currentCurve in currentCurveArr)
                {
                    Curve targetGeoCurve = currentCurve.GeometryCurve;
                    Line  targetGeoLine  = targetGeoCurve as Line;

                    if (targetGeoLine == null)
                    {
                        throw new Exception("Eave is not a straight line");
                    }

                    targetGeoLine = targetGeoLine.Flatten(currentRoofTotalHeight);

                    double currentDist = targetGeoLine.Project(currentPointOnRidge).Distance;
                    if (currentDist < minDist)
                    {
                        minDist        = currentDist;
                        targetEave     = currentCurve;
                        projectedPoint = targetGeoLine.Project(currentPointOnRidge).XYZPoint;
                    }
                }
            }

            double overHang = 0;

            try { overHang = CurrentRoof.get_Overhang(targetEave); }
            catch { }

            XYZ ridgePointFlatten = new XYZ(currentPointOnRidge.X, currentPointOnRidge.Y, currentRoofTotalHeight);

            //We just need to get the side that the eave is to move the point to that direction
            //so we dont need to get a specific eave, lets just project the first one with infinite bounds to get the direction
            if (RelatedRidgeEaves == null || RelatedRidgeEaves.Count == 0)
            {
                RelatedRidgeEaves = GetRelatedEaves();
            }

            if (RelatedRidgeEaves == null || RelatedRidgeEaves.Count == 0)
            {
                throw new Exception("Related eave or eaves to current singleRidge was not found");
            }


            Curve eaveCurve = RelatedRidgeEaves[0].AsCurve();

            if (eaveCurve as Line == null)
            {
                throw new Exception("Related eave is not a straight line!");
            }

            Line eaveLine = eaveCurve as Line;

            XYZ lineIntersectionPoint = GeometrySupport.GetRoofIntersectionFlattenLines(currentRidgeLine, ridgePointFlatten, eaveLine, currentRoofTotalHeight);

            if (lineIntersectionPoint == null)
            {
                throw new Exception("No Intersection between eave could be estabilished!");
            }

            XYZ overHangdirection = Line.CreateBound(projectedPoint, lineIntersectionPoint).Direction.Normalize();
            XYZ pointOnOverhang   = projectedPoint.Add(overHangdirection.Multiply(overHang));

            //We will get the point on the overhang because if we are working with a single panel ridge it may have overhangs
            XYZ pointOnSupport = GetSupportPoint(pointOnOverhang, currentRidgeLine.Direction.Normalize());

            //Now we will shoot the point up on the Roof
            XYZ startingPoint = new XYZ(pointOnSupport.X, pointOnSupport.Y, pointOnSupport.Z - 1);
            ReferenceIntersector currentRefIntersect = new ReferenceIntersector(CurrentRoof.Id, FindReferenceTarget.Element, CurrentRoof.Document.ActiveView as View3D);
            ReferenceWithContext currenRefContext    = currentRefIntersect.FindNearest(startingPoint, XYZ.BasisZ);

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

            XYZ projectedPointOnRoof = currenRefContext.GetReference().GlobalPoint;

            return(projectedPointOnRoof);
        }
Ejemplo n.º 15
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Select two walls and the dimension line point:

            Selection      sel  = uidoc.Selection;
            ReferenceArray refs = new ReferenceArray();

            try
            {
                ISelectionFilter f
                    = new JtElementsOfClassSelectionFilter <Wall>();

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please select first wall"));

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please pick dimension line "
                                + "point on second wall"));

                //rFace = sel.PickObject( ObjectType.Face,
                //  "Please select face on second wall at dimension line point" );
                //
                //rPoint = sel.PickObject( ObjectType.PointOnElement,
                //  "Please select point on first wall" );
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                message = "No two walls selected";
                return(Result.Failed);
            }

            // Ensure the two selected walls are straight and
            // parallel; determine their mutual normal vector
            // and a point on each wall for distance
            // calculations:

            Wall[]     walls = new Wall[2];
            List <int> ids   = new List <int>(2);

            XYZ[]              pts   = new XYZ[2];
            Line[]             lines = new Line[2];
            IntersectionResult ir;
            XYZ normal = null;
            int i      = 0;

            foreach (Reference r in refs)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Wall wall = r.Element as Wall; // 2011

                Wall wall = doc.GetElement(r) as Wall; // 2012

                walls[i] = wall;
                ids.Add(wall.Id.IntegerValue);

                // Obtain location curve and
                // check that it is straight:

                LocationCurve lc = wall.Location
                                   as LocationCurve;

                Curve curve = lc.Curve;
                lines[i] = curve as Line;

                if (null == lines[i])
                {
                    message = _prompt;
                    return(Result.Failed);
                }

                // Obtain normal vectors
                // and ensure that they are equal,
                // i.e. walls are parallel:

                if (null == normal)
                {
                    normal = Util.Normal(lines[i]);
                }
                else
                {
                    if (!Util.IsParallel(normal,
                                         Util.Normal(lines[i])))
                    {
                        message = _prompt;
                        return(Result.Failed);
                    }
                }

                // Obtain pick points and project
                // onto wall location lines:

                XYZ p = r.GlobalPoint;
                ir = lines[i].Project(p);

                if (null == ir)
                {
                    message = string.Format(
                        "Unable to project pick point {0} "
                        + "onto wall location line.",
                        i);

                    return(Result.Failed);
                }

                pts[i] = ir.XYZPoint;

                Debug.Print(
                    "Wall {0} id {1} at {2}, {3} --> point {4}",
                    i, wall.Id.IntegerValue,
                    Util.PointString(lines[i].GetEndPoint(0)),
                    Util.PointString(lines[i].GetEndPoint(1)),
                    Util.PointString(pts[i]));

                if (0 < i)
                {
                    // Project dimension point selected on second wall
                    // back onto first wall, and ensure that normal
                    // points from second wall to first:

                    ir = lines[0].Project(pts[1]);
                    if (null == ir)
                    {
                        message = string.Format(
                            "Unable to project selected dimension "
                            + "line point {0} on second wall onto "
                            + "first wall's location line.",
                            Util.PointString(pts[1]));

                        return(Result.Failed);
                    }
                    pts[0] = ir.XYZPoint;
                }

                ++i;
            }

            XYZ v = pts[0] - pts[1];

            if (0 > v.DotProduct(normal))
            {
                normal = -normal;
            }

            // Shoot a ray back from the second
            // picked wall towards first:

            Debug.Print(
                "Shooting ray from {0} in direction {1}",
                Util.PointString(pts[1]),
                Util.PointString(normal));

            View3D view = Get3DView(doc);

            if (null == view)
            {
                message = "No 3D view named '{3D}' found; "
                          + "run the View > 3D View command once "
                          + "to generate it.";

                return(Result.Failed);
            }

            //refs = doc.FindReferencesByDirection(
            //  pts[1], normal, view ); // 2011

            //IList<ReferenceWithContext> refs2
            //  = doc.FindReferencesWithContextByDirection(
            //    pts[1], normal, view ); // 2012

            // In the Revit 2014 API, the call to
            // FindReferencesWithContextByDirection causes a
            // warning saying:
            // "FindReferencesWithContextByDirection is obsolete:
            // This method is deprecated in Revit 2014.
            // Use the ReferenceIntersector class instead."

            ReferenceIntersector ri
                = new ReferenceIntersector(
                      walls[0].Id, FindReferenceTarget.Element, view);

            ReferenceWithContext ref2
                = ri.FindNearest(pts[1], normal);

            if (null == ref2)
            {
                message = "ReferenceIntersector.FindNearest"
                          + " returned null!";

                return(Result.Failed);
            }

            #region Obsolete code to determine the closest reference
#if NEED_TO_DETERMINE_CLOSEST_REFERENCE
            // Store the references to the wall surfaces:

            Reference[] surfrefs = new Reference[2] {
                null, null
            };

            // Find the two closest intersection
            // points on each of the two walls:

            double[] minDistance = new double[2] {
                double.MaxValue,
                double.MaxValue
            };

            //foreach( Reference r in refs )
            foreach (ReferenceWithContext rc in refs2)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Element e = r.Element; // 2011

                Reference r = rc.GetReference();
                Element   e = doc.GetElement(r); // 2012

                if (e is Wall)
                {
                    i = ids.IndexOf(e.Id.IntegerValue);

                    if (-1 < i &&
                        ElementReferenceType.REFERENCE_TYPE_SURFACE
                        == r.ElementReferenceType)
                    {
                        //GeometryObject g = r.GeometryObject; // 2011
                        GeometryObject g = e.GetGeometryObjectFromReference(r); // 2012

                        if (g is PlanarFace)
                        {
                            PlanarFace face = g as PlanarFace;

                            Line line = (e.Location as LocationCurve)
                                        .Curve as Line;

                            Debug.Print(
                                "Wall {0} at {1}, {2} surface {3} "
                                + "normal {4} proximity {5}",
                                e.Id.IntegerValue,
                                Util.PointString(line.GetEndPoint(0)),
                                Util.PointString(line.GetEndPoint(1)),
                                Util.PointString(face.Origin),
                                Util.PointString(face.Normal),
                                rc.Proximity);

                            // First reference: assert it is a face on this wall
                            // and the distance is half the wall thickness.
                            // Second reference: the first reference on the other
                            // wall; assert the distance between the two references
                            // equals the distance between the wall location lines
                            // minus half of the sum of the two wall thicknesses.

                            if (rc.Proximity < minDistance[i])
                            {
                                surfrefs[i]    = r;
                                minDistance[i] = rc.Proximity;
                            }
                        }
                    }
                }
            }

            if (null == surfrefs[0])
            {
                message = "No suitable face intersection "
                          + "points found on first wall.";

                return(Result.Failed);
            }

            if (null == surfrefs[1])
            {
                message = "No suitable face intersection "
                          + "points found on second wall.";

                return(Result.Failed);
            }

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], surfrefs[0], pts[1], surfrefs[1]);
#endif // NEED_TO_DETERMINE_CLOSEST_REFERENCE
            #endregion // Obsolete code to determine the closest reference

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], ref2.GetReference(), pts[1], refs.get_Item(1));

            return(Result.Succeeded);
        }
Ejemplo n.º 16
0
        public static void Calculate(UIApplication uiApp)
        {
            Document   doc   = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                using (TransactionGroup txGp = new TransactionGroup(doc))
                {
                    txGp.Start("Calculate height of hangers");

                    //Collect elements
                    var hangerSupports = fi.GetElements <FamilyInstance, Guid>
                                             (doc, new Guid("e0baa750-22ba-4e60-9466-803137a0cba8"), "Hænger");
                    //Is the following required?
                    HashSet <Element> allHangers = new HashSet <Element>(hangerSupports.Cast <Element>()
                                                                         .Where(x => x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory));

                    //Prepare common objects for intersection analysis
                    //Create a filter that filters for structural columns and framing
                    //Why columns? Maybe only framing is enough.

                    //Linked IFC files create DirectShapes!
                    ElementClassFilter filter = new ElementClassFilter(typeof(DirectShape));

                    //IList<ElementFilter> filterList = new List<ElementFilter>
                    //                    { new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming),
                    //                      new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns) };
                    //LogicalOrFilter bicFilter = new LogicalOrFilter(filterList);
                    //LogicalAndFilter fiAndBicFilter = new LogicalAndFilter(bicFilter, new ElementClassFilter(typeof(FamilyInstance)));

                    //Get the default 3D view
                    var view3D = Shared.Filter.Get3DView(doc);
                    if (view3D == null)
                    {
                        throw new Exception("No default 3D view named {3D} is found!.");
                    }

                    //Instantiate the Reference Intersector
                    var refIntersect = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);
                    refIntersect.FindReferencesInRevitLinks = true;

                    using (Transaction trans1 = new Transaction(doc))
                    {
                        trans1.Start("Calculate height to nearest framing");

                        foreach (Element hanger in allHangers)
                        {
                            //Find the point of the framing above the hanger
                            Transform trf    = ((FamilyInstance)hanger).GetTransform();
                            XYZ       Origin = new XYZ();
                            Origin = trf.OfPoint(Origin);
                            XYZ Direction = trf.BasisZ;
                            //XYZ Origin = ((LocationPoint)hanger.Location).Point;

                            ReferenceWithContext rwc = refIntersect.FindNearest(Origin, Direction);
                            if (rwc == null)
                            {
                                continue;
                            }
                            //throw new Exception($"Hanger {hanger.Id} did not find any steel supports!\n" +
                            //                    $"Check if elements are properly aligned.");
                            Reference reference    = rwc.GetReference();
                            XYZ       intersection = reference.GlobalPoint;

                            //Get the hanger's height above it's reference level
                            Parameter offsetPar     = hanger.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
                            double    offsetFromLvl = offsetPar.AsDouble();
                            //Just to make sure that the proper parameter is set
                            hanger.LookupParameter("PipeOffsetFromLevel").Set(offsetFromLvl);

                            //Calculate the height of the intersection above the reference level
                            ElementId refLvlId        = hanger.LevelId;
                            Level     refLvl          = (Level)doc.GetElement(refLvlId);
                            double    refLvlElevation = refLvl.Elevation;
                            double    profileHeight   = intersection.Z - refLvlElevation;

                            //Set the hanger value so it updates
                            hanger.LookupParameter("LevelHeight").Set(profileHeight);
                        }
                        trans1.Commit();
                    }
                    txGp.Assimilate();
                }
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //return Result.Failed;
            }
        }
Ejemplo n.º 17
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = commandData.Application.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            //选择一个点
            Reference refPoint = sel.PickObject(ObjectType.PointOnElement);
            XYZ       point1   = refPoint.GlobalPoint; //The position on which the reference is hit.???

            //射线方向及工作平面法向量
            XYZ rayDirection = XYZ.BasisZ;
            XYZ skVector     = XYZ.BasisX; //???????????

            //当选择的主体为平面时,射线根据选择的点与此面的法线方向进行放射
            if (refPoint.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE)
            {
                PlanarFace pFace = null;
                //主体是链接的图元时,获取平面的方法
                if (refPoint.LinkedElementId.IntegerValue != -1)
                {
                    RevitLinkInstance linkIIns = doc.GetElement(refPoint) as RevitLinkInstance;
                    Document          linkDoc  = linkIIns.GetLinkDocument();
                    Element           linkElem = linkDoc.GetElement(refPoint.LinkedElementId);
                    Options           opt      = new Options();
                    opt.DetailLevel = ViewDetailLevel.Fine;
                    GeometryElement geoElem = linkElem.get_Geometry(opt);
                    pFace = getTarFace(geoElem, point1); //point1是原始点.
                }
                else
                {
                    //判断是否FamilyInstance类型的族,采用不同的获取方法
                    Element elem = doc.GetElement(refPoint);
                    if (elem is FamilyInstance)
                    {
                        Options opt = new Options();
                        opt.DetailLevel = ViewDetailLevel.Fine;
                        GeometryElement ge = elem.get_Geometry(opt);
                        pFace = getTarFace(ge, point1);
                    }
                    else
                    {
                        pFace = elem.GetGeometryObjectFromReference(refPoint) as PlanarFace;
                    }
                }

                //修正射线方向及工作平面法向量
                if (pFace != null)
                {
                    rayDirection = pFace.FaceNormal;
                    skVector     = pFace.XVector;
                }
            }

            //获得视图
            View3D view3D = doc.ActiveView as View3D;

            //创建射线测量出第二点
            ExclusionFilter filter =
                new ExclusionFilter(new List <ElementId>()
            {
                refPoint.ElementId, refPoint.LinkedElementId
            });

            ReferenceIntersector refIntersector = new ReferenceIntersector(filter, FindReferenceTarget.All, view3D);

            refIntersector.FindReferencesInRevitLinks = true;
            ReferenceWithContext rwc = refIntersector.FindNearest(point1, rayDirection);

            if (rwc != null)
            {
                XYZ point2 = rwc.GetReference().GlobalPoint;
                //创建模型线
                Line line = Line.CreateBound(point1, point2);
                TaskDialog.Show("距离", line.Length.FeetToMm().ToString("0.00"));
                using (Transaction ts = new Transaction(doc, "尺寸"))
                {
                    ts.Start();
                    SketchPlane sk         = SketchPlane.Create(doc, Plane.CreateByNormalAndOrigin(skVector, point1));
                    ModelCurve  modelCurve = doc.Create.NewModelCurve(line, sk);
                    sel.SetElementIds(new List <ElementId>()
                    {
                        modelCurve.Id
                    });
                    ts.Commit();
                }
            }
            else
            {
                TaskDialog.Show("返回结果", "未检测到图元");
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Return the neighbouring BIM element generating
        /// the given room boundary curve c, assuming it
        /// is oriented counter-clockwise around the room
        /// if part of an interior loop, and vice versa.
        /// </summary>
        public Element GetElementByRay(
            UIApplication app,
            Document doc,
            View3D view3d,
            Curve c)
        {
            Element boundaryElement = null;

            // Tolerances

            const double minTolerance = 0.00000001;
            const double maxTolerance = 0.01;

            // Height of ray above room level:
            // ray starts from one foot above room level

            const double elevation = 1;

            // Ray starts not directly from the room border
            // but from a point offset slightly into it.

            const double stepInRoom = 0.1;

            // We could use Line.Direction if Curve c is a
            // Line, but since c also might be an Arc, we
            // calculate direction like this:

            XYZ lineDirection
                = (c.GetEndPoint(1) - c.GetEndPoint(0))
                  .Normalize();

            XYZ upDir = elevation * XYZ.BasisZ;

            // Assume that the room is on the left side of
            // the room boundary curve and wall on the right.
            // This is valid for both outer and inner room
            // boundaries (outer are counter-clockwise, inner
            // are clockwise). Start point is slightly inside
            // the room, one foot above room level.

            XYZ toRoomVec = stepInRoom * GetLeftDirection(
                lineDirection);

            XYZ pointBottomInRoom = c.Evaluate(0.5, true)
                                    + toRoomVec;

            XYZ startPoint = pointBottomInRoom + upDir;

            // We are searching for walls only

            ElementFilter wallFilter
                = new ElementCategoryFilter(
                      BuiltInCategory.OST_Walls);

            ReferenceIntersector intersector
                = new ReferenceIntersector(wallFilter,
                                           FindReferenceTarget.Element, view3d);

            // We don't want to find elements in linked files

            intersector.FindReferencesInRevitLinks = false;

            XYZ toWallDir = GetRightDirection(
                lineDirection);

            ReferenceWithContext context = intersector
                                           .FindNearest(startPoint, toWallDir);

            Reference closestReference = null;

            if (context != null)
            {
                if ((context.Proximity > minTolerance) &&
                    (context.Proximity < maxTolerance
                     + stepInRoom))
                {
                    closestReference = context.GetReference();

                    if (closestReference != null)
                    {
                        boundaryElement = doc.GetElement(
                            closestReference);
                    }
                }
            }
            return(boundaryElement);
        }
Ejemplo n.º 19
0
        static internal EdgeInfo GetCurveInformation(Element targetRoof, Curve targetCurve, IList <PlanarFace> targetPlanarFaceList)
        {
            if (targetPlanarFaceList != null && targetRoof != null && (targetRoof as FootPrintRoof) != null)
            {
                FootPrintRoof currentRoof = targetRoof as FootPrintRoof;
                foreach (PlanarFace currentPlanarFace in targetPlanarFaceList)
                {
                    EdgeArrayArray EdgeLoops = currentPlanarFace.EdgeLoops;
                    foreach (EdgeArray currentEdgeArray in EdgeLoops)
                    {
                        foreach (Edge currentEdge in currentEdgeArray)
                        {
                            if (currentEdge != null)
                            {
                                IList <Edge> currentEdges = new List <Edge>();
                                currentEdges.Add(currentEdge);
                                EdgeInfo currentEdgeInfo = new EdgeInfo();
                                Curve    edgeCurve       = currentEdge.AsCurve();

                                if (edgeCurve.IsAlmostEqualTo(targetCurve))
                                {
                                    if (edgeCurve.GetEndPoint(0).Z.IsAlmostEqualTo(currentPlanarFace.Origin.Z) && edgeCurve.GetEndPoint(1).Z.IsAlmostEqualTo(currentPlanarFace.Origin.Z))
                                    {
                                        currentEdgeInfo = new EdgeInfo {
                                            Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Eave, CurrentRoof = currentRoof
                                        };
                                        currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                        return(currentEdgeInfo);
                                    }
                                    else if (edgeCurve.GetEndPoint(0).Z.IsAlmostEqualTo(currentPlanarFace.Origin.Z) || edgeCurve.GetEndPoint(1).Z.IsAlmostEqualTo(currentPlanarFace.Origin.Z))
                                    {
                                        PlanarFace firstFace  = currentEdge.GetFace(0) as PlanarFace;
                                        PlanarFace secondFace = currentEdge.GetFace(1) as PlanarFace;

                                        if (!targetPlanarFaceList.Contains(firstFace) || !targetPlanarFaceList.Contains(secondFace))
                                        {
                                            currentEdgeInfo = new EdgeInfo {
                                                Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Gable, CurrentRoof = currentRoof
                                            };
                                            currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                            return(currentEdgeInfo);
                                        }
                                        else
                                        {
                                            if (GetOuterCurveLoop(firstFace).Count() == 3 || GetOuterCurveLoop(secondFace).Count() == 3)
                                            {
                                                currentEdgeInfo = new EdgeInfo {
                                                    Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Hip, CurrentRoof = currentRoof
                                                };
                                                currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                return(currentEdgeInfo);
                                            }
                                            else
                                            {
                                                XYZ startingPoint = targetCurve.GetEndPoint(0).Z < targetCurve.GetEndPoint(1).Z ? targetCurve.GetEndPoint(0) : targetCurve.GetEndPoint(1);

                                                XYZ extendedPoint = GetExtendedPoint(startingPoint, firstFace);
                                                XYZ rayTracePoint = new XYZ(extendedPoint.X, extendedPoint.Y, extendedPoint.Z + 999);

                                                ReferenceIntersector ReferenceIntersect = new ReferenceIntersector(targetRoof.Id, FindReferenceTarget.Element, (targetRoof.Document.ActiveView as View3D));
                                                ReferenceWithContext RefContext         = ReferenceIntersect.FindNearest(rayTracePoint, XYZ.BasisZ.Negate());

                                                if (RefContext == null)
                                                {
                                                    currentEdgeInfo = new EdgeInfo {
                                                        Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Hip, CurrentRoof = currentRoof
                                                    };
                                                    currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                    return(currentEdgeInfo);
                                                }

                                                currentEdgeInfo = new EdgeInfo {
                                                    Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Valley, CurrentRoof = currentRoof
                                                };
                                                currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                return(currentEdgeInfo);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (edgeCurve.GetEndPoint(0).Z.IsAlmostEqualTo(edgeCurve.GetEndPoint(1).Z))
                                        {
                                            if (targetPlanarFaceList.Contains(currentEdge.GetFace(0)) && targetPlanarFaceList.Contains(currentEdge.GetFace(1)))
                                            {
                                                currentEdgeInfo = new EdgeInfo {
                                                    Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Ridge, CurrentRoof = currentRoof
                                                };
                                                currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                return(currentEdgeInfo);
                                            }
                                            else
                                            {
                                                PlanarFace firstFace  = currentEdge.GetFace(0) as PlanarFace;
                                                PlanarFace secondFace = currentEdge.GetFace(1) as PlanarFace;

                                                XYZ startingPoint      = edgeCurve.Evaluate(0.5, true);
                                                XYZ crossedDirection   = Line.CreateBound(edgeCurve.GetEndPoint(0), edgeCurve.GetEndPoint(1)).Direction.CrossProduct(XYZ.BasisZ);
                                                XYZ crossedPointStart  = startingPoint.Add(crossedDirection.Multiply(0.02));
                                                XYZ crossedPointEnd    = startingPoint.Add(crossedDirection.Multiply(0.1));
                                                XYZ rayTracePointStart = new XYZ(crossedPointStart.X, crossedPointStart.Y, crossedPointStart.Z + 999);
                                                XYZ rayTracePointEnd   = new XYZ(crossedPointEnd.X, crossedPointEnd.Y, crossedPointEnd.Z + 999);

                                                ReferenceIntersector ReferenceIntersect = new ReferenceIntersector(targetRoof.Id, FindReferenceTarget.Element, (targetRoof.Document.ActiveView as View3D));
                                                ReferenceWithContext refStart           = ReferenceIntersect.FindNearest(rayTracePointStart, XYZ.BasisZ.Negate());
                                                ReferenceWithContext refEnd             = ReferenceIntersect.FindNearest(rayTracePointEnd, XYZ.BasisZ.Negate());

                                                bool isEave = true;
                                                if (refEnd != null)
                                                {
                                                    if (refStart != null)
                                                    {
                                                        //Document doc = currentRoof.Document;
                                                        //double refPointHeight = refEnd.GetReference().GlobalPoint.Z;
                                                        //double starPHeight = refStart.GetReference().GlobalPoint.Z;
                                                        //FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsElementType().Where(type => type.Name.Contains("DebugPoint2")).FirstOrDefault() as FamilySymbol;
                                                        //doc.Create.NewFamilyInstance(refEnd.GetReference().GlobalPoint, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                        //doc.Create.NewFamilyInstance(refStart.GetReference().GlobalPoint, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                        if (refEnd.GetReference().GlobalPoint.Z < refStart.GetReference().GlobalPoint.Z)
                                                        {
                                                            isEave = false;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    crossedPointStart  = startingPoint.Add(crossedDirection.Multiply(-0.02));
                                                    crossedPointEnd    = startingPoint.Add(crossedDirection.Multiply(-0.1));
                                                    rayTracePointStart = new XYZ(crossedPointStart.X, crossedPointStart.Y, crossedPointStart.Z + 999);
                                                    rayTracePointEnd   = new XYZ(crossedPointEnd.X, crossedPointEnd.Y, crossedPointEnd.Z + 999);

                                                    refStart = ReferenceIntersect.FindNearest(rayTracePointStart, XYZ.BasisZ.Negate());
                                                    refEnd   = ReferenceIntersect.FindNearest(rayTracePointEnd, XYZ.BasisZ.Negate());

                                                    if (refEnd != null)
                                                    {
                                                        if (refStart != null)
                                                        {
                                                            //Document doc = currentRoof.Document;
                                                            //double refPointHeight = refEnd.GetReference().GlobalPoint.Z;
                                                            //double starPHeight = refStart.GetReference().GlobalPoint.Z;
                                                            //FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsElementType().Where(type => type.Name.Contains("DebugPoint2")).FirstOrDefault() as FamilySymbol;
                                                            //doc.Create.NewFamilyInstance(refEnd.GetReference().GlobalPoint, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                            //doc.Create.NewFamilyInstance(refStart.GetReference().GlobalPoint, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                            if (refEnd.GetReference().GlobalPoint.Z < refStart.GetReference().GlobalPoint.Z)
                                                            {
                                                                isEave = false;
                                                            }
                                                        }
                                                    }
                                                }

                                                if (isEave)
                                                {
                                                    currentEdgeInfo = new EdgeInfo {
                                                        Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Eave, CurrentRoof = currentRoof
                                                    };
                                                    currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                    return(currentEdgeInfo);
                                                }
                                                else
                                                {
                                                    currentEdgeInfo = new EdgeInfo {
                                                        Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.RidgeSinglePanel, CurrentRoof = currentRoof
                                                    };
                                                    currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                    return(currentEdgeInfo);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (targetPlanarFaceList.Contains(currentEdge.GetFace(0)) && targetPlanarFaceList.Contains(currentEdge.GetFace(1)))
                                            {
                                                currentEdgeInfo = new EdgeInfo {
                                                    Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Hip, CurrentRoof = currentRoof
                                                };
                                                currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                return(currentEdgeInfo);
                                            }
                                            else
                                            {
                                                currentEdgeInfo = new EdgeInfo {
                                                    Edges = currentEdges, Curve = edgeCurve, RoofLineType = RoofLineType.Gable, CurrentRoof = currentRoof
                                                };
                                                currentEdgeInfo.RelatedPanelFaces = GetEdgeRelatedPanels(currentEdge, targetPlanarFaceList);
                                                return(currentEdgeInfo);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(new EdgeInfo {
                Edges = new List <Edge>(), Curve = targetCurve, RoofLineType = RoofLineType.Undefined, CurrentRoof = null
            });
        }
Ejemplo n.º 20
0
        private Result SlopeSelectedBuildingPad(UIDocument targetUIdoc, ref string message, double maxPointDistInFeet, double targetAngleInRadians)
        {
            Document  doc = targetUIdoc.Document;
            Selection sel = targetUIdoc.Selection;

            View3D current3dView = doc.ActiveView as View3D;

            if (current3dView == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_Not3DView;
                return(Result.Failed);
            }

            BuildingPad selectedBuildingPad = doc.GetElement(sel.PickObject(ObjectType.Element, new PadSelectionFilter(), Properties.Messages.SlopeGradingFromPads_SelectPad)) as BuildingPad;

            //Check if the Pad is associate with a Surface (never seen one doesnt, but anyways)
            ElementId topoElementID = selectedBuildingPad.HostId;

            if (topoElementID.Equals(ElementId.InvalidElementId))
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;
                return(Result.Failed);
            }

            TopographySurface currentTopo = doc.GetElement(topoElementID) as TopographySurface;

            if (currentTopo == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;;
                return(Result.Failed);
            }

            IList <CurveLoop> PadBoundaryLoops = new List <CurveLoop>();
            CurveLoop         outerLoop        = null;

            IList <Reference> TopFacesReferences = HostObjectUtils.GetTopFaces(selectedBuildingPad);

            if (TopFacesReferences.Count > 1)
            {
                message = Properties.Messages.SlopeGradingFromPads_PadsWithMoreThanOneUpperFace;
                return(Result.Failed);
            }

            XYZ plannarDirection = XYZ.BasisZ;
            XYZ plannarOrigin    = XYZ.Zero;

            // interate on the only face
            foreach (Reference currentFaceRef in TopFacesReferences)
            {
                GeometryObject currentFaceObj = selectedBuildingPad.GetGeometryObjectFromReference(currentFaceRef);
                if (currentFaceObj is PlanarFace)
                {
                    PlanarFace currentPlanarFace = currentFaceObj as PlanarFace;
                    plannarDirection = currentPlanarFace.FaceNormal;
                    plannarOrigin    = currentPlanarFace.Origin;
                    PadBoundaryLoops = currentPlanarFace.GetEdgesAsCurveLoops();
                }
                else
                {
                    message = Properties.Messages.SlopeGradingFromPads_UpperFaceNotPlanar;
                    return(Result.Failed);
                }
            }

            //Sort the curves so the outer loop comes first
            IList <IList <CurveLoop> > curveLoopLoop = ExporterIFCUtils.SortCurveLoops(PadBoundaryLoops);

            if (curveLoopLoop.Count > 0)
            {
                IList <CurveLoop> firstList = curveLoopLoop.First();
                if (firstList.Count > 0)
                {
                    outerLoop = firstList.First();
                }
            }

            if (outerLoop == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_OuterLoopIssue;
                return(Result.Failed);
            }

            //This will be the list of elements that the ReferenceIntersector will shoot the rays
            //If we try to shoot the rays only in the toposurface and the it has subregions, the reference
            //intersection will not recognize these regions, so its necessary to shoot rays to the surface and its subregions
            IList <ElementId> currentSubRegionsAndSurface = currentTopo.GetHostedSubRegionIds();

            currentSubRegionsAndSurface.Add(topoElementID);

            //Search for the max distance from the Pad to the topography
            //Doesnt matter if it is upwards or downwards, but we will check that, since the ray has to go to one direction
            //This is to estabilish what the distance will be using to create the slope to the right amount
            ReferenceIntersector topoRefIntersec = new ReferenceIntersector(currentSubRegionsAndSurface, FindReferenceTarget.Mesh, current3dView);

            double maxDist = double.NegativeInfinity;

            foreach (Curve currentCurve in outerLoop)
            {
                int    numberOfInteractions = 0;
                double increaseAmount       = 0;
                double currentParameter     = 0;
                EstabilishInteractionPoints(currentCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                for (int i = 0; i < numberOfInteractions; i++)
                {
                    if (i == 0)
                    {
                        currentParameter = 0;
                    }
                    else
                    {
                        currentParameter += increaseAmount;
                    }

                    XYZ currentPointToEvaluate = currentCurve.Evaluate(currentParameter, true);

                    ReferenceWithContext currentRefContext = topoRefIntersec.FindNearest(currentPointToEvaluate, XYZ.BasisZ);
                    if (currentRefContext == null)
                    {
                        currentRefContext = topoRefIntersec.FindNearest(currentPointToEvaluate, XYZ.BasisZ.Negate());
                    }

                    if (currentRefContext == null)
                    {
                        continue;
                    }

                    double currentDist = currentRefContext.Proximity;
                    if (currentDist > maxDist)
                    {
                        maxDist = currentDist;
                    }
                }
            }

            // if we haven't changed the maxdist yet, something went wrong
            if (maxDist == double.NegativeInfinity)
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;
                return(Result.Failed);
            }

            //Estabilish the offset from the pad
            double offsetDist = maxDist / Math.Tan(targetAngleInRadians);

            using (TopographyEditScope topoEditGroup = new TopographyEditScope(doc, Properties.Messages.SlopeGradingFromPads_Transaction))
            {
                topoEditGroup.Start(topoElementID);
                using (Transaction t = new Transaction(doc, Properties.Messages.SlopeGradingFromPads_Transaction))
                {
                    t.Start();

                    CurveLoop offsetLoop = null;

                    try
                    {
                        offsetLoop = CurveLoop.CreateViaOffset(outerLoop, offsetDist, plannarDirection);
                    }
                    catch
                    {
                        message += Properties.Messages.SlopeGradingFromPads_OuterOffsetLoopIssue;
                        return(Result.Failed);
                    }

                    #region DebugCurve Loop

                    //Plane p = new Plane(plannarDirection, plannarOrigin);
                    //SketchPlane sktP = SketchPlane.Create(doc, p);
                    //foreach (Curve currentOffsetCurve in offsetLoop)
                    //{
                    //    doc.Create.NewModelCurve(currentOffsetCurve, sktP);
                    //}

                    #endregion


                    foreach (Curve currentOffsetCurve in offsetLoop)
                    {
                        int    numberOfInteractions = 0;
                        double increaseAmount       = 0;
                        double currentParameter     = 0;

                        EstabilishInteractionPoints(currentOffsetCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                        for (int i = 0; i < numberOfInteractions; i++)
                        {
                            if (i == 0)
                            {
                                currentParameter = 0;
                            }
                            else
                            {
                                currentParameter += increaseAmount;
                            }

                            XYZ currentPointOffset = currentOffsetCurve.Evaluate(currentParameter, true);

                            ReferenceWithContext currentRefContext = topoRefIntersec.FindNearest(currentPointOffset, XYZ.BasisZ);
                            if (currentRefContext == null)
                            {
                                currentRefContext = topoRefIntersec.FindNearest(currentPointOffset, XYZ.BasisZ.Negate());
                            }
                            //if we couldn't find points upwards and downwards, the topo is near the border, so we cant add points
                            if (currentRefContext == null)
                            {
                                continue;
                            }

                            Reference currentReference  = currentRefContext.GetReference();
                            XYZ       currentPointToAdd = currentReference.GlobalPoint;

                            if (currentTopo.ContainsPoint(currentPointToAdd))
                            {
                                continue;
                            }

                            IList <XYZ> ListPointToAdd = new List <XYZ>();
                            ListPointToAdd.Add(currentPointToAdd);

                            currentTopo.AddPoints(ListPointToAdd);
                        }
                    }

                    foreach (Curve currentCurve in outerLoop)
                    {
                        int    numberOfInteractions = 0;
                        double increaseAmount       = 0;
                        double currentParameter     = 0;
                        EstabilishInteractionPoints(currentCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                        for (int i = 0; i < numberOfInteractions; i++)
                        {
                            if (i == 0)
                            {
                                currentParameter = 0;
                            }
                            else
                            {
                                currentParameter += increaseAmount;
                            }

                            XYZ currentPointToAdd = currentCurve.Evaluate(currentParameter, true);

                            if (currentTopo.ContainsPoint(currentPointToAdd))
                            {
                                continue;
                            }

                            IList <XYZ> ListPointToAdd = new List <XYZ>();
                            ListPointToAdd.Add(currentPointToAdd);

                            currentTopo.AddPoints(ListPointToAdd);
                        }
                    }
                    t.Commit();
                }
                topoEditGroup.Commit(new TopographyFailurePreprocessor());

                return(Result.Succeeded);
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              // Select two walls and the dimension line point:

              Selection sel = uidoc.Selection;
              ReferenceArray refs = new ReferenceArray();

              try
              {
            ISelectionFilter f
              = new JtElementsOfClassSelectionFilter<Wall>();

            refs.Append( sel.PickObject(
              ObjectType.Element, f,
              "Please select first wall" ) );

            refs.Append( sel.PickObject(
              ObjectType.Element, f,
              "Please pick dimension line "
              + "point on second wall" ) );

            //rFace = sel.PickObject( ObjectType.Face,
            //  "Please select face on second wall at dimension line point" );
            //
            //rPoint = sel.PickObject( ObjectType.PointOnElement,
            //  "Please select point on first wall" );
              }
              catch( Autodesk.Revit.Exceptions.OperationCanceledException )
              {
            message = "No two walls selected";
            return Result.Failed;
              }

              // Ensure the two selected walls are straight and
              // parallel; determine their mutual normal vector
              // and a point on each wall for distance
              // calculations:

              Wall[] walls = new Wall[2];
              List<int> ids = new List<int>( 2 );
              XYZ[] pts = new XYZ[2];
              Line[] lines = new Line[2];
              IntersectionResult ir;
              XYZ normal = null;
              int i = 0;

              foreach( Reference r in refs )
              {
            // 'Autodesk.Revit.DB.Reference.Element' is
            // obsolete: Property will be removed. Use
            // Document.GetElement(Reference) instead.
            //Wall wall = r.Element as Wall; // 2011

            Wall wall = doc.GetElement( r ) as Wall; // 2012

            walls[i] = wall;
            ids.Add( wall.Id.IntegerValue );

            // Obtain location curve and
            // check that it is straight:

            LocationCurve lc = wall.Location
              as LocationCurve;

            Curve curve = lc.Curve;
            lines[i] = curve as Line;

            if( null == lines[i] )
            {
              message = _prompt;
              return Result.Failed;
            }

            // Obtain normal vectors
            // and ensure that they are equal,
            // i.e. walls are parallel:

            if( null == normal )
            {
              normal = Util.Normal( lines[i] );
            }
            else
            {
              if( !Util.IsParallel( normal,
            Util.Normal( lines[i] ) ) )
              {
            message = _prompt;
            return Result.Failed;
              }
            }

            // Obtain pick points and project
            // onto wall location lines:

            XYZ p = r.GlobalPoint;
            ir = lines[i].Project( p );

            if( null == ir )
            {
              message = string.Format(
            "Unable to project pick point {0} "
            + "onto wall location line.",
            i );

              return Result.Failed;
            }

            pts[i] = ir.XYZPoint;

            Debug.Print(
              "Wall {0} id {1} at {2}, {3} --> point {4}",
              i, wall.Id.IntegerValue,
              Util.PointString( lines[i].GetEndPoint( 0 ) ),
              Util.PointString( lines[i].GetEndPoint( 1 ) ),
              Util.PointString( pts[i] ) );

            if( 0 < i )
            {
              // Project dimension point selected on second wall
              // back onto first wall, and ensure that normal
              // points from second wall to first:

              ir = lines[0].Project( pts[1] );
              if( null == ir )
              {
            message = string.Format(
              "Unable to project selected dimension "
              + "line point {0} on second wall onto "
              + "first wall's location line.",
              Util.PointString( pts[1] ) );

            return Result.Failed;
              }
              pts[0] = ir.XYZPoint;
            }

            ++i;
              }

              XYZ v = pts[0] - pts[1];
              if( 0 > v.DotProduct( normal ) )
              {
            normal = -normal;
              }

              // Shoot a ray back from the second
              // picked wall towards first:

              Debug.Print(
            "Shooting ray from {0} in direction {1}",
            Util.PointString( pts[1] ),
            Util.PointString( normal ) );

              View3D view = Get3DView( doc );

              if( null == view )
              {
            message = "No 3D view named '{3D}' found; "
              + "run the View > 3D View command once "
              + "to generate it.";

            return Result.Failed;
              }

              //refs = doc.FindReferencesByDirection(
              //  pts[1], normal, view ); // 2011

              //IList<ReferenceWithContext> refs2
              //  = doc.FindReferencesWithContextByDirection(
              //    pts[1], normal, view ); // 2012

              // In the Revit 2014 API, the call to
              // FindReferencesWithContextByDirection causes a
              // warning saying:
              // "FindReferencesWithContextByDirection is obsolete:
              // This method is deprecated in Revit 2014.
              // Use the ReferenceIntersector class instead."

              ReferenceIntersector ri
            = new ReferenceIntersector(
              walls[0].Id, FindReferenceTarget.Element, view );

              ReferenceWithContext ref2
            = ri.FindNearest( pts[1], normal );

              if( null == ref2 )
              {
            message = "ReferenceIntersector.FindNearest"
              + " returned null!";

            return Result.Failed;
              }

              #region Obsolete code to determine the closest reference
            #if NEED_TO_DETERMINE_CLOSEST_REFERENCE
              // Store the references to the wall surfaces:

              Reference[] surfrefs = new Reference[2] {
            null, null };

              // Find the two closest intersection
              // points on each of the two walls:

              double[] minDistance = new double[2] {
            double.MaxValue,
            double.MaxValue };

              //foreach( Reference r in refs )
              foreach( ReferenceWithContext rc in refs2 )
              {
            // 'Autodesk.Revit.DB.Reference.Element' is
            // obsolete: Property will be removed. Use
            // Document.GetElement(Reference) instead.
            //Element e = r.Element; // 2011

            Reference r = rc.GetReference();
            Element e = doc.GetElement( r ); // 2012

            if( e is Wall )
            {
              i = ids.IndexOf( e.Id.IntegerValue );

              if( -1 < i
            && ElementReferenceType.REFERENCE_TYPE_SURFACE
              == r.ElementReferenceType )
              {
            //GeometryObject g = r.GeometryObject; // 2011
            GeometryObject g = e.GetGeometryObjectFromReference( r ); // 2012

            if( g is PlanarFace )
            {
              PlanarFace face = g as PlanarFace;

              Line line = ( e.Location as LocationCurve )
            .Curve as Line;

              Debug.Print(
            "Wall {0} at {1}, {2} surface {3} "
            + "normal {4} proximity {5}",
            e.Id.IntegerValue,
            Util.PointString( line.GetEndPoint( 0 ) ),
            Util.PointString( line.GetEndPoint( 1 ) ),
            Util.PointString( face.Origin ),
            Util.PointString( face.Normal ),
            rc.Proximity );

              // First reference: assert it is a face on this wall
              // and the distance is half the wall thickness.
              // Second reference: the first reference on the other
              // wall; assert the distance between the two references
              // equals the distance between the wall location lines
              // minus half of the sum of the two wall thicknesses.

              if( rc.Proximity < minDistance[i] )
              {
            surfrefs[i] = r;
            minDistance[i] = rc.Proximity;
              }
            }
              }
            }
              }

              if( null == surfrefs[0] )
              {
            message = "No suitable face intersection "
              + "points found on first wall.";

            return Result.Failed;
              }

              if( null == surfrefs[1] )
              {
            message = "No suitable face intersection "
              + "points found on second wall.";

            return Result.Failed;
              }

              CmdDimensionWallsIterateFaces
            .CreateDimensionElement( doc.ActiveView,
            pts[0], surfrefs[0], pts[1], surfrefs[1] );
            #endif // NEED_TO_DETERMINE_CLOSEST_REFERENCE
              #endregion // Obsolete code to determine the closest reference

              CmdDimensionWallsIterateFaces
            .CreateDimensionElement( doc.ActiveView,
            pts[0], ref2.GetReference(), pts[1], refs.get_Item( 1 ) );

              return Result.Succeeded;
        }
Ejemplo n.º 22
0
        public StringBuilder Export(string pipeLineAbbreviation, HashSet <Element> elements, Document document)
        {
            Document doc = document;
            string   key = pipeLineAbbreviation;
            //The list of fittings, sorted by TYPE then SKEY
            IList <Element> fittingsList = elements.
                                           OrderBy(e => e.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString()).
                                           ThenBy(e => e.get_Parameter(new plst().PCF_ELEM_SKEY.Guid).AsString()).ToList();

            StringBuilder sbFittings = new StringBuilder();

            foreach (Element element in fittingsList)
            {
                sbFittings.AppendLine(element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString());
                sbFittings.AppendLine("    COMPONENT-IDENTIFIER " + element.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).AsString());

                if (element.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == "EXISTING-INCLUDE")
                {
                    sbFittings.AppendLine("    STATUS DOTTED-UNDIMENSIONED");
                    sbFittings.AppendLine("    MATERIAL-LIST EXCLUDE");
                }

                //Write Plant3DIso entries if turned on
                if (iv.ExportToIsogen)
                {
                    sbFittings.Append(Composer.Plant3DIsoWriter(element, doc));
                }

                //Cast the elements gathered by the collector to FamilyInstances
                FamilyInstance familyInstance = (FamilyInstance)element;
                Options        options        = new Options();

                //Gather connectors of the element
                var cons = mp.GetConnectors(element);

                //Switch to different element type configurations
                switch (element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString())
                {
                case ("ELBOW"):
                    sbFittings.Append(EndWriter.WriteEP1(element, cons.Primary));
                    sbFittings.Append(EndWriter.WriteEP2(element, cons.Secondary));
                    sbFittings.Append(EndWriter.WriteCP(familyInstance));

                    sbFittings.Append("    ANGLE ");

                    Parameter par = element.LookupParameter("Angle");
                    if (par == null)
                    {
                        par = element.LookupParameter("angle");
                    }
                    if (par == null)
                    {
                        throw new Exception($"Angle parameter on elbow {element.Id.IntegerValue} does not exist or is named differently!");
                    }
                    sbFittings.Append((Conversion.RadianToDegree(par.AsDouble()) * 100).ToString("0"));
                    sbFittings.AppendLine();

                    break;
                //case ("BEND"):
                //    sbFittings.Append(EndWriter.WriteEP1(element, cons.Primary));
                //    sbFittings.Append(EndWriter.WriteEP2(element, cons.Secondary));
                //    sbFittings.Append(EndWriter.WriteCP(familyInstance));
                //    break;

                case ("TEE"):
                    //Process endpoints of the component
                    sbFittings.Append(EndWriter.WriteEP1(element, cons.Primary));
                    sbFittings.Append(EndWriter.WriteEP2(element, cons.Secondary));
                    sbFittings.Append(EndWriter.WriteCP(familyInstance));
                    sbFittings.Append(EndWriter.WriteBP1(element, cons.Tertiary));

                    break;

                case ("REDUCER-CONCENTRIC"):
                    sbFittings.Append(EndWriter.WriteEP1(element, cons.Primary));
                    sbFittings.Append(EndWriter.WriteEP2(element, cons.Secondary));

                    break;

                case ("REDUCER-ECCENTRIC"):
                    goto case ("REDUCER-CONCENTRIC");

                case ("COUPLING"):
                    goto case ("REDUCER-CONCENTRIC");

                case ("FLANGE"):
                    //Process endpoints of the component
                    //Secondary goes first because it is the weld neck point and the primary second because it is the flanged end
                    //(dunno if it is significant); It is not, it should be specified the type of end, BW, PL, FL etc. to work correctly.

                    sbFittings.Append(EndWriter.WriteEP1(element, cons.Secondary));
                    sbFittings.Append(EndWriter.WriteEP2(element, cons.Primary));

                    break;

                case ("FLANGE-BLIND"):
                    sbFittings.Append(EndWriter.WriteEP1(element, cons.Primary));

                    XYZ    endPointOriginFlangeBlind = cons.Primary.Origin;
                    double connectorSizeFlangeBlind  = cons.Primary.Radius;

                    //Analyses the geometry to obtain a point opposite the main connector.
                    //Extraction of the direction of the connector and reversing it
                    XYZ  reverseConnectorVector = -cons.Primary.CoordinateSystem.BasisZ;
                    Line detectorLine           = Line.CreateBound(endPointOriginFlangeBlind, endPointOriginFlangeBlind + reverseConnectorVector * 10);
                    //Begin geometry analysis
                    GeometryElement geometryElement = familyInstance.get_Geometry(options);

                    //Prepare resulting point
                    XYZ endPointAnalyzed = null;

                    foreach (GeometryObject geometry in geometryElement)
                    {
                        if (geometry is GeometryInstance instance)
                        {
                            foreach (GeometryObject instObj in instance.GetInstanceGeometry())
                            {
                                Solid solid = instObj as Solid;
                                if (null == solid || 0 == solid.Faces.Size || 0 == solid.Edges.Size)
                                {
                                    continue;
                                }
                                // Get the faces
                                foreach (Face face in solid.Faces)
                                {
                                    IntersectionResultArray results = null;
                                    XYZ intersection           = null;
                                    SetComparisonResult result = face.Intersect(detectorLine, out results);
                                    if (result == SetComparisonResult.Overlap)
                                    {
                                        intersection = results.get_Item(0).XYZPoint;
                                        if (intersection.IsAlmostEqualTo(endPointOriginFlangeBlind) == false)
                                        {
                                            endPointAnalyzed = intersection;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    sbFittings.Append(EndWriter.WriteEP2(element, endPointAnalyzed, connectorSizeFlangeBlind));

                    break;

                case ("CAP"):
                    goto case ("FLANGE-BLIND");

                case ("OLET"):
                    XYZ endPointOriginOletPrimary   = cons.Primary.Origin;
                    XYZ endPointOriginOletSecondary = cons.Secondary.Origin;

                    //get reference elements
                    Pipe refPipe = null;
                    var  refCons = mp.GetAllConnectorsFromConnectorSet(cons.Primary.AllRefs);

                    Connector refCon = refCons.Where(x => x.Owner.IsType <Pipe>()).FirstOrDefault();
                    if (refCon == null)
                    {
                        //Find the target pipe
                        var filter               = new ElementClassFilter(typeof(Pipe));
                        var view3D               = Shared.Filter.Get3DView(doc);
                        var refIntersect         = new ReferenceIntersector(filter, FindReferenceTarget.Element, view3D);
                        ReferenceWithContext rwc = refIntersect.FindNearest(cons.Primary.Origin, cons.Primary.CoordinateSystem.BasisZ);
                        var refId = rwc.GetReference().ElementId;
                        refPipe = (Pipe)doc.GetElement(refId);

                        if (refPipe == null)
                        {
                            throw new Exception($"Olet {element.Id.IntegerValue} cannot find a reference Pipe!");
                        }
                    }
                    else
                    {
                        refPipe = (Pipe)refCon.Owner;
                    }

                    Cons refPipeCons = mp.GetConnectors(refPipe);

                    //Following code is ported from my python solution in Dynamo.
                    //The olet geometry is analyzed with congruent rectangles to find the connection point on the pipe even for angled olets.
                    XYZ    B = endPointOriginOletPrimary; XYZ D = endPointOriginOletSecondary; XYZ pipeEnd1 = refPipeCons.Primary.Origin; XYZ pipeEnd2 = refPipeCons.Secondary.Origin;
                    XYZ    BDvector = D - B; XYZ ABvector = pipeEnd1 - pipeEnd2;
                    double angle = Conversion.RadianToDegree(ABvector.AngleTo(BDvector));
                    if (angle > 90)
                    {
                        ABvector = -ABvector;
                        angle    = Conversion.RadianToDegree(ABvector.AngleTo(BDvector));
                    }
                    Line   refsLine = Line.CreateBound(pipeEnd1, pipeEnd2);
                    XYZ    C        = refsLine.Project(B).XYZPoint;
                    double L3       = B.DistanceTo(C);
                    XYZ    E        = refsLine.Project(D).XYZPoint;
                    double L4       = D.DistanceTo(E);
                    double ratio    = L4 / L3;
                    double L1       = E.DistanceTo(C);
                    double L5       = L1 / (ratio - 1);
                    XYZ    A;
                    if (angle < 89)
                    {
                        XYZ ECvector = C - E;
                        ECvector = ECvector.Normalize();
                        double L = L1 + L5;
                        ECvector = ECvector.Multiply(L);
                        A        = E.Add(ECvector);

                        #region Debug
                        //Debug
                        //Place family instance at points to debug the alorithm
                        //StructuralType strType = (StructuralType)4;
                        //FamilySymbol familySymbol = null;
                        //FilteredElementCollector collector = new FilteredElementCollector(doc);
                        //IEnumerable<Element> collection = collector.OfClass(typeof(FamilySymbol)).ToElements();
                        //FamilySymbol marker = null;
                        //foreach (Element e in collection)
                        //{
                        //    familySymbol = e as FamilySymbol;
                        //    if (null != familySymbol.Category)
                        //    {
                        //        if ("Structural Columns" == familySymbol.Category.Name)
                        //        {
                        //            break;
                        //        }
                        //    }
                        //}

                        //if (null != familySymbol)
                        //{
                        //    foreach (Element e in collection)
                        //    {
                        //        familySymbol = e as FamilySymbol;
                        //        if (familySymbol.FamilyName == "Marker")
                        //        {
                        //            marker = familySymbol;
                        //            Transaction trans = new Transaction(doc, "Place point markers");
                        //            trans.Start();
                        //            doc.Create.NewFamilyInstance(A, marker, strType);
                        //            doc.Create.NewFamilyInstance(B, marker, strType);
                        //            doc.Create.NewFamilyInstance(C, marker, strType);
                        //            doc.Create.NewFamilyInstance(D, marker, strType);
                        //            doc.Create.NewFamilyInstance(E, marker, strType);
                        //            trans.Commit();
                        //        }
                        //    }

                        //}
                        #endregion
                    }
                    else
                    {
                        A = E;
                    }
                    angle = Math.Round(angle * 100);

                    sbFittings.Append(EndWriter.WriteCP(A));

                    sbFittings.Append(EndWriter.WriteBP1(element, cons.Secondary));

                    sbFittings.Append("    ANGLE ");
                    sbFittings.Append(Conversion.AngleToPCF(angle));
                    sbFittings.AppendLine();

                    break;
                }

                Composer elemParameterComposer = new Composer();
                sbFittings.Append(elemParameterComposer.ElemParameterWriter(element));

                #region CII export
                if (iv.ExportToCII)
                {
                    sbFittings.Append(Composer.CIIWriter(doc, key));
                }
                #endregion

                sbFittings.Append("    UNIQUE-COMPONENT-IDENTIFIER ");
                sbFittings.Append(element.UniqueId);
                sbFittings.AppendLine();
            }

            //// Clear the output file
            //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Fittings.pcf", new byte[0]);

            //// Write to output file
            //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Fittings.pcf"))
            //{
            //    w.Write(sbFittings);
            //    w.Close();
            //}

            return(sbFittings);
        }
Ejemplo n.º 23
0
        public Result add_dimension_from_points(ViewPlan floorView, XYZ pt1, XYZ normal1, XYZ pt2, XYZ normal2, string dimension, XYZ offset)
        {
            Transaction trans = new Transaction(doc);

            offset = new XYZ(offset.X / 12.0, offset.Y / 12.0, offset.Z);
            pt1    = new XYZ(pt1.X / 12, pt1.Y / 12, pt1.Z);
            pt2    = new XYZ(pt2.X / 12, pt2.Y / 12, pt2.Z);

            ElementClassFilter filter = new ElementClassFilter(typeof(WallType));

            ViewFamilyType viewFamily = new FilteredElementCollector(doc)
                                        .OfClass(typeof(ViewFamilyType))
                                        .Cast <ViewFamilyType>()
                                        .First(x => x.ViewFamily == ViewFamily.ThreeDimensional);

            View3D view;

            using (trans = new Transaction(doc))
            {
                trans.Start("Create temp view");
                view = View3D.CreateIsometric(doc, viewFamily.Id);
                trans.Commit();
            }

            List <BuiltInCategory> builtInCats
                = new List <BuiltInCategory>();

            builtInCats.Add(BuiltInCategory.OST_Roofs);
            builtInCats.Add(BuiltInCategory.OST_Ceilings);
            builtInCats.Add(BuiltInCategory.OST_Floors);
            builtInCats.Add(BuiltInCategory.OST_Walls);

            ElementMulticategoryFilter intersectFilter = new ElementMulticategoryFilter(builtInCats);

            ReferenceIntersector ri1 = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, view);
            ReferenceIntersector ri2 = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, view);

            ReferenceWithContext ref1 = ri1.FindNearest(pt1, normal1);
            ReferenceWithContext ref2 = ri2.FindNearest(pt2, normal2);

            using (trans = new Transaction(doc))
            {
                trans.Start("Delete temp view");
                doc.Delete(view.Id);
                trans.Commit();
            }

            ReferenceArray ra = new ReferenceArray();

            ra.Append(ref1.GetReference());
            ra.Append(ref2.GetReference());

            Line      line = Line.CreateBound(pt1.Add(offset), pt1.Add(offset).Add(normal1));
            Dimension dim;

            DimensionType dType = null;


            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create New Dimension");
                dim = doc.Create.NewDimension(floorView, line, ra);

                if (dimension.Equals(""))
                {
                    dType = new FilteredElementCollector(doc)
                            .OfClass(typeof(DimensionType))
                            .Cast <DimensionType>().FirstOrDefault(q
                                                                   => q.Name == "type-unknown");
                }
                else if (dimension.Equals(dim.ValueString))
                {
                    dType = new FilteredElementCollector(doc)
                            .OfClass(typeof(DimensionType))
                            .Cast <DimensionType>().FirstOrDefault(q
                                                                   => q.Name == "type-correct");
                }
                else
                {
                    dType = new FilteredElementCollector(doc)
                            .OfClass(typeof(DimensionType))
                            .Cast <DimensionType>().FirstOrDefault(q
                                                                   => q.Name == "type-incorrect");
                }

                dim.DimensionType = dType;
                t.Commit();
            }

            return(Result.Succeeded);
        }
        public static void Calculate(UIApplication uiApp)
        {
            Document   doc   = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                using (TransactionGroup txGp = new TransactionGroup(doc))
                {
                    txGp.Start("Calculate height of hangers");

                    //Collect elements
                    var hangerSupports = fi.GetElements <FamilyInstance, Guid>
                                             (doc, new Guid("e0baa750-22ba-4e60-9466-803137a0cba8"), "Hænger");
                    //Is the following required?
                    HashSet <Element> allHangers = new HashSet <Element>(hangerSupports.Cast <Element>()
                                                                         .Where(x => x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory));

                    //Prepare common objects for intersection analysis
                    //Create a filter that filters for structural columns and framing
                    //Why columns? Maybe only framing is enough.

                    //Linked IFC files create DirectShapes!
                    //ElementClassFilter filter = new ElementClassFilter(typeof(DirectShape));

                    IList <ElementFilter> filterList = new List <ElementFilter>
                    {
                        new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming),
                        new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns),
                        new ElementCategoryFilter(BuiltInCategory.OST_Floors)
                    };
                    LogicalOrFilter bicFilter = new LogicalOrFilter(filterList);

                    IList <ElementFilter> filterList2 = new List <ElementFilter>
                    {
                        new ElementClassFilter(typeof(FamilyInstance)),
                        new ElementClassFilter(typeof(Floor))
                    };
                    LogicalOrFilter classFilter = new LogicalOrFilter(filterList2);

                    LogicalAndFilter fiAndBicFilter = new LogicalAndFilter(bicFilter, classFilter);
                    //new ElementClassFilter(typeof(FamilyInstance)));

                    //Get the default 3D view
                    var view3D = Shared.Filter.Get3DView(doc);
                    if (view3D == null)
                    {
                        throw new Exception("No default 3D view named {3D} is found!.");
                    }

                    //Instantiate the Reference Intersector
                    var refIntersect = new ReferenceIntersector(fiAndBicFilter, FindReferenceTarget.Face, view3D);
                    refIntersect.FindReferencesInRevitLinks = true;

                    //Prepare to find levels
                    HashSet <Level> levels = fi.GetElements <Level, BuiltInCategory>(doc, BuiltInCategory.OST_Levels);

                    using (Transaction trans1 = new Transaction(doc))
                    {
                        trans1.Start("Calculate height to nearest framing");

                        foreach (Element hanger in allHangers)
                        {
                            //Find the point of the framing above the hanger
                            Transform trf    = ((FamilyInstance)hanger).GetTransform();
                            XYZ       Origin = new XYZ();
                            Origin = trf.OfPoint(Origin);
                            XYZ Direction = trf.BasisZ;
                            //XYZ Origin = ((LocationPoint)hanger.Location).Point;

                            ReferenceWithContext rwc = refIntersect.FindNearest(Origin, Direction);
                            if (rwc != null)
                            {
                                //throw new Exception($"Hanger {hanger.Id} did not find any steel supports!\n" +
                                //                    $"Check if elements are properly aligned.");
                                Reference reference    = rwc.GetReference();
                                XYZ       intersection = reference.GlobalPoint;

                                //Get the hanger's height above it's reference level
                                Parameter offsetPar     = hanger.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
                                double    offsetFromLvl = offsetPar.AsDouble();
                                //Just to make sure that the proper parameter is set
                                hanger.LookupParameter("PipeOffsetFromLevel").Set(offsetFromLvl);

                                //Calculate the height of the intersection above the reference level
                                ElementId refLvlId        = hanger.LevelId;
                                Level     refLvl          = (Level)doc.GetElement(refLvlId);
                                double    refLvlElevation = refLvl.Elevation;
                                double    profileHeight   = intersection.Z - refLvlElevation;

                                //Set the hanger value so it updates
                                hanger.LookupParameter("LevelHeight").Set(profileHeight);

                                //Set the values for the BeamClamps
                                if (hanger.FamilyName() == "Spring Hanger - Witzenmann-Hydra - Type 11" ||
                                    hanger.FamilyName() == "Rigid Hanger - Hydra - Type 11" ||
                                    hanger.FamilyName() == "Spring Hanger - Witzenmann-Hydra - Type 12")
                                {
                                    //Instantiate the Reference Intersector
                                    var refIntersectElement = new ReferenceIntersector(fiAndBicFilter, FindReferenceTarget.Element, view3D);
                                    refIntersectElement.FindReferencesInRevitLinks = true;
                                    ReferenceWithContext rwcElement = refIntersect.FindNearest(Origin, Direction);
                                    if (rwcElement != null)
                                    {
                                        Reference referenceElement = rwcElement.GetReference();
                                        Element   element          = doc.GetElement(reference);

                                        if (element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralFraming)
                                        {
                                            FamilyInstance fi = element as FamilyInstance;

                                            //StructuralSection ss = fi.Symbol.GetStructuralSection();
                                            ////StructuralSectionUtils.GetStructuralSection(doc, element.Id);
                                            //StructuralSectionShape sss = ss.StructuralSectionShape;

                                            FamilySymbol fs              = fi.Symbol;
                                            double       flangeWidth     = fs.LookupParameter("bf").AsDouble();
                                            double       flangeThickness = fs.LookupParameter("tf").AsDouble();

                                            hanger.LookupParameter("ProfilKlammeFlangeBredde")?.Set(flangeWidth);
                                            hanger.LookupParameter("ProfilKlammeFlangeTykkelse")?.Set(flangeThickness);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //Determine levels
                                List <(Level lvl, double dist)> levelsWithDist = new List <(Level lvl, double dist)>(levels.Count);

                                foreach (Level level in levels)
                                {
                                    (Level, double)result = (level, ((LocationPoint)hanger.Location).Point.Z - level.Elevation);
                                    if (result.Item2 < 1e-6)
                                    {
                                        levelsWithDist.Add(result);
                                    }
                                }

                                var minimumLevel = levelsWithDist.MaxBy(x => x.dist).FirstOrDefault();
                                if (minimumLevel.Equals(default))
Ejemplo n.º 25
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get UIDocument and Document
            UIApplication uiapp = commandData.Application;
            Application   app   = uiapp.Application;
            UIDocument    uidoc = commandData.Application.ActiveUIDocument;
            Document      doc   = uidoc.Document;


            try
            {
                //Create Filtered Element Collector
                FilteredElementCollector atCollector = new FilteredElementCollector(doc);
                FilteredElementCollector lfCollector = new FilteredElementCollector(doc);
                //Create Filter - All Air Terminals in project | Lights in project
                ElementCategoryFilter terminalsFilter = new ElementCategoryFilter(BuiltInCategory.OST_DuctTerminal);
                ElementCategoryFilter lightsFilter    = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtures);

                //Create lists with the filters
                IList <Element> airTerminals     = atCollector.WherePasses(terminalsFilter).WhereElementIsNotElementType().ToElements();
                IList <Element> lightingFixtures = lfCollector.WherePasses(lightsFilter).WhereElementIsNotElementType().ToElements();

                if (airTerminals != null)
                {
                    //Check for ceiling above and move air terminals up
                    foreach (Element ele in airTerminals)
                    {
                        //Get air terminal height
                        Parameter atHeight = ele.LookupParameter("Offset");

                        //Get air terminal name / Boolean for filtering out wall based
                        FamilyInstance familyInstance = ele as FamilyInstance;
                        FamilySymbol   familySymbol   = familyInstance.Symbol;
                        String         familyName     = familySymbol.FamilyName;
                        Boolean        atWallBased    = familyName.Contains("wall") || familyName.Contains("Wall") || familyName.Contains("Louver");

                        if (atWallBased != true)
                        {
                            //Parameter atHeight = ele.get_Parameter(BuiltInParameter.offset)
                            //Create a Project Ray from element location
                            LocationPoint locP = ele.Location as LocationPoint;
                            XYZ           p1   = locP.Point;

                            //Ray Direction Up
                            XYZ RayZ = new XYZ(0, 0, 1);

                            //******************************* Determine what the ray will intersect with***********************************

                            //Only getting interseting elements from the active view not entire model | change to whole model once code is completed
                            //or open a predetermined view

                            //Filter
                            ElementCategoryFilter filterC = new ElementCategoryFilter(BuiltInCategory.OST_Ceilings);

                            ReferenceIntersector refI = new ReferenceIntersector(filterC, FindReferenceTarget.Element, (View3D)doc.ActiveView)
                                                        //ReferenceIntersector refI = new ReferenceIntersector((View3D)doc.ActiveView)
                            {
                                FindReferencesInRevitLinks = true
                            };
                            ReferenceWithContext refC = refI.FindNearest(p1, RayZ);

                            //******************************************************************************************************************

                            if (refC != null)
                            {
                                Reference refel    = refC.GetReference();
                                XYZ       intPoint = refel.GlobalPoint;
                                Double    dist     = p1.DistanceTo(intPoint);

                                RevitLinkInstance linkinstance = doc.GetElement(refel.ElementId) as RevitLinkInstance;
                                Element           linkElem     = linkinstance.GetLinkDocument().GetElement(refel.LinkedElementId);

                                Parameter pHeight = linkElem.LookupParameter("Height Offset From Level");

                                if (pHeight.AsValueString() != atHeight.AsValueString())
                                {
                                    //Set Parameter Value
                                    using (Transaction trans = new Transaction(doc, "Set Parameter"))
                                    {
                                        trans.Start();

                                        atHeight.SetValueString(pHeight.AsValueString());

                                        trans.Commit();

                                        //Category refCat = linkElem.Category;
                                        //TaskDialog.Show("Ray", string.Format("Intersecting Ceiling offset is {0}",
                                        //    pHeight.AsValueString() + Environment.NewLine
                                        //    + "Diffuser Height: " + ele.LookupParameter("Offset").AsValueString() + Environment.NewLine
                                        //    + "Category: " + ele.Category.Name + Environment.NewLine
                                        //    + "Instance: " + ele.Name + Environment.NewLine)
                                        //    );
                                    }
                                }
                            }
                        }
                    }
                    //Check for ceiling below and move air terminals down
                    foreach (Element ele in airTerminals)
                    {
                        //Get air terminal height
                        Parameter atHeight = ele.LookupParameter("Offset");

                        //Get air terminal name / Boolean for filtering out wall based
                        FamilyInstance familyInstance = ele as FamilyInstance;
                        FamilySymbol   familySymbol   = familyInstance.Symbol;
                        String         familyName     = familySymbol.FamilyName;
                        Boolean        atWallBased    = familyName.Contains("wall") || familyName.Contains("Wall") || familyName.Contains("Louver");

                        if (atWallBased != true)
                        {
                            //Create a Project Ray from element location
                            LocationPoint locP = ele.Location as LocationPoint;
                            XYZ           p1   = locP.Point;

                            //Ray Direction Up
                            XYZ RayZ = new XYZ(0, 0, -1);

                            //******************************* Determine what the ray will intersect with***********************************

                            //Only getting interseting elements from the active view not entire model | change to whole model once code is completed
                            //or open a predetermined view

                            //Filter
                            ElementCategoryFilter filterC = new ElementCategoryFilter(BuiltInCategory.OST_Ceilings);

                            ReferenceIntersector refI = new ReferenceIntersector(filterC, FindReferenceTarget.Element, (View3D)doc.ActiveView)
                                                        //ReferenceIntersector refI = new ReferenceIntersector((View3D)doc.ActiveView)
                            {
                                FindReferencesInRevitLinks = true
                            };
                            ReferenceWithContext refC = refI.FindNearest(p1, RayZ);

                            //******************************************************************************************************************

                            if (refC != null)
                            {
                                Reference refel    = refC.GetReference();
                                XYZ       intPoint = refel.GlobalPoint;
                                Double    dist     = p1.DistanceTo(intPoint);

                                RevitLinkInstance linkinstance = doc.GetElement(refel.ElementId) as RevitLinkInstance;
                                Element           linkElem     = linkinstance.GetLinkDocument().GetElement(refel.LinkedElementId);

                                Parameter pHeight = linkElem.LookupParameter("Height Offset From Level");

                                if (pHeight.AsValueString() != atHeight.AsValueString())
                                {
                                    //Set Parameter Value
                                    using (Transaction trans = new Transaction(doc, "Set Parameter"))
                                    {
                                        trans.Start();

                                        atHeight.SetValueString(pHeight.AsValueString());

                                        trans.Commit();

                                        //Category refCat = linkElem.Category;
                                        //TaskDialog.Show("Ray", string.Format("Intersecting Ceiling offset is {0}",
                                        //    pHeight.AsValueString() + Environment.NewLine
                                        //    + "Diffuser Height: " + ele.LookupParameter("Offset").AsValueString() + Environment.NewLine
                                        //    + "Category: " + ele.Category.Name + Environment.NewLine
                                        //    + "Instance: " + ele.Name + Environment.NewLine)
                                        //    );
                                    }
                                }
                            }
                        }
                    }
                }

                if (lightingFixtures != null)
                {
                    //Check for ceiling above and move air terminals up
                    foreach (Element ele in lightingFixtures)
                    {
                        //Get lighting fixture height
                        Parameter lfHeight = ele.LookupParameter("Offset");

                        //Get air terminal name / Boolean for filtering out wall based
                        FamilyInstance familyInstance = ele as FamilyInstance;
                        FamilySymbol   familySymbol   = familyInstance.Symbol;
                        String         familyName     = familySymbol.FamilyName;
                        Boolean        lfWallBased    = familyName.Contains("wall") || familyName.Contains("Wall");

                        if (lfWallBased != true)
                        {
                            //Parameter atHeight = ele.get_Parameter(BuiltInParameter.offset)
                            //Create a Project Ray from element location
                            LocationPoint locP = ele.Location as LocationPoint;
                            XYZ           p1   = locP.Point;

                            //Ray Direction Up
                            XYZ RayZ = new XYZ(0, 0, 1);

                            //******************************* Determine what the ray will intersect with***********************************

                            //Only getting interseting elements from the active view not entire model | change to whole model once code is completed
                            //or open a predetermined view

                            //Filter
                            ElementCategoryFilter filterC = new ElementCategoryFilter(BuiltInCategory.OST_Ceilings);

                            ReferenceIntersector refI = new ReferenceIntersector(filterC, FindReferenceTarget.Element, (View3D)doc.ActiveView)
                                                        //ReferenceIntersector refI = new ReferenceIntersector((View3D)doc.ActiveView)
                            {
                                FindReferencesInRevitLinks = true
                            };
                            ReferenceWithContext refC = refI.FindNearest(p1, RayZ);

                            //******************************************************************************************************************

                            if (refC != null)
                            {
                                Reference refel    = refC.GetReference();
                                XYZ       intPoint = refel.GlobalPoint;
                                Double    dist     = p1.DistanceTo(intPoint);

                                RevitLinkInstance linkinstance = doc.GetElement(refel.ElementId) as RevitLinkInstance;
                                Element           linkElem     = linkinstance.GetLinkDocument().GetElement(refel.LinkedElementId);

                                Parameter pHeight = linkElem.LookupParameter("Height Offset From Level");

                                if (pHeight.AsValueString() != lfHeight.AsValueString())
                                {
                                    //Set Parameter Value
                                    using (Transaction trans = new Transaction(doc, "Set Parameter"))
                                    {
                                        trans.Start();

                                        lfHeight.SetValueString(pHeight.AsValueString());

                                        trans.Commit();

                                        //Category refCat = linkElem.Category;
                                        //TaskDialog.Show("Ray", string.Format("Intersecting Ceiling offset is {0}",
                                        //    pHeight.AsValueString() + Environment.NewLine
                                        //    + "Diffuser Height: " + ele.LookupParameter("Offset").AsValueString() + Environment.NewLine
                                        //    + "Category: " + ele.Category.Name + Environment.NewLine
                                        //    + "Instance: " + ele.Name + Environment.NewLine)
                                        //    );
                                    }
                                }
                            }
                        }
                    }
                    //Check for ceiling below and move air terminals down
                    foreach (Element ele in lightingFixtures)
                    {
                        //Get lighting fixture height
                        Parameter lfHeight = ele.LookupParameter("Offset");

                        //Get air terminal name / Boolean for filtering out wall based
                        FamilyInstance familyInstance = ele as FamilyInstance;
                        FamilySymbol   familySymbol   = familyInstance.Symbol;
                        String         familyName     = familySymbol.FamilyName;
                        Boolean        lfWallBased    = familyName.Contains("wall") || familyName.Contains("Wall");

                        if (lfWallBased != true)
                        {
                            //Parameter atHeight = ele.get_Parameter(BuiltInParameter.offset)
                            //Create a Project Ray from element location
                            LocationPoint locP = ele.Location as LocationPoint;
                            XYZ           p1   = locP.Point;

                            //Ray Direction Up
                            XYZ RayZ = new XYZ(0, 0, -1);

                            //******************************* Determine what the ray will intersect with***********************************

                            //Only getting interseting elements from the active view not entire model | change to whole model once code is completed
                            //or open a predetermined view

                            //Filter
                            ElementCategoryFilter filterC = new ElementCategoryFilter(BuiltInCategory.OST_Ceilings);

                            ReferenceIntersector refI = new ReferenceIntersector(filterC, FindReferenceTarget.Element, (View3D)doc.ActiveView)
                                                        //ReferenceIntersector refI = new ReferenceIntersector((View3D)doc.ActiveView)
                            {
                                FindReferencesInRevitLinks = true
                            };
                            ReferenceWithContext refC = refI.FindNearest(p1, RayZ);

                            //******************************************************************************************************************

                            if (refC != null)
                            {
                                Reference refel    = refC.GetReference();
                                XYZ       intPoint = refel.GlobalPoint;
                                Double    dist     = p1.DistanceTo(intPoint);

                                RevitLinkInstance linkinstance = doc.GetElement(refel.ElementId) as RevitLinkInstance;
                                Element           linkElem     = linkinstance.GetLinkDocument().GetElement(refel.LinkedElementId);

                                Parameter pHeight = linkElem.LookupParameter("Height Offset From Level");

                                if (pHeight.AsValueString() != lfHeight.AsValueString())
                                {
                                    //Set Parameter Value
                                    using (Transaction trans = new Transaction(doc, "Set Parameter"))
                                    {
                                        trans.Start();

                                        lfHeight.SetValueString(pHeight.AsValueString());

                                        trans.Commit();

                                        //Category refCat = linkElem.Category;
                                        //TaskDialog.Show("Ray", string.Format("Intersecting Ceiling offset is {0}",
                                        //    pHeight.AsValueString() + Environment.NewLine
                                        //    + "Diffuser Height: " + ele.LookupParameter("Offset").AsValueString() + Environment.NewLine
                                        //    + "Category: " + ele.Category.Name + Environment.NewLine
                                        //    + "Instance: " + ele.Name + Environment.NewLine)
                                        //    );
                                    }
                                }
                            }
                        }
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
        void AdjustColumnHeightsUsingReferenceIntersector(
            Document doc,
            IList <ElementId> ids)
        {
            View3D view = doc.ActiveView as View3D;

            if (null == view)
            {
                throw new Exception(
                          "Please run this command in a 3D view.");
            }

            int allColumns     = 0;
            int successColumns = 0;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Attach Columns Tops");

                foreach (ElementId elemId in ids)
                {
                    Element elem = doc.GetElement(elemId);

                    if ((BuiltInCategory)elem.Category.Id.IntegerValue
                        == BuiltInCategory.OST_StructuralColumns)
                    {
                        allColumns++;

                        FamilyInstance column = elem as FamilyInstance;

                        // Collect beams and slabs

                        List <BuiltInCategory> builtInCats = new List <BuiltInCategory>();
                        builtInCats.Add(BuiltInCategory.OST_Floors);
                        builtInCats.Add(BuiltInCategory.OST_StructuralFraming);
                        ElementMulticategoryFilter filter
                            = new ElementMulticategoryFilter(builtInCats);

                        // Remove old column attachement

                        if (ColumnAttachment.GetColumnAttachment(column, 1) != null)
                        {
                            ColumnAttachment.RemoveColumnAttachment(column, 1);
                        }

                        BoundingBoxXYZ elemBB = elem.get_BoundingBox(view);

                        XYZ elemLoc    = (elem.Location as LocationPoint).Point;
                        XYZ elemCenter = new XYZ(elemLoc.X, elemLoc.Y, elemLoc.Z + 0.1);
                        XYZ b1         = new XYZ(elemBB.Min.X, elemBB.Min.Y, elemBB.Min.Z + 0.1);
                        XYZ b2         = new XYZ(elemBB.Max.X, elemBB.Max.Y, elemBB.Min.Z + 0.1);
                        XYZ b3         = new XYZ(elemBB.Min.X, elemBB.Max.Y, elemBB.Min.Z + 0.1);
                        XYZ b4         = new XYZ(elemBB.Max.X, elemBB.Min.Y, elemBB.Min.Z + 0.1);

                        List <XYZ> points = new List <XYZ>(5);
                        points.Add(b1);
                        points.Add(b2);
                        points.Add(b3);
                        points.Add(b4);
                        points.Add(elemCenter);

                        ReferenceIntersector refI = new ReferenceIntersector(
                            filter, FindReferenceTarget.All, view);

                        XYZ rayd = XYZ.BasisZ;
                        ReferenceWithContext refC = null;
                        foreach (XYZ pt in points)
                        {
                            refC = refI.FindNearest(pt, rayd);
                            if (refC != null)
                            {
                                break;
                            }
                        }

                        if (refC != null)
                        {
                            Reference reference = refC.GetReference();
                            ElementId id        = reference.ElementId;
                            Element   e         = doc.GetElement(id);

                            ColumnAttachment.AddColumnAttachment(
                                doc, column, e, 1,
                                ColumnAttachmentCutStyle.None,
                                ColumnAttachmentJustification.Minimum,
                                0);

                            successColumns++;
                        }
                        else
                        {
                            // Change color of columns to red

                            Color color = new Color((byte)255, (byte)0, (byte)0);
                            OverrideGraphicSettings ogs = new OverrideGraphicSettings();
                            ogs.SetProjectionLineColor(color);
                            view.SetElementOverrides(elem.Id, ogs);
                        }
                    }
                }
                tx.Commit();
            }
        }
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name);

                if (doc.ActiveView.GetType() != typeof(View3D))
                {
                    MessageBox.Show("ActiveView is not typeof View3D.");
                    return;
                }

                FamilyInstance myFamilyInstance_NerfGun = null;
                if (uidoc.Selection.GetElementIds().Count == 0)
                {
                    string myString_RememberLast = doc.ProjectInformation.get_Parameter(BuiltInParameter.PROJECT_NUMBER).AsString();
                    int    n;
                    if (int.TryParse(myString_RememberLast, out n))
                    {
                        myFamilyInstance_NerfGun = doc.GetElement(new ElementId(n)) as FamilyInstance;
                    }
                }
                else
                {
                    myFamilyInstance_NerfGun = doc.GetElement(uidoc.Selection.GetElementIds().First()) as FamilyInstance;
                }


                if (myFamilyInstance_NerfGun == null)
                {
                    MessageBox.Show("Please perform step 5 of 19 first." + Environment.NewLine + Environment.NewLine + "(Placing Nerf Gun)");
                    return;
                }

                ///            TECHNIQUE 14 OF 19 (EE14_Draw3D_IntersectorLines.cs)
                ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ DRAW INTERSECTOR LINES FROM NERF GUN ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                ///
                /// Interfaces and ENUM's:
                ///     BuiltInParameter.POINT_ELEMENT_DRIVEN
                ///     IFailuresPreprocessor
                ///
                ///
                /// Demonstrates classes:
                ///     ReferencePoint
                ///     AdaptiveComponentInstanceUtils
                ///     Transform
                ///     TransactionGroup
                ///     Random*
                ///     ElementMulticategoryFilter
                ///     ReferenceIntersector
                ///
                ///
                /// Key methods:
                ///     AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(
                ///     myReferencePoint.GetCoordinateSystem(
                ///     refIntersector.FindNearest(
                ///     myReferenceWithContext.GetReference(
                ///     uidoc.RefreshActiveView();
                ///
                ///
                ///
                /// * class is actually part of the .NET framework (not Revit API)
                ///
                ///
                ///	https://github.com/joshnewzealand/Revit-API-Playpen-CSharp

                uidoc.Selection.SetElementIds(new List <ElementId>());

                ReferencePoint myReferencePoint = doc.GetElement(AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(myFamilyInstance_NerfGun).First()) as ReferencePoint;

                Transform myTransform_FromNurfGun = myReferencePoint.GetCoordinateSystem();


                using (TransactionGroup transGroup = new TransactionGroup(doc))
                {
                    transGroup.Start("Transaction Group");

                    if (!myReferencePoint.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).IsReadOnly)
                    {
                        using (Transaction tx = new Transaction(doc))
                        {
                            tx.Start("Unhost");

                            myReferencePoint.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).Set(0);

                            tx.Commit();
                            uidoc.RefreshActiveView();
                        }
                    }

                    MyPreProcessor preproccessor = new MyPreProcessor();

                    for (int i = 1; i <= 100; i++)
                    {
                        if (i > 100)
                        {
                            MessageBox.Show("Stopped at 'i > 100' because more will cause Revit to 'freeze up'.");
                            break;
                        }

                        Random rnd = new Random();
                        OverrideGraphicSettings ogs = new OverrideGraphicSettings();
                        ogs.SetProjectionLineColor(new Autodesk.Revit.DB.Color((byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256)));

                        using (Transaction tx = new Transaction(doc))
                        {
                            FailureHandlingOptions options = tx.GetFailureHandlingOptions();
                            options.SetFailuresPreprocessor(preproccessor);
                            tx.SetFailureHandlingOptions(options);

                            tx.Start("Splatter Gun");

                            Line myLine_BasisX = Line.CreateUnbound(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisX);
                            myReferencePoint.Location.Rotate(myLine_BasisX, GetRandomNumber());

                            Line myLine_BasisZ = Line.CreateUnbound(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisZ);
                            myReferencePoint.Location.Rotate(myLine_BasisZ, GetRandomNumber());

                            myTransform_FromNurfGun = myReferencePoint.GetCoordinateSystem();

                            List <BuiltInCategory> builtInCats = new List <BuiltInCategory>();
                            builtInCats.Add(BuiltInCategory.OST_Roofs);
                            builtInCats.Add(BuiltInCategory.OST_Ceilings);
                            builtInCats.Add(BuiltInCategory.OST_Floors);
                            builtInCats.Add(BuiltInCategory.OST_Walls);
                            builtInCats.Add(BuiltInCategory.OST_Doors);
                            builtInCats.Add(BuiltInCategory.OST_Windows);
                            builtInCats.Add(BuiltInCategory.OST_CurtainWallPanels);
                            builtInCats.Add(BuiltInCategory.OST_CurtainWallMullions);

                            ElementMulticategoryFilter intersectFilter = new ElementMulticategoryFilter(builtInCats);
                            ReferenceIntersector       refIntersector  = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, doc.ActiveView as View3D);

                            ReferenceWithContext myReferenceWithContext = refIntersector.FindNearest(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisZ);

                            if (myReferenceWithContext != null)
                            {
                                Reference myReferenceHosting_Normal = myReferenceWithContext.GetReference();

                                Element myElement_ContainingFace = doc.GetElement(myReferenceHosting_Normal.ElementId);
                                Face    myFace = myElement_ContainingFace.GetGeometryObjectFromReference(myReferenceHosting_Normal) as Face;
                                if (myFace.GetType() != typeof(PlanarFace))
                                {
                                    return;                                        // continue;
                                }
                                Plane       plane       = Plane.CreateByNormalAndOrigin(myTransform_FromNurfGun.BasisX, myTransform_FromNurfGun.Origin);
                                SketchPlane sketchPlane = SketchPlane.Create(doc, plane);

                                if (myTransform_FromNurfGun.Origin.DistanceTo(myReferenceHosting_Normal.GlobalPoint) > 0.0026)//minimum lenth check
                                {
                                    Line line = Line.CreateBound(myTransform_FromNurfGun.Origin, myReferenceHosting_Normal.GlobalPoint);

                                    ModelLine myModelLine = doc.Create.NewModelCurve(line, sketchPlane) as ModelLine;

                                    doc.ActiveView.SetElementOverrides(myModelLine.Id, ogs);

                                    myWindow1.myListElementID_SketchPlanesToDelete.Add(sketchPlane.Id);

                                    Transform myXYZ_FamilyTransform = Transform.Identity;

                                    if (myReferenceHosting_Normal.ConvertToStableRepresentation(doc).Contains("INSTANCE"))
                                    {
                                        myXYZ_FamilyTransform = (myElement_ContainingFace as FamilyInstance).GetTotalTransform();
                                    }

                                    PlanarFace myPlanarFace = myFace as PlanarFace;

                                    Transform myTransform = Transform.Identity;
                                    myTransform.Origin = myReferenceHosting_Normal.GlobalPoint;
                                    myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector);
                                    myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector);
                                    myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal);

                                    SketchPlane mySketchPlane = SketchPlane.Create(doc, myReferenceHosting_Normal);

                                    // Create a geometry circle in Revit application
                                    XYZ    xVec        = myTransform.OfVector(XYZ.BasisX);
                                    XYZ    yVec        = myTransform.OfVector(XYZ.BasisY);
                                    double startAngle2 = 0;
                                    double endAngle2   = 2 * Math.PI;
                                    double radius2     = 1.23;
                                    Arc    geomPlane3  = Arc.Create(myTransform.OfPoint(new XYZ(0, 0, 0)), radius2, startAngle2, endAngle2, xVec, yVec);

                                    ModelArc arc = doc.Create.NewModelCurve(geomPlane3, mySketchPlane) as ModelArc;
                                    //doc.Delete(sketch2.Id);

                                    doc.ActiveView.SetElementOverrides(arc.Id, ogs);
                                }
                            }
                            tx.Commit();
                            uidoc.RefreshActiveView();
                        }
                    }
                    transGroup.Assimilate();
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE05_Part1" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
        /// <summary>
        /// Return a reference to the topmost face of the given element.
        /// </summary>
        private Reference FindTopMostReference(Element e)
        {
            Reference ret = null;
            Document  doc = e.Document;

            #region Revit 2012
#if _2012
            using (SubTransaction t = new SubTransaction(doc))
            {
                t.Start();

                // Create temporary 3D view

                //View3D view3D = doc.Create.NewView3D( // 2012
                //  viewDirection ); // 2012

                ViewFamilyType vft
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(ViewFamilyType))
                      .Cast <ViewFamilyType>()
                      .FirstOrDefault <ViewFamilyType>(x =>
                                                       ViewFamily.ThreeDimensional == x.ViewFamily);

                Debug.Assert(null != vft,
                             "expected to find a valid 3D view family type");

                View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013

                XYZ eyePosition      = XYZ.BasisZ;
                XYZ upDirection      = XYZ.BasisY;
                XYZ forwardDirection = -XYZ.BasisZ;

                view.SetOrientation(new ViewOrientation3D(
                                        eyePosition, upDirection, forwardDirection));

                XYZ viewDirection = -XYZ.BasisZ;

                BoundingBoxXYZ bb = e.get_BoundingBox(view);

                XYZ max = bb.Max;

                XYZ minAtMaxElevation = Create.NewXYZ(
                    bb.Min.X, bb.Min.Y, max.Z);

                XYZ centerOfTopOfBox = 0.5
                                       * (minAtMaxElevation + max);

                centerOfTopOfBox += 10 * XYZ.BasisZ;

                // Cast a ray through the model
                // to find the topmost surface

#if DEBUG
                //ReferenceArray references
                //  = doc.FindReferencesByDirection(
                //    centerOfTopOfBox, viewDirection, view3D ); // 2011

                IList <ReferenceWithContext> references
                    = doc.FindReferencesWithContextByDirection(
                          centerOfTopOfBox, viewDirection, view); // 2012

                double closest = double.PositiveInfinity;

                //foreach( Reference r in references )
                //{
                //  // 'Autodesk.Revit.DB.Reference.Element' is
                //  // obsolete: Property will be removed. Use
                //  // Document.GetElement(Reference) instead.
                //  //Element re = r.Element; // 2011

                //  Element re = doc.GetElement( r ); // 2012

                //  if( re.Id.IntegerValue == e.Id.IntegerValue
                //    && r.ProximityParameter < closest )
                //  {
                //    ret = r;
                //    closest = r.ProximityParameter;
                //  }
                //}

                foreach (ReferenceWithContext r in references)
                {
                    Element re = doc.GetElement(
                        r.GetReference()); // 2012

                    if (re.Id.IntegerValue == e.Id.IntegerValue &&
                        r.Proximity < closest)
                    {
                        ret     = r.GetReference();
                        closest = r.Proximity;
                    }
                }

                string stable_reference = null == ret ? null
          : ret.ConvertToStableRepresentation(doc);
#endif // DEBUG

                ReferenceIntersector ri
                    = new ReferenceIntersector(
                          e.Id, FindReferenceTarget.Element, view);

                ReferenceWithContext r2 = ri.FindNearest(
                    centerOfTopOfBox, viewDirection);

                if (null == r2)
                {
                    Debug.Print("ReferenceIntersector.FindNearest returned null!");
                }
                else
                {
                    ret = r2.GetReference();

                    Debug.Assert(stable_reference.Equals(ret
                                                         .ConvertToStableRepresentation(doc)),
                                 "expected same reference from "
                                 + "FindReferencesWithContextByDirection and "
                                 + "ReferenceIntersector");
                }
                t.RollBack();
            }
#endif // _2012
            #endregion // Revit 2012

            Options opt = doc.Application.Create
                          .NewGeometryOptions();

            opt.ComputeReferences = true;

            GeometryElement geo = e.get_Geometry(opt);

            foreach (GeometryObject obj in geo)
            {
                GeometryInstance inst = obj as GeometryInstance;

                if (null != inst)
                {
                    geo = inst.GetSymbolGeometry();
                    break;
                }
            }

            Solid solid = geo.OfType <Solid>()
                          .First <Solid>(sol => null != sol);

            double z = double.MinValue;

            foreach (Face f in solid.Faces)
            {
                BoundingBoxUV b        = f.GetBoundingBox();
                UV            p        = b.Min;
                UV            q        = b.Max;
                UV            midparam = p + 0.5 * (q - p);
                XYZ           midpoint = f.Evaluate(midparam);
                XYZ           normal   = f.ComputeNormal(midparam);

                if (Util.PointsUpwards(normal))
                {
                    if (midpoint.Z > z)
                    {
                        z   = midpoint.Z;
                        ret = f.Reference;
                    }
                }
            }
            return(ret);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Idling event handler.
        /// </summary>
        /// <remarks>
        /// We keep the handler very simple. First check
        /// if we still have the form. If not, unsubscribe
        /// from Idling, for we no longer need it and it
        /// makes Revit speedier. If the form is around,
        /// check if it has a request ready and process
        /// it accordingly.
        /// </remarks>
        public void IdlingHandler(
            object sender,
            IdlingEventArgs args)
        {
            UIApplication uiapp = sender as UIApplication;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            // UI document is null if the project is closed.

            if (null == uidoc || _form.IsDisposed)
            {
                uiapp.Idling -= IdlingHandler;
            }
            else // form still exists
            {
                Document doc  = uidoc.Document;
                View     view = doc.ActiveView;

                UIView uiview = GetActiveUiView(uidoc);

                Rectangle rect = uiview.GetWindowRectangle();

                Point p = System.Windows.Forms.Cursor.Position;

                double dx = (double)(p.X - rect.Left)
                            / (rect.Right - rect.Left);

                double dy = (double)(p.Y - rect.Bottom)
                            / (rect.Top - rect.Bottom);

                IList <XYZ> corners = uiview.GetZoomCorners();
                XYZ         a       = corners[0];
                XYZ         b       = corners[1];
                XYZ         v       = b - a;

                XYZ q = a
                        + dx * v.X * XYZ.BasisX
                        + dy * v.Y * XYZ.BasisY;

                // If the current view happens to be a 3D view,
                // we could simply use it right away. In
                // general we have to find a different one to
                // run the ReferenceIntersector in.

                View3D view3d = GetView3d(doc);

                XYZ viewdir = view.ViewDirection;

                XYZ origin = q + 1000 * viewdir;

                // Find all elements:

                //ReferenceIntersector ri
                //  = new ReferenceIntersector( view3d );

                // Find all elements except roofs:

                ElementFilter f = new ElementCategoryFilter(
                    BuiltInCategory.OST_Roofs, true);

                ReferenceIntersector ri
                    = new ReferenceIntersector(f,
                                               FindReferenceTarget.Element, view3d);

                ReferenceWithContext rc
                    = ri.FindNearest(origin, -viewdir);

                string s = "Element not found";

                if (null != rc)
                {
                    Reference r = rc.GetReference();

                    Element e = doc.GetElement(r);

                    s = ElementDescription(e);
                }

                // Move tooltip to current cursor
                // location and set tooltip text.

                _form.Location = p + new Size(_form.Offset);
                _form.SetText(s);
            }
        }