public static void Draw(Point3dCollection points, int deep, ref List<Entity> ents) { if (deep == 0) { DrawPolygon(points, ref ents); return; } else { Point3dCollection middlePoints = CalculateMiddlePoints(points); Point3dCollection aux = new Point3dCollection(); aux.Add( points[0] ); aux.Add( middlePoints[0] ); aux.Add( middlePoints[2] ); Draw(aux, deep-1, ref ents); // aux.Clear(); aux = new Point3dCollection(); aux.Add( middlePoints[0] ); aux.Add( points[1] ); aux.Add( middlePoints[1]); Draw(aux, deep - 1, ref ents); // aux.Clear(); aux = new Point3dCollection(); aux.Add( middlePoints[2]); aux.Add( middlePoints[1] ); aux.Add( points[2]); Draw(aux, deep - 1, ref ents); } }
private bool _drawing; // Drawing mode active public KinectSwitchJig( Document doc, Transaction tr, double profSide, double factor ) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _lastDrawnVertex = -1; _resizing = false; _drawing = false; _created = new DBObjectCollection(); _profSide = profSide; _segFactor = factor; switchm = 0; Words.Add("red"); Words.Add("green"); Words.Add("blue"); Words.Add("yellow"); Words.Add("pink"); Words.Add("magenta"); Words.Add("cyan"); }
public KinectDelayJig( int numShots, double delay ) { // Initialise the various members _numShots = numShots; _points = new Point3dCollection(); _snapped = new List<Point3dCollection>(); _totalVecs = new List<ColoredPoint3d>(); _snapshot = false; _timer = new System.Timers.Timer(delay * 1000); _timer.Enabled = false; // Hook up the Elapsed event for the timer _timer.Elapsed += delegate(object source, ElapsedEventArgs args) { // Flag that it's time to capture a snapshot _snapshot = true; // Turn off the timer to be re-enabled later ((Timer)source).Enabled = false; }; }
public static Point3dCollection CalculateMiddlePoints(Point3dCollection basePoints) { Point3dCollection auxC= new Point3dCollection(); auxC.Add( PointBetweenPoints(basePoints[0], basePoints[1]) ); auxC.Add( PointBetweenPoints(basePoints[1], basePoints[2]) ); auxC.Add( PointBetweenPoints(basePoints[2], basePoints[0]) ); return auxC; }
public BBox(Point3d min, Point3d max) { this.Min = min; this.Max = max; this.Geometry = new Point3dCollection(); this.Geometry.Add(min); this.Geometry.Add(new Point3d(max.X, min.Y, 0)); this.Geometry.Add(max); this.Geometry.Add(new Point3d(min.X, max.Y, 0)); }
public Sierpinski(Point3d center, float rad) { this.center = center; this.rad = rad; points = new Point3dCollection(); ents = new List<Entity>(); points.Add( new Point3d(center.X + (rad * Math.Cos(90 * deg2rad)), center.Y + (rad * Math.Sin(90 * deg2rad)), center.Z)); points.Add( new Point3d(center.X + (rad * Math.Cos(210 * deg2rad)), center.Y + (rad * Math.Sin(210 * deg2rad)), center.Z)); points.Add( new Point3d(center.X + (rad * Math.Cos(330 * deg2rad)), center.Y + (rad * Math.Sin(330 * deg2rad)), center.Z)); }
public Cuadrado(int Depth, Point3d pt0, Point3d pt1, Point3d pt2, Point3d pt3) { this.Depth = Depth; pts = new Point3dCollection(); pts.Add(pt0); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); Lab3.DBMan.DrawGeometry(pts, true); }
/// <summary> /// Creates a Polyline with default settings (layer, color, etc.) with the specified vertices. /// Only the X and Y coordinates are taken into account, width is zero, and no bulges are added. /// </summary> /// <param name="vertices">Vertices that will compose the polyline.</param> public static Polyline CreatePolyline(Point3dCollection vertices) { Polyline polyline = new Polyline(); polyline.SetDatabaseDefaults(); for (int i = 0; i < vertices.Count; i++) { polyline.AddVertexAt(i, new Point2d(vertices[i].X, vertices[i].Y), 0, 0, 0); } return polyline; }
public void CreateGeometry() { Geometry = new Point3dCollection(); Double delta = Math.PI * 2 / Sides; Double x, y; for (int i = 0; i < Sides; i++) { x = this.Center.X + this.Apotema * Math.Cos(delta * i); y = this.Center.Y + this.Apotema * Math.Sin(delta * i); Geometry.Add(new Point3d(x, y, 0)); } }
public Pixel(Color c, Point3d center, Double size = 10) { this.center = center; this.c = c; this.size = size; points = new Point3dCollection(); points.Add(new Point3d(this.center.X - this.size / 2, this.center.Y - this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X + this.size / 2, this.center.Y - this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X + this.size / 2, this.center.Y + this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X - this.size / 2, this.center.Y + this.size / 2, this.center.Z)); this.face = new Face( points[0], points[1], points[2], points[3], true, true, true, true); this.face.Color = this.c; }
private bool _drawing; // Drawing mode active public KinectPolyJig(Document doc, Transaction tr) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _lineSegs = new List<LineSegment3d>(); _lines = new DBObjectCollection(); _cursor = null; _calibrating = true; _drawing = false; }
public double totalDistance(Point3dCollection PointList, int floatRound, int index) { int i = 0; double Distance = 0; foreach (Point3d p in PointList) { if (i + 1 > PointList.Count - 1) { break; } Distance += PointList[i].DistanceTo(PointList[i + 1]); if (i == index){break;} i++; } return Math.Round(Distance, floatRound); }
/// <summary> /// Gets the vertices of a polyline. /// </summary> /// <param name="polyline">Polyline, Polyline2d, or Polyline3d from which to obtain the vertices</param> public static Point3dCollection GetVertices(Curve polyline) { Point3dCollection vertices = new Point3dCollection(); if (polyline is Polyline) { Polyline pline = (Polyline)polyline; for (int i = 0; i < pline.NumberOfVertices; i++) { vertices.Add(pline.GetPoint3dAt(i)); } } else { Database database = HostApplicationServices.WorkingDatabase; Transaction transaction = database.TransactionManager.StartTransaction(); if (polyline is Polyline2d) { Polyline2d pline2d = (Polyline2d)polyline; foreach (Object vertex in pline2d) { if (vertex is Vertex2d) { vertices.Add(((Vertex2d)vertex).Position); } else if (vertex is ObjectId) { vertices.Add(((Vertex2d)transaction.GetObject((ObjectId)vertex, OpenMode.ForRead)).Position); } } } else if (polyline is Polyline3d) { Polyline3d pline3d = (Polyline3d)polyline; foreach (ObjectId vertexId in pline3d) { PolylineVertex3d vertex = (PolylineVertex3d)transaction.GetObject(vertexId, OpenMode.ForRead); vertices.Add(vertex.Position); } } transaction.Dispose(); } return vertices; }
private bool _drawing; // Drawing mode active public KinectSolidsJig( Document doc, Transaction tr, double profRad ) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _cursor = null; _drawing = false; _profile = null; _sweepOpts = null; _path = null; _tube = null; _profRad = profRad; _sweepBroken = false; }
/** * @brief Metodo que descompone una curva en un conjunto de segmentos de línea que aproximan o recubren la curva original. * * @param cur Entidad curva que debe ser linealizada. * @param numSeg Número de líneas en las que tiene que ser partida la curva. * @param acBlkTbl Tabla de bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param acBlkTblRec Tabla de registros de los bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param t Transaccion abierta para manipular la tabla de bloques de AutoCAD. * @param LayerId Parámetro del tipo ObjectId que identifica la capa a la que tendrán que asociarse las nuevas líneas generadas por el proceso * de descomposición de la curva. * @param dwfg Parámetro del tipo dwgFile donde se almacenaran las nuevas líneas creadas a partir del proceso de descomposición de la curva. * * @return Devuelve una colección de entidades tipo linea bajo la clase DBObjectCollection. **/ public static DBObjectCollection curvaAlineas(Curve cur, int numSeg, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec,Transaction t, ObjectId LayerId, dwgFile dwfg) { DBObjectCollection ret = new DBObjectCollection(); // Collect points along our curve Point3dCollection pts = new Point3dCollection(); // Split the curve's parameter space into // equal parts double startParam = cur.StartParam; double segLen = (cur.EndParam - startParam) / numSeg; // Loop along it, getting points each time for (int i = 0; i < numSeg + 1; i++) { Point3d pt = cur.GetPointAtParameter(startParam + segLen * i); pts.Add(pt); } if (pts != null && pts.Count > 0) { if (pts.Count == 1) { // Retornamos un punto. } else if (pts.Count >= 2) { // Retornamos una secuencia de lineas for (int i = 0; i < pts.Count - 1; i++) { Line ln = new Line(); ln.StartPoint = pts[i]; ln.EndPoint = pts[i + 1]; ln.LayerId = LayerId; acBlkTblRec.AppendEntity(ln); t.AddNewlyCreatedDBObject(ln, true); dwfg.objetosArtificiales.Add(ln.ObjectId); ret.Add(ln); } } } return ret; }
SelectionCrossingPolygon() { Point3dCollection pts = new Point3dCollection(); if (Utils.AcadUi.GetPline3dCollection(pts)) { PromptSelectionResult result; if (m_cbApplyFilter.Checked) { result = m_editor.SelectCrossingPolygon(pts, GetSelectionFilter()); } else { result = m_editor.SelectCrossingPolygon(pts); } ShowPromptResult("Select: Crossing Polygon", result); } }
public override bool ViewportDraw(ViewportDraw worldDraw, ObjectId entityId, DrawType type, Point3d?imageGripPoint, int gripSizeInPixels) { CoordinateSystem3d eCS = GetECS(entityId); Point2d numPixelsInUnitSquare = worldDraw.Viewport.GetNumPixelsInUnitSquare(GripPoint); double num = (double)gripSizeInPixels / numPixelsInUnitSquare.X; Point3dCollection point3dCollections = new Point3dCollection(); point3dCollections.Add((GripPoint - (num * eCS.Xaxis)) - (num * eCS.Yaxis)); point3dCollections.Add((GripPoint - (num * eCS.Xaxis)) + (num * eCS.Yaxis)); point3dCollections.Add((GripPoint + (num * eCS.Xaxis)) + (num * eCS.Yaxis)); point3dCollections.Add((GripPoint + (num * eCS.Xaxis)) - (num * eCS.Yaxis)); worldDraw.SubEntityTraits.FillType = FillType.FillAlways; worldDraw.Geometry.Polygon(point3dCollections); worldDraw.SubEntityTraits.FillType = FillType.FillNever; worldDraw.SubEntityTraits.TrueColor = new EntityColor(0, 0, 0); worldDraw.Geometry.Polygon(point3dCollections); return(true); }
public DBObjectCollection createBoreSymbol(Point3dCollection pts) { DBObjectCollection dbObjColl = new DBObjectCollection(); Transaction tr = acCurDb.TransactionManager.StartTransaction(); using (tr) { // Open the Layer table for read LayerTable acLyrTbl; acLyrTbl = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; LayerTableRecord acLyrRec; acLyrRec = tr.GetObject(acCurDb.Clayer, OpenMode.ForRead) as LayerTableRecord; // for mtext bore length //Point3d txtInsertion = new Point3d(); //double txtAngle = 0; foreach (Entity ent in _runningLine.GetOffsetCurves(1)) { Polyline offsetTop = (Polyline)ent; offsetTop.Layer = acLyrRec.Name; //////////txtInsertion = getMidPoint(offsetTop); //////////////////////////////////////////////////////i left off here // need to cut the offset line at 1 foot from each side of driveway dbObjColl.Add(offsetTop); } foreach (Entity ent in _runningLine.GetOffsetCurves(-1)) { Polyline offsetBot = (Polyline)ent; offsetBot.Layer = acLyrRec.Name; dbObjColl.Add(offsetBot); } } return(dbObjColl); }
public static Polyline3d AlignmentToPolyline3d2(Alignment alignment, Profile profile) { Point3d point; Polyline3d p3d = null; var elevations = new Point3dCollection(); var station = 0d; double elevation; var db = alignment.Database; using (var tr = db.TransactionManager.StartTransaction()) { var polylineId = alignment.GetPolyline(); using (var polyline = tr.GetObject(polylineId, OpenMode.ForRead) as Polyline) { do { station += 0.001; if (station > polyline.Length) { station = polyline.Length; } elevation = profile.ElevationAt(station); point = polyline.GetPointAtDist(station); point = new Point3d(point.X, point.Y, elevation); elevations.Add(point); } while (station < polyline.Length); var fid = FeatureLine.Create("george", polylineId); var featureLine = tr.GetObject(fid, OpenMode.ForWrite) as FeatureLine; foreach (Point3d p in elevations) { featureLine.InsertElevationPoint(p); } var objs = new DBObjectCollection(); featureLine.Explode(objs); p3d = new Polyline3d(Poly3dType.SimplePoly, elevations, polyline.Closed); } } return(p3d); }
public static Polyline3d CreateSquare(SizeF area, double border = 0) { var pts = new Point3dCollection { new Point3d(-border, -border, 0), new Point3d(-border, area.Height + border, 0), new Point3d(area.Width + border, area.Height + border, 0), new Point3d(area.Width + border, -border, 0) }; var polyline = new Polyline3d(Poly3dType.SimplePoly, pts, true); if (border > 0) { polyline.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 0, 0); } return(polyline); }
//convert parts to splines (works for line and arcs*Not arcs yet) static private Spline convertSpline(DBObject dbo) { if (dbo is Spline) { return(dbo as Spline); } if (dbo is Arc) { Arc arcDat = dbo as Arc; Spline seg = new Spline(); //whatever that is return(seg); } else if (dbo is Line) { Line lDat = dbo as Line; Point3dCollection vertices = new Point3dCollection(); vertices.Add(lDat.StartPoint); vertices.Add(lDat.EndPoint); Polyline3d tempPline = new Polyline3d(); //polyine 3D has to be in btr before adding vertices Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTableRecord btr = (BlockTableRecord)(trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)); btr.AppendEntity(tempPline); foreach (Point3d pnt in vertices) { using (PolylineVertex3d poly3dVert = new PolylineVertex3d(pnt)) { tempPline.AppendVertex(poly3dVert); } } trans.Commit(); } Spline seg = tempPline.Spline; tempPline.Erase(true); return(seg); } return(null); }
public string getWindowText(Point3d pt1, Point3d pt2) { Editor editor = Application.DocumentManager.MdiActiveDocument.Editor; TypedValue[] array = new TypedValue[] { new TypedValue(0, "TEXT") }; SelectionFilter selectionFilter = new SelectionFilter(array); Point3dCollection point3dCollection = new Point3dCollection(); Point3d point3d = new Point3d(pt2.X, pt1.Y, 0.0); Point3d point3d2 = new Point3d(pt1.X, pt2.Y, 0.0); point3dCollection.Add(pt1); point3dCollection.Add(point3d2); point3dCollection.Add(pt2); point3dCollection.Add(point3d); Polyline3d polyline3d = this.CreatePolye(point3dCollection); double area = polyline3d.Area; Point3dCollection point3dCollection2 = new Point3dCollection(); polyline3d.GetStretchPoints(point3dCollection2); PromptSelectionResult ents = editor.SelectCrossingPolygon(point3dCollection2); DBObjectCollection entityCollection = this.GetEntityCollection(ents); string text = ""; foreach (Entity entity in entityCollection) { if (entity is DBText) { DBText dBText = entity as DBText; if (dBText != null) { if (!dBText.TextString.Equals("")) { } text += dBText.TextString; } } } return(text); }
/// <summary> /// 求两条曲线的交点,本函数为应对Polyline.IntersectWith函数的Bug /// Vrsion : 2009.02.10 Sieben /// Vrsion : 2010.12.25 增加判断输入实体是否为平面实体 /// </summary> /// <param name="ent1"></param> /// <param name="ent2"></param> /// <returns></returns> public static Point3dCollection IntersectWith(Entity ent1, Entity ent2, Intersect intersectType) { try { if (ent1 is Polyline || ent2 is Polyline) { if (ent1 is Polyline && ent2 is Polyline) { Polyline pline1 = (Polyline)ent1; Polyline pline2 = (Polyline)ent2; return(IntersectWith(pline1.ConvertTo(false), pline2.ConvertTo(false), intersectType)); } else if (ent1 is Polyline) { Polyline pline1 = (Polyline)ent1; return(IntersectWith(pline1.ConvertTo(false), ent2, intersectType)); } else { Polyline pline2 = (Polyline)ent2; return(IntersectWith(ent1, pline2.ConvertTo(false), intersectType)); } } else { Point3dCollection interPs = new Point3dCollection(); if (ent1.IsPlanar && ent2.IsPlanar) { ent1.IntersectWith(ent2, intersectType, new Plane(Point3d.Origin, Vector3d.ZAxis), interPs, 0, 0); } else { ent1.IntersectWith(ent2, intersectType, interPs, 0, 0); } return(interPs); } } catch (System.Exception ex) { return(null); } }
private static IEnumerable <Polyline> GenerateManholeStep(Curve stepLine, Entity innerRing) { const double outerLength = 350; const double outerDepth = 129; const double innerLength = outerLength - 60; const double innerDepth = outerDepth - 30; var innerPt = new Point3dCollection(); stepLine.IntersectWith(innerRing, Intersect.OnBothOperands, innerPt, IntPtr.Zero, IntPtr.Zero); var vec = innerPt[0].GetVectorTo(stepLine.StartPoint); var outerDist = vec.Length - Math.Sqrt(Math.Pow(vec.Length, 2) - Math.Pow(outerLength / 2, 2)); var outerStart = innerPt[0] + vec * (outerDist / vec.Length); var outerEnd = innerPt[0] + vec * ((outerDist + outerDepth) / vec.Length); var outerLine = new Line(outerStart, outerEnd); var outerOffsetPlus = (Line)outerLine.GetOffsetCurves(outerLength / 2)[0]; var outerOffsetMinus = (Line)outerLine.GetOffsetCurves(-outerLength / 2)[0]; var outer = new Polyline(); outer.AddVertexAt(0, new Point2d(outerOffsetPlus.StartPoint.X, outerOffsetPlus.StartPoint.Y), 0, 0, 0); outer.AddVertexAt(1, new Point2d(outerOffsetPlus.EndPoint.X, outerOffsetPlus.EndPoint.Y), 0, 0, 0); outer.AddVertexAt(2, new Point2d(outerOffsetMinus.EndPoint.X, outerOffsetMinus.EndPoint.Y), 0, 0, 0); outer.AddVertexAt(3, new Point2d(outerOffsetMinus.StartPoint.X, outerOffsetMinus.StartPoint.Y), 0, 0, 0); var innerDist = vec.Length - Math.Sqrt(Math.Pow(vec.Length, 2) - Math.Pow(innerLength / 2, 2)); var innerStart = innerPt[0] + vec * (innerDist / vec.Length); var innerEnd = innerPt[0] + vec * ((outerDist + innerDepth) / vec.Length); var innerLine = new Line(innerStart, innerEnd); var innerOffsetPlus = (Line)innerLine.GetOffsetCurves(innerLength / 2)[0]; var innerOffsetMinus = (Line)innerLine.GetOffsetCurves(-innerLength / 2)[0]; var inner = new Polyline(); inner.AddVertexAt(0, new Point2d(innerOffsetPlus.StartPoint.X, innerOffsetPlus.StartPoint.Y), 0, 0, 0); inner.AddVertexAt(1, new Point2d(innerOffsetPlus.EndPoint.X, innerOffsetPlus.EndPoint.Y), 0, 0, 0); inner.AddVertexAt(2, new Point2d(innerOffsetMinus.EndPoint.X, innerOffsetMinus.EndPoint.Y), 0, 0, 0); inner.AddVertexAt(3, new Point2d(innerOffsetMinus.StartPoint.X, innerOffsetMinus.StartPoint.Y), 0, 0, 0); return(new[] { outer, inner }); }
private IntersectionInfo IntersectLineAndCurve(Line line, Curve curve, Point3d sorucePoint, ExtendType desireExtendType) { var points = new Point3dCollection(); line.IntersectWith(curve, Intersect.ExtendThis, points, IntPtr.Zero, IntPtr.Zero); if (points.Count == 0) { return(null); } // NOTE: Use Line's GetParameterAtPoint will throw exception if the intersect point is // on the line's extension, but LineSegment3d.GetParameterOf is available, so I convert // the Line to LineSegment3d here. var lineSegment = new LineSegment3d(line.StartPoint, line.EndPoint); Point3d?nearestPoint = null; double? nearestDist = null; foreach (Point3d point in points) { var param = lineSegment.GetParameterOf(point); var extendType = CurveIntersectUtils.ParamToExtendTypeForLine(param); if (extendType != desireExtendType) { continue; } var dist = (point - sorucePoint).LengthSqrd; if (nearestDist == null || dist < nearestDist.Value) { nearestDist = dist; nearestPoint = point; } } IntersectionInfo result = null; if (nearestPoint != null) { result = new IntersectionInfo(desireExtendType, ExtendType.None, nearestPoint.Value); } return(result); }
public static Point3dCollection PointCollection(Polyline acPoly) { var PoColl = new Point3dCollection(); var A = new List <Point3d>(); for (int i = 0; i < acPoly.NumberOfVertices; i++) { try { var a = acPoly.GetPoint3dAt(i); var x = Math.Round(a.X, 2); var y = Math.Round(a.Y, 2); var z = Math.Round(a.Z, 2); A.Add(new Point3d(x, y, z)); } catch { } } var B = A.Distinct(new Point3dComparer()).ToList(); if (!B.First().Equals(B.Last())) { B.Add(B.First()); } for (int i = 0; i < B.Count - 1; i++) { if (B[i].DistanceTo(B[i + 1]) == 0) { continue; } PoColl.Add(B[i]); } PoColl.Add(B.Last()); return(PoColl); }
public static void WriteInDatabase(PLine_1 pline) { Editor arg_0F_0 = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database workingDatabase = HostApplicationServices.WorkingDatabase; using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1); List <ngeometry.VectorGeometry.Point> list = pline.GetVertices().ToList(); if (pline.IsClosed) { list.RemoveAt(list.Count - 1); } Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(list); Polyline3d polyline3d = new Polyline3d(0, point3dCollection, false); point3dCollection.Dispose(); if (pline.IsClosed) { polyline3d.Closed = (true); } bool flag = false; polyline3d.LayerId = (DBManager.CreateLayer(pline.CADData.Layer.Name, 7, false, ref flag)); Autodesk.AutoCAD.Colors.Color color = null; short colorIndex = pline.CADData.ColorIndex; if (pline.CADData.Color != System.Drawing.Color.Empty) { color = Autodesk.AutoCAD.Colors.Color.FromColor(pline.CADData.Color); } if (color == null) { polyline3d.ColorIndex = ((int)colorIndex); } else { polyline3d.Color = (color); } blockTableRecord.AppendEntity(polyline3d); transaction.AddNewlyCreatedDBObject(polyline3d, true); transaction.Commit(); } }
public static Extents3d Limits(Point3dCollection points) { double xmin = double.MaxValue; double xmax = double.MinValue; double ymin = double.MaxValue; double ymax = double.MinValue; double zmin = double.MaxValue; double zmax = double.MinValue; foreach (Point3d pt in points) { xmin = Math.Min(xmin, pt.X); xmax = Math.Max(xmax, pt.X); ymin = Math.Min(ymin, pt.Y); ymax = Math.Max(ymax, pt.Y); zmin = Math.Min(zmin, pt.Z); zmax = Math.Max(zmax, pt.Z); } return(new Extents3d(new Point3d(xmin, ymin, zmin), new Point3d(xmax, ymax, zmax))); }
public static SelectionSet IntersectedObjs(Point3d P1, Point3d P2) { var PoColl = new Point3dCollection(); PoColl.Add(P1); PoColl.Add(P2); PoColl.Add(Utils.PointUtil.Move(P2, 0, 1)); PoColl.Add(Utils.PointUtil.Move(P1, 0, 1)); var PSR = AC.Editor.SelectCrossingPolygon(PoColl); if (PSR.Status != PromptStatus.OK) { AC.Editor.WriteMessage("\n취소"); return(null); } return(PSR.Value); }
public double totalDistance(Point3dCollection PointList, int floatRound, int index) { int i = 0; double Distance = 0; foreach (Point3d p in PointList) { if (i + 1 > PointList.Count - 1) { break; } Distance += PointList[i].DistanceTo(PointList[i + 1]); if (i == index) { break; } i++; } return(Math.Round(Distance, floatRound)); }
public static ObjectId[] SelectEntitisInModelSpaceByViewport(Document doc, Point3dCollection boundaryInModelSpace) { //doc.Editor.SwitchToModelSpace(); LayoutManager lm = LayoutManager.Current; lm.CurrentLayout = "Model"; ObjectId[] ids = null; PromptSelectionResult res = doc.Editor.SelectCrossingPolygon(boundaryInModelSpace); if (res.Status == PromptStatus.OK) { ids = res.Value.GetObjectIds(); } //doc.Editor.SwitchToPaperSpace(); return(ids); }
public void Props() { DwgTest.ExecuteActionsInDwg(KnownValues.Notches1.DrawingPath, (db, trans) => { var(sourceCurve, sourceNotches, targetCurve) = KnownValues.Notches1.ToObjects(db, trans); var notchCollection = new Point3dCollection(sourceNotches.ToArray()); var notchSegments = sourceCurve.GetSplitCurves(notchCollection); var sourceLength = AcadHelpers.GetCurveLength(sourceCurve); var facet1 = notchSegments[0] as Curve; var facet1Length = AcadHelpers.GetCurveLength(facet1); var facet1RatioByLengths = facet1Length / sourceLength; //var facet1RatioByParams = sourceCurve.GetParameterAtPoint(notchCollection[0]) / (sourceCurve.EndParam - sourceCurve.StartParam); //facet1RatioByLengths.ShouldBe(facet1RatioByParams); }); }
public static SurfaceVolumeInfo?GetVolumeInfo(TinVolumeSurface volumeSurface, Polyline border) { if (!border.Closed) { Tools.GetAcadEditor().WriteMessage("\nPolyline not closed"); return(null); } Point3dCollection points = border.GetPoints(); try { return(volumeSurface.GetBoundedVolumes(points)); } catch (System.Exception ex) { Tools.GetAcadEditor().WriteMessage("\n" + ex.Message); return(null); } }
public DrawForbidenAreaJig(Matrix3d ucs) : base(new Polyline()) { // Create a point collection to store our vertices _Point3dCollection = new Point3dCollection(); // Create a temporary plane, to help with calcs Point3d origin = new Point3d(0, 0, 0); Vector3d normal = new Vector3d(0, 0, 1); normal = normal.TransformBy(ucs); m_plane = new Plane(origin, normal); // Create polyline, set defaults, add dummy vertex Polyline pline = Entity as Polyline; pline.SetDatabaseDefaults(); pline.Normal = normal; pline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0); }
public void CreateSurface() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Topography.SurfaceType surface = Topography.PickSurface(); if (surface == Topography.SurfaceType.None) { return; } if (ShowSettings()) { try { IEnumerable <ObjectId> items = SelectEntitites(); Point3dCollection points = ReadPoints(items, MaxPointSpacing); if (points.Count > 0) { Topography topo = Topography.Instance; topo.SurfaceFromPoints(points, surface); doc.Editor.WriteMessage(topo.OriginalTIN.Triangles.Count.ToString() + " adet üçgen oluşturuldu."); } if (EraseEntities) { AcadUtility.AcadEntity.EraseEntities(db, items); } } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.ToString(), "XCOM", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public ObjectId CreateBlockWithAttributes() { Database db = HostApplicationServices.WorkingDatabase; ObjectId blockId = ObjectId.Null; BlockTableRecord record = new BlockTableRecord(); record.Name = "RMNUM"; using (Transaction trans = db.TransactionManager.StartTransaction()) { Point3dCollection points = new Point3dCollection(); points.Add(new Point3d(-18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, 6.0, 0.0)); points.Add(new Point3d(-18.0, 6.0, 0.0)); Polyline2d pline = new Polyline2d(Poly2dType.SimplePoly, points, 0.0, true, 0.0, 0.0, null); record.AppendEntity(pline); AttributeDefinition attdef = new AttributeDefinition(); attdef.Position = new Point3d(0.0, 0.0, 0.0); attdef.Height = 8.0; //设置文字高度 attdef.Rotation = 0.0; //设置文字旋转角度 attdef.HorizontalMode = TextHorizontalMode.TextMid; //设置水平对齐方式 attdef.VerticalMode = TextVerticalMode.TextVerticalMid; //设置垂直对齐方式 attdef.Prompt = "Room Number:"; //设置属性提示 attdef.TextString = "0000"; //设置属性的缺省值 attdef.Tag = "NUMBER"; //设置属性标签 attdef.Invisible = false; //设置不可见选项为假 attdef.Verifiable = false; //设置验证方式为假 attdef.Preset = false; //设置预置方式为假 attdef.Constant = false; //设置常数方式为假 record.Origin = points[3]; record.AppendEntity(attdef); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if (!bt.Has("RMNUM")) //判断是否存在名为"RMNUM"的块 { blockId = bt.Add(record); //在块表中加入"RMNUM"块 trans.AddNewlyCreatedDBObject(record, true); trans.Commit(); } } return(blockId); }
public static List <MeshDatas> GetMeshDatas() { Document activeDoc = Application.DocumentManager.MdiActiveDocument; Database db = activeDoc.Database; Editor ed = activeDoc.Editor; TypedValue[] values = { new TypedValue((int)DxfCode.Start, "MESH") }; SelectionFilter filter = new SelectionFilter(values); PromptSelectionResult psr = ed.SelectAll(filter); SelectionSet ss = psr.Value; if (ss == null) { return(null); } List <MeshDatas> datas = new List <MeshDatas>(); using (Transaction trans = db.TransactionManager.StartTransaction()) { for (int i = 0; i < ss.Count; ++i) { SubDMesh mesh = trans.GetObject(ss[i].ObjectId, OpenMode.ForRead) as SubDMesh; Point3dCollection collPoints = new Point3dCollection(); // Get the vertices information int vcount = 0; foreach (Point3d vertex in mesh.Vertices) { //ed.WriteMessage(String.Format("\n Vertex {0} - {1} {2}", vcount++, vertex.X, vertex.Y)); collPoints.Add(new Point3d(vertex.X, vertex.Y, vertex.Z)); } datas.Add(new MeshDatas { Mesh = mesh, Increment = i, Points = collPoints }); } trans.Commit(); } return(datas); }
public void CurveBoolean() { // 提示用户选择所要计算距离的两条直线 ObjectIdCollection polyIds = new ObjectIdCollection(); if (PromptSelectEnts("\n请选择要处理的复合线:", "LWPOLYLINE", ref polyIds)) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; if (polyIds.Count != 1) { ed.WriteMessage("\n必须选择一条多段线进行操作."); return; } var plineId = DrawWallMethod(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { if (plineId.Equals(ObjectId.Null)) { return; } polyIds.Add(plineId); // 获得两条曲线的交点 Polyline poly1 = (Polyline)trans.GetObject(polyIds[0], OpenMode.ForRead); Polyline poly2 = (Polyline)trans.GetObject(polyIds[1], OpenMode.ForRead); Point3dCollection intPoints = new Point3dCollection(); poly1.IntersectWith(poly2, Intersect.OnBothOperands, intPoints, 0, 0); if (intPoints.Count < 2) { ed.WriteMessage("\n曲线交点少于2个, 无法进行计算."); } // 根据交点和参数值获得交点之间的曲线 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); GetCurveBetweenIntPoints(trans, btr, poly1, poly2, intPoints); trans.Commit(); } } }
StretchPoints() { m_db = Utils.Db.GetCurDwg(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Point3dCollection pts = new Point3dCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager; while (true) { PromptEntityResult prEntRes = ed.GetEntity("\nSelect entity to show stretch points"); if (prEntRes.Status != PromptStatus.OK) { break; } using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) { AcDb.Entity ent = (AcDb.Entity)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead); pts.Clear(); // reset to no points each time through loop ent.GetStretchPoints(pts); if (pts.Count == 0) { Utils.AcadUi.PrintToCmdLine("\nNo stretch points specified!"); } else { for (int i = 0; i < pts.Count; i++) { Utils.AcadUi.PrintToCmdLine(string.Format("\nSTRETCH[{0:d}]: {1}", i, Utils.AcadUi.PtToStr(pts[i]))); MakePointEnt(pts[i], 1, tr); } } tr.Commit(); } } }
public Entity CreateMesh() { // Get the data from the current model var vertices = _currentFaceModel.CalculateVerticesForAlignment( _currentFaceAlignment ); var indices = _currentFaceModel.TriangleIndices; // Copy the vertices to our point array var verts = new Point3dCollection(); for (int i = 0; i < vertices.Count; ++i) { var vert = vertices[i]; verts.Add(new Point3d(vert.X, vert.Y, -vert.Z)); } // Get our faces in the right format var faces = new Int32Collection(); for (int i = 0; i < indices.Count; i += 3) { faces.Add(3); faces.Add((int)indices[i]); faces.Add((int)(indices[i + 1])); faces.Add((int)(indices[i + 2])); } // Create and return the SubDMesh var sdm = new SubDMesh(); sdm.SetSubDMesh(verts, faces, 0); return(sdm); }
public static SqlBytes SerializeSqlGeographyMultiPoint(Point3dCollection points3d) { var result = ""; foreach (Point3d point in points3d) { if (points3d.IndexOf(point) == 0) { result = String.Format("MULTIPOINT (({0} {1} {2})", point.X, point.Y, point.Z); } result += String.Format(",({0} {1} {2})", point.X, point.Y, point.Z); } if (String.IsNullOrEmpty(result)) { return(null); } result += ")"; //, null)"; SqlGeometry multipoint = SqlGeometry.STMPointFromText(new SqlChars(result), 0); return(multipoint.Serialize()); }
public static Point3dCollection RetrieveLidarFile(DateTime time, string hole) { if (hole == null) { throw new ArgumentNullException(nameof(hole)); } DatabaseCommands command = new DatabaseCommands(); var path = command.GetPointPathByDate(time, hole); var dir = Path.GetDirectoryName(path); var name = Path.GetFileName(path); if (name == null) { throw new ArgumentNullException(nameof(name)); } Point3dCollection lidarpoints = CreateAllSurface.ReadPointCloudFile.ReadFile(dir, name); return(lidarpoints); }
private Point3dCollection filterSinks(ObjectIdCollection drops, double longest) { Point3dCollection sinks = new Point3dCollection(); foreach (ObjectId id in drops) { Polyline3d drop = id.GetObject(OpenMode.ForRead) as Polyline3d; if (drop.Length > (longest * .25)) { sinks.Add(drop.EndPoint); string msg = String.Format( "Sink located at: ({0},{1})\n", drop.EndPoint.X, drop.EndPoint.Y); write(msg); } } return(sinks); }
private void markSinks(Transaction ts, Point3dCollection sinks) { // now lets mark each endpoint BlockTable acBlkTbl = _database.BlockTableId .GetObject(OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec = acBlkTbl[BlockTableRecord.ModelSpace] .GetObject(OpenMode.ForWrite) as BlockTableRecord; // set the point style _document.Database.Pdmode = 35; _document.Database.Pdsize = 10; foreach (Point3d sink in sinks) { DBPoint sinkPoint = new DBPoint(sink); sinkPoint.Color = Color.FromRgb(0, 255, 255); sinkPoint.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(sinkPoint); ts.AddNewlyCreatedDBObject(sinkPoint, true); } }
/* * internal bool IsBelongs(LandPolygon curNeighbor) * { * foreach( PolygonSegment segmentNeighbor in curNeighbor.GetPolygonSegments()) * { * Point2d point = segmentNeighbor.MediumPoint; * if ( ! this.IsBelongs(point) ) * { * return false; * } * } * * return true; * * } * * internal bool IsBelongs(PolygonSegment segment) * { * throw new NotImplementedException(); * } * * internal bool IsBelongs(Point2d point) * { * Point2d findPoints = this.FindPoint(point); * if (findPoints != Point2d.Origin) * { * return true; * } * * List<Point2dCollection> points = new List<Point2dCollection>(); * * points.Add( * new Point2dCollection * ( * new Point2d[] * { point, point.Add( new Vector2d(0, 100000) ) } * * ) * ); * points.Add( * new Point2dCollection * ( * new Point2d[] * { point, point.Add( new Vector2d(0, -100000) ) } * * ) * ); * points.Add( * new Point2dCollection * ( * new Point2d[] * { point, point.Add( new Vector2d(100000, 0) ) } * * ) * ); * points.Add( * new Point2dCollection * ( * new Point2d[] * { point, point.Add( new Vector2d(-100000, 0) ) } * * ) * ); * * * AcDb.Polyline2d polygon = CAD.ServiceSimpleElements.CreatePolyline2d(this.Points,true); * * List<Point3dCollection> intersects = new List<Point3dCollection>(4); * Point3dCollection intersect; * * for (int i = 0; i < 4; i++) * { * intersect = new Point3dCollection(); * CAD.ServiceSimpleElements.CreatePolyline2d(points[i], false) * .IntersectWith(polygon, AcDb.Intersect.ExtendThis, intersect,IntPtr.Zero, IntPtr.Zero); * intersects.Add( DeleteDuplicatePoints(intersect) ); * } * * if ( * intersects[0].Count == intersects[1].Count * && intersects[2].Count == intersects[3].Count * && intersects[0].Count == intersects[3].Count * ) * { * if (intersects[0].Count % 2 == 0) return false; * else return true; * } * else * { * return false; * } * * } */ private Point3dCollection DeleteDuplicatePoints(Point3dCollection points) { Dictionary <int, Point3d> dicPoints = new Dictionary <int, Point3d>(); foreach (Point3d pnt in points) { if (!dicPoints.ContainsKey(pnt.GetHashCode())) { dicPoints.Add(pnt.GetHashCode(), pnt); } } Point3dCollection newPoints = new Point3dCollection(); foreach (KeyValuePair <int, Point3d> item in dicPoints) { newPoints.Add(item.Value); } return(newPoints); }
public static void book01() { Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction(); BlockTable bt = (BlockTable)tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); Point3d[] pts = new Point3d[]{ new Point3d(15.0, 12.0, 0.0), new Point3d(30.0, 44.0, 0.0), new Point3d(60.0, 10.0, 0.0), new Point3d(25.0, 30.0, 0.0) }; Point3dCollection points = new Point3dCollection(); for (int i = 0; i < 4; i++) { points.Add(pts[i]); } Spline spline = new Spline(points, 4, 0.0); btr.AppendEntity(spline); tr.AddNewlyCreatedDBObject(spline, true); tr.Commit(); tr.Dispose(); }
public KinectrotateCylinderJig( Document doc, Transaction tr, double profSide, double factor ) { // Initialise the various members _doc = doc; _tr = tr; _vertices = new Point3dCollection(); _lastDrawnVertex = -1; _resizing = false; _resizebool = 0; _drawing = false; leftHand = new Point3d(); rightHand = new Point3d(); leftHip = new Point3d(); _isRotate = false; vRot = new Vector3d(); _changeaxis = false; _firstdraw = 0; ct = 0; _created = new DBObjectCollection(); _profSide = profSide; _segFactor = factor; cube = new Solid3d(); cube.CreateFrustum(0.5, 0.5, 0.8,0.5); Words.Add("red"); Words.Add("green"); Words.Add("blue"); Words.Add("yellow"); Words.Add("pink"); Words.Add("magenta"); Words.Add("cyan"); }
public void GetGripPoints(Point3dCollection gripPoints, IntegerCollection snapModes, IntegerCollection geometryIds) { createInstance(); BaseEntity.GetGripPoints(gripPoints, snapModes,geometryIds); tr.Dispose(); }
public void GetObjectSnapPoints(ObjectSnapModes snapMode, int gsSelectionMark, Point3d pickPoint, Point3d lastPoint, Matrix3d viewTransform, Point3dCollection snapPoints, IntegerCollection geometryIds, Matrix3d insertionMat) { createInstance(); BaseEntity.GetObjectSnapPoints(snapMode, gsSelectionMark, pickPoint, lastPoint, viewTransform, snapPoints, geometryIds, insertionMat); tr.Dispose(); }
private Point3dCollection GetAllButLast( Point3dCollection pts, int n ) { Point3dCollection res = new Point3dCollection(); for (int i = 0; i < pts.Count - n; i++) { res.Add(pts[i]); } return res; }
// Helper functions to extract/blank portions of our // vertex list (when we want to draw the beginning of it) private void ClearAllButLast(Point3dCollection pts, int n) { while (pts.Count > n) { pts.RemoveAt(0); } _lastDrawnVertex = -1; }
private bool GenerateTube( double profRad, Point3dCollection pts, out Solid3d sol ) { bool readyToBreak; // Let's start by creating our spline path using (Spline path = new Spline(pts, 0, 0.0)) { double pathLen = path.GetDistanceAtParameter(path.EndParam); readyToBreak = (pathLen > _profSide * _segFactor); // And our sweep profile Circle profile = new Circle(pts[0], pts[1] - pts[0], profRad); using (profile) { // Then our sweep options SweepOptionsBuilder sob = new SweepOptionsBuilder(); // Align the entity to sweep to the path sob.Align = SweepOptionsAlignOption.AlignSweepEntityToPath; // The base point is the start of the path sob.BasePoint = path.StartPoint; // The profile will rotate to follow the path sob.Bank = true; using (SweepOptions sweepOpts = sob.ToSweepOptions()) { sol = new Solid3d(); sol.ColorIndex = ColorIndex; // Sweep our profile along our path sol.CreateSweptSolid(profile, path, sweepOpts); } } } _lastDrawnVertex = pts.Count - 1; return readyToBreak; }
public static ObjectId DrawGeometry(Point3dCollection pts, Boolean close = true) { ObjectId id = new ObjectId(); //Abrimos el documento activo Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; //Abrimos la BD Database dwg = doc.Database; //Se utiliza el using para cerrar la //transacción //El Transaction Manager administra las transacciones y se //encuentra dentro de la BD using (Transaction tr = dwg.TransactionManager.StartTransaction()) { try { //1: Abre el espacio activo de la aplicación BlockTableRecord currentSpace = (BlockTableRecord) dwg.CurrentSpaceId.GetObject(OpenMode.ForWrite); //2: Dibujar la geometría como una polilínea Polyline pl = new Polyline(); for (int i = 0; i < pts.Count; i++) pl.AddVertexAt(i, pts[i].Convert2d( new Plane(new Point3d(0, 0, 0), Vector3d.ZAxis)), 0, 0, 0); pl.Closed = close; pl.Color = Color.FromRgb(0, 255, 0); //3: Anexar geometría al espacio currentSpace.AppendEntity(pl); tr.AddNewlyCreatedDBObject(pl, true); tr.Commit(); } catch (Exception exc) { //Si algo sale mal aborta ed.WriteMessage(exc.Message); tr.Abort(); } } return id; }
public void BoundingBoxIntersectWith(Entity entityPointer, Intersect intersectType, Point3dCollection points, IntPtr thisGraphicSystemMarker, IntPtr otherGraphicSystemMarker) { createInstance(); BaseEntity.BoundingBoxIntersectWith(entityPointer, intersectType,points,thisGraphicSystemMarker,otherGraphicSystemMarker); tr.Dispose(); }
public void GetStretchPoints(Point3dCollection stretchPoints) { createInstance(); BaseEntity.GetStretchPoints(stretchPoints); tr.Dispose(); }
public void IntersectWith(Entity entityPointer, Intersect intersectType, Plane projectionPlane, Point3dCollection points, long thisGraphicSystemMarker, long otherGraphicSystemMarker) { createInstance(); BaseEntity.IntersectWith(entityPointer, intersectType, projectionPlane, points, thisGraphicSystemMarker, otherGraphicSystemMarker); tr.Dispose(); }
private void Create_symbol1() { string blockName = "symbol1"; DBObjectCollection entityCollection = new DBObjectCollection(); Line ent1 = new Line(new Point3d(0, 0.12, 0), new Point3d(0, -0.12, 0)); ent1.Layer = "0"; entityCollection.Add(ent1); Point3dCollection verties = new Point3dCollection(); verties.Add(new Point3d(0, 0, 0)); verties.Add(new Point3d(0.077, 0.064, 0)); verties.Add(new Point3d(0.077, -0.064, 0)); verties.Add(new Point3d(0, 0, 0)); Polyline2d ent2 = new Polyline2d(Poly2dType.SimplePoly, verties, 0, false, 0, 0, new DoubleCollection(new double[] { 0, 0, 0, 0 })); ent2.Layer = "0"; entityCollection.Add(ent2); TryInsertBlockRecord(blockName, entityCollection); }
public void GetIntersectionsRiver() { Database db = HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); #region For Word string filepath = "D:\\intersections_rivers.docx"; using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { try { // Add a main document part. MainDocumentPart mainPart = docX.AddMainDocumentPart(); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles1 = new Styles(); DocDefaults docDefaults = new DocDefaults( new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" })), new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto })); styles1.AppendChild(docDefaults); styleDefinitionsPart.Styles = styles1; mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body()); ParagraphProperties paragraphProperties1 = new ParagraphProperties( new Justification() { Val = JustificationValues.Center }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" } )); Paragraph para = body.AppendChild(new Paragraph()); para.AppendChild(paragraphProperties1); Run run = para.AppendChild(new Run()); RunProperties runProperties1 = new RunProperties( new Bold()); // String msg contains the text, "Hello, Word!" run.AppendChild(runProperties1); run.AppendChild(new Text("ПРИЛОЖЕНИЕ")); run.AppendChild(new Break()); run.AppendChild(new Text("Ведомость пересечений")); run.AppendChild(new Break()); var table = new DocumentFormat.OpenXml.Wordprocessing.Table(); // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa }, new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa }, new TableBorders( new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }), new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" } ); // Append the TableProperties object to the empty table. table.AppendChild<TableProperties>(tblProp); // Add 3 columns to the table. TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn()); table.AppendChild(tg); TableRow tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 430 }), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Наимен. водотока")))), //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"}) new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Пикетное положение пересечения")))), new TableCell( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Ширина водотока в межень")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new VerticalMerge() { Val = MergedCellValues.Restart }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Глуб. водотока")))), new TableCell( new TableCellProperties( new GridSpan() { Val = 3 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Горизонт воды")))), new TableCell(new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим.")))) ); table.AppendChild(tr1); TableRow tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 419 }), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run()))); table.AppendChild(tr2); TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 }); #endregion while (true) { //using (tr) //{ try { #region Поиск пересечений BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline >>"); peo.SetRejectMessage("\nМожно только polyline >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { break; } DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) return; PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for the start point pPtOpts.Message = "\nВведи начало: "; pPtRes = doc.Editor.GetPoint(pPtOpts); PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): "); PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik); //zoom /*PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) return;*/ // Extract its extents Extents3d ext; Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead); ext = enti.GeometricExtents; trans.Commit(); } ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse()); ZoomWin(ed, ext.MinPoint, ext.MaxPoint); // //Polyline poly = (Polyline)ent as Polyline; Curve curv = ent as Curve; DBObjectCollection pcurves = new DBObjectCollection(); curv.Explode(pcurves); TypedValue[] values = new TypedValue[] { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; SelectionFilter filter = new SelectionFilter(values); Point3dCollection fence = new Point3dCollection(); double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection double step = leng / 256;// set number of steps to your suit int num = Convert.ToInt32(leng / step); for (int i = 0; i < num; i++) { Point3d pp = curv.GetPointAtDist(step * i); fence.Add(curv.GetClosestPointTo(pp, false)); } PromptSelectionResult selres = ed.SelectFence(fence, filter); if (selres.Status != PromptStatus.OK) return; Point3dCollection intpts = new Point3dCollection(); DBObjectCollection qcurves = new DBObjectCollection(); //ed.WriteMessage("\nCheck"); foreach (SelectedObject selobj in selres.Value) { DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject; if (selobj.ObjectId != curv.ObjectId) { DBObjectCollection icurves = new DBObjectCollection(); Curve icurv = obj as Curve; icurv.Explode(icurves); foreach (DBObject dbo in icurves) { if (!qcurves.Contains(dbo)) qcurves.Add(dbo); } } } //ed.WriteMessage("\n{0}", qcurves.Count); int j = 0; Point3dCollection polypts = new Point3dCollection(); for (int i = 0; i < pcurves.Count; ++i) { for (j = 0; j < qcurves.Count; ++j) { Curve curve1 = pcurves[i] as Curve; Curve curve2 = qcurves[j] as Curve; Point3dCollection pts = new Point3dCollection(); curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); foreach (Point3d pt in pts) { if (!polypts.Contains(pt)) polypts.Add(pt); } } } #endregion try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new ParagraphMarkRunProperties(new Bold()), new Justification() { Val = JustificationValues.Center }), new Run(new RunProperties( new Bold()), new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" + ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" + ((100 * getpikRes.Value + pline.Length) % 100).ToString("F"))))))); } } catch { ed.WriteMessage("\nError."); } Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional // for debug only Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count)); if (polypts.Count == 0) { try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text("На данном участке трассы пересечения отсутствуют")))))); } } catch { ed.WriteMessage("\nError."); } } else { //List<double> pik = new List<double>(polypts.Count); double[] pik = new double[polypts.Count]; int numInter = 0; foreach (Point3d inspt in polypts) { double dist = 0; dist = 100 * getpikRes.Value; // test for visulization only /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt); circ.ColorIndex = 1; btr.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true);*/ Point3d curr = pPtRes.Value, next = pPtRes.Value; try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint)) for (int i = 0; i < pline.NumberOfVertices - 2; i++) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } else for (int i = pline.NumberOfVertices - 3; i >= 0; i--) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } } } catch { ed.WriteMessage("\nInvalid polyline."); } pik[numInter] = dist; numInter++; //ed.WriteMessage(" {0:0.00}\n", dist); } //pik.Sort(); Array.Sort(pik); for (int i = 0; i < polypts.Count; i++) { tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } } } catch { ed.WriteMessage("\nError"); } //} } tr.Commit(); body.AppendChild(table); body.AppendChild( new SectionProperties( new PageMargin() { Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1418U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U })); ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx"); } catch { ed.WriteMessage("\nError."); } } }
public static Polyline GetOffsetPolyline(Polyline line, bool IsLeftComp, double r) { Polyline newLine = new Polyline(); double offsetValue = (IsLeftComp) ? -r : r; for (int i = 1; i <= line.NumberOfVertices - 1; i++) { Polyline pl1 = new Polyline(); pl1.AddVertexAt(0, line.GetPoint2dAt(i - 1), line.GetBulgeAt(i - 1), 0, 0); pl1.AddVertexAt(1, line.GetPoint2dAt(i), line.GetBulgeAt(i), 0, 0); Polyline pl1Offset = pl1.GetOffsetCurves(offsetValue)[0] as Polyline; AddToDrawing(pl1Offset);//debug if (i == 1)//第一点,且当前曲线并不是封闭的 { newLine.AddVertexAt(0, new Point2d(pl1Offset.StartPoint.X, pl1Offset.StartPoint.Y), 0, 0, 0); if (line.NumberOfVertices == 2)//如果只是一条线的话 { newLine.AddVertexAt(0, new Point2d(pl1Offset.EndPoint.X, pl1Offset.EndPoint.Y), -pl1Offset.GetBulgeAt(0), 0, 0); } } if (line.NumberOfVertices > 2 && i < line.NumberOfVertices - 1) { Polyline pl2 = new Polyline(); pl2.AddVertexAt(0, line.GetPoint2dAt(i), line.GetBulgeAt(i), 0, 0); pl2.AddVertexAt(1, line.GetPoint2dAt(i + 1), line.GetBulgeAt(i + 1), 0, 0); Polyline pl2Offset = pl2.GetOffsetCurves(offsetValue)[0] as Polyline; AddToDrawing(pl2Offset);//debug //两个偏移后的Polyline进行相交 Point3dCollection points = new Point3dCollection(); pl2Offset.IntersectWith(pl1Offset, Intersect.ExtendBoth, points, IntPtr.Zero, IntPtr.Zero); Point2d TheIntersectPoint; if (points.Count == 0) { //无交点,只存在于两个在同一根直线上的情况 //或者同一个圆上 newLine.AddVertexAt(0, pl1Offset.GetPoint2dAt(1), -pl1Offset.GetBulgeAt(1), 0, 0); continue; } else if (points.Count == 1) TheIntersectPoint = new Point2d(points[0].X, points[0].Y);//1个交点,说明是直线和直线相交 else { //2个交点,那就需要判断是哪一个了 //与pl2offset的终点进行比较,距离较近的那个就是了 double dist1 = points[0].DistanceTo(pl2.StartPoint); double dist2 = points[1].DistanceTo(pl2.StartPoint); if (dist1 > dist2) TheIntersectPoint = new Point2d(points[1].X, points[1].Y); else TheIntersectPoint = new Point2d(points[0].X, points[0].Y); } double newBulge = GetOffsetCurveBulge.Get(IsLeftComp, r, line, TheIntersectPoint, i, pl1Offset.GetPoint2dAt(0)); newLine.AddVertexAt(0, TheIntersectPoint, newBulge, 0, 0); if (i == line.NumberOfVertices - 2)//最后一个点的时候 { double bulge = GetOffsetCurveBulge.Get(IsLeftComp, r, line, pl2Offset.GetPoint2dAt(1), i + 1, pl2Offset.GetPoint2dAt(0)); newLine.AddVertexAt(0, new Point2d(pl2Offset.EndPoint.X, pl2Offset.EndPoint.Y), bulge, 0, 0); } pl2.Dispose(); pl2Offset.Dispose(); } pl1.Dispose(); pl1Offset.Dispose(); } ReversePolyline(newLine); // newLine.ReverseCurve();//反转多段线 return newLine; }
public virtual DBObjectCollection GetSplitCurves(Point3dCollection points) { createInstance(); DBObjectCollection GetSplitC = BaseCurve.GetSplitCurves(points); tr.Dispose(); return GetSplitC; }