Esempio n. 1
0
        public void IsLineLike_Curve_CorrectlyIdentifiesLine()
        {
            var line = Line.ByStartPointEndPoint(
                Point.Origin(),
                Point.ByCoordinates(12, 3, 2));

            var revitCurve = line.ToRevitType(false);

            Assert.True(CurveUtils.IsLineLike(revitCurve));
        }
Esempio n. 2
0
        public static Surface SurfaceFromBoundaryCurves(Group <Curve> boundaryCurves, out List <Curve> unusedCurves)
        {
            List <Curve>  curves       = CurveUtils.Join(boundaryCurves);
            Plane         plane        = null;
            Group <Curve> closedCurves = new Group <Curve>();

            unusedCurves = new List <Curve>();
            foreach (Curve boundary in boundaryCurves)
            {
                if (boundary.IsPlanar() && boundary.IsClosed())
                {
                    Curve xY = boundary.DuplicateCurve();
                    if (plane == null && xY.TryGetPlane(out plane))
                    {
                        closedCurves.Add(xY);
                    }
                    else if (plane != null && plane.InPlane(xY.ControlPointVector, xY.Dimensions + 1, 0.001))
                    {
                        closedCurves.Add(xY);
                    }
                    else
                    {
                        unusedCurves.Add(xY);
                    }
                }
                else
                {
                    unusedCurves.Add(boundary);
                }
            }
            if (plane != null)
            {
                Point  centre = closedCurves.Bounds().Centre;
                Vector axis   = plane.Normal;
                double angle  = VectorUtils.VectorAngle(BH.oM.Geometry.Vector.ZAxis(), axis);

                Transform t1 = Geometry.Transform.Rotation(centre, axis, angle);
                Transform t2 = Geometry.Transform.Translation(BH.oM.Geometry.Point.Origin - centre) * t1;

                closedCurves.Transform(t2);
                Vector extents = closedCurves.Bounds().Extents;

                Point p1 = new Point(extents.X, -extents.Y, 0);
                Point p2 = new Point(extents.X, extents.Y, 0);
                Point p3 = new Point(-extents.X, -extents.Y, 0);
                Point p4 = new Point(-extents.X, extents.Y, 0);

                Surface surface = SurfaceFrom4Points(p1, p2, p3, p4);

                surface.Transform(t2.Inverse());
                surface.TrimmingCurves.AddRange(closedCurves);
                return(surface);
            }
            return(null);
        }
Esempio n. 3
0
        public override void Check(IEnumerable <ObjectId> selectedObjectIds)
        {
            if (!selectedObjectIds.Any())
            {
                return;
            }

            var group = CalculateIntersectionKdTree(selectedObjectIds, true, Editor);

            // Check each intersection whether it's a missing vertex.
            var database = Editor.Document.Database;

            using (var transaction = database.TransactionManager.StartTransaction())
            {
                foreach (var pair in group)
                {
                    var curve = transaction.GetObject(pair.Key, OpenMode.ForRead) as Curve;
                    if (curve == null)
                    {
                        continue;
                    }

                    var vertices         = CurveUtils.GetDistinctVertices(curve, transaction);
                    var noneVertexPoints = new List <Point3d>();
                    foreach (var point in pair.Value)
                    {
                        var ret = CheckPointIsVertex(vertices, point, transaction);
                        if (!ret)
                        {
                            noneVertexPoints.Add(point);
                        }
                    }

                    if (noneVertexPoints.Count > 0)
                    {
                        _missingVertexInfos.Add(new MissingVertexInfo()
                        {
                            PolylineId = pair.Key,
                            Positions  = noneVertexPoints
                        });
                    }
                }
                transaction.Commit();
            }

            //foreach (var info in _missingVertexInfos)
            //{
            //    Editor.WriteMessage("\n{0}:", info.PolylineId.Handle.ToString());
            //    foreach (var point in info.Positions)
            //    {
            //        Editor.WriteMessage(" {0} ", point.ToString());
            //    }
            //    Editor.WriteMessage("\n");
            //}
        }
Esempio n. 4
0
        public static bool TryJoin(Brep b1, Brep b2, out Brep result)
        {
            List <Curve> c1 = CurveUtils.Join(b1.GetExternalEdges());
            List <Curve> c2 = CurveUtils.Join(b2.GetExternalEdges());

            List <Curve> nakedEdges      = new List <Curve>();
            List <Curve> overlappedEdges = new List <Curve>();
            List <Point> pts             = new List <Point>();

            List <Curve> updatedN = new List <Curve>();
            List <Curve> updatedI = new List <Curve>();

            for (int i = 0; i < c1.Count; i++)
            {
                for (int j = 0; j < c2.Count; j++)
                {
                    if (Intersect.CurveCurve(c1[i], c2[j], 0.001, out pts, out overlappedEdges, out nakedEdges))
                    {
                        updatedN.AddRange(nakedEdges);
                        updatedN.AddRange(overlappedEdges);
                    }
                }
            }
            if (updatedN.Count > 0)
            {
                Group <Brep> polySurface = new Group <Brep>();

                if (b1 is PolySurface)
                {
                    polySurface.AddRange((b1 as PolySurface).Surfaces);
                }
                else
                {
                    polySurface.Add(b1);
                }

                if (b2 is PolySurface)
                {
                    polySurface.AddRange((b2 as PolySurface).Surfaces);
                }
                else
                {
                    polySurface.Add(b2);
                }
                result = new PolySurface(polySurface);
                result.GetExternalEdges().AddRange(updatedN);
                result.GetInternalEdges().AddRange(updatedI);
                return(true);
            }
            else
            {
                result = null;
                return(false);
            }
        }
        protected override Status FixImpl(CheckResult checkResult, out List <ObjectId> resultIds)
        {
            resultIds = new List <ObjectId>();
            var crossingCheckResult = checkResult as CrossingCheckResult;

            if (crossingCheckResult == null)
            {
                return(Status.Rejected);
            }

            var crossingInfo = crossingCheckResult.CrossingInfo;
            var distinctIds  = new HashSet <ObjectId>();

            distinctIds.Add(crossingInfo.SourceId);
            distinctIds.Add(crossingInfo.TargetId);

            using (var transaction = Document.Database.TransactionManager.StartTransaction())
            {
                //// distinctIds == 1说明是自交线
                bool isSelfIntersection = (distinctIds.Count == 1);

                var modelSpace = (BlockTableRecord)transaction.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(Document.Database), OpenMode.ForWrite);
                foreach (var sourceId in distinctIds)
                {
                    var sourceCurve = transaction.GetObject(sourceId, OpenMode.ForWrite) as Curve;
                    DBObjectCollection allSplitCurves = null;
                    if (isSelfIntersection)
                    {
                        allSplitCurves = CurveUtils.SplitSelfIntersectCurve(sourceCurve, crossingInfo.IntersectPoints, transaction);
                    }
                    else // Use CurveUtils.SplitCurve take less time.
                    {
                        allSplitCurves = CurveUtils.SplitCurve(sourceCurve, crossingInfo.IntersectPoints);
                    }

                    // The splitted curves has the same layer with original curve,
                    // so we needn't set its layer explicitly.
                    foreach (Curve splitCurve in allSplitCurves)
                    {
                        var curveId = modelSpace.AppendEntity(splitCurve);
                        transaction.AddNewlyCreatedDBObject(splitCurve, true);
                        // Add splited curve to resultIds.
                        resultIds.Add(curveId);
                    }

                    if (allSplitCurves.Count > 0)
                    {
                        // Erase the old one
                        sourceCurve.Erase();
                    }
                }
                transaction.Commit();
            }
            return(Status.Fixed);
        }
        public void CurvesAreSimilar_Ellipse()
        {
            var a = Autodesk.DesignScript.Geometry.Ellipse.ByOriginRadii(Point.ByCoordinates(0, 0, 0), 1.0, 2.0);
            var b = Autodesk.DesignScript.Geometry.Ellipse.ByOriginRadii(Point.ByCoordinates(0, 0, 0), 2.0, 1.0);

            var revitEllipse1 = a.ToRevitType();
            var revitEllipse2 = b.ToRevitType();

            Assert.True(CurveUtils.CurvesAreSimilar(revitEllipse1, revitEllipse1));
            Assert.False(CurveUtils.CurvesAreSimilar(revitEllipse1, revitEllipse2));
        }
        public void IsLineLike_Curve_CorrectlyIdentifiesStraightNurbsCurve()
        {
            var points =
                Enumerable.Range(0, 10)
                .Select(x => Autodesk.DesignScript.Geometry.Point.ByCoordinates(x, 0));

            var nurbsCurve = NurbsCurve.ByPoints(points, 3);
            var revitCurve = nurbsCurve.ToRevitType(false);

            Assert.True(CurveUtils.IsLineLike(revitCurve));
        }
Esempio n. 8
0
        private void InternalSetReferencePoints(ReferencePointArray pts)
        {
            var cbp     = ((Autodesk.Revit.DB.CurveByPoints)InternalCurveElement) as Autodesk.Revit.DB.CurveByPoints;
            var crvPnts = cbp.GetPoints();

            if (!CurveUtils.PointArraysAreSame(crvPnts, pts))
            {
                TransactionManager.Instance.EnsureInTransaction(Document);
                ((Autodesk.Revit.DB.CurveByPoints)InternalCurveElement).SetPoints(pts);
                TransactionManager.Instance.TransactionTaskDone();
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Build a linked list for vertices.
        /// </summary>
        /// <param name="curve"></param>
        /// <param name="transaction"></param>
        /// <param name="isLoop">Indicate whether the curve is a loop</param>
        /// <returns></returns>
        public static LinkedPoint GetLinkedPoints(Curve curve, Transaction transaction, bool isLoop)
        {
            var vertices = CurveUtils.GetDistinctVertices(curve, transaction);

            // Make sure the first point is not equal to the last one.
            if (vertices.Count > 1 && vertices[0] == vertices[vertices.Count - 1])
            {
                vertices.RemoveAt(vertices.Count - 1);
            }

            return(GetLinkedPoints(vertices, isLoop));
        }
Esempio n. 10
0
        protected override Status FixImpl(CheckResult checkResult, out List <ObjectId> resultIds)
        {
            resultIds = new List <ObjectId>();
            var undershootCheckResult = checkResult as UnderShootCheckResult;

            if (undershootCheckResult == null)
            {
                return(Status.Rejected);
            }

            var intersection = undershootCheckResult.IntersectionInfo;

            using (var transaction = Document.Database.TransactionManager.StartTransaction())
            {
                // Extend source curve
                CurveUtils.ExtendCurve(intersection.SourceId, intersection.IntersectPoint, intersection.SourceExtendType, transaction);
                resultIds.Add(intersection.SourceId);

                // Break target curve
                if (BreakTargetCurve)
                {
                    var blockTable = (BlockTable)transaction.GetObject(Document.Database.BlockTableId, OpenMode.ForRead);
                    var modelSpace = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    var splittedCurves = CurveUtils.SplitCurve(intersection.TargetId, new Point3d[] { intersection.IntersectPoint }, transaction);
                    if (splittedCurves != null && splittedCurves.Count > 0)
                    {
                        foreach (DBObject dbObj in splittedCurves)
                        {
                            var splitedCurve = dbObj as Entity;
                            if (splitedCurve == null)
                            {
                                continue;
                            }

                            var objId = modelSpace.AppendEntity(splitedCurve);
                            transaction.AddNewlyCreatedDBObject(splitedCurve, true);
                            resultIds.Add(objId);
                        }

                        // Erase the original one
                        var sourceCurve = (Entity)transaction.GetObject(intersection.TargetId, OpenMode.ForRead) as Curve;
                        if (sourceCurve != null)
                        {
                            sourceCurve.UpgradeOpen();
                            sourceCurve.Erase();
                        }
                    }
                }
                transaction.Commit();
            }
            return(Status.Fixed);
        }
Esempio n. 11
0
        public static void TestConvexHull()
        {
            var currentDoc = Application.DocumentManager.MdiActiveDocument;
            var editor     = currentDoc.Editor;
            var database   = currentDoc.Database;
            // Only select polyline and polyline 2d.
            ObjectId polylineId = ObjectId.Null;

            while (true)
            {
                var options = new PromptEntityOptions("\n选择一条曲线:");
                var result  = editor.GetEntity(options);
                if (result.Status == PromptStatus.OK)
                {
                    polylineId = result.ObjectId;
                    break;
                }

                if (result.Status == PromptStatus.Cancel)
                {
                    break;
                }

                editor.WriteMessage("\n选择无效");
            }

            if (polylineId.IsNull)
            {
                return;
            }

            using (var transaction = database.TransactionManager.StartTransaction())
            {
                IEnumerable <Point3d> points = CurveUtils.GetDistinctVertices(polylineId, transaction);
                var convex = new ConvexHull <Point3d>(points, it => it.X, it => it.Y,
                                                      (x, y) => new Point3d(x, y, 0), (a, b) => a == b);
                convex.CalcConvexHull();

                var hullPoints = convex.GetResultsAsArrayOfPoint();
                var polyline   = new Autodesk.AutoCAD.DatabaseServices.Polyline();
                for (int i = 0; i < hullPoints.Length; i++)
                {
                    polyline.AddVertexAt(i, new Point2d(hullPoints[i].X, hullPoints[i].Y), 0, 1, 1);
                }
                polyline.ColorIndex = 2;

                var modelspaceId = SymbolUtilityServices.GetBlockModelSpaceId(database);
                var modelspace   = transaction.GetObject(modelspaceId, OpenMode.ForWrite) as BlockTableRecord;
                modelspace.AppendEntity(polyline);
                transaction.AddNewlyCreatedDBObject(polyline, true);
                transaction.Commit();
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Set the geometry curve used by the ModelCurve
        /// </summary>
        /// <param name="c"></param>
        protected void InternalSetCurve(Curve c)
        {
            if (CurveUtils.CurvesAreSimilar(InternalCurveElement.GeometryCurve, c))
                return;

            if (!InternalCurveElement.GeometryCurve.IsBound && c.IsBound)
            {
                c = c.Clone();
                c.MakeUnbound();
            }
            setCurveMethod(this.InternalCurveElement, c);
        }
Esempio n. 13
0
        private IEnumerable <CurveCrossingInfo> FilterCrossInfos(IEnumerable <CurveCrossingInfo> crossInfos, out IEnumerable <CurveCrossingInfo> duplicateEntities)
        {
            duplicateEntities = new List <CurveCrossingInfo>();
            var result = new List <CurveCrossingInfo>();

            foreach (var curveCrossingInfo in crossInfos)
            {
                // Filter out duplicate entities
                if (AreDuplicateEntities(curveCrossingInfo))
                {
                    ((List <CurveCrossingInfo>)duplicateEntities).Add(curveCrossingInfo);
                    continue;
                }

                var sourcePoints = CurveUtils.GetCurveEndPoints(curveCrossingInfo.SourceId, _transaction);
                var targetPoints = new Point3d[0];
                if (curveCrossingInfo.TargetId != curveCrossingInfo.SourceId)
                {
                    targetPoints = CurveUtils.GetCurveEndPoints(curveCrossingInfo.TargetId, _transaction);
                }
                sourcePoints = DistinctEndPoints(sourcePoints);
                targetPoints = DistinctEndPoints(targetPoints);

                var points = new List <Point3d>();
                foreach (var point3D in curveCrossingInfo.IntersectPoints)
                {
                    // Whether point3D is end point of each cuve

                    //// If sourcePoints.Length is 1 or 0, means it's a loop, loop need to be splitted.
                    //if (sourcePoints.Length >= 2 && sourcePoints.Contains(point3D) &&
                    //    targetPoints.Length >= 2 && targetPoints.Contains(point3D))
                    //    continue;

                    // If curveCrossingInfo.SourceId == curveCrossingInfo.TargetId, it's a self intersection.
                    if (sourcePoints.Contains(point3D) && targetPoints.Contains(point3D) &&
                        curveCrossingInfo.SourceId != curveCrossingInfo.TargetId)
                    {
                        continue;
                    }

                    points.Add(point3D);
                }
                if (points.Count > 0)
                {
                    var newCrossingInfo = new CurveCrossingInfo(curveCrossingInfo.SourceId, curveCrossingInfo.TargetId,
                                                                points.ToArray());
                    result.Add(newCrossingInfo);
                }
            }
            return(result);
        }
Esempio n. 14
0
        public void IsLineLike_Curve_CorrectlyIdentifiesNonStraightNurbsCurve()
        {
            var points = new[]
            {
                Point.ByCoordinates(5, 5, 0),
                Point.ByCoordinates(0, 0, 0),
                Point.ByCoordinates(-5, 5, 0),
                Point.ByCoordinates(-10, 5, 0)
            };

            var nurbsCurve = NurbsCurve.ByPoints(points, 3);

            Assert.False(CurveUtils.IsLineLike(nurbsCurve.ToRevitType(false)));
        }
Esempio n. 15
0
        public Vector3 GetSplinePoint(float tX, float tY)
        {
            int iX  = (int)(tX * ControlSizeX);
            int i0X = Mathf.Max(0, iX - 1);
            int i1X = Mathf.Min(iX, ControlSizeX - 1);
            int i2X = Mathf.Min(iX + 1, ControlSizeX - 1);

            int iY  = (int)(tY * ControlSizeY);
            int i0Y = Mathf.Max(0, iY - 1);
            int i1Y = Mathf.Min(iY, ControlSizeY - 1);
            int i2Y = Mathf.Min(iY + 1, ControlSizeY - 1);

            var p00 = GetControl(i0X, i0Y);
            var p10 = GetControl(i1X, i0Y);
            var p20 = GetControl(i2X, i0Y);

            var p01 = GetControl(i0X, i1Y);
            var p11 = GetControl(i1X, i1Y);
            var p21 = GetControl(i2X, i1Y);

            var p02 = GetControl(i0X, i2Y);
            var p12 = GetControl(i1X, i2Y);
            var p22 = GetControl(i2X, i2Y);

            var cPoint10 = (p00 + p10) * 0.5f;
            var cPoint20 = (p10 + p20) * 0.5f;

            var cPoint11 = (p01 + p11) * 0.5f;
            var cPoint21 = (p11 + p21) * 0.5f;

            var cPoint12 = (p02 + p12) * 0.5f;
            var cPoint22 = (p12 + p22) * 0.5f;

            float tStepX   = 1.0f / ControlSizeX;
            float localTx  = (tX % tStepX) * ControlSizeX;
            var   resultX0 = CurveUtils.GetBezierPoint(cPoint10, p10, cPoint20, localTx);
            var   resultX1 = CurveUtils.GetBezierPoint(cPoint11, p11, cPoint21, localTx);
            var   resultX2 = CurveUtils.GetBezierPoint(cPoint12, p12, cPoint22, localTx);

            var cPoint1Y = (resultX0 + resultX1) * 0.5f;
            var cPoint2Y = (resultX2 + resultX1) * 0.5f;

            float tStepY  = 1.0f / ControlSizeY;
            float localTy = (tY % tStepY) * ControlSizeY;

            return(CurveUtils.GetBezierPoint(cPoint1Y, resultX1, cPoint2Y, localTy));
        }
Esempio n. 16
0
        public override void Check(IEnumerable <ObjectId> selectedObjectIds)
        {
            if (!selectedObjectIds.Any())
            {
                return;
            }

            var database = Editor.Document.Database;
            var group    = CalculateIntersection(selectedObjectIds, true, database);

            // Check each intersection whether it's a missing vertex.
            // TODO: 用一个比较低的精度去比较一个交点是否是顶点
            using (var tolerance = new SafeToleranceOverride(_tolerance, _tolerance))
                using (var transaction = database.TransactionManager.StartTransaction())
                {
                    foreach (var pair in group)
                    {
                        var curve = transaction.GetObject(pair.Key, OpenMode.ForRead) as Curve;
                        if (curve == null)
                        {
                            continue;
                        }

                        var vertices         = CurveUtils.GetDistinctVertices(curve, transaction);
                        var noneVertexPoints = new List <Point3d>();
                        foreach (var point in pair.Value)
                        {
                            var ret = CheckPointIsVertex(vertices, point, transaction);
                            if (!ret)
                            {
                                noneVertexPoints.Add(point);
                            }
                        }

                        if (noneVertexPoints.Count > 0)
                        {
                            _missingVertexInfos.Add(new MissingVertexInfo()
                            {
                                PolylineId = pair.Key,
                                Positions  = noneVertexPoints
                            });
                        }
                    }
                    transaction.Commit();
                }
        }
Esempio n. 17
0
        public void IsLineLike_Curve_CorrectlyIdentifiesNonStraightHermiteWithStraightControlPoints()
        {
            var points =
                Enumerable.Range(0, 10)
                .Select(x => new XYZ(x, 0, 0));

            var hs = HermiteSpline.Create(
                points.ToList(),
                false,
                new HermiteSplineTangents()
            {
                StartTangent = new XYZ(0, 0, 1),
                EndTangent   = new XYZ(1, 0, 0)
            });

            Assert.False(CurveUtils.IsLineLike(hs));
        }
Esempio n. 18
0
        public void CurvesAreSimilar_Arcs()
        {
            var a = Arc.ByCenterPointRadiusAngle(Point.ByCoordinates(0, 0, 0), 1.0, 0, 90, Vector.ZAxis());
            var b = Arc.ByCenterPointRadiusAngle(Point.ByCoordinates(1, 1, 1), 1.0, 0, 90, Vector.ZAxis());
            var c = Arc.ByCenterPointRadiusAngle(Point.ByCoordinates(0, 0, 0), 2.0, 0, 90, Vector.ZAxis());
            var d = Arc.ByCenterPointRadiusAngle(Point.ByCoordinates(0, 0, 0), 2.0, 20, 90, Vector.ZAxis());

            var revitArc1 = a.ToRevitType();
            var revitArc2 = b.ToRevitType();
            var revitArc3 = c.ToRevitType();
            var revitArc4 = d.ToRevitType();

            Assert.True(CurveUtils.CurvesAreSimilar(revitArc1, revitArc1));
            Assert.False(CurveUtils.CurvesAreSimilar(revitArc1, revitArc2));
            Assert.False(CurveUtils.CurvesAreSimilar(revitArc1, revitArc3));
            Assert.False(CurveUtils.CurvesAreSimilar(revitArc1, revitArc4));
        }
Esempio n. 19
0
        protected override IEnumerable <CheckResult> CheckImpl(IEnumerable <Autodesk.AutoCAD.DatabaseServices.ObjectId> selectedObjectIds)
        {
            var result = new List <AntiClockwisePolygonCheckResult>();

            if (!selectedObjectIds.Any())
            {
                return(result);
            }

            var database = selectedObjectIds.First().Database;

            using (var tr = database.TransactionManager.StartTransaction())
            {
                foreach (var objectId in selectedObjectIds)
                {
                    var pline = tr.GetObject(objectId, OpenMode.ForRead);
                    if (pline == null)
                    {
                        continue;
                    }

                    bool bIsCloseWise = false;
                    if (pline is Polyline)
                    {
                        bIsCloseWise = CurveUtils.IsPolygonClockWise(pline as Polyline);
                    }
                    else if (pline is Polyline2d)
                    {
                        bIsCloseWise = CurveUtils.IsPolygonClockWise(pline as Polyline2d, tr);
                    }
                    else
                    {
                        continue;
                    }

                    if (!bIsCloseWise)
                    {
                        result.Add(new AntiClockwisePolygonCheckResult(objectId));
                    }
                }

                tr.Commit();
            }
            return(result);
        }
Esempio n. 20
0
        private void InternalSetCurve(Autodesk.Revit.DB.Curve crv)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // Updating the curve will cause a document modification event
            // which will be handled by this node and could cause an
            // infinite loop. Check the framing's curve for similarity to the
            // provided curve and update only if the two are different.

            var locCurve = InternalFamilyInstance.Location as LocationCurve;

            if (!CurveUtils.CurvesAreSimilar(locCurve.Curve, crv))
            {
                locCurve.Curve = crv;
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
Esempio n. 21
0
        public void CurvesAreSimilar_Lines()
        {
            var a = Point.ByCoordinates(0, 0);
            var b = Point.ByCoordinates(1, 1);
            var c = Point.ByCoordinates(2, 2);

            var line1 = Line.ByStartPointEndPoint(a, b);
            var line2 = Line.ByStartPointEndPoint(b, a);
            var line3 = Line.ByStartPointEndPoint(a, c);

            var revitLine1 = line1.ToRevitType();
            var revitLine2 = line2.ToRevitType();
            var revitLine3 = line3.ToRevitType();

            Assert.True(CurveUtils.CurvesAreSimilar(revitLine1, revitLine1));
            Assert.False(CurveUtils.CurvesAreSimilar(revitLine1, revitLine2));
            Assert.False(CurveUtils.CurvesAreSimilar(revitLine1, revitLine3));
        }
Esempio n. 22
0
        CurveVertexKdTree <CurveVertex> CreatePolygonKdTree(IEnumerable <ObjectId> objectIds, Transaction transaction)
        {
            var vertices = new List <CurveVertex>();

            foreach (var objectId in objectIds)
            {
                var points = CurveUtils.GetDistinctVertices(objectId, transaction);
                if (points[0] == points[points.Count - 1])
                {
                    points.RemoveAt(points.Count - 1);
                }
                vertices.AddRange(points.Select(it => new CurveVertex(it, objectId)));
            }

            var kdTree = new CurveVertexKdTree <CurveVertex>(vertices, it => it.Point.ToArray(), ignoreZ: true);

            return(kdTree);
        }
Esempio n. 23
0
        override public bool FindRayIntersection(Ray3f worldRay, out SORayHit hit)
        {
            hit = null;

            // project world ray into local coords
            FScene scene    = GetScene();
            Ray3f  sceneRay = scene.ToSceneRay(worldRay);
            Ray3f  localRay = SceneTransforms.SceneToObject(this, sceneRay);

            // also need width in local coords
            float sceneWidth = scene.ToSceneDimension(visibleWidth);
            float localWidth = SceneTransforms.SceneToObject(this, sceneWidth) * HitWidthMultiplier;

            // bounding-box hit test (would be nice to do w/o object allocation...)
            AxisAlignedBox3d hitBox = localBounds;

            hitBox.Expand(localWidth);
            IntrRay3AxisAlignedBox3 box_test = new IntrRay3AxisAlignedBox3(localRay, hitBox);

            if (box_test.Find() == false)
            {
                return(false);
            }

            // raycast against curve (todo: spatial data structure for this? like 2D polycurve bbox tree?)
            double rayHitT;

            if (CurveUtils.FindClosestRayIntersection(curve, localWidth, localRay, out rayHitT))
            {
                hit = new SORayHit();
                // transform local hit point back into world coords
                Vector3f rayPos   = localRay.PointAt((float)rayHitT);
                Vector3f scenePos = SceneTransforms.ObjectToSceneP(this, rayPos);
                hit.hitPos    = SceneTransforms.SceneToWorldP(scene, scenePos);
                hit.fHitDist  = worldRay.Project(hit.hitPos);
                hit.hitNormal = Vector3f.Zero;
                hit.hitGO     = root;
                hit.hitSO     = this;
                return(true);
            }
            return(false);
        }
Esempio n. 24
0
 public static Action <List <Vector3d> > MakeLoopOnSurfaceProcessorF(FScene scene, IProjectionTarget surface,
                                                                     Func <float> SampleRateF, Func <bool> ClosedF,
                                                                     float fSmoothAlpha = 0.2f, int nSmoothIter = 15)
 {
     return((vertices) => {
         CurveResampler resampler = new CurveResampler();
         IWrappedCurve3d temp_curve = new IWrappedCurve3d()
         {
             VertexList = vertices, Closed = ClosedF()
         };
         float rate = SampleRateF();
         List <Vector3d> result = resampler.SplitCollapseResample(temp_curve, rate, rate * 0.6);
         if (result != null && result.Count > 3)
         {
             vertices.Clear();
             vertices.AddRange(result);
         }
         CurveUtils.InPlaceSmooth(vertices, fSmoothAlpha, nSmoothIter, ClosedF());
         gs.CurveDrawingUtil.ProjectToTarget_Scene(vertices, scene, surface);
     });
 }
Esempio n. 25
0
        /// <summary>
        /// Set the curve internally.  Returns false if this method failed to set the curve
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        private bool InternalSetSketchPlaneFromCurve(Autodesk.Revit.DB.Curve c)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            // Infer the sketch plane
            Autodesk.Revit.DB.Plane plane = CurveUtils.GetPlaneFromCurve(c, false);

            // attempt to change the sketch plane
            bool   needsRemake = false;
            string idSpUnused  = resetSketchPlaneMethod(this.InternalCurveElement, c, plane, out needsRemake);

            // if we got a valid id, delete the old sketch plane
            if (idSpUnused != String.Empty)
            {
                DocumentManager.Instance.DeleteElement(new ElementUUID(idSpUnused));
            }

            TransactionManager.Instance.TransactionTaskDone();

            return(!needsRemake);
        }
Esempio n. 26
0
        private CurveVertexKdTree <CurveVertex> BuildCurveVertexKdTree2(IEnumerable <ObjectId> allIds, Transaction transaction)
        {
            var allVertices = new List <CurveVertex>();

            foreach (var id in allIds)
            {
                var points = CurveUtils.GetDistinctVertices(id, transaction);
                if (!points.Any())
                {
                    continue;
                }

                var vertices = points.Select(it => new CurveVertex(it, id));

                allVertices.AddRange(vertices);
            }

            var kdTree = new CurveVertexKdTree <CurveVertex>(allVertices, it => it.Point.ToArray(), ignoreZ: true);

            return(kdTree);
        }
Esempio n. 27
0
        private void BuildCurveVertexKdTree(IEnumerable <ObjectId> allIds, Transaction transaction,
                                            out Dictionary <ObjectId, CurveVertex[]> curveVertices, out CurveVertexKdTree <CurveVertex> kdTree)
        {
            curveVertices = new Dictionary <ObjectId, CurveVertex[]>();
            var allVertices = new List <CurveVertex>();

            foreach (var id in allIds)
            {
                var points = CurveUtils.GetDistinctVertices(id, transaction);
                if (!points.Any())
                {
                    continue;
                }

                var vertices = points.Select(it => new CurveVertex(it, id));
                curveVertices[id] = vertices.ToArray();

                allVertices.AddRange(vertices);
            }

            kdTree = new CurveVertexKdTree <CurveVertex>(allVertices, it => it.Point.ToArray(), ignoreZ: true);
        }
Esempio n. 28
0
        private void BuildBspTree(IEnumerable <ObjectId> allIds)
        {
            var allBspSegments = new List <BspSegment>();

            foreach (var id in allIds)
            {
                var curve = _transaction.GetObject(id, OpenMode.ForRead) as Curve;
                if (curve == null)
                {
                    continue;
                }

                var segments    = CurveUtils.GetSegment2dsOfCurve(curve, _transaction);
                var bspSegments = segments.Select(it => new BspSegment()
                {
                    EntityId    = id,
                    LineSegment = it
                });
                allBspSegments.AddRange(bspSegments);
            }
            _bspTree = new Curve2dBspTree(allBspSegments);
        }
Esempio n. 29
0
        private static Curve Flatten3dCurveOnPlane(Curve c, Plane plane)
        {
            if (c is Autodesk.Revit.DB.HermiteSpline)
            {
                var hs = c as Autodesk.Revit.DB.HermiteSpline;
                plane = CurveUtils.GetPlaneFromCurve(c, false);
                var projPoints = new List <XYZ>();
                foreach (var pt in hs.ControlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return(Autodesk.Revit.DB.HermiteSpline.Create(projPoints, false));
            }

            if (c is Autodesk.Revit.DB.NurbSpline)
            {
                var ns = c as Autodesk.Revit.DB.NurbSpline;
                if (plane == null)
                {
                    var bestFitPlane = Autodesk.DesignScript.Geometry.Plane.ByBestFitThroughPoints(
                        ns.CtrlPoints.ToList().ToPoints(false));

                    plane = bestFitPlane.ToPlane(false);
                }

                var projPoints = new List <XYZ>();
                foreach (var pt in ns.CtrlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return(Autodesk.Revit.DB.NurbSpline.Create(projPoints, ns.Weights.Cast <double>().ToList(), ns.Knots.Cast <double>().ToList(), ns.Degree, ns.isClosed, ns.isRational));
            }

            return(c);
        }
Esempio n. 30
0
        /// <summary>
        /// Set the plane and the curve internally.
        /// </summary>
        private void InternalSetSketchPlaneFromCurve(Curve newCurve)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            Plane newPlane = CurveUtils.GetPlaneFromCurve(newCurve, false);
            Plane oldPlane = InternalCurveElement.SketchPlane.GetPlane();

            var angleBetweenPlanes     = newPlane.Normal.AngleTo(oldPlane.Normal);
            var distanceBetweenOrigins = newPlane.Origin.DistanceTo(oldPlane.Origin);

            Autodesk.Revit.DB.SketchPlane sp = null;

            // Planes are different.
            if (angleBetweenPlanes > tolerance || distanceBetweenOrigins > tolerance)
            {
                sp = GetSketchPlaneFromCurve(newCurve);
                InternalCurveElement.SetSketchPlaneAndCurve(sp, newCurve);
            }
            // Planes are the same.
            else
            {
                InternalSetCurve(newCurve);
            }

            string idSpUnused = String.Empty;

            if (sp != null && InternalCurveElement.SketchPlane.Id != sp.Id)
            {
                idSpUnused = sp.UniqueId;
            }

            // if we got a valid id, delete the old sketch plane
            if (idSpUnused != String.Empty)
            {
                DocumentManager.Instance.DeleteElement(new ElementUUID(idSpUnused));
            }

            TransactionManager.Instance.TransactionTaskDone();
        }