double GetFrontXCoord(double zz) { Line Ruler = new Line(new Point3d(0, 0, zz), new Point3d(1, 0, zz)); Point3dCollection pts = new Point3dCollection(); foreach (Line fl in new List <Line> { FrontA, FrontC }) { pts.Clear(); Ruler.IntersectWith(fl, Intersect.ExtendThis, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count != 0) { return(pts[0].X); } } foreach (Arc fl in new List <Arc> { FrontB, FrontD, FrontE }) { pts.Clear(); Ruler.IntersectWith(fl, Intersect.ExtendThis, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count != 0) { return(pts[0].X); } } return(0); }
double GetBackXCoord(double zz) { Line Ruler = new Line(new Point3d(0, 0, zz), new Point3d(1, 0, zz)); Point3dCollection pts = new Point3dCollection(); pts.Clear(); Ruler.IntersectWith(BackLineA, Intersect.ExtendThis, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count != 0) { return(pts[0].X); } else { pts.Clear(); Ruler.IntersectWith(BackLineB, Intersect.ExtendThis, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count != 0) { return(pts[0].X); } else { pts.Clear(); Ruler.IntersectWith(BackLineC, Intersect.ExtendThis, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count != 0) { return(pts[0].X); } else { return(0); } } } }
public void CutLine(Entity ent1, Entity ent2, List <Line> listLines) { Point3dCollection pt3dColl = new Point3dCollection(); Point3d[] ptArr1 = new Point3d[3]; Point3d[] ptArr2 = new Point3d[3]; //listLines[0].IntersectWith(ent1, Intersect.OnBothOperands,pt3dColl,IntPtr.Zero,IntPtr.Zero); //ptArr1[0] = pt3dColl[0]; //pt3dColl.Clear(); listLines[1].IntersectWith(ent1, Intersect.OnBothOperands, pt3dColl, IntPtr.Zero, IntPtr.Zero); ptArr1[1] = pt3dColl[0]; pt3dColl.Clear(); listLines[2].IntersectWith(ent1, Intersect.OnBothOperands, pt3dColl, IntPtr.Zero, IntPtr.Zero); ptArr1[2] = pt3dColl[0]; pt3dColl.Clear(); //////////////////////// //listLines[0].IntersectWith(ent2, Intersect.OnBothOperands, pt3dColl, IntPtr.Zero, IntPtr.Zero); //ptArr2[0] = pt3dColl[0]; //pt3dColl.Clear(); listLines[1].IntersectWith(ent2, Intersect.OnBothOperands, pt3dColl, IntPtr.Zero, IntPtr.Zero); ptArr2[1] = pt3dColl[0]; pt3dColl.Clear(); listLines[2].IntersectWith(ent2, Intersect.OnBothOperands, pt3dColl, IntPtr.Zero, IntPtr.Zero); ptArr2[2] = pt3dColl[0]; pt3dColl.Clear(); //Line line1 = new Line(ptArr1[0], ptArr2[0]); Line line2 = new Line(ptArr1[1], ptArr2[1]); Line line3 = new Line(ptArr1[2], ptArr2[2]); List <Entity> list = new List <Entity>(); list.Add(listLines[0]); list.Add(line2); list.Add(line3); ObjectId layer1 = AddLayer(Db, "ECD斜梁1", System.Drawing.Color.DeepPink); ObjectId layer2 = AddLayer(Db, "ECD斜梁2", System.Drawing.Color.DeepPink); line2.LayerId = layer1; line3.LayerId = layer1; list[0].LayerId = layer2; list.ForEach(l => { l.Color = Color.FromColor(System.Drawing.Color.DeepPink); }); DBHelper.ToSpace(list); listLines.ForEach(ll => ll.Dispose()); list.ForEach(lll => lll.Dispose()); }
public void Cleanup() { _vertices.Clear(); foreach (DBObject obj in _created) { obj.Dispose(); } _created.Clear(); }
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); } }
public void AddPolylines() { ClearTransients(); // Dispose of the database objects foreach (DBObject obj in _lines) { obj.Dispose(); } _lines.Clear(); // Create a true database-resident 3D polyline // (and let it be green) if (_vertices.Count > 1) { var btr = (BlockTableRecord)_tr.GetObject( _doc.Database.CurrentSpaceId, OpenMode.ForWrite ); var pl = new Polyline3d( Poly3dType.SimplePoly, _vertices, false ); pl.ColorIndex = 3; btr.AppendEntity(pl); _tr.AddNewlyCreatedDBObject(pl, true); } _vertices.Clear(); }
protected override SamplerStatus SamplerData() { // Generate a point cloud try { // Use a user-defined sampling the points for the jig _vecs = GeneratePointCloud(Sampling); // Extract the points for display in the jig _points.Clear(); foreach (ColoredPoint3d vec in _vecs) { _points.Add( new Point3d(vec.X, vec.Y, vec.Z) ); } } catch {} ForceMessage(); return(SamplerStatus.OK); }
public static void PlotSideLine(Database db, Line AxisLine, Line StartLine, Line EndLine, double scale, bool isLeft = false) { using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3dCollection pts = new Point3dCollection(); Point3d LimitA, LimitB; StartLine.IntersectWith(AxisLine, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); LimitA = pts[0]; pts.Clear(); EndLine.IntersectWith(AxisLine, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); LimitB = pts[0]; Point3d st, ed; double distA = Math.Abs(LimitA.DistanceTo(AxisLine.StartPoint)); double distB = Math.Abs(LimitB.DistanceTo(AxisLine.EndPoint)); int dir = LimitA.Y > AxisLine.StartPoint.Y ? 1 : -1; int dirx = isLeft ? -1 : 1; double kk = AxisLine.GetK(); for (int i = 0; i < distA / 2 / scale; i++) { double dy = i * 2 * scale * dir; st = AxisLine.StartPoint.Convert3D(dy / kk, dy); if (i % 2 == 0) { ed = st.Convert3D(dirx * 2 * scale, 0, 0); } else { ed = st.Convert3D(dirx * 4 * scale, 0, 0); } Line tmp = new Line(st, ed); modelSpace.AppendEntity(tmp); tr.AddNewlyCreatedDBObject(tmp, true); } for (int i = 0; i < distB / 2 / scale; i++) { double dy = -i * 2 * scale * dir; st = AxisLine.EndPoint.Convert3D(dy / kk, dy); if (i % 2 == 0) { ed = st.Convert3D(dirx * 2 * scale, 0, 0); } else { ed = st.Convert3D(dirx * 4 * scale, 0, 0); } Line tmp = new Line(st, ed); tmp.Layer = "细线"; modelSpace.AppendEntity(tmp); tr.AddNewlyCreatedDBObject(tmp, true); } tr.Commit(); } }
public static Line CutByDoubleLine(this Line aline, Point2d minPoint, Point2d maxPoint, bool isInf = true) { Line res = (Line)aline.Clone(); Line A = new Line(minPoint.Convert3D(), minPoint.Convert3D(1)); Line B = new Line(maxPoint.Convert3D(), maxPoint.Convert3D(1)); Point3dCollection pts = new Point3dCollection(); pts.Clear(); aline.IntersectWith(A, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); res.StartPoint = pts[0]; pts.Clear(); aline.IntersectWith(B, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); res.EndPoint = pts[0]; return(res); }
public static void RemoveDuplicate([NotNull] this Point3dCollection pts, Tolerance tol) { var ptsClean = RemoveDuplicate(pts.Cast <Point3d>().ToList(), tol); pts.Clear(); foreach (var pt in ptsClean) { pts.Add(pt); } }
/// <summary> /// Попадает ли точка внутрь полилинии. /// Предполагается, что полилиния имеет замкнутый контур. /// Подходит для полилиний с дуговыми сегментами. /// Работает медленнее чем IsPointInsidePolygon(), примерно в 10 раз. /// </summary> /// <param name="pt"></param> /// <param name="onIsInside">Если исходная точка лежит на полилинии, то считать, что она внутри или нет: True - внутри, False - снаружи.</param> /// <param name="pl"></param> /// <exception cref="Exceptions.ErrorException">Не удалось определить за несколько попыток.</exception> public static bool IsPointInsidePolyline([NotNull] this Polyline pl, Point3d pt, bool onIsInside = false) { using (var ray = new Ray()) { ray.BasePoint = pt; var vec = new Vector3d(0, 1, pt.Z); ray.SecondPoint = pt + vec; using (var ptsIntersects = new Point3dCollection()) { bool isContinue; var isPtOnPolyline = false; var countWhile = 0; do { using (var plane = new Plane()) { pl.IntersectWith(ray, Intersect.OnBothOperands, plane, ptsIntersects, IntPtr.Zero, IntPtr.Zero); } isContinue = ptsIntersects.Cast <Point3d>().Any(p => { if (pt.IsEqualTo(p)) { isPtOnPolyline = true; return(true); } var param = pl.GetParameterAtPointTry(p); return(Math.Abs(param % 1) < 0.0001); }); if (isPtOnPolyline) { return(onIsInside); } if (isContinue) { vec = vec.RotateBy(0.01, Vector3d.ZAxis); ray.SecondPoint = pt + vec; ptsIntersects.Clear(); countWhile++; if (countWhile > 3) { throw new ErrorException(new Errors.Error( "Не определено попадает ли точка внутрь полилинии.", pt.GetRectangleFromCenter(3), Matrix3d.Identity, System.Drawing.SystemIcons.Error)); } } } while (isContinue); return(NetLib.MathExt.IsOdd(ptsIntersects.Count)); } } }
public void cmdWillStart(object o, CommandEventArgs e) { if (e.GlobalCommandName == "MOVE") { //Set the global variables bEditCommand = true; bDoRepositioning = false; //Delete all stored information changedObjects.Clear(); employeePositions.Clear(); } }
public void Cleanup() { if (_path != null) { _path.Dispose(); _path = null; } ; if (_profile != null) { _profile.Dispose(); _profile = null; } ; if (_tube != null) { _tube.Dispose(); _tube = null; } ; _sweepOpts = null; _vertices.Clear(); }
protected override SamplerStatus Sampler(JigPrompts prompts) { // We don't really need a point, but we do need some // user input event to allow us to loop, processing // for the Kinect input PromptPointResult ppr = prompts.AcquirePoint("\nClick to capture: "); if (ppr.Status == PromptStatus.OK) { if (Finished) { CancelJig(); return(SamplerStatus.Cancel); } // Generate a point cloud try { // Use a user-defined sampling the points for the jig _vecs = GeneratePointCloud(Sampling); // Extract the points for display in the jig _points.Clear(); foreach (ColoredPoint3d vec in _vecs) { _points.Add( new Point3d(vec.X, vec.Y, vec.Z) ); } ForceMessage(); } catch { } return(SamplerStatus.OK); } return(SamplerStatus.Cancel); }
public void IntersectionTest() { Editor m_ed = Application.DocumentManager.MdiActiveDocument.Editor; Database m_db = HostApplicationServices.WorkingDatabase; PromptEntityOptions m_peo = new PromptEntityOptions("\n请选择第一条曲线:"); PromptEntityResult m_per = m_ed.GetEntity(m_peo); if (m_per.Status != PromptStatus.OK) { return; } ObjectId m_objid1 = m_per.ObjectId; m_peo = new PromptEntityOptions("\n请选择第二条曲线:"); m_per = m_ed.GetEntity(m_peo); if (m_per.Status != PromptStatus.OK) { return; } ObjectId m_objid2 = m_per.ObjectId; using (Transaction m_tr = m_db.TransactionManager.StartTransaction()) { Curve m_cur1 = (Curve)m_tr.GetObject(m_objid1, OpenMode.ForRead); Curve m_cur2 = (Curve)m_tr.GetObject(m_objid2, OpenMode.ForRead); Point3dCollection m_ints = new Point3dCollection(); m_cur1.IntersectWith(m_cur2, Intersect.OnBothOperands, new Plane(), m_ints, 0, 0); //得出的所有交点在c1曲线上 foreach (Point3d m_pt in m_ints) { m_ed.WriteMessage("\n第一条曲线与第二条曲线交点:{0}", m_pt); } m_ed.WriteMessage("\n==="); m_ints.Clear(); m_cur2.IntersectWith(m_cur1, Intersect.OnBothOperands, new Plane(), m_ints, 0, 0); //得出的所有交点在c2曲线上 foreach (Point3d m_pt in m_ints) { m_ed.WriteMessage("\n第二条曲线与第条曲线一交点:{0}", m_pt); } m_tr.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(); } } }
protected override SamplerStatus SamplerData() { // Generate a point cloud try { // Use a user-defined sampling the points for the jig var frame = _frameReader.AcquireLatestFrame(); ProcessMultiSourceFrame(frame); _vecs = GeneratePointCloud(Sampling); // Extract the points for display in the jig _points.Clear(); if (_vecs != null) { foreach (var vec in _vecs) { _points.Add( new Point3d(vec.X, vec.Y, vec.Z) ); } } } catch (System.Exception ex) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage( "\nException: {0}", ex.Message ); } ForceMessage(); return(SamplerStatus.OK); }
public static void RemoveDuplicatePointFromPoint3DCollection(Point3dCollection source) { var result = new Point3dCollection(); foreach (Point3d point3D in source) { // Check duplicate if (DetectDuplicatePoint(result, point3D)) { continue; } result.Add(point3D); } // 如果个数不等的话: if (result.Count != source.Count) { source.Clear(); foreach (Point3d point3D in result) { source.Add(point3D); } } }
public string AddInfluencedTime( int month, int day, double startTime, double endTime, double interval, double angleSun, double latitude, double longitude, double windowsDirection, double windowsDownHeight, double windowsUpHeight, Line line, Line influencedLine) { Point3d startPoint, endPoint; startPoint = line.StartPoint; endPoint = line.EndPoint; List <double> influenceTime = new List <double>(); influenceTime.Clear(); List <string> influenceWay = new List <string>(); influenceWay.Clear(); //Dictionary<string,string> periodInfTimeTable = new Dictionary<string,string>; bool influenceStart = false; //ed.WriteMessage("start time : " + startTime + "\n"); //ed.WriteMessage("end time : " + endTime + "\n"); //interval = interval * 60; for (double now = startTime; now <= endTime; now += interval) { double h0 = GetSolorHighPosition_rad(angleSun, latitude, longitude, now); double alpha = getAlphaPosition_rad(angleSun, latitude, longitude, h0, now); //ed.WriteMessage("Here1\n"); //ed.WriteMessage("Time: " + now +" h0 :" + rad2Angle(h0) + " alpha : " + rad2Angle(alpha) + "\n"); if (h0 <= 0 || (alpha + windowsDirection >= Math.PI / 2 && windowsDirection != Math.PI) || (alpha + windowsDirection <= -1 * Math.PI / 2 && windowsDirection != Math.PI) || (windowsDirection == Math.PI && (alpha + windowsDirection <= 1.50 * Math.PI) && (alpha + windowsDirection >= Math.PI / 2.0) )) { continue; } Point3d p1 = getReflectedLinePoint_rad( startPoint, windowsDownHeight, h0, alpha, windowsDirection); Point3d p2 = getReflectedLinePoint_rad( startPoint, windowsUpHeight, h0, alpha, windowsDirection); Point3d p3 = getReflectedLinePoint_rad( endPoint, windowsUpHeight, h0, alpha, windowsDirection); Point3d p4 = getReflectedLinePoint_rad( endPoint, windowsDownHeight, h0, alpha, windowsDirection); Point3dCollection points = new Point3dCollection(); points.Add(p1); points.Add(p2); points.Add(p3); points.Add(p4); //cadOperator.drawLine(new Line(p1, p2)); //cadOperator.drawLine(new Line(p2, p3)); //cadOperator.drawLine(new Line(p3, p4)); /////////////////// //PartialTimePeriod(); if (isLineInOrIntersectPolygons(points, influencedLine)) { if (!influenceStart) { influenceTime.Add(now); influenceStart = true; influenceTime.Add(now); } else { influenceTime[influenceTime.Count - 1] = now; } } else { if (influenceStart) { influenceTime[influenceTime.Count - 1] = now; influenceStart = false; } } points.Clear(); } string influceceTimeString = ""; bool firstFlag = true; FormServices formServices = new FormServices(); ed.WriteMessage("influence time count: " + influenceTime.Count + "\n"); for (int i = 0; i < influenceTime.Count(); i += 2) { double start, end; start = influenceTime[i]; end = influenceTime[i + 1]; if (firstFlag) { firstFlag = false; } else { influceceTimeString += ","; } influceceTimeString += formServices.convertTimeDouble2String(start); influceceTimeString += "-"; influceceTimeString += formServices.convertTimeDouble2String(end); } return(influceceTimeString); }
BoundingBoxIntersectWith() { m_db = Utils.Db.GetCurDwg(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // get intersection type from user PromptKeywordOptions prIntType = new PromptKeywordOptions("\nExtend objects"); prIntType.Keywords.Add("None"); prIntType.Keywords.Add("First"); prIntType.Keywords.Add("Second"); prIntType.Keywords.Add("Both"); PromptResult prIntTypeRes = ed.GetKeywords(prIntType); if (prIntTypeRes.Status != PromptStatus.OK) { return; } //Intersect intType = Intersect.ExtendBoth; //if (prIntTypeRes.StringResult == "None") // intType = Intersect.OnBothOperands; //else if (prIntTypeRes.StringResult == "First") // intType = Intersect.ExtendThis; //else if (prIntTypeRes.StringResult == "Second") // intType = Intersect.ExtendArgument; //else // intType = Intersect.ExtendBoth; PromptEntityOptions prEnt1 = new PromptEntityOptions("\nSelect first entity"); PromptEntityOptions prEnt2 = new PromptEntityOptions("\nSelect intersecting entity"); Point3dCollection pts = new Point3dCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager; while (true) { PromptEntityResult prEnt1Res = ed.GetEntity(prEnt1); if (prEnt1Res.Status != PromptStatus.OK) { return; } PromptEntityResult prEnt2Res = ed.GetEntity(prEnt2); if (prEnt2Res.Status != PromptStatus.OK) { return; } using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) { AcDb.Entity ent1 = (AcDb.Entity)tr.GetObject(prEnt1Res.ObjectId, OpenMode.ForRead); AcDb.Entity ent2 = (AcDb.Entity)tr.GetObject(prEnt2Res.ObjectId, OpenMode.ForRead); MakeExtentsBlock(ent1.GeometricExtents); pts.Clear(); //ent1.BoundingBoxIntersectWith(ent2, intType, pts, 0, 0); // TBD: Fix JMA if (pts.Count == 0) { Utils.AcadUi.PrintToCmdLine("\nObjects do not intersect!"); } else { for (int i = 0; i < pts.Count; i++) { Utils.AcadUi.PrintToCmdLine(string.Format("\nINTERSECT PT: {0}", Utils.AcadUi.PtToStr(pts[i]))); MakePointEnt(pts[i], 3, tr); } } tr.Commit(); } } }
GripPoints() { m_db = Utils.Db.GetCurDwg(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Point3dCollection pts = new Point3dCollection(); IntegerCollection osnapModes = new IntegerCollection(); IntegerCollection geomIds = new IntegerCollection(); Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager; while (true) { PromptEntityResult prEntRes = ed.GetEntity("\nSelect entity to show grip 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 osnapModes.Clear(); geomIds.Clear(); //TBD: Throws a "Value cannot be null exception" ent.GetGripPoints(pts, osnapModes, geomIds); if (pts.Count == 0) { Utils.AcadUi.PrintToCmdLine("\nNo grip points specified!"); } else { for (int i = 0; i < pts.Count; i++) { Utils.AcadUi.PrintToCmdLine(string.Format("\nGRIP[{0:d}]: {1}", i, Utils.AcadUi.PtToStr(pts[i]))); MakePointEnt(pts[i], 2, tr); } } if (osnapModes.Count == 0) { Utils.AcadUi.PrintToCmdLine("\nNo osnap modes specified!"); } else { for (int i = 0; i < osnapModes.Count; i++) { Utils.AcadUi.PrintToCmdLine(string.Format("\nOSNAP MODE[{0:d}]: {1}", i, osnapModes[i])); } } if (geomIds.Count == 0) { Utils.AcadUi.PrintToCmdLine("\nNo geometry IDs specified!"); } else { for (int i = 0; i < geomIds.Count; i++) { Utils.AcadUi.PrintToCmdLine(string.Format("\nGEOM ID[{0:d}]: {1}", i, geomIds[i].ToString())); } } tr.Commit(); } } }
//获取夹点,简单实体应重载该函数以获取更灵活的控制 public override void GetGripPoints(Entity entity, GripDataCollection grips, double curViewUnitSize, int gripSize, Vector3d curViewDir, GetGripPointsFlags bitFlags) { try { objectId = entity.ObjectId; if (objectId.IsErased) { return; } if (entity is BlockReference) { var brf = entity as BlockReference; bool b = FeatureGripsMapping.instance.grips.ContainsKey(brf.Name); if (b) { double xdist1 = FeatureGripsMapping.instance.grips[brf.Name].xdistn1; double ydist1 = FeatureGripsMapping.instance.grips[brf.Name].ydistn1; double xdist2 = FeatureGripsMapping.instance.grips[brf.Name].xdistn2; double ydist2 = FeatureGripsMapping.instance.grips[brf.Name].ydistn2; //double startAngle = FeatureGripsMapping.instance.grips[brf.Name].angle; //grips.Remove(grips[2]); pt1 = new Point3d(brf.Position.X + xdist1, brf.Position.Y + ydist1, 0); pt2 = new Point3d(brf.Position.X + xdist2, brf.Position.Y + ydist2, 0); pt1 = pt1.RotateBy(brf.Rotation /* + Math.PI / 180 *startAngle*/, Vector3d.ZAxis, brf.Position); pt2 = pt2.RotateBy(brf.Rotation /* + Math.PI / 180 * startAngle*/, Vector3d.ZAxis, brf.Position); grips.Add(new UserGripData(pt1)); if (pt2 != brf.Position) { grips.Add(new UserGripData(pt2)); } // 取出当前窗口大小 var viewsize = (double)Application.GetSystemVariable("VIEWSIZE"); // 得到当前选择集的集合 var sset = entity.Database.GetEditor().SelectImplied().Value; if (sset != null) { var objIds = sset.GetObjectIds(); if (objIds.Any()) { var sels = objIds.Last(); // if (viewsize <= 0.00025) { if (selents != sels) { selents = sels; snapDevs(entity.ObjectId); } } } } } else { //pt1 = pt2 = Point3d.Origin; pt1 = pt2 = brf.Position; nods1.Clear(); nods2.Clear(); } base.GetGripPoints(entity, grips, curViewUnitSize, gripSize, curViewDir, bitFlags); } else if (entity is DBText) { var txt = entity as DBText; grips.Add(new UserGripData(txt.Position)); } else if (entity is MText) { var txt = entity as MText; grips.Add(new UserGripData(txt.Location)); } } catch (System.Exception ex) { PublicMethod.Instance.Editor.WriteMessageWithReturn("UserGripOverrule::GetGripPoints :" + ex.Message + "\n"); } }
public void ExtractSpillwayPositions() { Document adoc = Application.DocumentManager.MdiActiveDocument; if (adoc == null) { return; } Database db = adoc.Database; Editor ed = adoc.Editor; List <Polyline3d> highlighted = new List <Polyline3d>(); try { Plane horizontalPlane = new Plane(Point3d.Origin, Vector3d.ZAxis); //Указать линию КПЧ и линии перелома откоса (они должны быть в соответствующих слоях) TypedValue[] tv = new TypedValue[] { new TypedValue(0, "POLYLINE"), new TypedValue(8, "КПЧ,ОТК") };//ограничение по слоям SelectionFilter flt = new SelectionFilter(tv); PromptSelectionOptions opts = new PromptSelectionOptions(); opts.MessageForAdding = "\nВыберите 3d-полилинии, обозначающие край проезжей части" + "и переломы откоса (только с одной стороны дороги). Линии должны быть в слоях КПЧ и ОТК"; PromptSelectionResult res = ed.GetSelection(opts, flt); if (res.Status == PromptStatus.OK) { SelectionSet sset = res.Value; //Отобрать только полилинии в нужных слоях Dictionary <string, List <Polyline3dInfo> > slopeLines = new Dictionary <string, List <Polyline3dInfo> >(); //Считать направление полилинии соответствующим направлению дороги bool? toTheRight = null;//водосброс справа от КПЧ Polyline3dInfo baseLine = null; using (Transaction tr = db.TransactionManager.StartTransaction()) { WrongPolylinesException wrongPolylinesException = new WrongPolylinesException(); //Отбор линий в служебных слоях foreach (SelectedObject acSSObj in sset) { Polyline3d currPoly = tr.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Polyline3d; if (currPoly != null) { if (currPoly.Layer.Equals("КПЧ") || currPoly.Layer.Equals("ОТК")) { List <Polyline3dInfo> polylines = null; slopeLines.TryGetValue(currPoly.Layer, out polylines); if (polylines == null) { polylines = new List <Polyline3dInfo>(); slopeLines.Add(currPoly.Layer, polylines); } polylines.Add(new Polyline3dInfo(currPoly.Layer, currPoly)); } } } //Проверить, что есть весь набор слоев - КПЧ, ОТК if (!slopeLines.ContainsKey("КПЧ") || !slopeLines.ContainsKey("ОТК")) { wrongPolylinesException.Mistakes = wrongPolylinesException.Mistakes | Mistake.NotEnoughLayers; } //Проверить, что в слое КПЧ находится только 1 полилиния List <Polyline3dInfo> checkList1 = null; slopeLines.TryGetValue("КПЧ", out checkList1); if (checkList1 == null || checkList1.Count != 1) { wrongPolylinesException.Mistakes = wrongPolylinesException.Mistakes | Mistake.TooManyLinesInOneLayer; } #region Проперка непересечения линий //Проверить что линии откоса не пересекают друг друга в плане //TODO: ВРЕМЕННО отказался от проверки взаимного пересечения линий откоса. Нужно учесть возможность частичного совпадения линий /* * List<Polyline3dInfo> slopeLinesList = slopeLines.Values.ToList().Aggregate((l1, l2) => * { * return l1.Concat(l2).ToList(); * }); * bool exitLoop = false; * for (int i = 0; i < slopeLinesList.Count; i++) * { * for (int j = i + 1; j < slopeLinesList.Count; j++) * { * Polyline3d poly1 = slopeLinesList[i].Poly3d; * Polyline3d poly2 = slopeLinesList[j].Poly3d; * Point3dCollection intersectPts = new Point3dCollection(); * poly1.IntersectWith(poly2, Intersect.OnBothOperands, * horizontalPlane, intersectPts, * new IntPtr(0), new IntPtr(0)); * * //TODO!!!!! Не считать точки пересечения если в точках пересечения происходит полное совпадение вершин двух полилиний * //В это случае скорее всего полилинии просто сливаются в одну. Это допустимо для коридора * * * * if (intersectPts.Count > 0) * { * * * * wrongPolylinesException.Mistakes = wrongPolylinesException.Mistakes | Mistake.LinesAreIntersecting; * exitLoop = true; * break; * } * } * if (exitLoop) * break; * } */ #endregion //Проверить, что все точки откоса расположены с одной стороны от КПЧ //Определить водосброс направо или налево //TODO: Проверить сонаправленность линий! (низкий приоритет) //Для всех кодов определить участки КПЧ. Параметры взаимного расположения расчитываются в горизонтальной проекции //По начальным точкам линий определить расположение линии справа или слева от КПЧ //базовая линия - КПЧ List <Polyline3dInfo> list = null; slopeLines.TryGetValue("КПЧ", out list); if (list != null && list.Count > 0) { baseLine = list.First(); foreach (KeyValuePair <string, List <Polyline3dInfo> > kvp in slopeLines) { if (!kvp.Key.Equals("КПЧ")) { foreach (Polyline3dInfo poly3dInfo in kvp.Value) { poly3dInfo.BaseLine = baseLine.Poly2d; poly3dInfo.ComputeParameters(); poly3dInfo.ComputeOrientation(); //проверка, что все линии с одной стороны от базовой if (toTheRight != null) { if (toTheRight != poly3dInfo.ToTheRightOfBaseLine) { wrongPolylinesException.Mistakes = wrongPolylinesException.Mistakes | Mistake.WrongOrientation; } } else { toTheRight = poly3dInfo.ToTheRightOfBaseLine; } } } } } if (wrongPolylinesException.Mistakes != Mistake.None) { throw wrongPolylinesException; } #region Test //ed.WriteMessage("\nОшибок нет\ntoTheRight = " + toTheRight); ////Начертить круги в точках начала и конца полилиний //BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //BlockTableRecord ms // = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //foreach (KeyValuePair<string, List<Polyline3dInfo>> kvp in slopeLines) //{ // if (!kvp.Key.Equals("КПЧ")) // { // foreach (Polyline3dInfo poly3dInfo in kvp.Value) // { // Point3d pt1 = poly3dInfo.Poly3d.GetPointAtParameter(poly3dInfo.StartParameter); // Point3d pt2 = poly3dInfo.Poly3d.GetPointAtParameter(poly3dInfo.EndParameter); // Point3d pt3 = baseLine.Poly3d.GetPointAtParameter(poly3dInfo.StartParameterBase); // Point3d pt4 = baseLine.Poly3d.GetPointAtParameter(poly3dInfo.EndParameterBase); // foreach (Point3d pt in new Point3d[] { pt1, pt2, pt3, pt4 }) // { // using (Circle circle = new Circle(pt, Vector3d.ZAxis, 1)) // { // circle.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); // ms.AppendEntity(circle); // tr.AddNewlyCreatedDBObject(circle, true); // } // } // using (Line line = new Line(pt1, pt3)) // { // line.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); // ms.AppendEntity(line); // tr.AddNewlyCreatedDBObject(line, true); // } // using (Line line = new Line(pt2, pt4)) // { // line.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); // ms.AppendEntity(line); // tr.AddNewlyCreatedDBObject(line, true); // } // } // } //} #endregion tr.Commit(); } //Включать подсветку 3d полилиний, которые участвуют в расчете highlighted.Clear(); foreach (KeyValuePair <string, List <Polyline3dInfo> > kvp in slopeLines) { foreach (Polyline3dInfo p3dI in kvp.Value) { p3dI.Poly3d.Highlight(); highlighted.Add(p3dI.Poly3d); } } int spillwayNum = 1; PositionData positionData = new PositionData(); while (true) { //Указать точку расположения водосброса PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); pPtOpts.Message = "\nУкажите точку расположения водосброса: "; pPtRes = adoc.Editor.GetPoint(pPtOpts); if (pPtRes.Status == PromptStatus.OK) { Point3d pickedPt = new Point3d(pPtRes.Value.X, pPtRes.Value.Y, 0); Point3d nearestPtOnBase = baseLine.Poly2d.GetClosestPointTo(pickedPt, true); //найти ближайшую точку базовой линии double pickedParameterBase = baseLine.Poly2d.GetParameterAtPoint(nearestPtOnBase); //параметр базовой линии в этой точке //Найти все линии откоса, которые расположены в районе данного параметра //Предполагается, что для каждого кода есть только одна такая List <Polyline3dInfo> pickedPtSlopeLines = slopeLines["ОТК"].FindAll(l => l.StartParameterBase <= pickedParameterBase && l.EndParameterBase >= pickedParameterBase); if (pickedPtSlopeLines.Count > 1)//Проверить, что найдены минимум 2 линии перелома откоса { //Найти ближайшую линию к базовой линии - это бровка Polyline3dInfo edgeLine = null; double minDist = double.MaxValue; foreach (Polyline3dInfo p3dI in pickedPtSlopeLines) { Point3d ptOnLine = p3dI.Poly2d.GetClosestPointTo(nearestPtOnBase, false); double distance = ptOnLine.DistanceTo(nearestPtOnBase); if (distance < minDist) { minDist = distance; edgeLine = p3dI; } } Point3d nearestPtOnEdge = edgeLine.Poly2d.GetClosestPointTo(pickedPt, true); //найти ближайшую точку бровки double pickedParameterEdge = edgeLine.Poly2d.GetParameterAtPoint(nearestPtOnEdge); //параметр бровки в этой точке //Найти касательную к бровке Vector3d tangentVector = edgeLine.Poly2d.GetFirstDerivative(pickedParameterEdge); double rotateAngle = toTheRight.Value ? -Math.PI / 2 : Math.PI / 2; Vector3d spillWayVector = tangentVector.RotateBy(rotateAngle, Vector3d.ZAxis).GetNormal();//вектор водосброса, перпендикулярный бровке Line spillWayAxis = new Line(nearestPtOnEdge, nearestPtOnEdge + spillWayVector); Point3dCollection intersections = new Point3dCollection(); baseLine.Poly2d.IntersectWith(spillWayAxis, Intersect.ExtendArgument, horizontalPlane, intersections, new IntPtr(0), new IntPtr(0)); if (intersections.Count > 0) { Point3d basePt = intersections[0];//Точка пересечения оси водосброса с КПЧ //Найти точки пересечения перпендикуляра к ОТК0 и остальными линиями откоса //Отсортировать все линии по удаленности от КПЧ в этой точке SortedDictionary <Point3d, Polyline3dInfo> intersectionPts = new SortedDictionary <Point3d, Polyline3dInfo>(new PtsSortComparer(basePt)); pickedPtSlopeLines.Add(baseLine); foreach (Polyline3dInfo p3dI in pickedPtSlopeLines) { intersections.Clear(); p3dI.Poly2d.IntersectWith(spillWayAxis, Intersect.ExtendArgument, horizontalPlane, intersections, new IntPtr(0), new IntPtr(0)); if (intersections.Count > 0) { intersectionPts.Add(intersections[0], p3dI); } } if (intersectionPts.Count == pickedPtSlopeLines.Count)//Проверить, что все пересечения найдены { //intersectionPts содержит все линии с точками пересечения в нужном порядке, //но все точки пересечения лежат на плоскости XY //Расчитать трехмерные точки Point3dCollection pts = new Point3dCollection(); foreach (KeyValuePair <Point3d, Polyline3dInfo> kvp in intersectionPts) { Point3d pt2d = kvp.Key; pt2d = kvp.Value.Poly2d.GetClosestPointTo(pt2d, false);//по какой-то причине в некоторых случаях без этой строки вылетала ошибка при получении параметра double param = kvp.Value.Poly2d.GetParameterAtPoint(pt2d); Point3d pt3d = kvp.Value.Poly3d.GetPointAtParameter(param); pts.Add(pt3d); } using (Transaction tr = db.TransactionManager.StartTransaction()) { //Регистрация приложения Utils.RegisterApp(db, tr); ObjectId layerId = Utils.CreateLayerIfNotExists("ВОДОСБРОС", db, tr, null, Color.FromColorIndex(ColorMethod.ByAci, 150), LineWeight.LineWeight030); BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //Вычерчивание 3d полилинии по линии водосброса using (Polyline3d poly3d = new Polyline3d()) { poly3d.LayerId = layerId; poly3d.PolyType = Poly3dType.SimplePoly; ms.AppendEntity(poly3d); tr.AddNewlyCreatedDBObject(poly3d, true); foreach (Point3d pt in pts) { PolylineVertex3d vertex = new PolylineVertex3d(pt); poly3d.AppendVertex(vertex); tr.AddNewlyCreatedDBObject(vertex, true); } //В расширенные данные записать название водосброса poly3d.XData = new ResultBuffer( new TypedValue(1001, Constants.AppName), new TypedValue(1000, spillwayNum.ToString())); } tr.Commit(); } Vector3d baseVector = Vector3d.YAxis; int sign = Math.Sign(baseVector.CrossProduct(spillWayVector).Z); double rotation = spillWayVector.GetAngleTo(baseVector) * sign; //в радианах rotation = rotation * 180 / (Math.PI); //в градусах List <Slope> slopes = new List <Slope>(); //Сохраниение расположения водосброса и всех уклонов for (int i = 0; i < pts.Count - 1; i++) { Point3d pt1 = pts[i]; Point3d pt2 = pts[i + 1]; Point2d pt1_2d = new Point2d(pt1.X, pt1.Y); Point2d pt2_2d = new Point2d(pt2.X, pt2.Y); double len = pt1_2d.GetDistanceTo(pt2_2d); if (len > 0) { double s = (pt2.Z - pt1.Z) / len; slopes.Add(new Slope() { S = s, Len = len }); } } SpillwayPosition spillwayPosition = new SpillwayPosition() { Name = spillwayNum.ToString(), X = pts[0].X, Y = pts[0].Y, Z = pts[0].Z, Z_Rotation = rotation, ToTheRight = toTheRight.Value, Slopes = slopes }; spillwayNum++; positionData.SpillwayPositions.Add(spillwayPosition); } } } } else { //ed.WriteMessage("\nвыбор закончен"); break; } } //ed.WriteMessage("\nпродолжение выполнения"); //Сериализация расположений. Сохранить xml в папку рядом с файлом if (positionData.SpillwayPositions.Count > 0) { //TODO: Учесть возможные ошибки из-за отсутствия прав string filename = null; int n = 0; do { filename = Path.Combine(Path.GetDirectoryName(adoc.Name), Path.GetFileNameWithoutExtension(adoc.Name) /*"SpillwayPositions"*/ + "_" + n + ".xml"); n++; } while (File.Exists(filename)); XmlSerializer xmlSerializer = new XmlSerializer(typeof(PositionData)); using (StreamWriter sw = new StreamWriter(filename)) { xmlSerializer.Serialize(sw, positionData); } //Cообщение о том, что все выполнено ed.WriteMessage("\nПоложение водосбросов сохранено в файле " + filename); } } } catch (System.Exception ex) { //Utils.ErrorToCommandLine(ed, "Ошибка при извлечении расположений водосбросов", ex); CommonException(ex, "Ошибка при извлечении расположений водосбросов"); } finally { foreach (Polyline3d p3d in highlighted) { p3d.Unhighlight(); } } }
public static void test26() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; EntityList itemEnts = new EntityList(); Point3d insertPt;//插入文字的位置 Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // 获取PickFirst选择集 PromptSelectionOptions promptSelOpt1 = new PromptSelectionOptions(); promptSelOpt1.MessageForAdding = "\n请选择需要编号的车位"; SelectionFilter frameFilter = new SelectionFilter( new TypedValue[] { new TypedValue(0, "INSERT"), }); // PromptSelectionResult acSSPrompt = ed.SelectImplied(); PromptSelectionResult acSSPrompt = ed.GetSelection(promptSelOpt1, frameFilter); SelectionSet acSSet; List <Entity> entityList = new List <Entity>(); List <string> layerNameList = new List <string>(); List <Extents3d> extentsList = new List <Extents3d>(); if (acSSPrompt.Status != PromptStatus.OK) { //提示用户交互 ed.WriteMessage("\n请先选择要编号的设备"); return; } else { //编号局部变量 int number = ed.GetInteger("\n请输入编号起始数字").Value; number--; int height = ed.GetInteger("\n请输入编号文字的高度").Value; string prefix = ed.GetString("\n请输入编号字母前缀(如A-)").StringResult; prefix = prefix.ToUpper(); acSSet = acSSPrompt.Value; foreach (ObjectId id in acSSet.GetObjectIds().Reverse()) { BlockReference bref = tr.GetObject(id, OpenMode.ForRead) as BlockReference; BlockTableRecord btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId objectId in btr) { Entity ent = tr.GetObject(objectId, OpenMode.ForRead) as Entity; string name = ent.GetType().Name; ed.WriteMessage(ent.GetType().Name); //var name = ent.GetType().Name; if (name == "Polyline") { entityList.Add(ent); } } } //现在只需要Extent3D数据 foreach (Entity ent in entityList) { extentsList.Add(ent.GeometricExtents); } foreach (var ent in entityList) { Point3dCollection collection = new Point3dCollection(); //存放矩形的四个点、 Point3dCollection collection1 = new Point3dCollection(); //存放矩形的2个点、 Point3dCollection collection2 = new Point3dCollection(); //存放矩形的2个点、 Point3dCollection collection3 = new Point3dCollection(); //存放交点 Polyline pl1 = new Polyline(); Polyline pl2 = new Polyline(); number++; var id = ent.ObjectId; Polyline pl = (Polyline)tr.GetObject(id, OpenMode.ForRead); var num = pl.NumberOfVertices; int[] vertexIndex = new int[num]; for (int i = 0; i < num; i++) { vertexIndex[i] = i; } foreach (var item in vertexIndex) { collection.Add(pl.GetPoint3dAt(item)); } collection1.Add(collection[0]); collection1.Add(collection[2]); collection2.Add(collection[1]); collection2.Add(collection[3]); DBHelper.CreatePolyline(pl1, collection1); DBHelper.CreatePolyline(pl2, collection2); pl1.IntersectWith(pl2, Intersect.OnBothOperands, new Plane(), collection3, IntPtr.Zero, IntPtr.Zero); insertPt = collection3[0]; CreateItemNo(insertPt, itemEnts, prefix, number, height); collection.Clear(); collection1.Clear(); collection2.Clear(); collection3.Clear(); pl1.Dispose(); pl2.Dispose(); //tr.AddNewlyCreatedDBObject(itemEnts,true); } } db.AddToCurrentSpace(itemEnts); ed.WriteMessage(itemEnts.GetType().Name); // db.AddToModelSpace(itemEnts); tr.Commit();//提交事务处理 } }
// 获取实体信息 public void GetEntitiesInfo(ArrayList entities, Transaction trans, BlockTableRecord btr, int numSample, Document doc, Editor ed) { ArrayList uuid = new ArrayList(); ArrayList geom = new ArrayList(); // 坐标点集合 ArrayList colorList = new ArrayList(); // 颜色集合 ArrayList type = new ArrayList(); // 类型集合 ArrayList layerName = new ArrayList(); ArrayList tableName = new ArrayList(); // 表名 System.Data.DataTable attributeList = new System.Data.DataTable(); // 属性集合 ArrayList attributeIndexList = new ArrayList(); //属性索引集合 ArrayList tuliList = new ArrayList(); //图例集合 string projectId = ""; //项目ID string chartName = ""; //表名称 ArrayList kgGuide = new ArrayList(); //控规引导 string srid = ""; //地理坐标系统编号 ArrayList parentId = new ArrayList(); //配套设施所在地块集合 ArrayList textContent = new ArrayList(); // 文字内容(GIS端展示) ArrayList blockContent = new ArrayList(); // 块内容(GIS端展示) Dictionary <string, string> result = new Dictionary <string, string>(); // 汇总 // 遍历所有实体 foreach (object entity in entities) { ArrayList singlePositionList = new ArrayList(); // 单个实体坐标点集合 //取得边界数 int loopNum = 1; if (entity is Hatch) { loopNum = (entity as Hatch).NumberOfLoops; type.Add("polygon"); } Point3dCollection col_point3d = new Point3dCollection(); BulgeVertexCollection col_ver = new BulgeVertexCollection(); Curve2dCollection col_cur2d = new Curve2dCollection(); for (int i = 0; i < loopNum; i++) { col_point3d.Clear(); HatchLoop hatLoop = null; if (entity is Hatch) { try { hatLoop = (entity as Hatch).GetLoopAt(i); } catch (System.Exception) { continue; } //如果HatchLoop为PolyLine if (hatLoop.IsPolyline) { col_ver = hatLoop.Polyline; foreach (BulgeVertex vertex in col_ver) { col_point3d.Add(new Point3d(vertex.Vertex.X, vertex.Vertex.Y, 0)); } } } // 如果实体为Polyline if (entity is Polyline) { // 类型 type.Add("polyline"); Polyline polyline = (Polyline)entity; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); } } //// 如果实体为Curve //if (entity is Curve) //{ // col_cur2d = hatLoop.Curves; // foreach (Curve2d item in col_cur2d) // { // Point2d[] M_point2d = item.GetSamplePoints(numSample); // foreach (Point2d pt in M_point2d) // { // if (!col_point3d.Contains(new Point3d(pt.X, pt.Y, 0))) // col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); // } // } //} // 如果实体为Point2d if (entity is DBPoint) { type.Add("point"); DBPoint entity3 = (DBPoint)entity; col_point3d.Add(new Point3d(entity3.Position.X, entity3.Position.Y, 0)); } // 如果实体为Point if (entity is Point3d) { type.Add("point"); Point3d entity3 = (Point3d)entity; col_point3d.Add(entity3); } // 如果实体为文字 if (entity is MText) { type.Add("text"); col_point3d.Add(new Point3d((entity as MText).Location.X, (entity as MText).Location.Y, 0)); } // 如果实体为文字 if (entity is DBText) { type.Add("text"); col_point3d.Add(new Point3d((entity as DBText).Position.X, (entity as DBText).Position.Y, 0)); } // 块参照 if (entity is BlockReference) { type.Add("block"); col_point3d.Add(new Point3d((entity as BlockReference).Position.X, (entity as BlockReference).Position.Y, 0)); } double[] pointPositionList = new double[2]; //单个点的坐标点集合 // 经纬度转换 foreach (Point3d point in col_point3d) { pointPositionList = new double[2] { Transform(point)[0], Transform(point)[1] }; singlePositionList.Add(pointPositionList); } // 经纬度转换结束 } // 单个实体几何坐标数量循环结束 // UUID Entity entityLayer = (Entity)entity; Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); uuid.Add(str); // 坐标 geom.Add(singlePositionList); // 颜色 if (entity is Point3d) { colorList.Add(""); // 图层名 layerName.Add("无"); } else { LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(entityLayer.LayerId, OpenMode.ForRead); string color; color = entityLayer.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(entityLayer.LayerId) : ColorTranslator.ToHtml(entityLayer.Color.ColorValue); colorList.Add(color); // 图层名 layerName.Add(ltr.Name); } // 表名 tableName.Add("a"); // 属性索引 // 获取每个闭合多段线对应的个体编号和用地代号 ArrayList tagList = new ArrayList(); PromptSelectionResult psrss = ed.SelectCrossingPolygon(col_point3d); // 获取闭合区域内实体方法 if (psrss.Status == PromptStatus.OK) { tagList.Clear(); SelectionSet SS = psrss.Value; ObjectId[] idArray = SS.GetObjectIds(); // 如果读取的块参照数量大于1,取中心点在闭合多段线的块参照 if (idArray.Length > 1) { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { BlockReference ent2 = (BlockReference)ent1; if (IsInPolygon(ent2.Position, col_point3d)) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); //MessageBox.Show("Tag: " + acAttRef.Tag + "\n" + // "Value: " + acAttRef.TextString + "\n"); } } } } } // 如果读取的块参照数量等于1,取中心点在闭合多段线的块参照 else { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); } } } } } // 如果地块编码属性只有两个属性值,attributeIndexList,如果少于2个或者多于2个都视为异常,添加空。 if (tagList.Count == 2) { attributeIndexList.Add(tagList[0] + "_" + tagList[1]); } else { attributeIndexList.Add(""); } // 属性 readAttributeList attributeListObj = new readAttributeList(); attributeList = attributeListObj.AttributeList(); // 配套设施所属的地块UUID // 获取块参照的属性值 ArrayList blockAttribute = new ArrayList(); // 是否是地块编码本身 string isBlockNum = ""; // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID if (entity is BlockReference) { // 清除原有内容 blockAttribute.Clear(); // 如果entity有两个属性值,可以判断这是一个地块编码 if (((BlockReference)entity).AttributeCollection.Count == 2) { isBlockNum = "Block"; } // 获取地块界限图层上的所有实体 ArrayList polylineEntities = new ArrayList(); // 找出地块界限里的所有闭合多段线,并判断当前块标注实体是否在某一个闭合多段线内,如果在,找出该闭合多段线内的块参照个体编号 TypedValue[] tvs = new TypedValue[1] { new TypedValue( (int)DxfCode.LayerName, "地块界限" ) }; SelectionFilter sf = new SelectionFilter(tvs); PromptSelectionResult psr = ed.SelectAll(sf); if (psr.Status == PromptStatus.OK) { SelectionSet SS = psr.Value; ObjectId[] idArray = SS.GetObjectIds(); //MessageBox.Show(idArray.Length.ToString()); Point3dCollection polylinePoint3d = new Point3dCollection(); for (int j = 0; j < idArray.Length; j++) { // 清除原有内容 polylinePoint3d.Clear(); Entity ent1 = trans.GetObject(idArray[j], OpenMode.ForWrite) as Entity; if (ent1 is Polyline && (ent1 as Polyline).Closed) { Polyline polyline = (Polyline)ent1; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); polylinePoint3d.Add(new Point3d(pt.X, pt.Y, 0)); } // 获取闭合多段线(地块)内的所有实体 PromptSelectionResult psrss2 = ed.SelectCrossingPolygon(polylinePoint3d); if (psrss2.Status == PromptStatus.OK) { SelectionSet SS2 = psrss2.Value; ObjectId[] idArray2 = SS2.GetObjectIds(); // 如果读取的块参照数量大于1,且包含当前实体,找出当前块参照所在的闭合多段线 if (idArray2.Length > 1) { for (int i = 0; i < idArray2.Length; i++) { Entity ent2 = (Entity)idArray2[i].GetObject(OpenMode.ForRead); // 判断是否是配套设施开始 if (ent2 is BlockReference && (ent2 as BlockReference).Position.X == (entity as BlockReference).Position.X) { for (int k = 0; k < idArray2.Length; k++) { Entity ent3 = (Entity)idArray2[k].GetObject(OpenMode.ForRead); if (ent3 is BlockReference) { // 判断块参照中心点是否在闭合多段线内,只读取中心点在闭合多段线内的块参照 if (IsInPolygon((ent3 as BlockReference).Position, polylinePoint3d)) { foreach (ObjectId rt in ((BlockReference)ent3).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; blockAttribute.Add(acAttRef.TextString); } } } } } // 判断是否是配套设施结束 } } } // 获取闭合多段线(地块)内的所有实体结束 } } } } // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID 结束 // 如果地块编码属性只有两个属性值,而且不是地块编码块参照,添加到parentId,如果少于2个或者多于2个都视为异常,添加空。 if (blockAttribute.Count == 2 && isBlockNum != "Block") { parentId.Add(blockAttribute[0] + "_" + blockAttribute[1]); } else { parentId.Add(""); } // 文字内容(GIS端展示) if (entity is DBText) { textContent.Add((entity as DBText).TextString); } else if (entity is MText) { textContent.Add((entity as MText).Text); } else if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = ""; if ((entity as BlockReference).AttributeCollection.Count > 0) { foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = text + acAttRef.TextString + "//"; } text = text.Substring(0, text.Length - 2); } textContent.Add(text); } else { textContent.Add(""); } // 块内容(GIS端展示) if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = "//"; foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = acAttRef.TextString + text; //singleBlockContent.Add(acAttRef.TextString); } blockContent.Add(text); //blockContent.Add(singleBlockContent); } else { blockContent.Add(""); } } // 所有的实体循环结束 // 图例 readAttributeList attributeListObj3 = new readAttributeList(); //tuliList.Add(attributeListObj3.TuliList()); tuliList.Add(""); // 项目名 //string projectIdBaseAddress = "http://172.18.84.70:8081/PDD/pdd/individual-manage!findAllProject.action"; //var projectIdHttp = (HttpWebRequest)WebRequest.Create(new Uri(projectIdBaseAddress)); //var response = projectIdHttp.GetResponse(); //var stream = response.GetResponseStream(); //var sr = new StreamReader(stream, Encoding.UTF8); //var content = sr.ReadToEnd(); //MessageBox.Show(content); projectId = "D3DEC178-2C05-C5F1-F6D3-45729EB9436A"; // 图表名或者叫文件名 chartName = Path.GetFileName(ed.Document.Name); // 控规引导 readAttributeList attributeListObj2 = new readAttributeList(); kgGuide = attributeListObj2.KgGuide(); //地理坐标系统编号 srid = "4326"; // 发文字信息 RegulatoryPost.FenTuZe.FenTuZe.SendData(result, uuid, geom, colorList, type, layerName, tableName, attributeIndexList, attributeList, tuliList, projectId, chartName, kgGuide, srid, parentId, textContent, blockContent); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~ methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~// ///// <summary> ///// Save all data before start AutoPoleInstallation ///// </summary> ///// <returns></returns> //private bool PrepareData() //{ // Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // OleDbConnection aConnection = new OleDbConnection(Atend.Control.ConnectionString.AccessCnString); // OleDbTransaction aTransaction; // try // { // aConnection.Open(); // aTransaction = aConnection.BeginTransaction(); // try // { // if (!selectedPole.AccessInsert(aTransaction, aConnection, true, true)) // { // throw new System.Exception("selectedPole.AccessInsert"); // } // if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.Conductor) // { // if (!SelectedConsol.AccessInsert(aTransaction, aConnection, true, true)) // { // throw new System.Exception("SelectedConsol.AccessInsert"); // } // if (!SelectedConsolTension.AccessInsert(aTransaction, aConnection, true, true)) // { // throw new System.Exception("SelectedConsolTension.AccessInsert"); // } // } // else if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.SelfKeeper) // { // if (!SelectedClamp.AccessInsert(aTransaction, aConnection, true, true)) // { // throw new System.Exception("SelectedClamp.AccessInsert"); // } // if (!SelectedClampTension.AccessInsert(aTransaction, aConnection, true, true)) // { // throw new System.Exception("SelectedClampTension.AccessInsert"); // } // } // } // catch (System.Exception ex2) // { // ed.WriteMessage("ERROR PrepareData: {0} \n", ex2.Message); // aTransaction.Rollback(); // aConnection.Close(); // return false; // } // } // catch (System.Exception ex1) // { // ed.WriteMessage("ERROR PrepareData: {0} \n", ex1.Message); // aConnection.Close(); // return false; // } // aTransaction.Commit(); // aConnection.Close(); // return true; //} public bool PoleInstallationWithoutForbiddenArea(Guid SelectedPoleDpackageCode) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; bool Answer = true; List <ObjectIdCollection> _AllConsols = new List <ObjectIdCollection>(); ObjectIdCollection _AllClamps = new ObjectIdCollection(); double _SectionLength = 0; double _SpanLength = 0; int _SectionCount = SectionCalculation(out _SectionLength); int _SpanCount = SpanCalculation(_SectionLength, out _SpanLength); Atend.Base.Acad.AT_INFO CurrentBranchInfo = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(BranchEntity.ObjectId); ObjectIdCollection t = new ObjectIdCollection(); try { Atend.Global.Acad.DrawEquips.AcDrawPole _AcDrawPole = null; Atend.Global.Acad.DrawEquips.AcDrawCirclePole _AcDrawCirclePole = null; Atend.Global.Acad.DrawEquips.AcDrawPolygonPole _AcDrawPolygonPole = null; if (_SpanLength != -1) { CalculateSectionPoints(branchEntity.StartPoint, branchEntity.EndPoint, _SectionCount); Atend.Base.Design.DPackage PolePack = Atend.Base.Design.DPackage.AccessSelectByNodeCode(SelectedPoleDpackageCode); //Start Pole consols or clamp if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.Conductor) { t.Add(GetStartConsolOrClamp()); _AllConsols.Add(t); } else { _AllClamps.Add(GetStartConsolOrClamp()); } for (int SectionCounter = 0; SectionCounter < _SectionCount; SectionCounter++) { SpanPoints.Clear(); CalculateSpanPoints(SectionPoints[SectionCounter], SectionPoints[SectionCounter + 1], _SpanCount); for (int SpanCounter = 1; SpanCounter < _SpanCount; SpanCounter++) { Atend.Base.Design.DPoleInfo PoleInfo = new Atend.Base.Design.DPoleInfo(); PoleInfo.HalterCount = 0; PoleInfo.HalterType = 0; PoleInfo.Factor = 0; if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.Conductor) { #region Counductor //ed.WriteMessage("~~~~~~~~{0}~~~~~~~~~~~~~~GO TO SHAPE~~~~~~~~~~~{1}~~~~~~~~~~~~~~\n", SelectedPole.Shape, SelectedPole.Type); if (SelectedPole.Shape == 0) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~TWO~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawCirclePole = new Atend.Global.Acad.DrawEquips.AcDrawCirclePole(); #region POLECircle _AcDrawCirclePole.UseAccess = true; _AcDrawCirclePole.ePole = SelectedPole; _AcDrawCirclePole.ProjectCode = PolePack.ProjectCode; _AcDrawCirclePole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawCirclePole.dPoleInfo = PoleInfo; _AcDrawCirclePole.eConsols.Add(SelectedConsol); _AcDrawCirclePole.eConsolCount.Add(2); _AcDrawCirclePole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawCirclePole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawCirclePole.eConsolUseAccess.Add(false); _AcDrawCirclePole.eHalterCount = 0; if (!_AcDrawCirclePole.DrawPoleCircle(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } _AllConsols.Add(t); #endregion } else if (SelectedPole.Shape == 1) { if (SelectedPole.Type == 2)//pertic { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~THREE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawPolygonPole = new Atend.Global.Acad.DrawEquips.AcDrawPolygonPole(); #region PolePolygon _AcDrawPolygonPole.UseAccess = true; _AcDrawPolygonPole.ePole = SelectedPole; _AcDrawPolygonPole.ProjectCode = PolePack.ProjectCode; _AcDrawPolygonPole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawPolygonPole.dPoleInfo = PoleInfo; _AcDrawPolygonPole.eConsols.Add(SelectedConsol); _AcDrawPolygonPole.eConsolCount.Add(2); _AcDrawPolygonPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPolygonPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPolygonPole.eConsolUseAccess.Add(false); _AcDrawPolygonPole.eHalterCount = 0; if (!_AcDrawPolygonPole.DrawPolePolygon(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } _AllConsols.Add(t); #endregion } else { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~ONE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawPole = new Atend.Global.Acad.DrawEquips.AcDrawPole(); #region Pole _AcDrawPole.UseAccess = true; _AcDrawPole.ePole = SelectedPole; _AcDrawPole.ProjectCode = PolePack.ProjectCode; _AcDrawPole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawPole.dPoleInfo = PoleInfo; _AcDrawPole.eConsols.Add(SelectedConsol); _AcDrawPole.eConsolCount.Add(2); _AcDrawPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPole.eConsolUseAccess.Add(false); _AcDrawPole.eHalterCount = 0; if (!_AcDrawPole.DrawPole(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } _AllConsols.Add(t); #endregion } } #endregion }//end of if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.Conductor) else if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.SelfKeeper) { #region Selfkeeper if (SelectedPole.Shape == 0) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~TWO~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawCirclePole = new Atend.Global.Acad.DrawEquips.AcDrawCirclePole(); #region POLECircle _AcDrawCirclePole.UseAccess = true; _AcDrawCirclePole.ePole = SelectedPole; _AcDrawCirclePole.ProjectCode = PolePack.ProjectCode; _AcDrawCirclePole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawCirclePole.dPoleInfo = PoleInfo; _AcDrawCirclePole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawCirclePole.eConsolCount = new ArrayList(); _AcDrawCirclePole.eConsolExistance = new ArrayList(); _AcDrawCirclePole.eConsolProjectCode = new ArrayList(); _AcDrawCirclePole.eConsolUseAccess = new ArrayList(); _AcDrawCirclePole.eHalterCount = 0; if (!_AcDrawCirclePole.DrawPoleCircle(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } //_AllClamps.Add(t[0]); #endregion } else if (SelectedPole.Shape == 1) { if (SelectedPole.Type == 2)//pertic { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~THREE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawPolygonPole = new Atend.Global.Acad.DrawEquips.AcDrawPolygonPole(); #region PolePolygon _AcDrawPolygonPole.UseAccess = true; _AcDrawPolygonPole.ePole = SelectedPole; _AcDrawPolygonPole.ProjectCode = PolePack.ProjectCode; _AcDrawPolygonPole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawPolygonPole.dPoleInfo = PoleInfo; _AcDrawPolygonPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPolygonPole.eConsolCount = new ArrayList(); _AcDrawPolygonPole.eConsolExistance = new ArrayList(); _AcDrawPolygonPole.eConsolProjectCode = new ArrayList(); _AcDrawPolygonPole.eConsolUseAccess = new ArrayList(); _AcDrawPolygonPole.eHalterCount = 0; if (!_AcDrawPolygonPole.DrawPolePolygon(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } //_AllClamps.Add(t[0]); #endregion } else { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~ONE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); _AcDrawPole = new Atend.Global.Acad.DrawEquips.AcDrawPole(); #region Pole _AcDrawPole.UseAccess = true; _AcDrawPole.ePole = SelectedPole; _AcDrawPole.ProjectCode = PolePack.ProjectCode; _AcDrawPole.Existance = Convert.ToByte(PolePack.IsExistance); _AcDrawPole.dPoleInfo = PoleInfo; _AcDrawPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPole.eConsolCount = new ArrayList(); _AcDrawPole.eConsolExistance = new ArrayList(); _AcDrawPole.eConsolProjectCode = new ArrayList(); _AcDrawPole.eConsolUseAccess = new ArrayList(); _AcDrawPole.eHalterCount = 0; if (!_AcDrawPole.DrawPole(SpanPoints[SpanCounter], GetStartPoleAngle() + 90, out t)) { throw new System.Exception("failor while drawing pole"); } //_AllClamps.Add(t[0]); #endregion } } #endregion Atend.Global.Acad.DrawEquips.AcDrawKalamp _AcDrawKalamp = new Atend.Global.Acad.DrawEquips.AcDrawKalamp(); _AcDrawKalamp.eClamp = SelectedClamp; _AcDrawKalamp.Existance = PolePack.IsExistance; _AcDrawKalamp.ProjectCode = PolePack.ProjectCode; _AcDrawKalamp.UseAccess = false; _AllClamps.Add(_AcDrawKalamp.DrawKalamp(Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(t[0])), t[0])); } //end of else if (SelectedBranch.ProductType == (int)Atend.Control.Enum.ProductType.SelfKeeper) } //end of span if (SectionCounter + 1 != _SectionCount) { //ed.WriteMessage("~~~~~~~~~~~~<<<SECTION>>>~~~~~~~~~~~~~\n"); if (_AcDrawPole != null) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~ONE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); if (CurrentBranchInfo.NodeType != (int)Atend.Control.Enum.ProductType.SelfKeeper) { _AcDrawPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPole.eConsols.Add(SelectedConsolTension); _AcDrawPole.eConsols.Add(SelectedConsolTension); _AcDrawPole.eConsolCount = new ArrayList(); _AcDrawPole.eConsolCount.Add(2); _AcDrawPole.eConsolCount.Add(2); _AcDrawPole.eConsolExistance = new ArrayList(); _AcDrawPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPole.eConsolProjectCode = new ArrayList(); _AcDrawPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPole.eConsolUseAccess = new ArrayList(); _AcDrawPole.eConsolUseAccess.Add(false); _AcDrawPole.eConsolUseAccess.Add(false); } else { _AcDrawPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPole.eConsolCount = new ArrayList(); _AcDrawPole.eConsolExistance = new ArrayList(); _AcDrawPole.eConsolProjectCode = new ArrayList(); _AcDrawPole.eConsolUseAccess = new ArrayList(); } _AcDrawPole.eHalterCount = 0; if (!_AcDrawPole.DrawPole(SectionPoints[SectionCounter + 1], GetStartPoleAngle(), out t)) { throw new System.Exception("failor while drawing pole"); } } else if (_AcDrawCirclePole != null) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~TWO~~~~~~~~~~~~~~~~~~~~~~~~~\n"); if (CurrentBranchInfo.NodeType != (int)Atend.Control.Enum.ProductType.SelfKeeper) { _AcDrawCirclePole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawCirclePole.eConsols.Add(SelectedConsolTension); _AcDrawCirclePole.eConsols.Add(SelectedConsolTension); _AcDrawCirclePole.eConsolCount = new ArrayList(); _AcDrawCirclePole.eConsolCount.Add(2); _AcDrawCirclePole.eConsolCount.Add(2); _AcDrawCirclePole.eConsolExistance = new ArrayList(); _AcDrawCirclePole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawCirclePole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawCirclePole.eConsolProjectCode = new ArrayList(); _AcDrawCirclePole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawCirclePole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawCirclePole.eConsolUseAccess = new ArrayList(); _AcDrawCirclePole.eConsolUseAccess.Add(false); _AcDrawCirclePole.eConsolUseAccess.Add(false); } else { _AcDrawCirclePole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawCirclePole.eConsolCount = new ArrayList(); _AcDrawCirclePole.eConsolExistance = new ArrayList(); _AcDrawCirclePole.eConsolProjectCode = new ArrayList(); _AcDrawCirclePole.eConsolUseAccess = new ArrayList(); } _AcDrawCirclePole.eHalterCount = 0; if (!_AcDrawCirclePole.DrawPoleCircle(SectionPoints[SectionCounter + 1], GetStartPoleAngle(), out t)) { throw new System.Exception("failor while drawing pole"); } } else if (_AcDrawPolygonPole != null) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~THREE~~~~~~~~~~~~~~~~~~~~~~~~~\n"); if (CurrentBranchInfo.NodeType != (int)Atend.Control.Enum.ProductType.SelfKeeper) { _AcDrawPolygonPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPolygonPole.eConsols.Add(SelectedConsolTension); _AcDrawPolygonPole.eConsols.Add(SelectedConsolTension); _AcDrawPolygonPole.eConsolCount = new ArrayList(); _AcDrawPolygonPole.eConsolCount.Add(2); _AcDrawPolygonPole.eConsolCount.Add(2); _AcDrawPolygonPole.eConsolExistance = new ArrayList(); _AcDrawPolygonPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPolygonPole.eConsolExistance.Add(Convert.ToByte(PolePack.IsExistance)); _AcDrawPolygonPole.eConsolProjectCode = new ArrayList(); _AcDrawPolygonPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPolygonPole.eConsolProjectCode.Add(PolePack.ProjectCode); _AcDrawPolygonPole.eConsolUseAccess = new ArrayList(); _AcDrawPolygonPole.eConsolUseAccess.Add(false); _AcDrawPolygonPole.eConsolUseAccess.Add(false); } else { _AcDrawPolygonPole.eConsols = new List <Atend.Base.Equipment.EConsol>(); _AcDrawPolygonPole.eConsolCount = new ArrayList(); _AcDrawPolygonPole.eConsolExistance = new ArrayList(); _AcDrawPolygonPole.eConsolProjectCode = new ArrayList(); _AcDrawPolygonPole.eConsolUseAccess = new ArrayList(); } ////ed.WriteMessage("### BBB ### \n"); _AcDrawPolygonPole.eHalterCount = 0; if (!_AcDrawPolygonPole.DrawPolePolygon(SectionPoints[SectionCounter + 1], GetStartPoleAngle(), out t)) { throw new System.Exception("failor while drawing pole"); } //ed.WriteMessage("### GGG ### \n"); } if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.Conductor) { _AllConsols.Add(t); } else if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.SelfKeeper) { Atend.Global.Acad.DrawEquips.AcDrawKalamp _AcDrawKalamp = new Atend.Global.Acad.DrawEquips.AcDrawKalamp(); _AcDrawKalamp.eClamp = SelectedClampTension; _AcDrawKalamp.Existance = PolePack.IsExistance; _AcDrawKalamp.ProjectCode = PolePack.ProjectCode; _AcDrawKalamp.UseAccess = false; _AllClamps.Add(_AcDrawKalamp.DrawKalamp(Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(t[0])), t[0])); } _AcDrawCirclePole = null; _AcDrawPole = null; _AcDrawPolygonPole = null; // ed.WriteMessage("~~~~~~~~~~~~<<<NOT SECTION>>>~~~~~~~~~~~~~\n"); }//change section } //End Pole consols if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.Conductor) { t = new ObjectIdCollection(); t.Add(GetEndConsolOrClamp()); _AllConsols.Add(t); } else if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.SelfKeeper) { //_AllClamps.Add(t[0]); _AllClamps.Add(GetEndConsolOrClamp()); } #region Do Branch Operation Here if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.Conductor) { #region Conductor Operation //delete conductor if (Atend.Global.Acad.DrawEquips.AcDrawConductor.DeleteConductorData(branchEntity.ObjectId)) { Atend.Global.Acad.DrawEquips.AcDrawConductor.DeleteConductor(branchEntity.ObjectId); } //ed.WriteMessage("~~~~~~ start sim keshi ~~~~~~~~~\n"); ObjectId LastConsol = ObjectId.Null, StartConsol = ObjectId.Null; for (int ii = 0; ii < _AllConsols.Count - 1; ii++) { //ed.WriteMessage("~~~~~~~~~~~~~~~~~~~~~~~~\n"); ObjectIdCollection o1 = _AllConsols[ii]; //foreach (ObjectId oii in o1) //{ // ed.WriteMessage("oi:{0}\n", oii); //} if (o1.Count == 1) { StartConsol = o1[0]; } else { if (o1[1] == LastConsol) { StartConsol = o1[0]; } else { StartConsol = o1[1]; } } ObjectIdCollection o2 = _AllConsols[ii + 1]; LastConsol = o2[0]; //ed.WriteMessage("Start:{0} , End:{1} \n", StartConsol, LastConsol); Atend.Global.Acad.DrawEquips.AcDrawConductor _AcDrawConductor = new Atend.Global.Acad.DrawEquips.AcDrawConductor(); _AcDrawConductor.UseAccess = true; //ed.WriteMessage("111 \n"); _AcDrawConductor.eConductorTip = Atend.Base.Equipment.EConductorTip.AccessSelectByCode(CurrentBranchInfo.ProductCode); //ed.WriteMessage("112 \n"); ///////////_AcDrawConductor.eConductors.Add(Atend.Base.Equipment.EConductor.AccessSelectByCode(_AcDrawConductor.eConductorTip.NeutralProductCode)); //ed.WriteMessage("113 \n"); //////////_AcDrawConductor.eConductors.Add(Atend.Base.Equipment.EConductor.AccessSelectByCode(5)); //ed.WriteMessage("114 \n"); /////////_AcDrawConductor.eConductors.Add(Atend.Base.Equipment.EConductor.AccessSelectByCode(5)); //ed.WriteMessage("115 \n"); Atend.Base.Design.DBranch _DBranch = Atend.Base.Design.DBranch.AccessSelectByCode(new Guid(CurrentBranchInfo.NodeCode)); if (_DBranch.Code != Guid.Empty) { _AcDrawConductor.Existance = _DBranch.IsExist; //ed.WriteMessage("116 \n"); _AcDrawConductor.ProjectCode = _DBranch.ProjectCode; //ed.WriteMessage("i will go to draw sim \n"); } else { _AcDrawConductor.Existance = 0; //ed.WriteMessage("116 \n"); _AcDrawConductor.ProjectCode = 0; //ed.WriteMessage("i will go to draw sim \n"); } _AcDrawConductor.DrawConductor(Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(StartConsol)), Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(LastConsol)), StartConsol, LastConsol, _SpanLength); //ed.WriteMessage("Start:{0} , End:{1} \n", StartConsol, LastConsol); } //ed.WriteMessage("~~~~~~ end sim keshi ~~~~~~~~~\n"); #endregion } else if (CurrentBranchInfo.NodeType == (int)Atend.Control.Enum.ProductType.SelfKeeper) { #region SelfKeeper Operation if (Atend.Global.Acad.DrawEquips.AcDrawSelfKeeper.DeleteSelfKeeperData(branchEntity.ObjectId)) { //ed.WriteMessage("delete data io{0}\n", branchEntity.ObjectId); if (Atend.Global.Acad.DrawEquips.AcDrawSelfKeeper.DeleteSelfKeeper(branchEntity.ObjectId, true)) { //ed.WriteMessage("delete graphic \n"); for (int ClampCounter = 0; ClampCounter < _AllClamps.Count - 1; ClampCounter++) { //ed.WriteMessage("draw self keeper \n"); //ed.WriteMessage("ANSWER={0} \n", oi); Atend.Global.Acad.DrawEquips.AcDrawSelfKeeper _AcDrawSelfKeeper = new Atend.Global.Acad.DrawEquips.AcDrawSelfKeeper(); _AcDrawSelfKeeper.UseAccess = true; _AcDrawSelfKeeper.eSelfKeeperTip = Atend.Base.Equipment.ESelfKeeperTip.AccessSelectByCode(SelectedBranch.ProductCode); _AcDrawSelfKeeper.Existance = SelectedBranch.IsExist; _AcDrawSelfKeeper.ProjectCode = SelectedBranch.ProjectCode; _AcDrawSelfKeeper.DrawSelfKeeper(Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(_AllClamps[ClampCounter])), Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(_AllClamps[ClampCounter + 1])), _AllClamps[ClampCounter], _AllClamps[ClampCounter + 1], _SpanLength); } } else { throw new System.Exception("while deleting self keeper"); } } else { throw new System.Exception("while deleting self keeper"); } #endregion } #endregion } else { ed.WriteMessage("طول اسپن قابل محاسبه نمی باشد" + "\n"); Answer = false; } } catch (System.Exception ex) { ed.WriteMessage("Error While Pole installation : {0} \n", ex.Message); Answer = false; } return(Answer); }
public void MyHook() { Database db = HostApplicationServices.WorkingDatabase; List <Entity> entityList = new List <Entity>(); List <Entity> centerMarkList = new List <Entity>(); List <Entity> MarkList = new List <Entity>(); Point3d pt1 = new Point3d(0, 0, 0); Point3d pt2 = new Point3d(5, -3, 0); Point3d pt3 = new Point3d(0, 70, 0); Point3d pt4 = new Point3d(-18, 46, 0); //已知圆心的圆 Circle c1 = new Circle(pt1, Vector3d.ZAxis, 20); Circle c2 = new Circle(pt2, Vector3d.ZAxis, 45); Circle c3 = new Circle(pt3, Vector3d.ZAxis, 10); Circle c4 = new Circle(pt3, Vector3d.ZAxis, 20); Circle c5 = new Circle(pt4, Vector3d.ZAxis, 8); //已知两条辅助线 Line l1 = new Line(new Point3d(5, -3 - 45, 0), new Point3d(-60, -3 - 45, 0)); l1.ColorIndex = 2; Line l2 = new Line(new Point3d(5, -3 - 45 + 64, 0), new Point3d(-60, -3 - 45 + 64, 0)); l2.ColorIndex = 2; //圆心线 Line lc1x = new Line(new Point3d(-30, 0, 0), new Point3d(30, 0, 0)); Line lc1y = new Line(new Point3d(0, -30, 0), new Point3d(0, 30, 0)); Line lc2x = new Line(new Point3d(-30 + 5, 0 - 3, 0), new Point3d(30 + 5, 0 - 3, 0)); Line lc2y = new Line(new Point3d(-30 + 5, 0 - 3, 0), new Point3d(30 + 5, 0 - 3, 0)); Line lc3x = new Line(new Point3d(-30, 0 + 70, 0), new Point3d(30, 0 + 70, 0)); Line lc3y = new Line(new Point3d(-30, 0 + 70, 0), new Point3d(30, 0 + 70, 0)); //需要求解的圆-->弧 //第一个切圆-->裁剪弧 Circle fc1 = new Circle(pt4, Vector3d.ZAxis, 8 + 18); Circle fc2 = new Circle(pt3, Vector3d.ZAxis, 20 + 18); Point3dCollection pc = new Point3dCollection(); fc1.IntersectWith(fc2, Intersect.OnBothOperands, pc, new IntPtr(0), new IntPtr(0)); fc1.Dispose(); fc2.Dispose(); foreach (Point3d p in pc) { if (p.X < c4.Center.X) { double sa = new Line(p, pt4).Angle; double sb = new Line(p, pt3).Angle; Arc a = new Arc(p, 18, sa, sb); entityList.Add(a); //第一条弧 break; } } //第二个切圆-->裁剪弧 Circle fc3 = new Circle(pt2, Vector3d.ZAxis, 45 + 86); Circle fc4 = new Circle(pt3, Vector3d.ZAxis, 20 + 86); pc.Clear(); fc3.IntersectWith(fc4, Intersect.OnBothOperands, pc, new IntPtr(0), new IntPtr(0)); fc3.Dispose(); fc4.Dispose(); foreach (Point3d p in pc) { if (p.X > c2.Center.X) { double sa = new Line(p, pt3).Angle; double sb = new Line(p, pt2).Angle; Arc a = new Arc(p, 86, sa, sb); entityList.Add(a); //第二条弧 break; } } //第三个切圆-->裁剪弧 Circle fc5 = new Circle(pt1, Vector3d.ZAxis, 20 + 9.7144); Circle fc6 = new Circle(pt2, Vector3d.ZAxis, 45 - 9.7144); pc.Clear(); fc5.IntersectWith(fc6, Intersect.OnBothOperands, pc, new IntPtr(0), new IntPtr(0)); fc5.Dispose(); fc6.Dispose(); foreach (Point3d p in pc) { if (p.X < c1.Center.X && p.Y < (-3 - 45 + 64)) { double sa = new Line(p, pt1).Angle; double sb = new Line(pt2, p).Angle; Arc a = new Arc(p, 9.7144, sa, sb); entityList.Add(a); //第三条弧 break; } } //线 Line fl3 = new Line(new Point3d(0, -30, 0), new Point3d(0, 100, 0)); fl3.TransformBy(Matrix3d.Rotation((Math.PI * 15 / 180), doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, fl3.EndPoint)); Point3d fp1 = fl3.GetClosestPointTo(c1.Center, true); Line l3 = new Line(c1.Center, fp1); pc.Clear(); l3.IntersectWith(c1, Intersect.ExtendThis, pc, new IntPtr(0), new IntPtr(0)); Point3d fp2 = l3.StartPoint; foreach (Point3d p in pc) { if (p.X > c1.Center.X) { fp2 = p; break; } } l3.Extend(50); l3.TransformBy(Matrix3d.Rotation((Math.PI * 90 / 180), doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis, fp2)); //l3.GetOffsetCurvesGivenPlaneNormal(Vector3d.XAxis, 18); Vector3d ve = new Vector3d(fp2.X, fp2.Y, fp2.Z); ve = ve.GetNormal(); //DBObjectCollection lc= l3.GetOffsetCurvesGivenPlaneNormal(ve, 14); DBObjectCollection lc = l3.GetOffsetCurves(14); //第四个切圆-->弧 Circle fc7 = new Circle(pt4, Vector3d.ZAxis, 22); Point3d sc1 = new Point3d(); foreach (Entity l in lc) { Point3dCollection fc = new Point3dCollection(); fc7.IntersectWith(l, Intersect.ExtendBoth, fc, new IntPtr(0), new IntPtr(0)); foreach (Point3d p in fc) { if (p.Y < pt4.Y) { //Circle tmpc = new Circle(p, Vector3d.ZAxis, 14); Arc a = new Arc(p, 14, new Line(pt1, fp1).Angle, new Line(p, pt4).Angle); entityList.Add(a); //第四条弧 break; } } } //公切线修剪 l3.StartPoint = fp2; l3.EndPoint = ((Arc)(entityList[entityList.Count - 1])).StartPoint; //修剪c5圆-->弧 Arc a1 = new Arc(c5.Center, c5.Radius, new Line(c5.Center, ((Arc)(entityList[0])).StartPoint).Angle, new Line(c5.Center, ((Arc)(entityList[3])).EndPoint).Angle); entityList.Add(a1);//第五条弧 //修剪C2号圆-->弧 Arc a2 = new Arc(c2.Center, c2.Radius, new Line(c2.Center, ((Arc)(entityList[2])).EndPoint).Angle, new Line(c2.Center, ((Arc)(entityList[1])).EndPoint).Angle); entityList.Add(a2);//第6条弧 //修剪C4号圆-->弧 Arc a3 = new Arc(c4.Center, c4.Radius, new Line(c4.Center, ((Arc)(entityList[1])).StartPoint).Angle, new Line(c4.Center, ((Arc)(entityList[0])).EndPoint).Angle); entityList.Add(a3);//第7条弧 //修剪c1号圆-->弧 Arc a4 = new Arc(c1.Center, c1.Radius, new Line(c1.Center, ((Arc)(entityList[2])).StartPoint).Angle, new Line(c1.Center, l3.StartPoint).Angle); entityList.Add(a4);//第8条弧 //画十字线 Point3d[] points = { pt1, pt2, pt3, pt4 }; foreach (Point3d p in points) { Line tmpl1 = new Line(new Point3d(p.X - 20, p.Y, 0), new Point3d(p.X + 20, p.Y, 0)); Line tmpl2 = new Line(new Point3d(p.X, p.Y - 20, 0), new Point3d(p.X, p.Y + 20, 0)); //tmpl1.Linetype = "CENTER2"; //tmpl2.Linetype = "CENTER2"; tmpl1.ColorIndex = 4; tmpl2.ColorIndex = 4; centerMarkList.Add(tmpl1); centerMarkList.Add(tmpl2); } //标注 //c3直径 DiametricDimension d1 = new DiametricDimension(); Line tmpl = new Line(c3.Center, new Point3d(c3.Center.X - 1, c3.Center.Y + 1, 0)); pc.Clear(); c3.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); d1.ChordPoint = pc[0]; d1.FarChordPoint = pc[1]; d1.LeaderLength = 20; d1.ColorIndex = 2; MarkList.Add(d1); //半径 RadialDimension r1 = new RadialDimension(); Arc tmparc = entityList[0] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 1, tmparc.Center.Y - 0.5, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r1.Center = tmparc.Center; r1.ChordPoint = pc[1].X > pc[0].X?pc[1]:pc[0]; r1.ColorIndex = 2; r1.LeaderLength = -5; MarkList.Add(r1); RadialDimension r2 = new RadialDimension(); tmparc = entityList[1] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X - 1, tmparc.Center.Y - 0.5, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r2.Center = tmparc.Center; r2.ChordPoint = pc[1].X > pc[0].X ? pc[0] : pc[1]; r2.ColorIndex = 2; r2.LeaderLength = -30; MarkList.Add(r2); RadialDimension r3 = new RadialDimension(); tmparc = entityList[2] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 1, tmparc.Center.Y - 0.2, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r3.Center = tmparc.Center; r3.ChordPoint = pc[1].X > pc[0].X ? pc[0] : pc[1]; r3.ColorIndex = 2; MarkList.Add(r3); RadialDimension r4 = new RadialDimension(); tmparc = entityList[3] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 0.35, tmparc.Center.Y + 1, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r4.Center = tmparc.Center; r4.ChordPoint = pc[1].X < pc[0].X ? pc[0] : pc[1]; r4.ColorIndex = 2; MarkList.Add(r4); RadialDimension r5 = new RadialDimension(); tmparc = entityList[4] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 0.35, tmparc.Center.Y + 1, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r5.Center = tmparc.Center; r5.ChordPoint = pc[1].X > pc[0].X ? pc[0] : pc[1]; r5.ColorIndex = 2; MarkList.Add(r5); RadialDimension r6 = new RadialDimension(); tmparc = entityList[5] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 1, tmparc.Center.Y - 1, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r6.Center = tmparc.Center; r6.ChordPoint = pc[1].X < pc[0].X ? pc[0] : pc[1]; r6.ColorIndex = 2; r6.LeaderLength = 20; MarkList.Add(r6); RadialDimension r7 = new RadialDimension(); tmparc = entityList[6] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X + 1, tmparc.Center.Y + 1, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r7.Center = tmparc.Center; r7.ChordPoint = pc[1].X < pc[0].X ? pc[0] : pc[1]; r7.ColorIndex = 2; r7.LeaderLength = 20; MarkList.Add(r7); RadialDimension r8 = new RadialDimension(); tmparc = entityList[7] as Arc; tmpl = new Line(tmparc.Center, new Point3d(tmparc.Center.X - 1, tmparc.Center.Y - 1, 0)); pc.Clear(); tmparc.IntersectWith(tmpl, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); r8.Center = tmparc.Center; r8.ChordPoint = pc[1].X > pc[0].X ? pc[0] : pc[1]; r8.ColorIndex = 2; r8.LeaderLength = 13; MarkList.Add(r8); //对齐标注1 AlignedDimension am1 = new AlignedDimension(); am1.XLine1Point = pt1; am1.XLine2Point = new Point3d(5, 0, 0); am1.DimLinePoint = new Point3d(0, -40, 0); am1.ColorIndex = 2; MarkList.Add(am1); //对齐标注2 AlignedDimension am2 = new AlignedDimension(); am2.XLine1Point = pt1; am2.XLine2Point = new Point3d(0, -3, 0); am2.DimLinePoint = new Point3d(40, 0, 0); am2.ColorIndex = 2; MarkList.Add(am2); //对齐标注3 AlignedDimension am3 = new AlignedDimension(); am3.XLine1Point = pt1; am3.XLine2Point = new Point3d(0, 70, 0); am3.DimLinePoint = new Point3d(70, 30, 0); am3.ColorIndex = 2; MarkList.Add(am3); //对齐标注4 AlignedDimension am4 = new AlignedDimension(); am4.XLine1Point = l1.EndPoint; am4.XLine2Point = l2.EndPoint; am4.DimLinePoint = new Point3d(-60, 0, 0); am4.ColorIndex = 2; MarkList.Add(am4); //对齐标注5 AlignedDimension am5 = new AlignedDimension(); am5.XLine1Point = new Point3d(0, 34, 0); am5.XLine2Point = new Point3d(-18, 34, 0); am5.DimLinePoint = new Point3d(0, 8, 0); am5.ColorIndex = 2; MarkList.Add(am5); //对齐标注6 AlignedDimension am6 = new AlignedDimension(); am6.XLine1Point = new Point3d(-18, 70, 0); am6.XLine2Point = new Point3d(-18, 46, 0); am6.DimLinePoint = new Point3d(-50, 0, 0); am6.ColorIndex = 2; MarkList.Add(am6); //角度标注1 LineAngularDimension2 lad1 = new LineAngularDimension2(); tmpl = new Line(new Point3d(0, 0, 0), new Point3d(0, 1, 0)); pc.Clear(); tmpl.IntersectWith(l3, Intersect.ExtendBoth, pc, new IntPtr(0), new IntPtr(0)); lad1.XLine2Start = pc[0]; lad1.XLine2End = pt1; lad1.XLine1Start = l3.EndPoint; lad1.XLine1End = l3.StartPoint; lad1.ArcPoint = new Point3d(10, 2, 0); lad1.ColorIndex = 2; MarkList.Add(lad1); AddEntities(MarkList.ToArray()); Entity[] es = { c3, l3 }; ////AddEntities(es); entityList.AddRange(es); //组成面域 DBObjectCollection dbc1 = new DBObjectCollection(); foreach (Entity e in entityList) { dbc1.Add(e); } dbc1.Add(c3); DBObjectCollection regions = new DBObjectCollection(); regions = Region.CreateFromCurves(dbc1); //doc.Editor.WriteMessage("r1{0}", dbc1regions.Count); Region re1 = regions[0] as Region; Region re2 = regions[1] as Region; doc.Editor.WriteMessage("r1:{0},r2:{1}", re1.Area, re2.Area); double area = re1.Area > re2.Area ?re1.Area - re2.Area:re2.Area - re1.Area; Area = area; doc.Editor.WriteMessage("面积{0}", area); //entityList.Clear(); //entityList.Add(r1); //entityList.Add(r2); foreach (Entity e in entityList) { e.ColorIndex = 1; } entityList.Add(l1); entityList.Add(l2); AddEntities(entityList.ToArray()); AddEntities(centerMarkList.ToArray()); }
// 判断点和多段线的位置关系 // 返回值:-1表示在多段线外部,0表示在多段线上,1表示在多段线内部 public static int PtRelationToPoly(Polyline pPoly, Point2d pt, double tol) { Debug.Assert(pPoly != null); // 1.如果点到多段线的最近点和给定的点重合,表示点在多段线上 Point3d closestPoint = pPoly.GetClosestPointTo(ToPoint3d(pt, pPoly.Elevation), false); // 多段线上与给定点距离最近的点 if (Math.Abs(closestPoint.X - pt.X) < tol && Math.Abs(closestPoint.Y - pt.Y) < tol) // 点在多段线上 { return(0); } // 2.第一个射线的方向是从最近点到当前点,起点是当前点 Ray pRay = new Ray(); pRay.BasePoint = new Point3d(pt.X, pt.Y, pPoly.Elevation); // 射线的起点是pt,方向为从最近点到pt,如果反向做判断,则最近点距离pt太近的时候,最近点也会被作为一个交点(这个交点不太容易被排除掉) // 此外,这样的射线方向很容易判断出点不在内部的情况 Vector3d vec = new Vector3d(-(closestPoint.X - pt.X), -(closestPoint.Y - pt.Y), 0); pRay.UnitDir = vec; // 3.射线与多段线计算交点 Point3dCollection intPoints = new Point3dCollection(); pPoly.IntersectWith(pRay, Intersect.OnBothOperands, intPoints, IntPtr.Zero, IntPtr.Zero); // IntersectWith函数经常会得到很近的交点,这些点必须进行过滤 FilterEqualPoints(intPoints, 1.0E-4); // 4.判断点和多段线的位置关系 RETRY: Point3d[] pts = new Point3d[10]; ////////////////////////////////////////////////////////////////////////// if (intPoints.Count > 0) { pts[0] = intPoints[0]; } if (intPoints.Count > 1) { pts[1] = intPoints[1]; } if (intPoints.Count > 2) { pts[2] = intPoints[2]; } if (intPoints.Count > 3) { pts[3] = intPoints[3]; } // 4.1 如果射线和多段线没有交点,表示点在多段线的外部 if (intPoints.Count == 0) { pRay.Dispose(); return(-1); } else { // 3.1 过滤掉由于射线被反向延长带来的影响 FilterEqualPoints(intPoints, ToPoint2d(closestPoint), 1.0E-4); // 2008-0907修订记录:当pt距离最近点比较近的时候,最近点竟然被作为一个交点! // 3.2 如果某个交点与最近点在给定点的同一方向,要去掉这个点(这个点明显不是交点,还是由于intersectwith函数的Bug) for (int i = intPoints.Count - 1; i >= 0; i--) { if ((intPoints[i].X - pt.X) * (closestPoint.X - pt.X) >= 0 && (intPoints[i].Y - pt.Y) * (closestPoint.Y - pt.Y) >= 0) { intPoints.RemoveAt(i); } } int count = intPoints.Count; for (int i = 0; i < intPoints.Count; i++) { if (PointIsPolyVert(pPoly, ToPoint2d(intPoints[i]), 1.0E-4)) // 只要有交点是多段线的顶点就重新进行判断 { // 处理给定点很靠近多段线顶点的情况(如果与顶点距离很近,就认为这个点在多段线上,因为这种情况没有什么好的判断方法) if (PointIsPolyVert(pPoly, new Point2d(pt.X, pt.Y), 1.0E-4)) { return(0); } // 将射线旋转一个极小的角度(2度)再次判断(假定这样不会再通过上次判断到的顶点) vec = vec.RotateBy(0.035, Vector3d.ZAxis); pRay.UnitDir = vec; intPoints.Clear(); pPoly.IntersectWith(pRay, Intersect.OnBothOperands, intPoints, IntPtr.Zero, IntPtr.Zero); goto RETRY; // 继续判断结果 } } pRay.Dispose(); if (count % 2 == 0) { return(-1); } else { return(1); } } }
public static Polyline[] PlotWallPlan(Database db, Line[] LSet, double width, bool isLeft, int scale) { Polyline PL1 = new Polyline() { Closed = true, Layer = "粗线" }; // 外框 Polyline PL2 = new Polyline() { Closed = false, Layer = "粗线" }; // 上拐角 Polyline PL3 = new Polyline() { Closed = false, Layer = "粗线" }; // 下拐角 Polyline PL4 = new Polyline() { Closed = false, Layer = "粗线" }; // 上内侧 Polyline PL5 = new Polyline() { Closed = false, Layer = "粗线" }; // 下内侧 Line L1 = new Line() { Layer = "虚线", LinetypeScale = 4.0 }; Line L4 = new Line() { Layer = "细线" }; // 上短线 Line L5 = new Line() { Layer = "细线" }; // 下短线 Line L6 = new Line() { Layer = "粗线" }; // 内墙 Line temp; Point3dCollection pts = new Point3dCollection(); Point2d UpperPt, LowerPt, UpperPt2, LowerPt2; double ang_red = LSet[0].Angle; if (isLeft) { LowerPt = LSet[0].StartPoint.Convert2D(); UpperPt = LSet[LSet.Length - 1].StartPoint.Convert2D(); UpperPt2 = LSet[LSet.Length - 2].StartPoint.Convert2D(); LowerPt2 = LSet[1].StartPoint.Convert2D(); } else { UpperPt = LSet[LSet.Length - 1].EndPoint.Convert2D(); UpperPt2 = LSet[LSet.Length - 2].EndPoint.Convert2D(); LowerPt2 = LSet[1].EndPoint.Convert2D(); LowerPt = LSet[0].EndPoint.Convert2D(); } using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; int direct = isLeft ? -1 : 1; double dy = (UpperPt.Y - LowerPt.Y) / Math.Cos(ang_red); double dy2 = 0; double thick, Wall_width, Wall_thick, Mouth_thick, Plate_thick; switch (width) { default: thick = 300; Wall_width = 1800; Wall_thick = 350; Mouth_thick = 250; Plate_thick = 250; break; case 1900: thick = 200; Wall_width = 1800 + 200; Wall_thick = 200; Mouth_thick = 200; Plate_thick = 200; break; case 2500: thick = 200; Wall_width = 2575 + 250; Wall_thick = 250; Mouth_thick = 250; Plate_thick = 250; break; case 4700: thick = 300; Wall_thick = 350; Wall_width = 3600; Mouth_thick = 250; Plate_thick = 300; break; } // 外框 Point2d p0, p1, p2, p3, p4, p5; dy2 = dy + Wall_width * Math.Tan(30.0 / 180.0 * Math.PI) * 2; p0 = LowerPt; p1 = p0.Convert2D(-direct * thick, 0); p2 = p1.Convert2D(0, dy); p3 = p2.Convert2D(direct * thick, 0); p4 = p3.Convert2D(direct * Wall_width, Wall_width * Math.Tan(30.0 / 180.0 * Math.PI)); p5 = p4.Convert2D(0, -dy2); PL1.AddVertexAt(0, p0, 0, 0, 0); PL1.AddVertexAt(1, p1, 0, 0, 0); PL1.AddVertexAt(2, p2, 0, 0, 0); PL1.AddVertexAt(3, p3, 0, 0, 0); PL1.AddVertexAt(4, p4, 0, 0, 0); PL1.AddVertexAt(5, p5, 0, 0, 0); PL1.TransformBy(Matrix3d.Rotation(ang_red, Vector3d.ZAxis, LowerPt.Convert3D())); modelSpace.AppendEntity(PL1); tr.AddNewlyCreatedDBObject(PL1, true); // 拐角 temp = new Line(PL1.GetPoint3dAt(4), PL1.GetPoint3dAt(5)); temp.TransformBy(Matrix3d.Displacement(new Vector3d(-direct * Mouth_thick * Math.Cos(ang_red), -direct * Mouth_thick * Math.Cos(ang_red) * Math.Sin(ang_red), 0))); temp.IntersectWith(PL1, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); p0 = PL1.GetPoint2dAt(4); p1 = temp.StartPoint.Convert2D(); p2 = pts[0].Convert2D(); PL2.AddVertexAt(0, p0, 0, 0, 0); PL2.AddVertexAt(1, p1, 0, 0, 0); PL2.AddVertexAt(2, p2, 0, 0, 0); modelSpace.AppendEntity(PL2); tr.AddNewlyCreatedDBObject(PL2, true); p0 = PL1.GetPoint2dAt(5); p1 = temp.EndPoint.Convert2D(); p2 = pts[1].Convert2D(); PL3.AddVertexAt(0, p0, 0, 0, 0); PL3.AddVertexAt(1, p1, 0, 0, 0); PL3.AddVertexAt(2, p2, 0, 0, 0); modelSpace.AppendEntity(PL3); tr.AddNewlyCreatedDBObject(PL3, true); L1.StartPoint = pts[0]; L1.EndPoint = pts[1]; modelSpace.AppendEntity(L1); tr.AddNewlyCreatedDBObject(L1, true); // 上内墙 pts = new Point3dCollection(); temp = new Line(PL1.GetPoint3dAt(3), PL1.GetPoint3dAt(4)); temp = (Line)temp.GetOffsetCurves(-Wall_thick * direct)[0]; temp.IntersectWith(LSet[LSet.Length - 2], Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); p0 = UpperPt2; p1 = pts[0].Convert2D(); pts.Clear(); temp.IntersectWith(PL1.GetLine(4), Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); p2 = pts[0].Convert2D(); PL4.AddVertexAt(0, p0, 0, 0, 0); PL4.AddVertexAt(1, p1, 0, 0, 0); PL4.AddVertexAt(2, p2, 0, 0, 0); modelSpace.AppendEntity(PL4); tr.AddNewlyCreatedDBObject(PL4, true); pts.Clear(); temp = new Line(PL1.GetPoint3dAt(0), PL1.GetPoint3dAt(5)); temp = (Line)temp.GetOffsetCurves(Wall_thick * direct)[0]; //temp.TransformBy(Matrix3d.Displacement(new Vector3d(0, Wall_thick / Math.Cos(30.0 / 180.0 * Math.PI), 0))); temp.IntersectWith(LSet[1], Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); p0 = LowerPt2; p1 = pts[0].Convert2D(); pts.Clear(); temp.IntersectWith(PL1.GetLine(4), Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero); p2 = pts[0].Convert2D(); PL5.AddVertexAt(0, p0, 0, 0, 0); PL5.AddVertexAt(1, p1, 0, 0, 0); PL5.AddVertexAt(2, p2, 0, 0, 0); modelSpace.AppendEntity(PL5); tr.AddNewlyCreatedDBObject(PL5, true); L6.StartPoint = PL1.GetPoint3dAt(3); L6.EndPoint = PL1.GetPoint3dAt(0); modelSpace.AppendEntity(L6); tr.AddNewlyCreatedDBObject(L6, true); DBText txt = new DBText(); Circle C1 = new Circle(); Circle C2 = new Circle(); Point2d PositionPoint = p0.Convert2D(direct * 10 * scale, 3 * scale); TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable; txt.TextString = (Plate_thick / 10).ToString(); txt.Height = 2 * scale; txt.Position = PositionPoint.Convert3D(); txt.HorizontalMode = TextHorizontalMode.TextCenter; txt.VerticalMode = TextVerticalMode.TextVerticalMid; txt.AlignmentPoint = PositionPoint.Convert3D(); txt.TextStyleId = st["fsdb"]; txt.Layer = "标注"; txt.WidthFactor = 0.75; C1 = new Circle(PositionPoint.Convert3D(), Vector3d.ZAxis, 1.3 * scale); C2 = new Circle(PositionPoint.Convert3D(), Vector3d.ZAxis, 1.6 * scale); C1.Layer = "标注"; C2.Layer = "标注"; modelSpace.AppendEntity(txt); tr.AddNewlyCreatedDBObject(txt, true); modelSpace.AppendEntity(C1); tr.AddNewlyCreatedDBObject(C1, true); modelSpace.AppendEntity(C2); tr.AddNewlyCreatedDBObject(C2, true); tr.Commit(); } Polyline[] res = new Polyline[] { PL1, PL2, PL3, PL4, PL5 }; return(res); }
public void WeldingLineStart() { #region Select welding mode var weldingModeOpts = new PromptKeywordOptions("\nWeld over points or object? "); weldingModeOpts.Keywords.Add("Points"); weldingModeOpts.Keywords.Add("polYline"); weldingModeOpts.Keywords.Add("Line"); weldingModeOpts.Keywords.Add("Circle"); weldingModeOpts.Keywords.Add("Arc"); weldingModeOpts.Keywords.Add("Block"); weldingModeOpts.Keywords.Default = "Points"; var weldingModeRslt = _ed.GetKeywords(weldingModeOpts); // If the user pressed cancel - return with no error if (weldingModeRslt.Status != PromptStatus.OK) { return; } if (weldingModeRslt.StringResult == "Block") { ImportInsulationBlock(); return; } var selectedObjectId = new ObjectId(); // If the user selected Points mode if (weldingModeRslt.StringResult == "Points") { //Prompt the user for vertices _weldingVertices.Clear(); _weldingVertices = GetPointsFromUser(); if (_weldingVertices.Count < 1) { return; } } // Else the user selected an Object mode from the list else { // Prompt for object var objectSelectionOpts = new PromptEntityOptions("\nSelect the object : "); objectSelectionOpts.SetRejectMessage("\nEntity is not of the predifined type :" + weldingModeRslt.StringResult); objectSelectionOpts.AddAllowedClass(typeof(Line), false); objectSelectionOpts.AddAllowedClass(typeof(Polyline), false); objectSelectionOpts.AddAllowedClass(typeof(Circle), false); objectSelectionOpts.AddAllowedClass(typeof(Arc), false); var objectSelectionRslt = _ed.GetEntity(objectSelectionOpts); // If the user pressed cancel - return with no error if (objectSelectionRslt.Status != PromptStatus.OK) { return; } // else get the slected object id and type selectedObjectId = objectSelectionRslt.ObjectId; } #endregion #region Welding side selection // Prompt the user to select object side M for middle - draw on the middle of the line or Point - for side. var weldingSideOpts = new PromptKeywordOptions("\nPick side point or draw in the middle. "); weldingSideOpts.Keywords.Add("Side"); weldingSideOpts.Keywords.Add("Middle "); weldingSideOpts.Keywords.Default = "Side"; var weldingSideRslt = _ed.GetKeywords(weldingSideOpts); // If the user pressed cancel - return with no error if (weldingSideRslt.Status != PromptStatus.OK) { return; } // If tThe user selected 'Side' var sidePoint = new Point3d(); if (weldingSideRslt.StringResult == "Side") { // Prompt the user to pick up a side point on the desired side. var sidePointOpts = new PromptPointOptions("\nPick side point : "); var sidePointRslt = _ed.GetPoint(sidePointOpts); // If the user pressed cancel - return with no error if (sidePointRslt.Status != PromptStatus.OK) { return; } sidePoint = sidePointRslt.Value; } // Else If the user selected 'Middle' else if (weldingSideRslt.StringResult == "Middle") { sidePoint = new Point3d(0, 0, 0); } // else // Not supposed to end here, because the choise in the prompt is restricted to two options #endregion #region Welding arcs lenght and distance selection // Prompt the user to set welding arcs lenght var weldingArcsChordOpts = new PromptDoubleOptions("\nWelding arcs lenght : ") { UseDefaultValue = true, DefaultValue = Settings.Default.WeldingArcsLenght }; var weldingArcsChordRslt = _ed.GetDouble(weldingArcsChordOpts); // If the user pressed cancel - return with no error if (weldingArcsChordRslt.Status != PromptStatus.OK) { return; } if (weldingArcsChordRslt.Value <= 0) { _ed.WriteMessage("Lenght must be positive number."); return; } Settings.Default.WeldingArcsLenght = weldingArcsChordRslt.Value; //else // The choice is Ok and lenght is provided. Continue... // Prompt the user to set the distance between the welding arcs var weldingArcsDistanceOpts = new PromptDoubleOptions("\nSet the distance between the welding arcs : ") { UseDefaultValue = true, DefaultValue = Settings.Default.WeldingArcsDistance }; var weldingArcsOffsetRslt = _ed.GetDouble(weldingArcsDistanceOpts); // If the user pressed cancel - return with no error if (weldingArcsOffsetRslt.Status != PromptStatus.OK) { return; } if (weldingArcsOffsetRslt.Value <= 0) { _ed.WriteMessage("Distance must be positive number."); } Settings.Default.WeldingArcsDistance = weldingArcsOffsetRslt.Value; Settings.Default.Save(); //else // The choice is Ok and distance is provided. Continue... #endregion #region Hand over the process to the specific drawing function _weldingArcs.Clear(); switch (weldingModeRslt.StringResult) { #region Points case "Points": for (var i = 0; i < _weldingVertices.Count; i++) { // слага ги в глобалната _weldingVertices[i] = _weldingVertices[i].TransformBy(GeometryUtility.GetTransforMatrixToWcs()); } using (var tr = _doc.Database.TransactionManager.StartTransaction()) { var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z); sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs()); // реперната точка и тя в глобалната var tP1 = new Point3d(0, 0, 0); var tP2 = new Point3d(_weldingVertices[1].X - _weldingVertices[0].X, _weldingVertices[1].Y - _weldingVertices[0].Y, _weldingVertices[1].Z - _weldingVertices[0].Z); var tP3 = new Point3d(sPt.X - _weldingVertices[0].X, sPt.Y - _weldingVertices[0].Y, sPt.Z - _weldingVertices[0].Z); var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false); for (var i = 0; i < _weldingVertices.Count; i++) { _weldingVertices[i] = _weldingVertices[i].TransformBy(ucs); } if (weldingSideRslt.StringResult == "Side") { sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem); sidePoint = sidePoint.TransformBy(ucs); } var oldUcs = _ed.CurrentUserCoordinateSystem; _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; _weldingArcs = BuildWeldingArcsOverPts(_weldingVertices, sidePoint, weldingArcsChordRslt.Value, weldingArcsOffsetRslt.Value, weldingArcsOffsetRslt.Value / 2); DrawWeldingLine(_weldingArcs, tr); _ed.CurrentUserCoordinateSystem = oldUcs; foreach (Arc a in _weldingArcs) { a.TransformBy(ucs.Inverse()); } tr.Commit(); } break; #endregion #region Line case "Line": using (var tr = _doc.Database.TransactionManager.StartTransaction()) { _weldingVertices.Clear(); var ent = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Entity; // Lishkov 07/07/2012 var name = ent.GetType().ToString(); // Lishkov 07/07/2012 if ((name.IndexOf("Line") < 0) || (name.IndexOf("Polyline") >= 0)) { MessageBox.Show("Selection is not Line !", "E R R O R"); break; } // Lishkov 07/07/2012 var weldingLine = (Line)tr.GetObject(selectedObjectId, OpenMode.ForWrite); var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z); sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs()); var tP1 = new Point3d(0, 0, 0); var tP2 = new Point3d(weldingLine.EndPoint.X - weldingLine.StartPoint.X, weldingLine.EndPoint.Y - weldingLine.StartPoint.Y, weldingLine.EndPoint.Z - weldingLine.StartPoint.Z); var tP3 = new Point3d(sPt.X - weldingLine.StartPoint.X, sPt.Y - weldingLine.StartPoint.Y, sPt.Z - weldingLine.StartPoint.Z); var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false); weldingLine.TransformBy(ucs); if (weldingSideRslt.StringResult == "Side") { sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem); sidePoint = sidePoint.TransformBy(ucs); } var oldUcs = _ed.CurrentUserCoordinateSystem; _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; _weldingVertices.Add(weldingLine.StartPoint); _weldingVertices.Add(weldingLine.EndPoint); _weldingArcs = BuildWeldingArcsOverPts(_weldingVertices, sidePoint, weldingArcsChordRslt.Value, weldingArcsOffsetRslt.Value, weldingArcsOffsetRslt.Value / 2); DrawWeldingLine(_weldingArcs, tr); _ed.CurrentUserCoordinateSystem = oldUcs; foreach (Arc a in _weldingArcs) { a.TransformBy(ucs.Inverse()); } weldingLine.TransformBy(ucs.Inverse()); tr.Commit(); } break; #endregion #region Polyline case "polYline": case "Polyline": case "polyline": using (var tr = _doc.Database.TransactionManager.StartTransaction()) { var weldingPoly = tr.GetObject(selectedObjectId, OpenMode.ForWrite) as Polyline; if (weldingPoly == null) { MessageBox.Show("Selection is not PolyLine !", "E R R O R"); break; } var temp = new Point3dCollection(); var temp1 = new Point3dCollection(); DBObjectCollection acDbObjColl = null; //acPoly.GetOffsetCurves(0.25); var acBlkTbl = tr.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable; var acBlkTblRec = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //офсетирано копие acDbObjColl = weldingPoly.GetOffsetCurves(0.001); //тестова на много малко разстояние от оригинала // Lishkov 07/07/2012 foreach (Entity acEnt in acDbObjColl) { // Add each offset object acBlkTblRec.AppendEntity(acEnt); tr.AddNewlyCreatedDBObject(acEnt, true); } Polyline weldingPolyOffset = null; try { weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline; } catch { } if (weldingPolyOffset != null) { //точките деления по двете полилинии temp = GeometryUtility.DividePoly(ref weldingPoly, weldingArcsOffsetRslt.Value); temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value); //проверка вярна ли е посоката на офсетиране var tP = sidePoint.TransformBy(GeometryUtility.GetTransforMatrixToWcs()); var dist1 = temp[0].DistanceTo(tP); var dist2 = temp1[0].DistanceTo(tP); foreach (Point3d p in temp) { if (p.DistanceTo(tP) < dist1) { dist1 = p.DistanceTo(tP); } } foreach (Point3d p in temp1) { if (p.DistanceTo(tP) < dist2) { dist2 = p.DistanceTo(tP); } } //ако не е вярна посоката на офсетиране #region if (dist1 < dist2) //ако посоката е грешна изтриваме тестовата и правим в обратна поскока на зададеното разстояние { weldingPolyOffset.Erase(); acDbObjColl = weldingPoly.GetOffsetCurves(-weldingArcsChordRslt.Value); foreach (Entity acEnt in acDbObjColl) { // Add each offset object acBlkTblRec.AppendEntity(acEnt); tr.AddNewlyCreatedDBObject(acEnt, true); } try { weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline; } catch { MessageBox.Show("Offset error", "E R R O R"); return; } temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value); } else //ако посоката е вярна изтриваме тестовата и правим в същата поскока на зададеното разстояние // Lishkov 07/07/2012 { weldingPolyOffset.Erase(); acDbObjColl = weldingPoly.GetOffsetCurves(weldingArcsChordRslt.Value); foreach (Entity acEnt in acDbObjColl) { // Add each offset object acBlkTblRec.AppendEntity(acEnt); tr.AddNewlyCreatedDBObject(acEnt, true); } try { weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline; } catch { MessageBox.Show("Offset error", "E R R O R"); return; } temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value); } #endregion //work var oldUcs = _ed.CurrentUserCoordinateSystem; _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; for (var i = 0; i < temp.Count - 1; i++) { var tempP = temp1[0]; var oP = temp1[0]; foreach (Point3d p in temp1) { if (temp[i].DistanceTo(p) < temp[i].DistanceTo(tempP)) { oP = tempP; tempP = p; } } var ucs = GeometryUtility.GetUcs(temp[i], temp[i + 1], tempP, true); Arc acArc; if (weldingSideRslt.StringResult != "Side") { acArc = new Arc( new Point3d(0, 0, 0), weldingArcsChordRslt.Value / 2, Math.PI / 2.0 + Math.PI, Math.PI / 2.0 + Math.PI + Math.PI ); } else { // BricsCAD hack acArc = new Arc( new Point3d(), weldingArcsChordRslt.Value / 2, Math.PI / 2.0 + Math.PI, Math.PI / 2.0 + Math.PI + Math.PI ) { Center = new Point3d(0, weldingArcsChordRslt.Value / 2, 0) }; } _weldingArcs.Add(acArc); try { acArc.TransformBy(ucs); } catch { _weldingArcs.RemoveAt(_weldingArcs.Count - 1); if (i > 0) { var tP1 = new Point3d(0, 0, 0); var tP2 = new Point3d(temp[i].X - temp[i - 1].X, temp[i].Y - temp[i - 1].Y, temp[i].Z - temp[i - 1].Z); var tP3 = new Point3d(oP.X - temp[i - 1].X, oP.Y - temp[i - 1].Y, oP.Z - temp[i - 1].Z); ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, true); try { _weldingArcs.Add(acArc); var lp1 = new Point3d(0, 0, 0); var lp2 = new Point3d(weldingArcsOffsetRslt.Value, 0, 0); var l = new Line3d(acArc.StartPoint, acArc.EndPoint); acArc.TransformBy(Matrix3d.Displacement(lp1.GetVectorTo(lp2))); acArc.TransformBy(ucs); acArc.TransformBy(Matrix3d.Displacement(-temp[i - 1].GetVectorTo(Point3d.Origin))); } catch { _weldingArcs.RemoveAt(_weldingArcs.Count - 1); } } } acArc.SetDatabaseDefaults(); } if (!weldingPoly.Closed) { var acA = (Arc)_weldingArcs[_weldingArcs.Count - 1]; var acArc = (Entity)acA.Clone(); acArc.TransformBy(Matrix3d.Displacement(temp[temp.Count - 2].GetVectorTo(temp[temp.Count - 1]))); _weldingArcs.Add(acArc); } weldingPolyOffset.Erase(); DrawWeldingLine(_weldingArcs, tr); _ed.CurrentUserCoordinateSystem = oldUcs; } tr.Commit(); } break; #endregion #region Circle case "Circle": // ElseIf the user picked up object of type 'arc' or 'circle' // Call the function that makes welding over arc or circle. // _Circle is an Arc with start angle of 0 and end angle of 360 using (var tr = _doc.Database.TransactionManager.StartTransaction()) { var weldingCircle = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Circle; if (weldingCircle != null) { using (var T = _doc.Database.TransactionManager.StartTransaction()) { var weldingLine = T.GetObject(selectedObjectId, OpenMode.ForWrite) as Circle; var r = new Ray { BasePoint = weldingLine.Center, UnitDir = weldingLine.Center.GetVectorTo(weldingLine.StartPoint) }; var pts = new Point3dCollection(); weldingLine.IntersectWith(r, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z); sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs()); var ucs = GeometryUtility.GetUcs(weldingLine.Center, pts[0], sPt, false); weldingLine.TransformBy(ucs); if (weldingSideRslt.StringResult == "Side") { sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem); sidePoint = sidePoint.TransformBy(ucs); } var oldUcs = _ed.CurrentUserCoordinateSystem; _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; var arcSide = GeometryUtility.SideOfPointToArc(weldingCircle.Center, weldingCircle.Radius, sidePoint); var sAng = -1 + weldingCircle.Center.DistanceTo(sidePoint) / weldingCircle.Radius; _weldingArcs = BuildWeldingArcsOverArc(weldingCircle.Center, weldingCircle.Radius, 0.0, 2 * Math.PI, /* sAng , */ weldingArcsChordRslt.Value, weldingArcsOffsetRslt.Value, 0, arcSide); DrawWeldingLine(_weldingArcs, T); _ed.CurrentUserCoordinateSystem = oldUcs; foreach (Arc a in _weldingArcs) { a.TransformBy(ucs.Inverse()); } weldingLine.TransformBy(ucs.Inverse()); T.Commit(); } } else { MessageBox.Show("\nYou did not slected object of type Circle. Try again..."); } tr.Commit(); } break; #endregion #region Arc case "Arc": using (var tr = _doc.Database.TransactionManager.StartTransaction()) { var weldingArc = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Arc; if (weldingArc != null) { using (var T = _doc.Database.TransactionManager.StartTransaction()) { var weldingLine = T.GetObject(selectedObjectId, OpenMode.ForWrite) as Arc; var sPt = sidePoint.TransformBy(GeometryUtility.GetTransforMatrixToWcs()); var tP1 = new Point3d(0, 0, 0); var tP2 = new Point3d(weldingLine.EndPoint.X - weldingLine.StartPoint.X, weldingLine.EndPoint.Y - weldingLine.StartPoint.Y, weldingLine.EndPoint.Z - weldingLine.StartPoint.Z); var tP3 = new Point3d(sPt.X - weldingLine.StartPoint.X, sPt.Y - weldingLine.StartPoint.Y, sPt.Z - weldingLine.StartPoint.Z); var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false); weldingLine.TransformBy(ucs); if (weldingSideRslt.StringResult == "Side") { sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem); sidePoint = sidePoint.TransformBy(ucs); } var oldUcs = _ed.CurrentUserCoordinateSystem; _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; var arcSide = GeometryUtility.SideOfPointToArc(weldingArc.Center, weldingArc.Radius, sidePoint); var sAng = -1 + weldingArc.Center.DistanceTo(sidePoint) / weldingArc.Radius; _weldingArcs = BuildWeldingArcsOverArc(weldingArc.Center, weldingArc.Radius, weldingArc.StartAngle, weldingArc.EndAngle, weldingArcsChordRslt.Value, weldingArcsOffsetRslt.Value, weldingArcsOffsetRslt.Value / 2, arcSide); DrawWeldingLine(_weldingArcs, T); _ed.CurrentUserCoordinateSystem = oldUcs; foreach (Arc a in _weldingArcs) { a.TransformBy(ucs.Inverse()); } weldingLine.TransformBy(ucs.Inverse()); T.Commit(); } } else { MessageBox.Show("\nYou did not slected object of type Arc. Try again..."); } tr.Commit(); } break; #endregion } #endregion }
/// <summary> /// Removes all existing hatching and regenerates it based on current applied levels. /// </summary> public void GenerateHatching() { //Remove all existing hatches foreach (PlotHatch ph in Hatches) { ph.Erase(); } Hatches.Clear(); Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; //Set to only work for exposed brickwork Transaction acTrans = acCurDb.TransactionManager.TopTransaction; //TODO: Optimise by cahcing Polyline perimeter = new Polyline(); //Build the perimeter line foreach (WallJoint wj in PerimeterPath) { perimeter.AddVertexAt(perimeter.NumberOfVertices, new Point2d(wj.Point.X, wj.Point.Y), 0, 0, 0); } perimeter.Closed = true; Polyline tankOffset = perimeter.GetOffsetCurves(-Properties.Settings.Default.P_Hatch_Offset)[0] as Polyline; Polyline exposedOffset = perimeter.GetOffsetCurves(Properties.Settings.Default.P_Hatch_Offset)[0] as Polyline; /*BlockTable acBlkTbl; * acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; * BlockTableRecord acBlkTblRec; * acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; * acBlkTblRec.AppendEntity(tankOffset); * acTrans.AddNewlyCreatedDBObject(tankOffset, true); */ //Calculate first point not at ground level int startIndex = 0; for (int i = 0; i < PerimeterPath.Count; i++) { if (PerimeterPath[i].Courses() == 0) { startIndex = i; break; } } Point3dCollection hatchBoundaryPoints = new Point3dCollection(); Point3dCollection hatchOffsetPoints = new Point3dCollection(); bool hatchActive = false; //Iterate around perimeter for (int i = startIndex; i <= PerimeterPath.Count + startIndex; i++) { int index; if (i >= PerimeterPath.Count) { index = i - PerimeterPath.Count; } else { index = i; } if (PerimeterPath[index].Courses() != 0) { if (!hatchActive) { hatchActive = true; if (index == 0) { hatchBoundaryPoints.Add(PerimeterPath[PerimeterPath.Count - 1].Point); } else { hatchBoundaryPoints.Add(PerimeterPath[index - 1].Point); } } hatchBoundaryPoints.Add(PerimeterPath[index].Point); if (PerimeterPath[index].Courses() > 0) { hatchOffsetPoints.Add(exposedOffset.GetPoint3dAt(index)); } else { hatchOffsetPoints.Add(tankOffset.GetPoint3dAt(index)); } } else //End potentially found { if (hatchActive) { hatchActive = false; hatchBoundaryPoints.Add(PerimeterPath[index].Point); for (int y = hatchOffsetPoints.Count - 1; y >= 0; y--) { hatchBoundaryPoints.Add(hatchOffsetPoints[y]); } //Create hatch PlotHatch ph = new PlotHatch(); ph.Generate(hatchBoundaryPoints); hatchBoundaryPoints.Clear(); hatchOffsetPoints.Clear(); Hatches.Add(ph); } } } /*BlockReference newBlockRef = (BlockReference)BlockRef.GetObject(OpenMode.ForWrite); * DBObjectCollection explodedBlock = new DBObjectCollection(); * newBlockRef.Explode(explodedBlock); * * foreach (Entity entToAdd in explodedBlock) * { * if (entToAdd is Polyline) * { * Polyline acPline = entToAdd as Polyline; * * // Open the Block table for read * BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; * * // Open the Block table record Model space for write * BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; * * //Add tanking and exposed brickwork * //Order levels by param along line to include doors in the correct place * var levelChanges = (from l in Level orderby l.Param ascending select l).ToList(); * * int startPoint = 0; * bool Tanking = false; * * //Check if first point is ok by seeing if there is a 150mm difference or less * if (Math.Round(levelChanges[0].Level, 3) < -0.15 && !(levelChanges[0].Absolute == true && double.Parse(levelChanges[0].TextValue) < FinishedFloorLevel - 0.150)) * { * //First point is not level, step backwards through the list untill point is found * int negCount = 0; * for (int i = levelChanges.Count - 1; i >= 0; i--) * { * if (Math.Round(levelChanges[i].Level, 3) < -0.15 && !(levelChanges[i].Absolute == true && double.Parse(levelChanges[i].TextValue) < FinishedFloorLevel - 0.150)) * { * negCount--; * } * else * { * //TODO: WOrk out why an if check? Thinks its so its doesnt go past the first ok pont. Change the outer if loop to a while?? * if (startPoint == 0) * { * startPoint = negCount; * } * } * } * } * * //Define point collections to hold the boundary coordinates * Point3dCollection hatchBoundaryPoints = new Point3dCollection(); * Point3dCollection hatchOffsetPoints = new Point3dCollection(); * * // Create the offset polyline * //TODO: Add check here for very small lines not able to be offset * DBObjectCollection offsetOutlineObjects = acPline.GetOffsetCurves(Civils.Constants.TankingHatchOffest); * Polyline offsetOutline = offsetOutlineObjects[0] as Polyline; * * for (int step = startPoint; step < levelChanges.Count; step++) * { * int i = 0; //Convert step to accessor * if (step < 0) * { * i = levelChanges.Count + startPoint; * * } else * { * i = step; * } * * //if (Math.Round(levelChanges[i].Level, 3) != -0.15 && !(levelChanges[i].Absolute == true && double.Parse(levelChanges[i].TextValue) == FinishedFloorLevel - 0.150)) * if (Math.Round(levelChanges[i].Level, 3) < -0.15 && !(levelChanges[i].Absolute == true && double.Parse(levelChanges[i].TextValue) < FinishedFloorLevel - 0.150)) * { * if (!Tanking) * { * Tanking = true; * //Stop overflow if the first point is one * if (i == 0) * { * hatchBoundaryPoints.Add(acPline.GetPointAtParameter(levelChanges[levelChanges.Count - 1].Param)); * } * else * { * hatchBoundaryPoints.Add(acPline.GetPointAtParameter(levelChanges[i - 1].Param)); * } * } * hatchBoundaryPoints.Add(acPline.GetPointAtParameter(levelChanges[i].Param)); * hatchOffsetPoints.Add(offsetOutline.GetPointAtParameter(levelChanges[i].Param)); * } * else * { * if (Tanking) * { * //end point found * Tanking = false; * hatchBoundaryPoints.Add(acPline.GetPointAtParameter(levelChanges[i].Param)); * * //Create hatch object * //Traverse outline backwards to pick up points * for (int j = hatchOffsetPoints.Count - 1; j >= 0; j--) * { * hatchBoundaryPoints.Add(hatchOffsetPoints[j]); * } * * // Lose this line in the real command * bool success = JPPCommandsInitialisation.setJPPLayers(); * * PlotHatch ph = new PlotHatch(); * ph.Generate(hatchBoundaryPoints); * Hatches.Add(ph); * * hatchBoundaryPoints.Clear(); * hatchOffsetPoints.Clear(); * } * } * } * * //Loop finished without tank ending, therefore first point is end * if(Tanking) * { * Tanking = false; * hatchBoundaryPoints.Add(acPline.GetPointAtParameter(levelChanges[0].Param)); * * //Create hatch object * //Traverse outline backwards to pick up points * for (int j = hatchOffsetPoints.Count - 1; j >= 0; j--) * { * hatchBoundaryPoints.Add(hatchOffsetPoints[j]); * } * * // Lose this line in the real command * bool success = JPPCommandsInitialisation.setJPPLayers(); * * PlotHatch ph = new PlotHatch(); * ph.Generate(hatchBoundaryPoints); * Hatches.Add(ph); * * hatchBoundaryPoints.Clear(); * hatchOffsetPoints.Clear(); * } * } * }*/ }