Beispiel #1
0
        private Room getOtherRoom(Room r1, BoundarySegment seg, XYZ point)
        {
            // we already know what one of the rooms is attached to a boundary segment.
            // this attempts to find the other.
            Curve crv = seg.GetCurve();

            XYZ vector = crv.GetEndPoint(1).Subtract(crv.GetEndPoint(0)).Normalize();

            XYZ otherVector = XYZ.BasisZ;

            if (vector.IsAlmostEqualTo(XYZ.BasisZ))
            {
                otherVector = XYZ.BasisY;
            }
            XYZ perp = vector.CrossProduct(otherVector).Normalize();

            XYZ       testp1    = point.Add(perp.Multiply(0.25));
            XYZ       testp2    = point.Add(perp.Negate().Multiply(0.25));
            Parameter phaseParm = r1.get_Parameter(BuiltInParameter.ROOM_PHASE);
            Phase     p         = _doc.GetElement(phaseParm.AsElementId()) as Phase;

            Room roomP1 = _doc.GetRoomAtPoint(testp1, p);
            Room roomP2 = _doc.GetRoomAtPoint(testp2, p);

            if ((roomP1 != null) && (roomP1.Id != r1.Id))
            {
                return(roomP1);
            }
            if ((roomP2 != null) && (roomP2.Id != r1.Id))
            {
                return(roomP2);
            }

            return(null);
        }
Beispiel #2
0
        /// <summary>
        /// 把两个相交L、V型线段,如果不是,则基于交点进行裁剪 只留下L、V型,进行倒角处理
        /// </summary>
        /// <param name="_line1"></param>
        /// <param name="_line2"></param>
        /// <param name="radius"></param>
        /// <param name="_newline1"></param>
        /// <param name="_newline2"></param>
        /// <returns></returns>
        public static Arc Chamfer(Line _line1, Line _line2, double radius, out Line _newline1, out Line _newline2)
        {
            List <Line> lines             = CutOffTwoLineByIntersectionPoint(_line1, _line2); //把两个相交线段,基于交点进行裁剪 只留下L、V型,进行倒角处理 该处处理,可以保证线的起点与终点的先后位置
            XYZ         intersectionPoint = GetIntersetionPointFromTwoLines(_line1, _line2);  //求出L or V交点
            XYZ         direction_line1   = lines[0].Direction;                               //求方向,再求角度
            XYZ         direction_line2   = lines[1].Direction;
            double      angle             = direction_line1.AngleTo(direction_line2);

            if (angle > Math.PI)
            {
                angle = Math.PI * 2 - angle;
            }
            //求圆弧的三角函数问题,需要深究——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
            XYZ point_arc_start = intersectionPoint.Add(direction_line1.Multiply(radius / (Math.Tan(angle / 2))));//使用正切三角函数,求出,圆弧与倒角直线相切点的位置
            XYZ point_arc_end   = intersectionPoint.Add(direction_line2.Multiply(radius / (Math.Tan(angle / 2))));

            XYZ direction_line3 = direction_line1.Add(direction_line2).Normalize();

            XYZ point_arc_middle = intersectionPoint.Add(direction_line3.Multiply((radius / Math.Sin(angle / 2)) - radius));// 使用正弦三角函数,求出,圆弧与倒角直线相切点的位置

            Arc arc = Arc.Create(point_arc_start, point_arc_end, point_arc_middle);

            _newline1 = Line.CreateBound(point_arc_start, lines[0].GetEndPoint(1));
            _newline2 = Line.CreateBound(point_arc_end, lines[1].GetEndPoint(1));
            return(arc);
        }
Beispiel #3
0
        public List <SpotDimension> CreatSpotDimensionOnFloorInLink(List <ElementId> floorids, View activeview, Document doc, RevitLinkInstance rli, ref string report)
        {
            List <SpotDimension> sds = new List <SpotDimension>();
            var a      = rli.GetTotalTransform();
            int errnum = 0;

            foreach (ElementId id in floorids)
            {
                Floor floor = rli.GetLinkDocument().GetElement(id) as Floor;

                Options option = new Options();
                option.ComputeReferences = true;
                option.View = activeview;
                option.IncludeNonVisibleObjects = false;
                GeometryElement geometry = floor.get_Geometry(option);
                if (geometry == null)
                {
                    continue;
                }
                foreach (GeometryObject geomobj in geometry)
                {
                    Solid gemosolid = geomobj as Solid;
                    if (gemosolid != null)
                    {
                        XYZ center = rli.GetTotalTransform().OfPoint(gemosolid.ComputeCentroid());
                        foreach (Face geomface in gemosolid.Faces)
                        {
                            PlanarFace plane = geomface as PlanarFace;
                            if (plane != null)
                            {
                                if (plane.FaceNormal.X == 0 && plane.FaceNormal.Y == 0 && plane.FaceNormal.Z == 1)
                                {
                                    //get reference for creation
                                    Reference refe = geomface.Reference.CreateLinkReference(rli);
                                    //get points for creation
                                    XYZ origin = center;
                                    XYZ bend   = origin.Add(new XYZ(0, 1, 0));
                                    XYZ end    = origin.Add(new XYZ(1, 1, 0));
                                    XYZ refpt  = origin;
                                    try
                                    {
                                        SpotDimension sd = doc.Create.NewSpotElevation(activeview, refe, origin, bend, end, refpt, false);
                                        sds.Add(sd);
                                    }
                                    catch (Autodesk.Revit.Exceptions.InvalidOperationException e)
                                    {
                                        errnum++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            report += "\n" + "在" + rli.Name + "有" + errnum.ToString() + "个楼板没有生成高程点.";
            return(sds);
        }
Beispiel #4
0
        //Функция расстановки семейства относительно Точки доступа

        public void CreateEquip(
            double xOffset,
            double yOffset,
            double zOffset,
            bool inRoom,
            string familyName,
            double ugoY = 0.0)
        {
            double angle;
            XYZ    eqLocation = null;
            Line   rotAxis    = null;

            var fs = Util.GetFamilySymbolByFamilyName(doc, familyName);

            if (!fs.IsActive)
            {
                fs.Activate();
            }

            if (inRoom)
            {
                if (fFlipped)
                {
                    angle = tdFO.Negate().AngleTo(new XYZ(0, 1, 0)) + Math.PI;
                }
                else
                {
                    angle = tdFO.AngleTo(new XYZ(0, 1, 0));
                }

                eqLocation = tdLocation.Add(tdFO.Negate().Multiply(tdD / 2 + yOffset / 304.8)).Add(tdHO.Negate().Multiply(tdW / 2 + xOffset / 304.8));
            }
            else
            {
                if (fFlipped)
                {
                    angle = tdFO.Negate().AngleTo(new XYZ(0, 1, 0));
                }
                else
                {
                    angle = tdFO.AngleTo(new XYZ(0, 1, 0)) + Math.PI;
                }

                eqLocation = tdLocation.Add(tdFO.Multiply(tdD / 2 + yOffset / 304.8)).Add(tdHO.Negate().Multiply(tdW / 2 + xOffset / 304.8));
            }


            rotAxis = Line.CreateBound(eqLocation, new XYZ(eqLocation.X, eqLocation.Y, eqLocation.Z + 1.0));
            var eq = doc.Create.NewFamilyInstance(eqLocation, fs, level, StructuralType.NonStructural);

            ElementTransformUtils.RotateElement(doc, eq.Id, rotAxis, angle);
            eq.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(zOffset / 304.8 + tdZShift);
            eq.LookupParameter("Смещение УГО по Y")?.Set(ugoY / 304.8);
        }
Beispiel #5
0
        public static IList <Solid> CreateSolid(Document doc, FamilyInstance familyInstance, Transform transform)
        {
            IList <Solid> solids = new List <Solid>();

            try
            {
                Curve    curve      = GetCurvemaxfamily(familyInstance);
                Element  ele        = doc.GetElement(familyInstance.Id);
                string[] parameters = new string[]
                {
                    "DIM_WWF_YY",
                    "DIM_LENGTH"
                };
                Parameter   pa          = LookupElementParameter(ele, parameters);
                double      lengthcurve = pa.AsDouble();
                XYZ         starpointfa = new XYZ(lengthcurve / 2, 0, 0);
                XYZ         endpointfa  = new XYZ(-lengthcurve / 2, 0, 0);
                XYZ         startpoint  = transform.OfPoint(starpointfa);
                XYZ         endpoint    = transform.OfPoint(endpointfa);
                XYZ         norm        = new XYZ((startpoint.X - endpoint.X), (startpoint.Y - endpoint.Y), (startpoint.Z - endpoint.Z));
                Plane       plane       = Plane.CreateByNormalAndOrigin(norm, startpoint);
                Transaction newtran     = new Transaction(doc, "ss");
                newtran.Start();
                SketchPlane stk       = SketchPlane.Create(doc, plane);
                XYZ         pt1       = startpoint.Add(0.01 * plane.XVec).Add(0.01 * plane.YVec);
                XYZ         pt2       = startpoint.Add(0.01 * plane.YVec);
                XYZ         pt3       = startpoint.Add(-0.01 * plane.YVec);
                XYZ         pt4       = startpoint.Add(0.01 * plane.XVec).Add(-0.01 * plane.YVec);
                XYZ         pt5       = (-1) * norm;
                Line        lineleft  = Line.CreateBound(pt1, pt2);
                Line        linetop   = Line.CreateBound(pt2, pt3);
                Line        lineright = Line.CreateBound(pt3, pt4);
                Line        linebot   = Line.CreateBound(pt4, pt1);
                CurveLoop   profile   = new CurveLoop();
                profile.Append(lineleft);
                profile.Append(linetop);
                profile.Append(lineright);
                profile.Append(linebot);
                IList <CurveLoop> listloop1 = new List <CurveLoop>();
                listloop1.Add(profile);
                Solid solid = GeometryCreationUtilities.CreateExtrusionGeometry(listloop1, pt5, lengthcurve);
                newtran.Commit();
                solids.Add(solid);
            }
            catch
            {
                solids = null;
            }
            return(solids);
        }
Beispiel #6
0
        public Result setup_stairs()
        {
            // https://help.autodesk.com/cloudhelp/2018/ENU/Revit-API/Revit_API_Developers_Guide/Revit_Geometric_Elements/Stairs_and_Railings/Creating_and_Editing_Stairs.html

            XYZ       stairsline  = new XYZ(146 / 12.0, 165 / 12.0, level.Elevation);
            ElementId newStairsId = null;

            using (StairsEditScope newStairsScope = new StairsEditScope(doc, "New Stairs"))
            {
                newStairsId = newStairsScope.Start(level.Id, level_above.Id);
                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create window");
                    Line locationLine = Line.CreateBound(
                        stairsline, stairsline.Add(new XYZ(15, 0, 0)));


                    StairsRun newRun2 = StairsRun.CreateStraightRun(doc, newStairsId, locationLine, StairsRunJustification.Center);
                    // newRun2.ActualRunWidth = 10;
                    t.Commit();
                }
                newStairsScope.Commit(new MyRevit.StairsFailurePreprocessor());
            }
            return(Result.Succeeded);
        }
Beispiel #7
0
        List <XYZ> GetDimensionPointsObsoleteFirstAttempt(
            Dimension dim)
        {
            Line dimLine = dim.Curve as Line;

            if (dimLine == null)
            {
                return(null);
            }
            List <XYZ> pts = new List <XYZ>();

            dimLine.MakeBound(0, 1);
            XYZ pt1       = dimLine.GetEndPoint(0);
            XYZ pt2       = dimLine.GetEndPoint(1);
            XYZ direction = pt2.Subtract(pt1).Normalize();

            pts.Add(pt1);
            if (dim.Segments.Size == 0)
            {
                pt2 = pt1.Add(direction.Multiply((double)dim.Value));
                pts.Add(pt2);
            }
            else
            {
                XYZ segmentPt0 = pt1;
                foreach (DimensionSegment seg in dim.Segments)
                {
                    XYZ segmentPt1 = segmentPt0.Add(direction.Multiply((double)seg.Value));
                    Debug.Print("pt  {0},  value  {1}", segmentPt1, (double)seg.Value);
                    pts.Add(segmentPt1);
                    segmentPt0 = segmentPt1;
                }
            }
            return(pts);
        }
Beispiel #8
0
        /// <summary>
        /// Set the correct PipingSystemType for the placed support family.
        /// </summary>
        /// <param name="commandData">The usual ExternalCommandData.</param>
        /// <param name="pipe">The pipe on which the support was placed.</param>
        /// <param name="support">The support that was placed.</param>
        private static (Pipe dummyPipe, Connector supportConnector) SetSystemType(ExternalCommandData commandData, Pipe pipe, Element support)
        {
            var app   = commandData.Application;
            var uiDoc = app.ActiveUIDocument;
            var doc   = uiDoc.Document;

            //Get the pipe type from pipe
            ElementId pipeTypeId = pipe.PipeType.Id;

            //Get system type from pipe
            ConnectorSet pipeConnectors = pipe.ConnectorManager.Connectors;
            Connector    pipeConnector  = (from Connector c in pipeConnectors where (int)c.ConnectorType == 1 select c).FirstOrDefault();
            ElementId    pipeSystemType = pipeConnector.MEPSystem.GetTypeId();

            //Get the connector from the support
            Connector connectorToConnect = (from Connector c in ((FamilyInstance)support).MEPModel.ConnectorManager.Connectors select c).FirstOrDefault();

            //Create a point in space to connect the pipe
            XYZ direction    = connectorToConnect.CoordinateSystem.BasisZ.Multiply(2);
            XYZ origin       = connectorToConnect.Origin;
            XYZ pointInSpace = origin.Add(direction);

            //Create the pipe
            Pipe dummyPipe = Pipe.Create(doc, pipeTypeId, pipe.ReferenceLevel.Id, connectorToConnect, pointInSpace);

            //Change the pipe system type to match the picked pipe (it is not always matching)
            dummyPipe.SetSystemType(pipeSystemType);

            return(dummyPipe, connectorToConnect);
        }
Beispiel #9
0
        public static Pipe CreateDummyPipe(XYZ pointToConnect, XYZ directionPoint, PointInSpace endInstance, ElementSymbol elementSymbol)
        {
            Pipe pipe = null;

            ElementId pipeTypeId = elementSymbol.PipeType.Id;

            //Collect levels and select one level
            FilteredElementCollector levelCollector = new FilteredElementCollector(PCFImport.doc);
            ElementClassFilter       levelFilter    = new ElementClassFilter(typeof(Level));
            ElementId levelId = levelCollector.WherePasses(levelFilter).FirstElementId();

            //Create vector to define pipe
            XYZ pipeDir      = pointToConnect - directionPoint;
            XYZ helperPoint1 = pointToConnect.Add(pipeDir.Multiply(2));

            //Create pipe
            pipe = Pipe.Create(PCFImport.doc, elementSymbol.PipingSystemType.Id, pipeTypeId, levelId,
                               pointToConnect, helperPoint1);
            //Set pipe diameter
            Parameter parameter = pipe.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM);

            parameter.Set(endInstance.Diameter);

            return(pipe);
        }
        /// <summary>
        /// Verify if a given point is inside the bounding poylgon
        /// </summary>
        /// <remarks>
        /// https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/#targetText=1)%20Draw%20a%20horizontal%20line,true%2C%20then%20point%20lies%20outside.
        /// </remarks>
        /// <param name="boundingPolygon">Bounding Polygon Curves</param>
        /// <param name="point"></param>
        /// <returns></returns>
        public bool IsInsideBounds(CurveLoop boundingPolygon, XYZ point)
        {
            var intersections = 0;
            var lineDir = XYZ.BasisX;

            var start = point;
            var end = point.Add(lineDir.Multiply(100000));
            Line line = Line.CreateBound(start, end);

            foreach (var curve in boundingPolygon)
            {
                // Check if the curve is on the edge of the line
                if (curve.Distance(point) < 0.00001) return true;

                curve.Intersect(line, out IntersectionResultArray intersectionArr);
                if (intersectionArr != null)
                {
                    intersections += intersectionArr.Size;
                }
            }

            // Checks if the number of intersections is odd
            if (intersections % 2 != 0) return true;

            return false;
        }
Beispiel #11
0
        private double CenterToBorder(XYZ targetDirection, FamilyInstance targetFamilyInstance)
        {
            ReferenceIntersector rayCaster = new ReferenceIntersector(targetFamilyInstance.Id, FindReferenceTarget.Face, doc.ActiveView as View3D);
            BoundingBoxXYZ       familyBB  = targetFamilyInstance.get_BoundingBox(null);

            Location familyLocation = targetFamilyInstance.Location;
            XYZ      objectCenter   = Utils.GetPoint.getMidPoint(familyBB.Min, familyBB.Max);

            if (familyLocation is LocationPoint)
            {
                LocationPoint familyPoint = targetFamilyInstance.Location as LocationPoint;
                objectCenter = new XYZ(familyPoint.Point.X, familyPoint.Point.Y, objectCenter.Z);
            }
            else
            {
                LocationCurve familyCurve = targetFamilyInstance.Location as LocationCurve;
                XYZ           midPoint    = Utils.GetPoint.getMidPoint(familyCurve.Curve.GetEndPoint(1), familyCurve.Curve.GetEndPoint(0));
                Line          line        = (familyCurve.Curve as Line);
                if (line == null)
                {
                    return(0);
                }
                XYZ    direct          = line.Direction;
                XYZ    cross           = XYZ.BasisZ.CrossProduct(direct);
                double offset          = targetFamilyInstance.get_Parameter(BuiltInParameter.Y_OFFSET_VALUE).AsDouble();
                XYZ    offsetFromMidle = cross.Multiply(offset);
                objectCenter = midPoint.Add(offsetFromMidle);
            }


            IList <ReferenceWithContext> hitFaces = rayCaster.Find(objectCenter, targetDirection);
            ReferenceWithContext         refFace  = null;

            if (hitFaces != null)
            {
                if (hitFaces.Count > 0)
                {
                    refFace = hitFaces.LastOrDefault();
                }
            }

            if (refFace != null)
            {
                //FamilySymbol pSafe = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel)
                //    .WhereElementIsElementType().Where(t => t.Name == "DebugPointSafe").FirstOrDefault() as FamilySymbol;

                //using (Transaction ta = new Transaction(doc, "hey"))
                //{
                //    ta.Start();
                //    doc.Create.NewFamilyInstance(refFace.GetReference().GlobalPoint, pSafe, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                //    doc.Create.NewFamilyInstance(objectCenter, pSafe, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                //    ta.Commit();
                //}
                return(refFace.GetReference().GlobalPoint.DistanceTo(objectCenter));
            }

            return(0);
        }
Beispiel #12
0
        private XYZ ComputeLeaderPosition(XYZ dir, XYZ origin)
        {
            XYZ leaderPos = new XYZ();

            leaderPos = dir * m_delta;
            leaderPos = leaderPos.Add(origin);
            return(leaderPos);
        }
Beispiel #13
0
        public static List <XYZ> GetDimensionPointsEnd(Document doc, Dimension dim)
        {
            XYZ p = null;

            try
            {
                p = dim.Origin;
            }
            catch (Autodesk.Revit.Exceptions.ApplicationException ex)
            {
                Debug.Assert(ex.Message.Equals("Cannot access this method if this dimension has more than one segment."));

                foreach (DimensionSegment seg in dim.Segments)
                {
                    p = seg.Origin;
                    break;
                }
            }

            Line dimLine = dim.Curve as Line;

            if (dimLine == null)
            {
                return(null);
            }
            List <XYZ> pts  = new List <XYZ>();
            List <XYZ> last = new List <XYZ>();

            dimLine.MakeBound(0, 1);
            XYZ pt1       = dimLine.GetEndPoint(0);
            XYZ pt2       = dimLine.GetEndPoint(1);
            XYZ direction = pt2.Subtract(pt1).Normalize();

            if (0 == dim.Segments.Size)
            {
                XYZ v = 0.5 * (double)dim.Value * direction;
                pts.Add(p - v);
                pts.Add(p + v);
            }
            else
            {
                foreach (DimensionSegment seg in dim.Segments)
                {
                    XYZ v = (double)seg.Value * direction;
                    if (0 == pts.Count)
                    {
                        pts.Add(p = (p - 0.5 * v));
                    }
                    pts.Add(p = p.Add(v));
                }
                foreach (var item in pts)
                {
                    last.Add(pts[0]);
                    last.Add(pts[dim.Segments.Size]);
                }
            }
            return(last);
        }
Beispiel #14
0
        public void XyzTest()
        {
            XYZ xyz  = new XYZ(1, 2, 3);
            XYZ test = xyz.Add(new XYZ(5, 6, 7));

            Assert.AreEqual(test.X, 6);
            Assert.AreEqual(test.Y, 8);
            Assert.AreEqual(test.Z, 10);
        }
Beispiel #15
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            // Get the handle of current document.
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            using (Transaction _transaction_ = new Transaction(doc))
            {
                // Get the element selection of current document.
                Selection selection = uidoc.Selection;
                ICollection <ElementId> selectedIds = uidoc.Selection.GetElementIds();

                if (0 == selectedIds.Count)
                {
                    // If no elements selected.
                    TaskDialog.Show("Revit", "You haven't selected any elements.");
                }
                else
                {
                    foreach (ElementId id in selectedIds)
                    {
                        Dimension dim = doc.GetElement(id) as Dimension;
                        if (dim != null)
                        {
                            XYZ startPoint = selection.PickPoint(ObjectSnapTypes.None, "Pick start");
                            _transaction_.Start("Set leader end point");
                            try
                            {
                                if (dim.Segments.IsEmpty)
                                {
                                    dim.LeaderEndPosition = startPoint;
                                }
                                else
                                {
                                    XYZ deltaVec = dim.Segments.get_Item(1).Origin.Subtract(dim.Segments.get_Item(0).Origin);
                                    XYZ offset   = new XYZ();
                                    foreach (DimensionSegment ds in dim.Segments)
                                    {
                                        ds.LeaderEndPosition = startPoint.Add(offset);
                                        offset = offset.Add(deltaVec);
                                    }
                                }
                                _transaction_.Commit();
                            }
                            catch (System.Exception ex)
                            {
                                TaskDialog.Show("Can't set dimension leader end point: {0}", ex.Message);
                                _transaction_.RollBack();
                            }
                        }
                    }
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
        }
Beispiel #16
0
        static public Line Extend(this Line line, double extensionDistance)
        {
            XYZ firstPoint  = line.GetEndPoint(0);
            XYZ secondPoint = line.GetEndPoint(1);
            XYZ direction   = line.Direction;

            firstPoint  = firstPoint.Add(-direction.Multiply(extensionDistance));
            secondPoint = secondPoint.Add(direction.Multiply(extensionDistance));

            return(Line.CreateBound(firstPoint, secondPoint));
        }
Beispiel #17
0
        public static Result CreatePipeFromConnector(ExternalCommandData cData)
        {
            try
            {
                Document doc = cData.Application.ActiveUIDocument.Document;

                //One element selected, creates pipe at random connector
                Selection selection = cData.Application.ActiveUIDocument.Selection;
                ElementId id        = selection.GetElementIds().FirstOrDefault();
                if (id == null)
                {
                    throw new Exception("Getting element from selection failed!");
                }
                Element element = doc.GetElement(id);
                if (element is Pipe)
                {
                    throw new Exception("This method does not work on pipes!");
                }
                var       cons = mp.GetALLConnectorsFromElements(element);
                Connector con  = (from Connector c in cons where c.IsConnected == false select c).FirstOrDefault();
                if (con == null)
                {
                    throw new Exception("No not connected connectors in element!");
                }

                //Create a point in space to connect the pipe
                XYZ direction    = con.CoordinateSystem.BasisZ.Multiply(2);
                XYZ origin       = con.Origin;
                XYZ pointInSpace = origin.Add(direction);

                //Get the typeId of most used pipeType
                var filter = fi.ParameterValueFilter("Stålrør, sømløse", BuiltInParameter.ALL_MODEL_TYPE_NAME);
                FilteredElementCollector col = new FilteredElementCollector(doc);
                var pipeType = col.OfClass(typeof(PipeType)).WherePasses(filter).ToElements().FirstOrDefault();
                if (pipeType == null)
                {
                    throw new Exception("Collection of PipeType failed!");
                }

                Transaction tx = new Transaction(doc);
                tx.Start("Create pipe!");
                //Create the pipe
                Pipe.Create(doc, pipeType.Id, element.LevelId, con, pointInSpace);
                tx.Commit();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }



            return(Result.Succeeded);
        }
Beispiel #18
0
        public void Add()
        {
            var p1 = new XYZ(1, 2, 3);

            Assert.AreEqual(new XYZ(2, 4, 6), p1.Added(new XYZ(1, 2, 3)));
            Assert.AreEqual(new XYZ(2, 4, 6), p1 + new XYZ(1, 2, 3));
            p1.Add(new XYZ(1, 2, 3));
            Assert.AreEqual(new XYZ(2, 4, 6), p1);
            p1 += new XYZ(1, 2, 3);
            Assert.AreEqual(new XYZ(3, 6, 9), p1);
        }
Beispiel #19
0
        public static View View3D(this Document document, XYZ eye, XYZ target, double horizontalFieldOfView, double viewRatio = 0.5625, string viewName = null, ElementId viewTemplateId = null, ViewDetailLevel viewDetailLevel = ViewDetailLevel.Coarse)
        {
            XYZ normal       = (target - eye).Normalize();
            XYZ planarEye    = new XYZ(eye.X, eye.Y, 0);
            XYZ planarTarget = new XYZ(target.X, target.Y, 0);
            XYZ planarNormal = (planarTarget - planarEye).Normalize();

            //get vertical and horizontal angle
            double verticalAngle   = (XYZ.BasisZ.AngleTo(normal) - Math.PI / 2) * (-1);
            double horizontalAngle = XYZ.BasisX.AngleOnPlaneTo(planarNormal, XYZ.BasisZ);

            //create view orientation
            ViewOrientation3D viewOrientation3D = new ViewOrientation3D(eye, CombineHorizontalWithVerticalAngles(horizontalAngle, verticalAngle + Math.PI / 2), CombineHorizontalWithVerticalAngles(horizontalAngle, verticalAngle));

            //information can be found here
            //https://knowledge.autodesk.com/support/revit-products/learn-explore/caas/CloudHelp/cloudhelp/2014/ENU/Revit/files/GUID-A7FA8DBC-830E-482D-9B66-147399524442-htm.html

            //rotate center point to the right side, representing HFOV start point
            double    angleToRotate = Math.PI / 2;
            Transform t1            = Transform.CreateRotationAtPoint(XYZ.BasisZ, angleToRotate * -1, target);
            XYZ       rotate        = target.Add((horizontalFieldOfView / 2) * (planarNormal * -1));
            XYZ       hfovLeft      = t1.OfPoint(rotate);
            XYZ       bottomLeft    = hfovLeft.Add(((viewRatio * horizontalFieldOfView) / 2) * (viewOrientation3D.UpDirection * -1));

            //for the right
            Transform t2        = Transform.CreateRotationAtPoint(XYZ.BasisZ, angleToRotate, target);
            XYZ       hfovRight = t2.OfPoint(rotate);
            XYZ       topRight  = hfovRight.Add(((viewRatio * horizontalFieldOfView) / 2) * viewOrientation3D.UpDirection);

            //lines for top and bottom
            Line topLine    = Line.CreateBound(topRight, eye);
            Line bottomLine = Line.CreateBound(bottomLeft, eye);

            // to calculate bb max/min offset we need to perform an inverse regression estimate using y=A+B/x
            double a = 0.9995538525; //constant for THIS inverse regression
            double b = -0.08573511;  //constant for THIS inverse regression
            //get line-based element's length
            double cameraLength  = planarEye.DistanceTo(planarTarget);
            double evaluateLines = a + (b / cameraLength);

            //creates plane to project point at and retrieve cropbox.min
            BH.oM.Geometry.Plane backClippingPlane = BH.Engine.Geometry.Create.Plane(BH.Revit.Engine.Core.Convert.PointFromRevit(target), BH.Revit.Engine.Core.Convert.VectorFromRevit(viewOrientation3D.ForwardDirection));
            BH.oM.Geometry.Point pointToProject    = BH.Revit.Engine.Core.Convert.PointFromRevit(bottomLine.Evaluate(evaluateLines, true));
            BH.oM.Geometry.Point bbBhomMin         = backClippingPlane.ClosestPoint(pointToProject);
            XYZ bbMin = BH.Revit.Engine.Core.Convert.ToRevit(bbBhomMin);
            XYZ bbMax = topLine.Evaluate(evaluateLines, true);

            BoundingBoxXYZ boundingBox3DCone = new BoundingBoxXYZ();

            boundingBox3DCone.Max = bbMax;
            boundingBox3DCone.Min = bbMin;

            return(View3D(document, viewName, boundingBox3DCone, viewOrientation3D, viewTemplateId, viewDetailLevel));
        }
Beispiel #20
0
        internal static XYZ OletP1Point(Cons cons)
        {
            XYZ endPointOriginOletPrimary   = cons.Primary.Origin;
            XYZ endPointOriginOletSecondary = cons.Secondary.Origin;

            //get reference elements
            var refCons = MepUtils.GetAllConnectorsFromConnectorSet(cons.Primary.AllRefs);

            Connector refCon = refCons.Where(x => x.Owner.IsType <Pipe>()).FirstOrDefault();

            if (refCon == null)
            {
                throw new Exception("refCon Owner cannot find a Pipe for element!");
            }
            Pipe refPipe = (Pipe)refCon.Owner;

            Cons refPipeCons = Shared.MepUtils.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);
            }
            else
            {
                A = E;
            }
            return(A);
        }
Beispiel #21
0
        /// <summary>
        /// 按XY的点的Z轴旋转
        /// </summary>
        /// <param name="point"></param>
        /// <param name="xyz"></param>
        /// <param name="verticalVector"></param>
        public static void RotateByXY(this Location point, XYZ xyz, XYZ verticalVector)
        {
            Line axis = Line.CreateBound(xyz, xyz.Add(new XYZ(0, 0, 10)));

            if (verticalVector.X > VLConstraintsForCSA.MiniValueForXYZ)
            {
                point.Rotate(axis, 2 * Math.PI - verticalVector.AngleTo(new XYZ(0, 1, verticalVector.Z)));
            }
            else
            {
                point.Rotate(axis, verticalVector.AngleTo(new XYZ(0, 1, verticalVector.Z)));
            }
        }
Beispiel #22
0
        public Arc Chamfer(Line line1, Line line2, double radius, out Line newline1, out Line newline2)
        {
            List <Line> lines = TwoLineOneOrigin(line1, line2);

            //get intersection
            XYZ intersection = GetIntersection(line1, line2);

            if (intersection == null)
            {
                newline1 = null;
                newline2 = null;
                return(null);
            }

            XYZ    direction_line1 = lines[0].Direction;
            XYZ    direction_line2 = lines[1].Direction;
            double angle           = direction_line1.AngleTo(direction_line2);

            if (angle > Math.PI)
            {
                angle = Math.PI * 2 - angle;
            }

            XYZ point_arc_start = intersection.Add(direction_line1.Multiply(radius / (Math.Tan(angle / 2))));
            XYZ point_arc_end   = intersection.Add(direction_line2.Multiply(radius / (Math.Tan(angle / 2))));

            XYZ direction_line3 = direction_line1.Add(direction_line2).Normalize();

            XYZ point_arc_middle = intersection.Add(direction_line3.Multiply((radius / Math.Sin(angle / 2)) - radius));

            Arc arc = Arc.Create(point_arc_start, point_arc_end, point_arc_middle);

            newline1 = Line.CreateBound(point_arc_start, lines[0].GetEndPoint(1));
            newline2 = Line.CreateBound(point_arc_end, lines[1].GetEndPoint(1));

            return(arc);
        }
        /// <summary>
        /// Create parallel grids (horizontal or vertical)
        /// </summary>
        /// <param name="basePoint">Top left base point</param>
        /// <param name="spaces">space distances between grids</param>
        /// <param name="startName">Name of the first grid</param>
        /// <param name="isHorizontal">whether this is horizontal or not</param>
        private void createGrids(XYZ basePoint, List <double> spaces, string startName, bool isHorizontal)
        {
            Document doc = _revitApp.ActiveUIDocument.Document;
            double   gridLength = 30, extLength = 3; // Unit: feet

            using (Transaction t = new Transaction(doc, "Create Grids"))
            {
                t.Start();
                XYZ offsetDir  = isHorizontal ? XYZ.BasisY.Multiply(-1) : XYZ.BasisX;
                XYZ startPoint = isHorizontal ? basePoint.Add(XYZ.BasisX.Multiply(-extLength)) : basePoint.Add(XYZ.BasisY.Multiply(extLength));
                XYZ endPoint   = isHorizontal ? startPoint.Add(XYZ.BasisX.Multiply(gridLength)) : startPoint.Add(XYZ.BasisY.Multiply(-gridLength));
                Autodesk.Revit.DB.Line geoLine = Autodesk.Revit.DB.Line.CreateBound(startPoint, endPoint);
                Autodesk.Revit.DB.Grid grid    = Autodesk.Revit.DB.Grid.Create(doc, geoLine);
                grid.Name = startName;
                foreach (double space in spaces)
                {
                    startPoint = startPoint.Add(offsetDir.Multiply(space));
                    endPoint   = endPoint.Add(offsetDir.Multiply(space));
                    geoLine    = Autodesk.Revit.DB.Line.CreateBound(startPoint, endPoint);
                    Autodesk.Revit.DB.Grid.Create(doc, geoLine);
                }
                t.Commit();
            }
        }
Beispiel #24
0
        //求Arc的切线的交点.
        public XYZ GetIntersectionByArcTangent(Arc arc)
        {
            XYZ    center           = arc.Center;
            XYZ    start            = arc.GetEndPoint(0);
            XYZ    end              = arc.GetEndPoint(1);
            Line   line_start       = Line.CreateBound(center, start);
            Line   line_end         = Line.CreateBound(center, end);
            XYZ    direction_start  = line_start.Direction;
            XYZ    direction_end    = line_end.Direction;
            XYZ    direction_center = direction_start.Add(direction_end).Normalize();
            double angle            = direction_start.AngleTo(direction_center);
            double radius           = arc.Radius;
            double length           = radius / (Math.Cos(angle));
            XYZ    result           = center.Add(direction_center.Multiply(length));

            return(result);
        }
Beispiel #25
0
        public void ImageTag(Document doc, SheetInfo info, ViewPortInfo vport)
        {
            // Create a new QRCoder Tag
            QRCoder.QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();

            // Generate a new QR Tag
            QRCoder.QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(data, QRCoder.QRCodeGenerator.ECCLevel.M);

            // Assemble a temp file name
            string tempfile = System.IO.Path.GetTempFileName() + ".QRTAG";

            // Get the Tags graphics element
            System.Drawing.Bitmap bmp = qrCode.GetGraphic(5);

            // Save it temporarily
            bmp.Save(tempfile);

            // Get the related view sheet
            View sheet = (View)doc.GetElement(info.sheetId);

            // Create a image element to return from import
            Element imageElement = null;

            // Get the Viewports label outline
            Outline labelOutline = vport.vport.GetLabelOutline();

            // Get the lower left corner
            XYZ labelCorner = new XYZ(info.sheet.Origin.X + (labelOutline.MinimumPoint.X), info.sheet.Origin.Y + labelOutline.MinimumPoint.Y, 0);

            // Add some distance value
            XYZ location = labelCorner.Add(new XYZ(0, -0.5 / 12.0, 0));

            // Import the image
            doc.Import(tempfile, new ImageImportOptions()
            {
                RefPoint = location, Placement = BoxPlacement.TopLeft
            }, sheet, out imageElement);

            // Delete temp file
            if (System.IO.File.Exists(tempfile))
            {
                System.IO.File.Delete(tempfile);
            }
        }
Beispiel #26
0
        private List <XYZ> GetDimensionPoints(Dimension dim, XYZ pStart)
        {
            Line       line = dim.Curve as Line;
            bool       flag = line == null;
            List <XYZ> result;

            if (flag)
            {
                result = null;
            }
            else
            {
                List <XYZ> list = new List <XYZ>();
                line.MakeBound(0.0, 1.0);
                XYZ  endPoint  = line.GetEndPoint(0);
                XYZ  endPoint2 = line.GetEndPoint(1);
                XYZ  xyz       = endPoint2.Subtract(endPoint).Normalize();
                bool flag2     = dim.Segments.Size == 0;
                if (flag2)
                {
                    XYZ xyz2 = 0.5 * dim.Value.Value * xyz;
                    list.Add(pStart - xyz2);
                    list.Add(pStart + xyz2);
                }
                else
                {
                    XYZ xyz3 = pStart;
                    foreach (object obj in dim.Segments)
                    {
                        DimensionSegment dimensionSegment = (DimensionSegment)obj;
                        XYZ  xyz4  = dimensionSegment.Value.Value * xyz;
                        bool flag3 = list.Count == 0;
                        if (flag3)
                        {
                            list.Add(xyz3 = pStart - 0.5 * xyz4);
                        }
                        list.Add(xyz3 = xyz3.Add(xyz4));
                    }
                }
                result = list;
            }
            return(result);
        }
        private void RotateElementCustom(double degrees, Element myEle)
        {
            UIDocument UiDoc = this.ActiveUIDocument;
            Document   doc   = UiDoc.Document;

            LocationCurve locCurve = myEle.Location as LocationCurve;

            if (null == locCurve)
            {
                XYZ point  = ((LocationPoint)myEle.Location).Point;
                XYZ point2 = point.Add(XYZ.BasisZ);

                Line axis = Line.CreateBound(point, point2);
                //Line lineAsAxis = Line.CreateBound(new XYZ(0, 0, 0), new XYZ(0, 0, 1));

                using (Transaction myTrans = new Transaction(doc, "RotateElement Location Point")){
                    myTrans.Start();
                    // Code here
                    ElementTransformUtils.RotateElement(doc, myEle.Id, axis, DegreesToRadians(degrees));
                    myTrans.Commit();
                }
            }

            else
            {
                using (Transaction myTrans = new Transaction(doc, "RotateElement Location Curve")){
                    myTrans.Start();
                    // Code here
                    Curve line = locCurve.Curve;
                    XYZ   sP   = line.GetEndPoint(0);
                    XYZ   eP   = line.GetEndPoint(1);
                    XYZ   mP   = new XYZ((sP.X + eP.X) / 2, (sP.Y + eP.Y) / 2, (sP.Z + eP.Z) / 2);

                    XYZ  mzP  = new XYZ(mP.X, mP.Y, mP.Z + 10);
                    Line axis = Line.CreateBound(mP, mzP);
                    locCurve.Rotate(axis, DegreesToRadians(degrees));

                    myTrans.Commit();
                }
            }
        }
Beispiel #28
0
        public override void Action()
        {
            StringBuilder st = new StringBuilder();
            //Create A Point
            XYZ p1 = new XYZ(1, 1, 1);
            XYZ p2 = new XYZ(1, 1, 10);

            p1.ShowMessageBox();
            //Point Zero
            XYZ zero1 = new XYZ(0, 0, 0);

            zero1.ShowMessageBox();
            XYZ zero2 = XYZ.Zero;

            zero2.ShowMessageBox();
            // Sum
            XYZ add = p1.Add(p2);

            add.ShowMessageBox();
            //Sub
            XYZ sub = p1.Subtract(p2);

            sub.ShowMessageBox();
            // mul
            XYZ multiply = p1.Multiply(5);

            multiply.ShowMessageBox();
            //div
            XYZ divide = p1.Divide(5);

            divide.ShowMessageBox();
            //
            XYZ a = new XYZ(1, 2, 3);

            a.IsZeroLength().ShowMessageBox();
            a.ShowMessageBox();
            //Normal
            XYZ normalize = a.Normalize();

            normalize.ShowMessageBox("normalize");
        }
Beispiel #29
0
        static internal XYZ GetRoofIntersectionFlattenLines(Line RidgeLine, XYZ ridgePointFlatten, Line eaveOrValleyLine, double flattenHeight)
        {
            Line eaveOrValleyInfiniteLine = (eaveOrValleyLine as Line).Flatten(flattenHeight);

            eaveOrValleyInfiniteLine.MakeUnbound();
            XYZ  crossedRidgeDirection    = ridgePointFlatten.Add(RidgeLine.Flatten(flattenHeight).Direction.CrossProduct(XYZ.BasisZ));
            Line crossedRidgeInfitineLine = Line.CreateBound(ridgePointFlatten, crossedRidgeDirection.Multiply(1));

            crossedRidgeInfitineLine = crossedRidgeInfitineLine.Flatten(flattenHeight);
            crossedRidgeInfitineLine.MakeUnbound();

            IntersectionResultArray lineInterserctions = null;

            eaveOrValleyInfiniteLine.Intersect(crossedRidgeInfitineLine, out lineInterserctions);

            if (lineInterserctions == null || lineInterserctions.Size > 1 || lineInterserctions.Size == 0)
            {
                return(null);
            }

            return(lineInterserctions.get_Item(0).XYZPoint);
        }
Beispiel #30
0
        /// <summary>
        /// Retrieve the start and end points of
        /// each dimension segment, based on the
        /// dimension origin determined above.
        /// </summary>
        List <XYZ> GetDimensionPoints(
            Dimension dim,
            XYZ pStart)
        {
            Line dimLine = dim.Curve as Line;

            if (dimLine == null)
            {
                return(null);
            }
            List <XYZ> pts = new List <XYZ>();

            dimLine.MakeBound(0, 1);
            XYZ pt1       = dimLine.GetEndPoint(0);
            XYZ pt2       = dimLine.GetEndPoint(1);
            XYZ direction = pt2.Subtract(pt1).Normalize();

            if (0 == dim.Segments.Size)
            {
                XYZ v = 0.5 * (double)dim.Value * direction;
                pts.Add(pStart - v);
                pts.Add(pStart + v);
            }
            else
            {
                XYZ p = pStart;
                foreach (DimensionSegment seg in dim.Segments)
                {
                    XYZ v = (double)seg.Value * direction;
                    if (0 == pts.Count)
                    {
                        pts.Add(p = (pStart - 0.5 * v));
                    }
                    pts.Add(p = p.Add(v));
                }
            }
            return(pts);
        }
Beispiel #31
0
        public void ImageTag(Document doc, SheetInfo info, ViewPortInfo vport)
        {
            // Create a new QRCoder Tag
            QRCoder.QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();

            // Generate a new QR Tag
            QRCoder.QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(data, QRCoder.QRCodeGenerator.ECCLevel.M);

            // Assemble a temp file name
            string tempfile = System.IO.Path.GetTempFileName() + ".QRTAG";

            // Get the Tags graphics element
            System.Drawing.Bitmap bmp = qrCode.GetGraphic(5);

            // Save it temporarily
            bmp.Save(tempfile);

            // Get the related view sheet
            View sheet = (View)doc.GetElement(info.sheetId);

            // Create a image element to return from import
            Element imageElement = null;

            // Get the Viewports label outline
            Outline labelOutline = vport.vport.GetLabelOutline();

            // Get the lower left corner
            XYZ labelCorner = new XYZ(info.sheet.Origin.X + (labelOutline.MinimumPoint.X), info.sheet.Origin.Y + labelOutline.MinimumPoint.Y, 0);

            // Add some distance value
            XYZ location = labelCorner.Add(new XYZ(0, -0.5/12.0, 0));

            // Import the image
            doc.Import(tempfile, new ImageImportOptions() { RefPoint = location, Placement = BoxPlacement.TopLeft }, sheet, out imageElement);

            // Delete temp file
            if (System.IO.File.Exists(tempfile)) System.IO.File.Delete(tempfile);
        }
Beispiel #32
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            if (!args[0].IsList)
                throw new Exception("A list of XYZs is required to average.");

            FSharpList<Value> lst = ((Value.List)args[0]).Item;

            XYZ average = new XYZ();
            foreach (Value v in lst)
            {
                XYZ pt = (XYZ)((Value.Container)v).Item;
                average = average.Add(pt);
            }

            average = average.Divide(lst.Count<Value>());
            pts.Add(average);

            return Value.NewContainer(average);
        }