insertCurve(ObjectId idAlign) { Alignment align = (Alignment)idAlign.getEnt(); AlignmentEntityCollection ents = align.Entities; PromptStatus ps; Point3d pnt3dPick = UserInput.getPoint("Select Curve PI", out ps, osMode: 1); AlignmentEntity lineBefore = null; AlignmentEntity lineAfter = null; for (int i = 0; i < ents.Count; i++) { AlignmentEntity ent = ents[i]; if (ent.EntityType == AlignmentEntityType.Line) { AlignmentLine line = (AlignmentLine)ent; if (line.EndPoint.IsEqualTo(pnt3dPick.Convert2d(BaseObjs.xyPlane), new Tolerance(.01, .01))) { lineBefore = line; } if (line.StartPoint.IsEqualTo(pnt3dPick.Convert2d(BaseObjs.xyPlane), new Tolerance(.01, .01))) { lineAfter = line; } } } AlignmentArc arc = ents.AddFreeCurve(lineBefore.EntityId, lineAfter.EntityId, 200.0, CurveParamType.Radius, false, CurveType.Compound); List <AlgnEntData> algnEntData = sortAlignEnts(align); fAlignEnts.updateForm(algnEntData); fAlignEnts.AlignHandle = align.Handle; Application.ShowModelessDialog(Application.MainWindow.Handle, fAlignEnts, false); }
protected override bool Update() { Polyline pline = Entity as Polyline; pline.SetPointAt(pline.NumberOfVertices - 1, m_tempPoint.Convert2d(m_plane)); return(true); }
/// <summary> /// Returns the tangents between the active CircularArc3d instance complete circle and a point. /// </summary> /// <remarks> /// Tangents start points are on the object to which this method applies, end points on the point passed as argument. /// Tangents are always returned in the same order: the tangent on the left side of the line from the circular arc /// center /// to the point before the one on the right side. /// </remarks> /// <param name="arc">The instance to which this method applies.</param> /// <param name="pt">The Point3d to which tangents are searched</param> /// <returns>An array of LineSegement3d representing the tangents (2) or null if there is none.</returns> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"> /// eNonCoplanarGeometry is thrown if the objects do not lies on the same plane. /// </exception> public static LineSegment3d[] GetTangentsTo(this CircularArc3d arc, Point3d pt) { // check if arc and point lies on the plane var normal = arc.Normal; var wcs2Ocs = Matrix3d.WorldToPlane(normal); var elevation = arc.Center.TransformBy(wcs2Ocs).Z; if (Math.Abs(elevation - pt.TransformBy(wcs2Ocs).Z) < Tolerance.Global.EqualPoint) { throw new Exception( ErrorStatus.NonCoplanarGeometry); } var plane = new Plane(Point3d.Origin, normal); _ = Matrix3d.PlaneToWorld(plane); var ca2D = new CircularArc2d(arc.Center.Convert2d(plane), arc.Radius); var lines2D = ca2D.GetTangentsTo(pt.Convert2d(plane)); if (lines2D == null) { return(null); } var result = new LineSegment3d[lines2D.Length]; for (var i = 0; i < lines2D.Length; i++) { var ls2D = lines2D[i]; result[i] = new LineSegment3d(ls2D.StartPoint.Convert3D(normal, elevation), ls2D.EndPoint.Convert3D(normal, elevation)); } return(result); }
/// <summary> /// Returns the tangents between the active CircularArc3d instance complete circle and a point. /// </summary> /// <remarks> /// Tangents start points are on the object to which this method applies, end points on the point passed as argument. /// Tangents are always returned in the same order: the tangent on the left side of the line from the circular arc center /// to the point before the one on the right side. /// </remarks> /// <param name="arc">The instance to which this method applies.</param> /// <param name="pt">The Point3d to which tangents are searched</param> /// <returns>An array of LineSegement3d representing the tangents (2) or null if there is none.</returns> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"> /// eNonCoplanarGeometry is thrown if the objects do not lies on the same plane.</exception> public static LineSegment3d[]? GetTangentsTo([NotNull] this CircularArc3d arc, Point3d pt) { // check if arc and point lies on the plane var normal = arc.Normal; var WCS2OCS = Matrix3d.WorldToPlane(normal); var elevation = arc.Center.TransformBy(WCS2OCS).Z; if (Math.Abs(elevation - pt.TransformBy(WCS2OCS).Z) < Tolerance.Global.EqualPoint) { throw new Autodesk.AutoCAD.Runtime.Exception( Autodesk.AutoCAD.Runtime.ErrorStatus.NonCoplanarGeometry); } var plane = new Plane(Point3d.Origin, normal); var ca2d = new CircularArc2d(arc.Center.Convert2d(plane), arc.Radius); var lines2d = ca2d.GetTangentsTo(pt.Convert2d(plane)); if (lines2d == null) { return(null); } var result = new LineSegment3d[lines2d.Length]; for (var i = 0; i < lines2d.Length; i++) { var ls2d = lines2d[i]; result[i] = new LineSegment3d(ls2d.StartPoint.Convert3d(normal, elevation), ls2d.EndPoint.Convert3d(normal, elevation)); } return(result); }
/// <summary> /// Updates this instance. /// </summary> /// <returns></returns> protected override bool Update() { Polyline poly = Entity as Polyline; poly.SetPointAt(poly.NumberOfVertices - 1, pnt3dTmp.Convert2d(plane)); return(true); }
private void UpdatePolyline() { Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs; Plane ucsPlane = new Plane(Point3d.Origin, Vector3d.ZAxis); Point2d p1 = Intersect(mp0.Convert2d(ucsPlane), mt0.Convert2d(ucsPlane), mp2.Convert2d(ucsPlane), mt2.Convert2d(ucsPlane)); Point3dCollection points = new Point3dCollection(); for (int i = 0; i <= mSegments; i++) { double t = (double)i / (double)mSegments; // Quadratic bezier curve with control vertices p0, p1 and p2 double x = (1 - t) * (1 - t) * mp0.X + 2 * (1 - t) * t * p1.X + t * t * mp2.X; double y = (1 - t) * (1 - t) * mp0.Y + 2 * (1 - t) * t * p1.Y + t * t * mp2.Y; points.Add(new Point3d(x, y, 0)); // Coordinates in UCS } Polyline pline = Entity as Polyline; Plane plinePlane = new Plane(Point3d.Origin, pline.Normal); pline.Reset(false, points.Count); foreach (Point3d pt in points) { Point3d wcsPt = pt.TransformBy(ucs2wcs); // Convert to WCS Point2d ecsPt = plinePlane.ParameterOf(wcsPt); // Convert to ECS pline.AddVertexAt(pline.NumberOfVertices, ecsPt, 0, 0, 0); } }
/// <summary> /// Returns the tangents between the active CircularArc3d instance complete circle and a point. /// </summary> /// <remarks> /// Tangents start points are on the object to which this method applies, end points on the point passed as argument. /// Tangents are always returned in the same order: the tangent on the left side of the line from the circular arc center /// to the point before the one on the right side. /// </remarks> /// <param name="arc">The instance to which this method applies.</param> /// <param name="pt">The Point3d to which tangents are searched</param> /// <returns>An array of LineSegement3d representing the tangents (2) or null if there is none.</returns> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"> /// eNonCoplanarGeometry is thrown if the objects do not lies on the same plane.</exception> public static LineSegment3d[] GetTangentsTo(this CircularArc3d arc, Point3d pt) { // check if arc and point lies on the plane Vector3d normal = arc.Normal; Matrix3d WCS2OCS = Matrix3d.WorldToPlane(normal); double elevation = arc.Center.TransformBy(WCS2OCS).Z; if (Math.Abs(elevation - pt.TransformBy(WCS2OCS).Z) < Tolerance.Global.EqualPoint) throw new Autodesk.AutoCAD.Runtime.Exception( Autodesk.AutoCAD.Runtime.ErrorStatus.NonCoplanarGeometry); Plane plane = new Plane(Point3d.Origin, normal); Matrix3d OCS2WCS = Matrix3d.PlaneToWorld(plane); CircularArc2d ca2d = new CircularArc2d(arc.Center.Convert2d(plane), arc.Radius); LineSegment2d[] lines2d = ca2d.GetTangentsTo(pt.Convert2d(plane)); if (lines2d == null) return null; LineSegment3d[] result = new LineSegment3d[lines2d.Length]; for (int i = 0; i < lines2d.Length; i++) { LineSegment2d ls2d = lines2d[i]; result[i] = new LineSegment3d(ls2d.StartPoint.Convert3d(normal, elevation), ls2d.EndPoint.Convert3d(normal, elevation)); } return result; }
/// <summary> /// Creates a new Polyline that is the result of projecting the polyline parallel to 'direction' onto 'plane' and returns it. /// </summary> /// <param name="pline">The polyline (any type) to project.</param> /// <param name="plane">The plane onto which the curve is to be projected.</param> /// <param name="direction">Direction (in WCS coordinates) of the projection.</param> /// <returns>The projected Polyline.</returns> internal static Polyline ProjectPolyline(Curve pline, Plane plane, Vector3d direction) { if (!(pline is Polyline) && !(pline is Polyline2d) && !(pline is Polyline3d)) { return(null); } plane = new Plane(Point3d.Origin.OrthoProject(plane), direction); using (DBObjectCollection oldCol = new DBObjectCollection()) using (DBObjectCollection newCol = new DBObjectCollection()) { pline.Explode(oldCol); foreach (DBObject obj in oldCol) { Curve crv = obj as Curve; if (crv != null) { Curve flat = crv.GetProjectedCurve(plane, direction); newCol.Add(flat); } obj.Dispose(); } PolylineSegmentCollection psc = new PolylineSegmentCollection(); for (int i = 0; i < newCol.Count; i++) { if (newCol[i] is Ellipse) { psc.AddRange(new PolylineSegmentCollection((Ellipse)newCol[i])); continue; } Curve crv = (Curve)newCol[i]; Point3d start = crv.StartPoint; Point3d end = crv.EndPoint; double bulge = 0.0; if (crv is Arc) { Arc arc = (Arc)crv; double angle = arc.Center.GetVectorTo(start).GetAngleTo(arc.Center.GetVectorTo(end), arc.Normal); bulge = Math.Tan(angle / 4.0); } psc.Add(new PolylineSegment(start.Convert2d(plane), end.Convert2d(plane), bulge)); } foreach (DBObject o in newCol) { o.Dispose(); } Polyline projectedPline = psc.Join(new Tolerance(1e-9, 1e-9))[0].ToPolyline(); projectedPline.Normal = direction; projectedPline.Elevation = plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z; if (!pline.StartPoint.Project(plane, direction).IsEqualTo(projectedPline.StartPoint, new Tolerance(1e-9, 1e-9))) { projectedPline.Normal = direction = direction.Negate(); projectedPline.Elevation = plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z; } return(projectedPline); } }
public static void ReplaceVertexAt(this Polyline pline, int index, Point3d point, double bulge, double startWidth, double endWidth) { if (pline.NumberOfVertices <= index) { return; } pline.AddVertexAt(index + 1, point.Convert2d(), bulge, startWidth, endWidth); pline.RemoveVertexAt(index); }
protected override bool Update() { // Update the dummy vertex to be our // 3D point projected onto our plane Polyline pline = Entity as Polyline; pline.SetPointAt(pline.NumberOfVertices - 1, m_tempPoint.Convert2d(m_plane)); return(true); }
/// <summary> /// Get angle of pnt1-pnt2 line to horizontal axis /// </summary> /// <param name="pnt1"></param> /// <param name="pnt2"></param> /// <returns></returns> public static double AngleFromXAxisInXYPlane( Point3d firstPoint, Point3d secondPoint) { Vector3d normal = new Vector3d(0, 0, 1); Plane plane = new Plane(new Point3d(0, 0, 0), normal); Point2d p1, p2; p1 = firstPoint.Convert2d(plane); p2 = secondPoint.Convert2d(plane); return(p1.GetVectorTo(p2).Angle); }
// Funkcje do rysowani polilinii ... protected override bool Update() { // Update the dummy vertex to be our 3D point // projected onto our plane Polyline pl = Entity as Polyline; if (pl.NumberOfVertices > 1) { pl.SetBulgeAt(pl.NumberOfVertices - 2, 0); } pl.SetPointAt(pl.NumberOfVertices - 1, _tempPoint.Convert2d(_plane)); return(true); }
protected override bool Update() { // Update the dummy vertex to be our // 3D point projected onto our plane Polyline pline = Entity as Polyline; pline.ConstantWidth = HeatSourceLayoutApp.globalProperty.BuildingOutlineWidth; pline.SetPointAt( pline.NumberOfVertices - 1, m_tempPoint.Convert2d(m_plane) ); return(true); }
public static void ZoomTo(Point3d point) { if (!IsModelSpaceActive) { return; } using (var trans = StartTransaction()) using (var currView = Editor.GetCurrentView()) { currView.CenterPoint = point.Convert2d(); Editor.SetCurrentView(currView); trans.Commit(); } }
///// <summary> ///// Начальный угол в плане (радиан). Начальное значение = 0 - восход. ///// Будут определены для этой расвчетной точки индивидуально ///// </summary> //public double AngleStartOnPlane { get; private set; } ///// <summary> ///// Конечный угол в плане (радиан). Начальное значение = 180 - заход ///// </summary> //public double AngleEndOnPlane { get; private set; } public CalcPointCentral(InsPoint insPt, CalcServiceCentral insCalcService) { this.map = insPt.Model.Map; buildingOwner = insPt.Building; this.insPt = insPt; ptCalc = insPt.Point; ptCalc2d = ptCalc.Convert2d(); this.calc = insCalcService; values = insCalcService.CalcValues; //AngleStartOnPlane = values.SunCalcAngleStartOnPlane; //AngleEndOnPlane = values.SunCalcAngleEndOnPlane; StartAnglesIllum = new IllumAreaBase(insPt, ptCalc2d, values.SunCalcAngleStartOnPlane, values.SunCalcAngleEndOnPlane, Point2d.Origin, Point2d.Origin); }
protected void InsertArrowBlRef(Point3d ptArrowBlPos, Point3d ptArrowDirect, bool doTrans, Matrix3d trans) { // Вставка стрелки и направление ее на указанную точку if (!panelBase.Service.Env.IdBtrArrow.IsNull) { if (doTrans) { ptArrowBlPos = ptArrowBlPos.TransformBy(trans); ptArrowDirect = ptArrowDirect.TransformBy(trans); } // вставка блока стрелки var blRefArrow = CreateBlRefInBtrDim(ptArrowBlPos, panelBase.Service.Env.IdBtrArrow, Settings.Default.SheetScale); if (blRefArrow == null) { return; } // поворот стрелки и установка длины Vector2d vecArrow = ptArrowDirect.Convert2d() - ptArrowBlPos.Convert2d(); blRefArrow.Rotation = vecArrow.Angle; // длина стрелки setDynParam(blRefArrow, "Длина", vecArrow.Length); } }
public SquareJig(Point3d first) : base(new Polyline()) { // Store the first point _fstPt = first; // And draw a pline using this point Point2d firstPointPlane = first.Convert2d(new Plane()); Polyline pline = base.Entity as Polyline; pline.AddVertexAt(0, firstPointPlane, 0, 0, 0); pline.AddVertexAt( 1, firstPointPlane.Add(new Vector2d(10, 0)), 0, 0, 0 ); pline.AddVertexAt( 2, firstPointPlane.Add(new Vector2d(10, 10)), 0, 0, 0 ); pline.AddVertexAt( 3, firstPointPlane.Add(new Vector2d(0, 10)), 0, 0, 0 ); pline.Closed = true; }
private static void placementAparts(Database db) { using (var t = db.TransactionManager.StartTransaction()) { ObjectId idTextStylePik = db.GetTextStylePIK(); var bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; var ms = bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord; int countAparts; var btrApartGroups = getGroupedAparts(bt, out countAparts); Point3d pt = Point3d.Origin; Point3d ptCenterPlace; using (var progress = new ProgressMeter()) { progress.SetLimit(countAparts); progress.Start("Расстановка квартир..."); foreach (var btrApartGroup in btrApartGroups) { progress.MeterProgress(); foreach (var idBtrApart in btrApartGroup) { var curPlaceWidth = placeWidth; var blRefApart = new BlockReference(pt, idBtrApart); blRefApart.SetDatabaseDefaults(db); var extApart = blRefApart.GeometricExtents; var lenApart = extApart.MaxPoint.X - extApart.MinPoint.X; if (lenApart > placeWidth) { curPlaceWidth = lenApart + 1000; } ptCenterPlace = new Point3d(pt.X + curPlaceWidth * 0.5, pt.Y - placeHeight * 0.5, 0); var ptBlCenter = extApart.Center(); // Перемещение блока в центр прямоугольной области Matrix3d displace = Matrix3d.Displacement(ptCenterPlace - ptBlCenter); blRefApart.TransformBy(displace); ms.AppendEntity(blRefApart); t.AddNewlyCreatedDBObject(blRefApart, true); // Подпись квартиры DBText text = new DBText(); text.SetDatabaseDefaults(); text.TextStyleId = idTextStylePik; text.Height = 900; text.TextString = getApartName(blRefApart.Name); text.Position = new Point3d(pt.X + 300, pt.Y + 300, 0); ms.AppendEntity(text); t.AddNewlyCreatedDBObject(text, true); // Прямоугольник расположения квартиры Polyline pl = new Polyline(4); pl.AddVertexAt(0, pt.Convert2d(), 0, 0, 0); pl.AddVertexAt(1, new Point2d(pt.X + curPlaceWidth, pt.Y), 0, 0, 0); pl.AddVertexAt(2, new Point2d(pt.X + curPlaceWidth, pt.Y - placeHeight), 0, 0, 0); pl.AddVertexAt(3, new Point2d(pt.X, pt.Y - placeHeight), 0, 0, 0); pl.Closed = true; pl.SetDatabaseDefaults(); ms.AppendEntity(pl); t.AddNewlyCreatedDBObject(pl, true); pt = new Point3d(pt.X + curPlaceWidth, pt.Y, 0); } pt = new Point3d(0, pt.Y - placeHeight - 8000, 0); } progress.Stop(); } t.Commit(); } }
protected void InsertArrowBlRef(Point3d ptArrowBlPos, Point3d ptArrowDirect, bool doTrans, Matrix3d trans) { // Вставка стрелки и направление ее на указанную точку if (!panelBase.Service.Env.IdBtrArrow.IsNull) { if (doTrans) { ptArrowBlPos = ptArrowBlPos.TransformBy(trans); ptArrowDirect = ptArrowDirect.TransformBy(trans); } // вставка блока стрелки var blRefArrow = CreateBlRefInBtrDim(ptArrowBlPos, panelBase.Service.Env.IdBtrArrow, Settings.Default.SheetScale); if (blRefArrow == null) return; // поворот стрелки и установка длины Vector2d vecArrow = ptArrowDirect.Convert2d() - ptArrowBlPos.Convert2d(); blRefArrow.Rotation = vecArrow.Angle; // длина стрелки setDynParam(blRefArrow, "Длина", vecArrow.Length); } }
TP2() { Point3d pnt3d1 = UserInput.getPoint("\nPick Corner 1: ", Pub.pnt3dO, out escaped, out ps, osMode: 0); if (pnt3d1 == Pub.pnt3dO) { return; } Point3d pnt3d2 = UserInput.getPoint("\nPick Baseline direction: ", pnt3d1, out escaped, out ps, osMode: 0); if (pnt3d1 == Pub.pnt3dO) { return; } Vector2d v2dX = pnt3d2.Convert2d(BaseObjs.xyPlane) - pnt3d1.Convert2d(BaseObjs.xyPlane); Vector2d v2dY = v2dX.RotateBy(System.Math.PI / 2); Vector3d v3dY = new Vector3d(v2dY.X, v2dY.Y, 0); Point3d pnt3dY = pnt3d1 + v3dY; Matrix3d m3d = UCsys.addUCS(pnt3d1, pnt3d2, "temp"); Point3d pnt3d0 = Db.wcsToUcs(pnt3d1); Polyline poly = jigPolylineArea(pnt3d0); UCsys.setUCS2World(); poly.ObjectId.transformToWcs(BaseObjs._db); escaped = UserInput.getUserInputDoubleAsString("\nEnter Elevation: ", out elev, elev); if (escaped) { return; } escaped = UserInput.getUserInputDoubleAsString("\nEnter Slope: ", out slope, slope); if (escaped) { return; } double dblSlope = double.Parse(slope); Point3d pnt3dCEN = poly.getCentroid(); Point3d pnt3dTAR = UserInput.getPoint("\nPick edge of polygon in the Direction of Increasing Slope: ", pnt3dCEN, out escaped, out ps, osMode: 641); if (pnt3dTAR == Pub.pnt3dO) { return; } ObjectIdCollection idspoly3d = new ObjectIdCollection(); double dblDist = 0.0; ObjectId idPoly3d = ObjectId.Null; pnt3dCEN = pnt3dCEN.addElevation(double.Parse(elev)); if (pnt3dTAR != Pub.pnt3dO) { dblDist = pnt3dCEN.getDistance(pnt3dTAR); } string nameLayer = string.Format("{0}-BORDER", "BASIN"); Layer.manageLayers(nameLayer); int numObj = 0; bool exists = false; ObjectId idDict = Dict.getNamedDictionary(apps.lnkBrks, out exists); if (exists) { numObj = idDict.getDictEntries().Count; } string nameSurf = string.Format("{0}{1}", "BASIN", numObj.ToString("00")); ObjectId idDictObj = Dict.addSubDict(idDict, nameSurf); using (BaseObjs._acadDoc.LockDocument()) { if (pnt3dTAR != Pub.pnt3dO) { pnt3dTAR = new Point3d(pnt3dTAR.X, pnt3dTAR.Y, pnt3dCEN.Z + dblDist * dblSlope); idPoly3d = Base_Tools45.C3D.DrawBasinBot.build3dPolyBasinBot(poly.ObjectId, pnt3dCEN, pnt3dTAR, dblSlope, nameLayer, apps.lnkBrks); } else { idPoly3d = Conv.poly_Poly3d(poly.ObjectId, double.Parse(elev), nameLayer); } idspoly3d.Add(idPoly3d); TinSurface surf = Surf.addTinSurface(nameSurf, out exists); if (exists) { Application.ShowAlertDialog(string.Format("Surface Name conflict - surface \"{0}\" already exists. Exiting...", nameSurf)); return; } surf.BreaklinesDefinition.AddStandardBreaklines(idspoly3d, 1.0, 0.0, 0.0, 0.0); surf.Rebuild(); } using (BaseObjs._acadDoc.LockDocument()) { BaseObjs.regen(); } }
public void cout() { Editor ed = acDoc.Editor; //Prompt options for running line PromptEntityOptions peo = new PromptEntityOptions("Select Running Line"); peo.SetRejectMessage("Running line not selected"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult perRunningLine = ed.GetEntity(peo); if (perRunningLine.Status != PromptStatus.OK) { return; } PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Line Number: "); pStrOpts.AllowSpaces = false; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); while (true) { Transaction trans = acCurDb.TransactionManager.StartTransaction(); using (trans) { // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = trans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = trans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //prompt for the block PromptEntityOptions peo2 = new PromptEntityOptions("\nSelect Block"); peo2.SetRejectMessage("\nnot a block"); peo2.AddAllowedClass(typeof(BlockReference), false); PromptEntityResult perBlock = ed.GetEntity(peo2); if (perBlock.Status != PromptStatus.OK) { return; } Polyline runningLine = trans.GetObject(perRunningLine.ObjectId, OpenMode.ForRead) as Polyline; BlockReference blkRef = trans.GetObject(perBlock.ObjectId, OpenMode.ForRead) as BlockReference; string str = String.Format("{0:0}", runningLine.GetDistAtPoint(blkRef.Position)); switch (str.Length) { case 1: str = "0+0" + str; break; case 2: str = "0+" + str; break; default: str = str.Substring(0, str.Length - 2) + "+" + str.Substring(str.Length - 2); break; } if (pStrRes.StringResult != "") { str = str + " LINE " + pStrRes.StringResult; } //prompt for insertion point PromptPointOptions pPtOpt = new PromptPointOptions("\nEnter Insertion Point"); PromptPointResult pPtRes = ed.GetPoint(pPtOpt); Point3d insPt = pPtRes.Value; CoordinateSystem3d cs = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d; Plane plane = new Plane(Point3d.Origin, cs.Zaxis); //create polyline Polyline rec = new Polyline(); rec.AddVertexAt(0, insPt.Convert2d(plane), 0, 0, 0); bool Xdir = true; bool Ydir = true; if (insPt.X < blkRef.Position.X) { Xdir = false; } // if (insPt.Y < blkRef.Position.Y) { Ydir = false; } if (Xdir) { if (Ydir) { //quadrant I rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant IV rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } else { if (Ydir) { //quadrant II rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant III rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } rec.Closed = true; rec.SetDatabaseDefaults(); //create leader Leader leader = new Leader(); leader.SetDatabaseDefaults(); leader.Layer = "DESIGN"; //create for station MText txt = new MText(); txt.SetDatabaseDefaults(); txt.Contents = "STA " + str; txt.Layer = "TEXT-2"; txt.TextHeight = 2.2; txt.Layer = "TEXT-2"; //body MText acMText = new MText(); acMText.SetDatabaseDefaults(); acMText.TextHeight = 2.2; acMText.Layer = "TEXT-2"; if (Xdir) { if (Ydir) { txt.Location = new Point3d(insPt.X + 1.33, insPt.Y + 11.1833, 0); txt.Attachment = AttachmentPoint.BottomLeft; acMText.Location = new Point3d(insPt.X + 1.65, insPt.Y + 4.95, 0); acMText.Attachment = AttachmentPoint.MiddleLeft; leader.AppendVertex(new Point3d(blkRef.Position.X + 1.5, blkRef.Position.Y + 1.5, 0)); } else { txt.Location = new Point3d(insPt.X + 1.33, insPt.Y + 1.2833, 0); txt.Attachment = AttachmentPoint.BottomLeft; acMText.Location = new Point3d(insPt.X + 1.65, insPt.Y - 4.95, 0); acMText.Attachment = AttachmentPoint.MiddleLeft; leader.AppendVertex(new Point3d(blkRef.Position.X + 1.5, blkRef.Position.Y - 1.5, 0)); } } else { if (Ydir) { txt.Location = new Point3d(insPt.X - 42.6643, insPt.Y + 11.1833, 0); txt.Attachment = AttachmentPoint.BottomLeft; acMText.Location = new Point3d(insPt.X - 42.35, insPt.Y + 4.95, 0); acMText.Attachment = AttachmentPoint.MiddleLeft; leader.AppendVertex(new Point3d(blkRef.Position.X - 1.5, blkRef.Position.Y + 1.5, 0)); } else { txt.Location = new Point3d(insPt.X - 42.6643, insPt.Y + 1.2833, 0); txt.Attachment = AttachmentPoint.BottomLeft; acMText.Location = new Point3d(insPt.X - 42.6383, insPt.Y - 4.95, 0); acMText.Attachment = AttachmentPoint.MiddleLeft; leader.AppendVertex(new Point3d(blkRef.Position.X - 1.5, blkRef.Position.Y - 1.5, 0)); } } leader.AppendVertex(insPt); MText addText = null; //create text for body string verbose; switch (blkRef.Name.ToUpper()) { case "CPR": verbose = DROP_BUCKET; break; case "CPR_T": verbose = TAP_PED; addText = new MText(); addText.SetDatabaseDefaults(); addText.TextHeight = 2.2; addText.Layer = "TEXT-2"; addText.Attachment = AttachmentPoint.TopLeft; addText.Location = new Point3d(acMText.Location.X, acMText.Location.Y - 7, 0); addText.Contents = "EXPRESS: BYPASS PED"; break; case "CPS_S": verbose = SPLITTER_PED; break; case "CPS": verbose = LE_PED; break; case "DH": verbose = AMP_PED; addText = new MText(); addText.SetDatabaseDefaults(); addText.TextHeight = 2.2; addText.Layer = "TEXT-2"; addText.Attachment = AttachmentPoint.TopLeft; addText.Location = new Point3d(acMText.Location.X, acMText.Location.Y - 7, 0); addText.Contents = "BASE 16\" DEEP"; break; case "DH_N": verbose = NODE_PED; addText = new MText(); addText.SetDatabaseDefaults(); addText.TextHeight = 2.2; addText.Layer = "TEXT-2"; addText.Attachment = AttachmentPoint.TopLeft; addText.Location = new Point3d(acMText.Location.X, acMText.Location.Y - 7, 0); addText.Contents = "BASE 24\" DEEP"; break; case "PS": verbose = POWER_SUPPLY; break; default: verbose = "BLOCK TYPE NOT RECOGNIZED"; break; } acMText.Contents = verbose; if (addText != null) { acBlkTblRec.AppendEntity(addText); trans.AddNewlyCreatedDBObject(addText, true); } //append to block table acBlkTblRec.AppendEntity(leader); trans.AddNewlyCreatedDBObject(leader, true); acBlkTblRec.AppendEntity(acMText); trans.AddNewlyCreatedDBObject(acMText, true); acBlkTblRec.AppendEntity(rec); trans.AddNewlyCreatedDBObject(rec, true); acBlkTblRec.AppendEntity(txt); trans.AddNewlyCreatedDBObject(txt, true); trans.Commit(); } } }
protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw wd) { // Update the dummy vertex to be our 3D point // projected onto our plane if (_isArcSeg) { Point3d lastVertex = _pline.GetPoint3dAt(_pline.NumberOfVertices - 2); Vector3d refDir; if (_pline.NumberOfVertices < 3) { refDir = new Vector3d(1.0, 1.0, 0.0); } else { // Check bulge to see if last segment was an arc or a line if (_pline.GetBulgeAt(_pline.NumberOfVertices - 3) != 0) { CircularArc3d arcSegment = _pline.GetArcSegmentAt(_pline.NumberOfVertices - 3); Line3d tangent = arcSegment.GetTangent(lastVertex); // Reference direction is the invert of the arc tangent // at last vertex refDir = tangent.Direction.MultiplyBy(-1.0); } else { Point3d pt = _pline.GetPoint3dAt(_pline.NumberOfVertices - 3); refDir = new Vector3d(lastVertex.X - pt.X, lastVertex.Y - pt.Y, lastVertex.Z - pt.Z); } } double angle = Class1.JigUtils.ComputeAngle(lastVertex, _tempPoint, refDir, _ucs); // Bulge is defined as tan of one fourth of included angle // Need to double the angle since it represents the included // angle of the arc // So formula is: bulge = Tan(angle * 2 * 0.25) double bulge = Math.Tan(angle * 0.5); _pline.SetBulgeAt(_pline.NumberOfVertices - 2, bulge); } else { // Line mode. Need to remove last bulge if there was one if (_pline.NumberOfVertices > 1) { _pline.SetBulgeAt(_pline.NumberOfVertices - 2, 0); } } _pline.SetPointAt(_pline.NumberOfVertices - 1, _tempPoint.Convert2d(_plane)); if (_pline.NumberOfVertices == 3) { _pline.Closed = true; ObjectIdCollection ids = new ObjectIdCollection(); ids.Add(_pline.ObjectId); // Add the hatch loops and complete the hatch _hat.Associative = true; _hat.AppendLoop(HatchLoopTypes.Default, ids); } if (!wd.RegenAbort) { wd.Geometry.Draw(_pline); if (_pline.NumberOfVertices > 2) { _hat.EvaluateHatch(true); if (!wd.RegenAbort) { wd.Geometry.Draw(_hat); } } } return(true); }
protected override bool Update() { // Update the dummy vertex to be our 3D point // projected onto our plane Polyline pl = Entity as Polyline; if (_isArcSeg) { Point3d lastVertex = pl.GetPoint3dAt(pl.NumberOfVertices - 2); Vector3d refDir; if (pl.NumberOfVertices < 3) { refDir = new Vector3d(1.0, 1.0, 0.0); } else { // Check bulge to see if last segment was an arc or a line if (pl.GetBulgeAt(pl.NumberOfVertices - 3) != 0) { CircularArc3d arcSegment = pl.GetArcSegmentAt(pl.NumberOfVertices - 3); Line3d tangent = arcSegment.GetTangent(lastVertex); // Reference direction is the invert of the arc tangent // at last vertex refDir = tangent.Direction.MultiplyBy(-1.0); } else { Point3d pt = pl.GetPoint3dAt(pl.NumberOfVertices - 3); refDir = new Vector3d( lastVertex.X - pt.X, lastVertex.Y - pt.Y, lastVertex.Z - pt.Z ); } } double angle = JigUtils.ComputeAngle( lastVertex, _tempPoint, refDir, _ucs ); // Bulge is defined as tan of one fourth of included angle // Need to double the angle since it represents the included // angle of the arc // So formula is: bulge = Tan(angle * 2 * 0.25) double bulge = Math.tan(angle * 0.5); pl.SetBulgeAt(pl.NumberOfVertices - 2, bulge); } else { // Line mode. Need to remove last bulge if there was one if (pl.NumberOfVertices > 1) { pl.SetBulgeAt(pl.NumberOfVertices - 2, 0); } } pl.SetPointAt( pl.NumberOfVertices - 1, _tempPoint.Convert2d(_plane) ); return(true); }
public static Point2d to2d(this Point3d point, PlanarEntity pl) { return(point.Convert2d(pl)); }
public MapBuilding GetBuildingInPoint(Point3d pt) { return(GetBuildingInPoint(pt.Convert2d())); }
public static Polyline[] BreakAtPoint([NotNull] this Polyline pline, Point3d brkPt) { brkPt = pline.GetClosestPointTo(brkPt, false); // le point spécifié est sur le point de départ de la polyligne if (brkPt.IsEqualTo(pline.StartPoint)) { return new[] { null, (Polyline)pline.Clone() } } ; // le point spécifié est sur le point de fin de la polyligne if (brkPt.IsEqualTo(pline.EndPoint)) { return new[] { (Polyline)pline.Clone(), null } } ; var param = pline.GetParameterAtPoint(brkPt); var index = (int)param; var num = pline.NumberOfVertices; var pl1 = (Polyline)pline.Clone(); if (pline.Closed) { pl1.AddVertexAt( pline.NumberOfVertices, pline.GetPoint2dAt(0), pline.GetStartWidthAt(num - 1), pline.GetEndWidthAt(num - 1), pline.GetBulgeAt(num - 1)); pl1.Closed = false; } var pl2 = (Polyline)pl1.Clone(); // le point spécifié est sur un sommet de la polyligne if (Math.Abs(NetLib.DoubleExt.Round(param, 6) - index) < 0.0001) { for (var i = pl1.NumberOfVertices - 1; i > index; i--) { pl1.RemoveVertexAt(i); } for (var i = 0; i < index; i++) { pl2.RemoveVertexAt(0); } return(new[] { pl1, pl2 }); } // le point spécifié est sur un segment var pt = brkPt.Convert2d(new Plane(Point3d.Origin, pline.Normal)); for (var i = pl1.NumberOfVertices - 1; i > index + 1; i--) { pl1.RemoveVertexAt(i); } pl1.SetPointAt(index + 1, pt); for (var i = 0; i < index; i++) { pl2.RemoveVertexAt(0); } pl2.SetPointAt(0, pt); if (Math.Abs(pline.GetBulgeAt(index)) > 0.0001) { var bulge = pline.GetBulgeAt(index); pl1.SetBulgeAt(index, MultiplyBulge(bulge, param - index)); pl2.SetBulgeAt(0, MultiplyBulge(bulge, index + 1 - param)); } return(new[] { pl1, pl2 }); }
public static Polyline?CreateRectangle(this Point3d pt, double length, double width, CellAlignment alignment, Vector3d dir) { return(CreateRectangle(pt.Convert2d(), length, width, alignment, dir.Convert2d())); }
changeAlignStartPoint() { //BEGIN: UPDATE PROFILE, TABLE, AND POIs AlgnData algnData = new AlgnData(); ObjectId idAlign = ObjectId.Null; Alignment objAlign = null; if (selectAlignment(idAlign)) { objAlign = fStake.ACTIVEALIGN; } else { return; } objAlign = fStake.ACTIVEALIGN; AlignmentEntityCollection objAlignEnts = objAlign.Entities; //BEGIN: UPDATE PROFILE, TABLE, AND POIs double dblLenAlign = objAlign.Length; PromptStatus ps; Point3d varPnt = UserInput.getPoint("Select Desired Start Point", out ps, osMode: 0); double dblStation = 0, dblOffset = 0; idAlign.getAlignStaOffset(varPnt, ref dblStation, ref dblOffset); double dblStationStart = objAlign.StartingStation; double dblStationDelta = dblStation - dblStationStart; // if varPnt is out of range then dblStation returns ZERO Profile profFLOWLINE = Prof.getProfile(idAlign, "FLOwLINE"); ProfilePVICollection pvis = profFLOWLINE.PVIs; List <POI> varPOI_Temp = new List <POI>(); foreach (ProfilePVI pvi in pvis) { POI poi = new POI { Station = Math.roundDown3(pvi.Station), Elevation = pvi.Elevation }; varPOI_Temp.Add(poi); } Debug.Print("varPOI_Temp Before"); for (int i = 0; i < varPOI_Temp.Count; i++) { Debug.Print(varPOI_Temp[i].Station + " " + varPOI_Temp[i].Elevation); } //adjust POI_Temp stationing for (int i = 0; i < varPOI_Temp.Count; i++) { POI poi = varPOI_Temp[i]; if (poi.Station < dblStationDelta + dblStationStart) { poi.Station = Math.roundDown3(dblLenAlign + varPOI_Temp[i].Station); } else { poi.Station = Math.roundDown3(varPOI_Temp[i].Station - dblStationDelta); } varPOI_Temp[i] = poi; } List <POI> poiTmp = new List <POI>(); var sortPOI_Temp = from t in varPOI_Temp orderby t.Station ascending select t; foreach (var t in sortPOI_Temp) { poiTmp.Add(t); } varPOI_Temp = poiTmp; int k = varPOI_Temp.Count; POI poitemp = varPOI_Temp[k - 1]; poitemp.Elevation = varPOI_Temp[0].Elevation; varPOI_Temp[k] = poitemp; Debug.Print("varPOI_Temp After"); for (int i = 0; i < k; i++) { Debug.Print(varPOI_Temp[i].Station + " " + varPOI_Temp[i].Elevation); } //END: UPDATE PROFILE, TABLE, AND POIs ObjectId idPoly = objAlign.GetPolyline(); Polyline poly = (Polyline)idPoly.getEnt(); string strAlignName = objAlign.Name; AlgnData aData; for (int j = 1; j < fStake.algnData.Count; j++) { aData = fStake.algnData[j]; if (aData.AlignHandle == objAlign.Handle) { break; } } objAlign.ReferencePointStation = 100.0; foreach (AlignmentEntity ent in objAlignEnts) { objAlignEnts.Remove(ent); } List <Vertex2d> v2ds = Conv.poly_Vertex2dList(idPoly); int p = 0; foreach (Vertex2d v in v2ds) { if (v.Position.IsEqualTo(varPnt, new Tolerance(0, 0))) { break; } p++; } List <Vertex2d> v2dsNew = new List <Vertex2d>(); for (int i = p; i < v2ds.Count; i++) { v2dsNew.Add(v2ds[i]); } for (int i = 1; i < p; i++) { v2dsNew.Add(v2ds[i]); } v2dsNew.Add(v2ds[p]); int lngID = 0; Point3d dblPntBeg = Pub.pnt3dO, dblPntEnd = Pub.pnt3dO, dblPntMid = Pub.pnt3dO; for (int i = 1; i < v2dsNew.Count; i++) { if (v2dsNew[i].Bulge == 0) { dblPntBeg = v2dsNew[i - 1].Position; dblPntEnd = v2dsNew[i = 0].Position; AlignmentLine objAlignEntTan = objAlign.Entities.AddFixedLine(lngID, dblPntBeg, dblPntEnd); lngID = objAlignEntTan.EntityId; } else { dblPntBeg = v2dsNew[i - 1].Position; dblPntEnd = v2dsNew[i = 0].Position; int intDir = 0; if (v2dsNew[i - 1].Bulge > 0) { intDir = 1; } else { intDir = -1; } Arc arc = (Arc)Arc.Create(IntPtr.Zero, true); arc.StartPoint = dblPntBeg; arc.EndPoint = dblPntEnd; Point3d pnt3dMidLC = dblPntBeg.getMidPoint3d(dblPntEnd); double lenLC = dblPntBeg.getDistance(dblPntEnd); double dirLC = dblPntBeg.getDirection(dblPntEnd); double lenM = System.Math.Abs(lenLC / 2 * v2dsNew[i - 1].Bulge); dblPntMid = pnt3dMidLC.traverse(dirLC + System.Math.PI / 2 * intDir, lenM); AlignmentArc objAlignEntArc = objAlign.Entities.AddFixedCurve(lngID, dblPntBeg, dblPntMid, dblPntEnd); lngID = objAlignEntArc.EntityId; } } objAlign.Update(); objAlign.ReferencePoint = varPnt.Convert2d(BaseObjs.xyPlane); objAlign.ReferencePointStation = System.Math.Round(100.0 + dblStationDelta, 3); //BEGIN: UPDATE PROFILE, TABLE, AND POIs List <POI> varpoi = fStake.POI_CALC; //POIs are updated when selectAlignment is executed //ADJUST POI STATIONING //need complete POIs for descriptions for (int i = 0; i < varpoi.Count; i++) { if (varpoi[i].Station < dblStationDelta + dblStationStart) { varpoi[i].Station = Math.roundDown3(dblLenAlign + varpoi[i].Station); } else { varpoi[i].Station = Math.roundDown3(varpoi[i].Station - dblStationDelta); } } varpoi = varpoi.sortPOIbyStation(); int n = varpoi.Count; varpoi[0].DescX = "BEG " + varpoi[0].Desc0; varpoi[n - 2].DescX = varpoi[n - 2].DescX.Replace("END", "").Trim(); varpoi[n - 1].DescX = varpoi[n - 1].DescX.Replace("BEG", "END").Trim(); if (fStake.ClassObj == "CURB") { Stake_AddProfile.makeProfile(idAlign, varPOI_Temp, "CURB", "ByLayout", true); } ObjectId idTable = Stake_Table.makeTable(idAlign, varpoi); Stake_Table.addTableData(idTable, varpoi); if (Stake_GetBC_EC.getBC_EC(idAlign, ref varpoi) == false) { return; } fStake.POI_CALC = varpoi; //END: UPDATE PROFILE, TABLE, AND POIs }
public void QB() { PromptEntityOptions selectCalloutOptions; PromptEntityResult selectedCalloutResults; BlockReference blkRef = null; string msAndKwds; string kwds; string verbose = "default"; //string station; string lineNumber; //need editor to prompt user Editor ed = doc.Editor; //Prompt options for running line PromptNestedEntityOptions promptRunningLineOpt = new PromptNestedEntityOptions("\nSelect Running Line"); promptRunningLineOpt.AllowNone = false; PromptNestedEntityResult runningLineResults = ed.GetNestedEntity(promptRunningLineOpt); if (runningLineResults.Status != PromptStatus.OK) { ed.WriteMessage("\nThe selected object is not running line"); return; } //prompt for line number PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Line Number: "); pStrOpts.AllowSpaces = false; PromptResult pStrRes = ed.GetString(pStrOpts); //prompt user to select object only allow DFWT blocks PromptEntityOptions peo = new PromptEntityOptions("\nSelect DFWT Block"); //check prompt results from user else return PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } while (true) { // Transaction trans = database.TransactionManager.StartTransaction(); using (trans) { //access block table and create block table record BlockTable bt = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //get the running line Polyline runningLine = trans.GetObject(runningLineResults.ObjectId, OpenMode.ForRead) as Polyline; //get the block reference //Entity nestedBlockEntity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity; //try { //BlockReference blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference; //} //catch //{ //} // ObjectId[] containerIds = per.GetContainers(); // foreach (ObjectId id in containerIds) // { //DBObject container = trans.GetObject(id, OpenMode.ForRead); //if (container is BlockReference) //{ // blkRef = container as BlockReference; //} // } try { Entity entity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity; blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference; } catch (InvalidCastException) { ed.WriteMessage("error when selecting block"); } string str = String.Format("{0:0}", runningLine.GetDistAtPoint(blkRef.Position)); switch (str.Length) { case 1: str = "0+0" + str; break; case 2: str = "0+" + str; break; default: str = str.Substring(0, str.Length - 2) + "+" + str.Substring(str.Length - 2); break; } if (pStrRes.StringResult != "") { str = str + " LINE " + pStrRes.StringResult; } // switch (blkRef.BlockName.ToUpper()) { case "CPR": msAndKwds = "\nSelect Type:[Drop Bucket/Tap pedestal/ Splitter Pedestal]"; kwds = "'Drop Bucket' 'Tap Pedestal' 'Tap Splitter'"; selectCalloutOptions = new PromptEntityOptions(msAndKwds, kwds); selectedCalloutResults = ed.GetEntity(selectCalloutOptions); switch (selectedCalloutResults.StringResult.ToUpper()) { case "DROP BUCKET": verbose = DROP_BUCKET; break; case "TAP PEDESTAL": verbose = TAP_PED; break; default: break; } break; case "CPS": break; default: ed.WriteMessage(blkRef.BlockName); break; } //.string msAndKwds = "\nCPR or [A/B/C]"; //string kwds = "Apple Bob Cat"; //peo.SetMessageAndKeywords(msAndKwds, kwds); //ed.WriteMessage(per1.StringResult); /************************************************************************************************ * Prompting for callout box insertion point * Set geometry for placing box ***********************************************************************************************/ PromptPointOptions pPtOpt = new PromptPointOptions("\nEnter Insertion Point"); PromptPointResult pPtRes = ed.GetPoint(pPtOpt); Point3d insPt = pPtRes.Value; CoordinateSystem3d cs = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d; Plane plane = new Plane(Point3d.Origin, cs.Zaxis); //create polyline Polyline rec = new Polyline(); rec.AddVertexAt(0, insPt.Convert2d(plane), 0, 0, 0); bool Xdir = true; bool Ydir = true; if (insPt.X < blkRef.Position.X) { Xdir = false; } // if (insPt.Y < blkRef.Position.Y) { Ydir = false; } if (Xdir) { if (Ydir) { //quadrant I rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant IV rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } else { if (Ydir) { //quadrant II rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant III rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } rec.Closed = true; rec.SetDatabaseDefaults(); /************************************************************************************************ * Add object to block table and Commit Transaction * ***********************************************************************************************/ MText mt = new MText(); mt.Contents = verbose; btr.AppendEntity(rec); btr.AppendEntity(mt); trans.AddNewlyCreatedDBObject(rec, true); trans.AddNewlyCreatedDBObject(mt, true); trans.Commit(); } } }
/// <summary> /// Построение разверток стены /// </summary> public void CreateRoll(Point3d ptStart, BlockTableRecord btr) { var rooms = Rooms.Where(r => r.HasRoll).OrderBy(r => r.Number?.Num); if (!rooms.Any()) { return; } Options opt = Options.Instance; Transaction t = btr.Database.TransactionManager.TopTransaction; Point2d ptRoom = ptStart.Convert2d(); var textHeight = 2.5 * (1 / btr.Database.Cannoscale.Scale); string textValue = string.Empty; // Подпись квартиры var ptTextFlat = new Point3d(ptStart.X, ptStart.Y + DrawHeight - 500, 0); using (var textFlat = addText(btr, t, ptTextFlat, Name, textHeight, TextHorizontalMode.TextLeft)) { textFlat.LayerId = RollUpService.LayerNonPlotId; } foreach (var room in rooms) { Point2d ptRoll = ptRoom; foreach (var roll in room.Rolls.OrderBy(r => r.Num, RollUpService.CompareName)) { Point2d ptSegment = ptRoll; foreach (var segment in roll.Segments) { // Полилиня сегмента addRectangle(btr, t, ptSegment, segment.Length, segment.Height); // Размер Point3d ptDim1 = ptSegment.Convert3d(); Point3d ptDim2 = new Point3d(ptDim1.X + segment.Length, ptDim1.Y, 0); Point3d ptDimLine = new Point3d(ptDim1.X + segment.Length * 0.5, ptDim1.Y - 500, 0); addDim(btr, t, ptDim1, ptDim2, ptDimLine); //// Для Тестов - индекс сегмента //var ptSegCenter = new Point2d(ptSegment.X + segment.Length * 0.5, ptSegment.Y + segment.Height * 0.5); //addText(btr, t, ptSegCenter, segment.Index.ToString(), textHeight); ptSegment = new Point2d(ptSegment.X + segment.Length, ptSegment.Y); } var ptText = new Point3d(ptRoll.X + roll.Length * 0.5, ptRoll.Y + roll.Height + textHeight, 0); textValue = "Вид " + (roll.View == null ? "0" : roll.Num.ToString()); addText(btr, t, ptText, textValue, textHeight); ptRoll = new Point2d(ptRoll.X + roll.Length + opt.RollViewOffset, ptRoll.Y); } // Полилиня помещения var ptRoomRectangle = new Point2d(ptRoom.X - 500, ptRoom.Y - 1000); using (var plRoomRect = addRectangle(btr, t, ptRoomRectangle, room.DrawLength + 1000, room.DrawHeight)) { plRoomRect.LayerId = RollUpService.LayerNonPlotId; } var ptTextRoom = new Point3d(ptRoom.X + room.DrawLength * 0.5, ptRoom.Y + room.Height + 1000 + textHeight, 0); textValue = "Помещение " + (room.Number == null ? "0" : room.Number.Num.ToString()); using (var textRoom = addText(btr, t, ptTextRoom, textValue, textHeight)) { textRoom.LayerId = RollUpService.LayerNonPlotId; } ptRoom = new Point2d(ptRoom.X + room.DrawLength + 2000, ptRoom.Y); } }
/// <summary> /// Creates a new instance of PolylineSegmentCollection from an Ellipse. /// </summary> /// <param name="ellipse">An Ellipse instance.</param> public PolylineSegmentCollection(Ellipse ellipse) { // PolylineSegmentCollection figuring the closed ellipse double pi = Math.PI; Plane plane = new Plane(Point3d.Origin, ellipse.Normal); Point3d cen3d = ellipse.Center; Point3d pt3d0 = cen3d + ellipse.MajorAxis; Point3d pt3d4 = cen3d + ellipse.MinorAxis; Point3d pt3d2 = ellipse.GetPointAtParameter(pi / 4.0); Point2d cen = cen3d.Convert2d(plane); Point2d pt0 = pt3d0.Convert2d(plane); Point2d pt2 = pt3d2.Convert2d(plane); Point2d pt4 = pt3d4.Convert2d(plane); Line2d line01 = new Line2d(pt0, (pt4 - cen).GetNormal() + (pt2 - pt0).GetNormal()); Line2d line21 = new Line2d(pt2, (pt0 - pt4).GetNormal() + (pt0 - pt2).GetNormal()); Line2d line23 = new Line2d(pt2, (pt4 - pt0).GetNormal() + (pt4 - pt2).GetNormal()); Line2d line43 = new Line2d(pt4, (pt0 - cen).GetNormal() + (pt2 - pt4).GetNormal()); Line2d majAx = new Line2d(cen, pt0); Line2d minAx = new Line2d(cen, pt4); Point2d pt1 = line01.IntersectWith(line21)[0]; Point2d pt3 = line23.IntersectWith(line43)[0]; Point2d pt5 = pt3.TransformBy(Matrix2d.Mirroring(minAx)); Point2d pt6 = pt2.TransformBy(Matrix2d.Mirroring(minAx)); Point2d pt7 = pt1.TransformBy(Matrix2d.Mirroring(minAx)); Point2d pt8 = pt0.TransformBy(Matrix2d.Mirroring(minAx)); Point2d pt9 = pt7.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt10 = pt6.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt11 = pt5.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt12 = pt4.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt13 = pt3.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt14 = pt2.TransformBy(Matrix2d.Mirroring(majAx)); Point2d pt15 = pt1.TransformBy(Matrix2d.Mirroring(majAx)); double bulge1 = Math.Tan((pt4 - cen).GetAngleTo(pt1 - pt0) / 2.0); double bulge2 = Math.Tan((pt1 - pt2).GetAngleTo(pt0 - pt4) / 2.0); double bulge3 = Math.Tan((pt4 - pt0).GetAngleTo(pt3 - pt2) / 2.0); double bulge4 = Math.Tan((pt3 - pt4).GetAngleTo(pt0 - cen) / 2.0); _contents.Add(new PolylineSegment(pt0, pt1, bulge1)); _contents.Add(new PolylineSegment(pt1, pt2, bulge2)); _contents.Add(new PolylineSegment(pt2, pt3, bulge3)); _contents.Add(new PolylineSegment(pt3, pt4, bulge4)); _contents.Add(new PolylineSegment(pt4, pt5, bulge4)); _contents.Add(new PolylineSegment(pt5, pt6, bulge3)); _contents.Add(new PolylineSegment(pt6, pt7, bulge2)); _contents.Add(new PolylineSegment(pt7, pt8, bulge1)); _contents.Add(new PolylineSegment(pt8, pt9, bulge1)); _contents.Add(new PolylineSegment(pt9, pt10, bulge2)); _contents.Add(new PolylineSegment(pt10, pt11, bulge3)); _contents.Add(new PolylineSegment(pt11, pt12, bulge4)); _contents.Add(new PolylineSegment(pt12, pt13, bulge4)); _contents.Add(new PolylineSegment(pt13, pt14, bulge3)); _contents.Add(new PolylineSegment(pt14, pt15, bulge2)); _contents.Add(new PolylineSegment(pt15, pt0, bulge1)); // if the ellipse is an elliptical arc: if (!ellipse.Closed) { double startParam, endParam; Point2d startPoint = ellipse.StartPoint.Convert2d(plane); Point2d endPoint = ellipse.EndPoint.Convert2d(plane); // index of the PolylineSegment closest to the ellipse start point int startIndex = GetClosestSegmentIndexTo(startPoint); // start point on the PolylineSegment Point2d pt = _contents[startIndex].ToCurve2d().GetClosestPointTo(startPoint).Point; // if the point is equal to the PolylineSegment end point, jump the next segment in collection if (pt.IsEqualTo(_contents[startIndex].EndPoint)) { if (startIndex == 15) { startIndex = 0; } else { startIndex++; } startParam = 0.0; } // else get the 'parameter' at point on the PolylineSegment else { startParam = _contents[startIndex].GetParameterOf(pt); } // index of the PolylineSegment closest to the ellipse end point int endIndex = GetClosestSegmentIndexTo(endPoint); // end point on the PolylineSegment pt = _contents[endIndex].ToCurve2d().GetClosestPointTo(endPoint).Point; // if the point is equals to the PolylineSegment startPoint, jump to the previous segment if (pt.IsEqualTo(_contents[endIndex].StartPoint)) { if (endIndex == 0) { endIndex = 15; } else { endIndex--; } endParam = 1.0; } // else get the 'parameter' at point on the PolylineSegment else { endParam = _contents[endIndex].GetParameterOf(pt); } // if the parameter at start point is not equal to 0.0, calculate the bulge if (startParam != 0.0) { _contents[startIndex].StartPoint = startPoint; _contents[startIndex].Bulge = _contents[startIndex].Bulge * (1.0 - startParam); } // if the parameter at end point is not equal to 1.0, calculate the bulge if (endParam != 1.0) //(endParam != 0.0) { _contents[endIndex].EndPoint = endPoint; _contents[endIndex].Bulge = _contents[endIndex].Bulge * (endParam); } // if both points are on the same segment if (startIndex == endIndex) { PolylineSegment segment = _contents[startIndex]; _contents.Clear(); _contents.Add(segment); } else if (startIndex < endIndex) { _contents.RemoveRange(endIndex + 1, 15 - endIndex); _contents.RemoveRange(0, startIndex); } else { _contents.AddRange(_contents.GetRange(0, endIndex + 1)); _contents.RemoveRange(0, startIndex); } } }
/// <summary> /// Breaks the polyline at specified point. /// </summary> /// <param name="pline">The polyline this method applies to.</param> /// <param name="brkPt">The point where to break the polyline.</param> /// <returns>An array of the two resullting polylines.</returns> public static Polyline[] BreakAtPoint(this Polyline pline, Point3d brkPt) { brkPt = pline.GetClosestPointTo(brkPt, false); // le point spécifié est sur le point de départ de la polyligne if (brkPt.IsEqualTo(pline.StartPoint)) return new Polyline[2] { null, (Polyline)pline.Clone() }; // le point spécifié est sur le point de fin de la polyligne if (brkPt.IsEqualTo(pline.EndPoint)) return new Polyline[2] { (Polyline)pline.Clone(), null }; double param = pline.GetParameterAtPoint(brkPt); int index = (int)param; int num = pline.NumberOfVertices; Polyline pl1 = (Polyline)pline.Clone(); if (pline.Closed) { pl1.AddVertexAt( pline.NumberOfVertices, pline.GetPoint2dAt(0), pline.GetStartWidthAt(num - 1), pline.GetEndWidthAt(num - 1), pline.GetBulgeAt(num - 1)); pl1.Closed = false; } Polyline pl2 = (Polyline)pl1.Clone(); // le point spécifié est sur un sommet de la polyligne if (Math.Round(param, 6) == index) { for (int i = pl1.NumberOfVertices - 1; i > index; i--) { pl1.RemoveVertexAt(i); } for (int i = 0; i < index; i++) { pl2.RemoveVertexAt(0); } return new Polyline[2] { pl1, pl2 }; } // le point spécifié est sur un segment Point2d pt = brkPt.Convert2d(new Plane(Point3d.Origin, pline.Normal)); for (int i = pl1.NumberOfVertices - 1; i > index + 1; i--) { pl1.RemoveVertexAt(i); } pl1.SetPointAt(index + 1, pt); for (int i = 0; i < index; i++) { pl2.RemoveVertexAt(0); } pl2.SetPointAt(0, pt); if (pline.GetBulgeAt(index) != 0.0) { double bulge = pline.GetBulgeAt(index); pl1.SetBulgeAt(index, MultiplyBulge(bulge, param - index)); pl2.SetBulgeAt(0, MultiplyBulge(bulge, index + 1 - param)); } return new Polyline[2] { pl1, pl2 }; }
public static DBObjectCollection PolylineFromRegion( Region reg ) { // We will return a collection of entities // (should include closed Polylines and other // closed curves, such as Circles) DBObjectCollection res = new DBObjectCollection(); // Explode Region -> collection of Curves / Regions DBObjectCollection cvs = new DBObjectCollection(); reg.Explode(cvs); // Create a plane to convert 3D coords // into Region coord system Plane pl = new Plane(new Point3d(0, 0, 0), reg.Normal); using (pl) { bool finished = false; while (!finished && cvs.Count > 0) { // Count the Curves and the non-Curves, and find // the index of the first Curve in the collection int cvCnt = 0, nonCvCnt = 0, fstCvIdx = -1; for (int i = 0; i < cvs.Count; i++) { Curve tmpCv = cvs[i] as Curve; if (tmpCv == null) { nonCvCnt++; } else { // Closed curves can go straight into the // results collection, and aren't added // to the Curve count if (tmpCv.Closed) { res.Add(tmpCv); cvs.Remove(tmpCv); // Decrement, so we don't miss an item i--; } else { cvCnt++; if (fstCvIdx == -1) { fstCvIdx = i; } } } } if (fstCvIdx >= 0) { // For the initial segment take the first // Curve in the collection Curve fstCv = (Curve)cvs[fstCvIdx]; // The resulting Polyline Polyline p = new Polyline(); // Set common entity properties from the Region p.SetPropertiesFrom(reg); // Add the first two vertices, but only set the // bulge on the first (the second will be set // retroactively from the second segment) // We also assume the first segment is counter- // clockwise (the default for arcs), as we're // not swapping the order of the vertices to // make them fit the Polyline's order p.AddVertexAt( p.NumberOfVertices, fstCv.StartPoint.Convert2d(pl), BulgeFromCurve(fstCv, false), 0, 0 ); p.AddVertexAt( p.NumberOfVertices, fstCv.EndPoint.Convert2d(pl), 0, 0, 0 ); cvs.Remove(fstCv); // The next point to look for Point3d nextPt = fstCv.EndPoint; // We no longer need the curve fstCv.Dispose(); // Find the line that is connected to // the next point // If for some reason the lines returned were not // connected, we could loop endlessly. // So we store the previous curve count and assume // that if this count has not been decreased by // looping completely through the segments once, // then we should not continue to loop. // Hopefully this will never happen, as the curves // should form a closed loop, but anyway... // Set the previous count as artificially high, // so that we loop once, at least. int prevCnt = cvs.Count + 1; while (cvs.Count > nonCvCnt && cvs.Count < prevCnt) { prevCnt = cvs.Count; foreach (DBObject obj in cvs) { Curve cv = obj as Curve; if (cv != null) { // If one end of the curve connects with the // point we're looking for... if (cv.StartPoint == nextPt || cv.EndPoint == nextPt) { // Calculate the bulge for the curve and // set it on the previous vertex double bulge = BulgeFromCurve(cv, cv.EndPoint == nextPt); if (bulge != 0.0) { p.SetBulgeAt(p.NumberOfVertices - 1, bulge); } // Reverse the points, if needed if (cv.StartPoint == nextPt) { nextPt = cv.EndPoint; } else { // cv.EndPoint == nextPt nextPt = cv.StartPoint; } // Add out new vertex (bulge will be set next // time through, as needed) p.AddVertexAt( p.NumberOfVertices, nextPt.Convert2d(pl), 0, 0, 0 ); // Remove our curve from the list, which // decrements the count, of course cvs.Remove(cv); cv.Dispose(); break; } } } } // Once we have added all the Polyline's vertices, // transform it to the original region's plane p.TransformBy(Matrix3d.PlaneToWorld(pl)); res.Add(p); if (cvs.Count == nonCvCnt) { finished = true; } } // If there are any Regions in the collection, // recurse to explode and add their geometry if (nonCvCnt > 0 && cvs.Count > 0) { foreach (DBObject obj in cvs) { Region subReg = obj as Region; if (subReg != null) { DBObjectCollection subRes = PolylineFromRegion(subReg); foreach (DBObject o in subRes) { res.Add(o); } cvs.Remove(subReg); subReg.Dispose(); } } } if (cvs.Count == 0) { finished = true; } } } return(res); }
public static LineSegment2d CreateLine2d(this Point3d pt1, Point3d pt2) { return(new LineSegment2d(pt1.Convert2d(), pt2.Convert2d())); }