Example #1
0
        private static void WipeoutEditOCM_Document_ImpliedSelectionChanged(object sender, EventArgs e)
        {
            PromptSelectionResult psr = AcApp.DocumentManager.MdiActiveDocument.Editor.SelectImplied();
            bool detach = true;

            if (psr.Value != null && psr.Value.Count == 1)
            {
                using (AcApp.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    using (OpenCloseTransaction tr = new OpenCloseTransaction())
                    {
                        foreach (SelectedObject selectedObject in psr.Value)
                        {
                            if (selectedObject.ObjectId == ObjectId.Null)
                            {
                                continue;
                            }
                            var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                            if (obj is Wipeout)
                            {
                                MiniFunctionsContextMenuExtensions.WipeoutEditObjectContextMenu.Attach();
                                detach = false;
                            }
                        }

                        tr.Commit();
                    }
                }
            }

            if (detach)
            {
                MiniFunctionsContextMenuExtensions.WipeoutEditObjectContextMenu.Detach();
            }
        }
Example #2
0
        handOverPoly3d2(this ObjectId idPoly3dOrg, List <Point3d> pnts3d)
        {
            Database          db         = BaseObjs._db;
            Point3dCollection pnts3dColl = new Point3dCollection();

            foreach (Point3d pnt3d in pnts3d)
            {
                pnts3dColl.Add(pnt3d);
            }

            using (OpenCloseTransaction tr = db.TransactionManager.StartOpenCloseTransaction())
            {
                Polyline3d poly3dOrg = (Polyline3d)tr.GetObject(idPoly3dOrg, OpenMode.ForRead);
                Debug.Print(poly3dOrg.Handle.ToString());

                Polyline3d poly3dNew = new Polyline3d(Poly3dType.SimplePoly, pnts3dColl, false);
                poly3dNew.SetDatabaseDefaults();
                poly3dNew.Layer = poly3dOrg.Layer;

                poly3dOrg.UpgradeOpen();
                poly3dOrg.HandOverTo(poly3dNew, true, true);
                Debug.Print(poly3dOrg.Handle.ToString());
                Debug.Print(poly3dNew.Handle.ToString());
                bool x = poly3dOrg.IsDisposed;
                poly3dOrg.Dispose();

                tr.AddNewlyCreatedDBObject(poly3dNew, true);
                tr.Commit();
            }
        }
Example #3
0
        public void MyCommand() // 这个方法可以使用任意名称,执行命令时使用上一句代码定义的名称
        {
            // Put your code here
            Database db = HostApplicationServices.WorkingDatabase;

            using (OpenCloseTransaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                Point3d          pt1 = new Point3d();
                Point3d          pt2 = new Point3d();
                Point3d          pt3 = new Point3d();

                if (GetPoint("\n输入起点:", out pt1) && GetPoint("\n输入起点:", out pt2) && GetPoint("\n输入起点:", out pt3))
                {
                    Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
                    FaneTriangleWrapper faneTriangle = new FaneTriangleWrapper(pt1, pt2, pt3);
                    //double area = faneTriangle.GetArea();
                    Point3dCollection collection = null;
                    faneTriangle.GetVerts(out collection);
                    foreach (Point3d item in collection)
                    {
                        ed.WriteMessage("\n三角形的顶点X坐标:{0}", item.X);
                    }
                    btr.AppendEntity(faneTriangle);
                    trans.AddNewlyCreatedDBObject(faneTriangle, true);

                    trans.Commit();
                }
            }
        }
Example #4
0
        private static List <object> GetLayerObjectsByLayerName(List <string> layerNames)
        {
            List <object> objects = new List <object>();

            if (layerNames.Count != 0)
            {
                using (OpenCloseTransaction trans = acCurDb.TransactionManager.StartOpenCloseTransaction())
                {
                    foreach (string layerName in layerNames)
                    {
                        try
                        {
                            TypedValue[] typedValue = new TypedValue[]
                            {
                                new TypedValue((int)DxfCode.LayerName, layerName)
                            };
                            SelectionFilter       filter = new SelectionFilter(typedValue);
                            PromptSelectionResult result = ed.SelectAll(filter);
                            SelectionSet          set    = result.Value;
                            ObjectId[]            ids    = set.GetObjectIds();
                            foreach (ObjectId entid in ids)
                            {
                                objects.Add(trans.GetObject(entid, OpenMode.ForRead));
                            }
                        }
                        catch (Exception)
                        {
                            ed.WriteMessage("\n获取信息出错。");
                        }
                    }
                    trans.Commit();
                }
            }
            return(objects);
        }
Example #5
0
        public static IEnumerable <Point3d> GetPointsFromPolyline([NotNull] this Database database, ObjectId id)
        {
            using (OpenCloseTransaction transAction = database.TransactionManager.StartOpenCloseTransaction())
            {
                object objectX = transAction.GetObject(id, OpenMode.ForRead);
                switch (objectX.GetType().ToString())
                {
                case "Autodesk.AutoCAD.DatabaseServices.Polyline3d":
                {
                    //Get a list of 3D points in parameter order
                    using (Polyline3d pl1 = (Polyline3d)objectX)
                    {
                        // We get curve here, its faster to get the
                        // parameters and point on a non database object
                        var curve            = pl1.GetGeCurve(new Tolerance(1e-10, 1e-10));
                        var polylineEndParam = (int)pl1.EndParam;

                        // Initialize list with dimensions specified (speed)
                        Point3d[] arrRes = new Point3d[polylineEndParam + 1];

                        for (int i = 0; i <= polylineEndParam; i++)
                        {
                            var distOnPl = pl1.GetDistanceAtParameter(i);
                            arrRes[i] = curve.EvaluatePoint(curve.GetParameterAtLength(0, distOnPl, true, 1e-10));
                        }
                        transAction.Commit();
                        return(arrRes);
                    }
                }

                default: throw new Exception("\r\n\t=> Selected object is not supported for this function.");
                }
            }
        }
Example #6
0
            protected CoordinateSystem3d GetECS(ObjectId entityId)
            {
                CoordinateSystem3d coordinateSystem3D = new CoordinateSystem3d(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis);

                if (!entityId.IsNull)
                {
                    using (OpenCloseTransaction openCloseTransaction = new OpenCloseTransaction())
                    {
                        Entity obj = (Entity)openCloseTransaction.GetObject(entityId, OpenMode.ForRead);
                        if (obj != null)
                        {
                            //if (obj.IsPlanar || obj is MLeader)
                            //{
                            Plane plane  = obj.GetPlane();
                            Plane plane1 = new Plane(plane.PointOnPlane, plane.Normal);
                            coordinateSystem3D = plane1.GetCoordinateSystem();
                            //}
                            //if (obj is Wipeout)
                            //{
                            //    CoordinateSystem3d orientation = (obj as Wipeout).Orientation;
                            //    Plane plane2 = new Plane(orientation.Origin, orientation.Zaxis.GetNormal());
                            //    coordinateSystem3d = plane2.GetCoordinateSystem();
                            //}
                        }
                        openCloseTransaction.Commit();
                    }
                }
                return(coordinateSystem3D);
            }
Example #7
0
        private static string Cells(int rows, int columns)
        {
            Point3dCollection     downPoints = new Point3dCollection();
            Point3dCollection     upPoints   = new Point3dCollection();
            string                textString = string.Empty;
            PromptSelectionResult psr;

            using (OpenCloseTransaction acTrans = AcCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                if (rows == 1 && columns == 1)
                {
                    cLines[rows].IntersectWith(rLines[rLines.Count - 1], Intersect.ExtendBoth, new Plane(), downPoints,
                                               IntPtr.Zero, IntPtr.Zero);
                    cLines[rows - 1].IntersectWith(rLines[1], Intersect.ExtendBoth, new Plane(), upPoints, IntPtr.Zero,
                                                   IntPtr.Zero);
                }
                else
                {
                    cLines[rows].IntersectWith(rLines[columns], Intersect.ExtendBoth, new Plane(), downPoints,
                                               IntPtr.Zero, IntPtr.Zero);
                    cLines[rows - 1].IntersectWith(rLines[columns - 1], Intersect.ExtendBoth, new Plane(), upPoints,
                                                   IntPtr.Zero, IntPtr.Zero);
                }

                psr = Ed.SelectCrossingWindow(downPoints[0], upPoints[0]);
                if (psr.Status == PromptStatus.OK)
                {
                    SelectionSet set = psr.Value;
                    foreach (SelectedObject text in set)
                    {
                        if (text != null)
                        {
                            MText acMText = acTrans.GetObject(text.ObjectId, OpenMode.ForWrite) as MText;
                            if (acMText == null)
                            {
                                DBText acText = acTrans.GetObject(text.ObjectId, OpenMode.ForRead) as DBText;
                                if (acText != null)
                                {
                                    textString = acText.TextString;
                                    return(textString);
                                }
                            }
                            else
                            {
                                textString = GetText(acMText.Contents);
                                return(textString);
                            }
                        }
                    }
                }
                acTrans.Commit();
            }
            return("null");
        }
Example #8
0
        }                                                 //保存公司内部图层
        private static void GetImgLayers(Database acCurDb)
        {
            List <string> Alllayers = new List <string>();

            using (OpenCloseTransaction trans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                LayerTable lt = trans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                Alllayers.AddRange(from ObjectId id in lt select trans.GetObject(id, OpenMode.ForRead) as LayerTableRecord into ltr select ltr.Name);
                string strexp = @"^0-BIM-";
                Regex  regex  = new Regex(strexp);
                ImgLayers = Alllayers.Where(layer => regex.IsMatch(layer)).ToList();
                trans.Commit();
            }
        }
Example #9
0
        public static ObjectId AddToModelSapce(this Database db, Entity ent)
        {
            ObjectId entId;

            using (OpenCloseTransaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable       bt  = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                entId = btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
                trans.Commit();
            }
            return(entId);
        }
Example #10
0
        private static bool ReadImgTable()
        {
            AcDoc   = Application.DocumentManager.MdiActiveDocument;
            AcCurDb = AcDoc.Database;
            Ed      = AcDoc.Editor;
            PromptSelectionResult psr = Ed.GetSelection();

            if (psr.Status == PromptStatus.OK)
            {
                SelectionSet ss = psr.Value;
                if (ss == null)
                {
                    return(false);
                }
                var ids = ss.GetObjectIds();
                using (OpenCloseTransaction acTrans = AcCurDb.TransactionManager.StartOpenCloseTransaction())
                {
                    foreach (var id in ids)
                    {
                        var dbLine = acTrans.GetObject(id, OpenMode.ForRead) as Line;
                        if (dbLine == null)
                        {
                            continue;
                        }
                        Vector2d ve = new Vector2d(dbLine.StartPoint.X - dbLine.EndPoint.X,
                                                   dbLine.StartPoint.Y - dbLine.EndPoint.Y);
                        if (ve.Angle == 0 || ve.Angle == Math.PI)
                        {
                            cLines.Add(dbLine);
                        }
                        else if (ve.Angle == Math.PI / 2 || ve.Angle == 1.5 * Math.PI)
                        {
                            rLines.Add(dbLine);
                        }
                    }
                    acTrans.Commit();
                }
                var temp = from line in cLines
                           orderby line.EndPoint.Y descending
                           select line;
                cLines = temp.ToList();

                temp = from line in rLines
                       orderby line.EndPoint.X
                       select line;
                rLines = temp.ToList();
                return(true);
            }
            return(false);
        }
Example #11
0
        /// <summary>
        /// 将实体添加到模型空间
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="ent">要添加的实体</param>
        /// <returns>返回添加到模型空间中的实体</returns>
        public static ObjectId AddToModelSpace(this Database db, Entity ent)
        {
            ObjectId entId; //用于返回添加到模型空间中的实体ObjectId

            //定义一个指向当前数据库的事务处理,以添加直线
            using (OpenCloseTransaction trans = db.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);                        //以只读方式打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //以写方式打开模型空间块表记录
                entId = btr.AppendEntity(ent);                                                                                //将图形对象的信息添加到块表记录中
                trans.AddNewlyCreatedDBObject(ent, true);                                                                     //把对象添加到事务处理中
                trans.Commit();                                                                                               //提交事务处理
            }
            return(entId);
        }
Example #12
0
        /// <summary>
        /// 获得图层上所有实体
        /// </summary>
        /// <param name="layerName">图层名</param>
        /// <returns></returns>
        private static List <MText> GetLayerDbtxtByLayerName(List <string> layerNames)
        {
            List <MText> txts = new List <MText>();

            if (layerNames.Count != 0)
            {
                using (OpenCloseTransaction trans = acCurDb.TransactionManager.StartOpenCloseTransaction())
                {
                    foreach (string layerName in layerNames)
                    {
                        try
                        {
                            TypedValue[] typedValue = new TypedValue[]
                            {
                                new TypedValue((int)DxfCode.LayerName, layerName),

                                //new TypedValue((int)DxfCode.Start, "MTEXT"),
                            };
                            SelectionFilter       filter = new SelectionFilter(typedValue);
                            PromptSelectionResult result = ed.SelectAll(filter);
                            //if (result.Value == null)
                            //{
                            //    return txts;
                            //}
                            SelectionSet set = result.Value;
                            ObjectId[]   ids = set.GetObjectIds();
                            foreach (ObjectId entid in ids)
                            {
                                //txts.Add(trans.GetObject(entid, OpenMode.ForRead) as DBText);
                                txts.Add(trans.GetObject(entid, OpenMode.ForRead) as MText);
                            }
                        }
                        catch (Exception)
                        {
                            ed.WriteMessage("\n获取文本信息出错。");
                        }
                    }
                    trans.Commit();
                }
            }
            var temp = from mtext in txts
                       orderby mtext.Location.Y descending, mtext.Location.X
            select mtext;

            txts = temp.ToList();
            return(txts);
        }
Example #13
0
        public static Tuple <IEnumerable <Point3d>, IEnumerable <Point3d> > GetPointsFrom2PolylinesWithPointWeeding([NotNull] this Database database, ObjectId id1, ObjectId id2, [GreaterThan(.0)] double weeding)
        {
            // Weeding, we only add the point when weeding factor has been satisfied.

            using (OpenCloseTransaction transAction = database.TransactionManager.StartOpenCloseTransaction())
            {
                object object1 = transAction.GetObject(id1, OpenMode.ForRead);
                object object2 = transAction.GetObject(id2, OpenMode.ForRead);

                if (object1.GetType().ToString() != "Autodesk.AutoCAD.DatabaseServices.Polyline3d" ||
                    object2.GetType().ToString() != "Autodesk.AutoCAD.DatabaseServices.Polyline3d")
                {
                    throw new Exception("\r\n\t=> Selected object is not supported for this function.");
                }

                //Get a list of 3D points in parameter order
                using (Polyline3d pl1 = (Polyline3d)object1)
                    using (Polyline3d pl2 = (Polyline3d)object2)
                    {
                        // We get curve here, its faster to get the parameters and
                        // point on a non database object
                        var curve1 = pl1.GetGeCurve(new Tolerance(1e-10, 1e-10));
                        var curve2 = pl2.GetGeCurve(new Tolerance(1e-10, 1e-10));

                        // Initialize list with dimensions specified (speed)
                        var       bounds     = (int)Math.Ceiling(pl1.Length / weeding) + 1;
                        Point3d[] arrRes1    = new Point3d[bounds];
                        Point3d[] arrRes2    = new Point3d[bounds];
                        var       arrCounter = 0;

                        // For each point on PL1 we find the closest point on PL2
                        // and create a tuple of the result.
                        for (double i = 0.0; i < pl1.Length; i += weeding)
                        {
                            var p1 = curve1.EvaluatePoint(curve1.GetParameterAtLength(0, i, true, 1e-10));
                            var p2 = curve2.GetClosestPointTo(p1, new Tolerance(1e-10, 1e-10)).Point;
                            arrRes1[arrCounter]   = p1;
                            arrRes2[arrCounter++] = p2;
                        }
                        arrRes1[arrCounter] = pl1.EndPoint;
                        arrRes2[arrCounter] = curve2.GetClosestPointTo(pl1.EndPoint, new Tolerance(1e-10, 1e-10)).Point;
                        transAction.Commit();
                        return(new Tuple <IEnumerable <Point3d>, IEnumerable <Point3d> >(arrRes1, arrRes2));
                    }
            }
        }
        private static void Document_ImpliedSelectionChanged(object sender, EventArgs e)
        {
            var psr    = AcApp.DocumentManager.MdiActiveDocument.Editor.SelectImplied();
            var detach = true;

            if (psr.Value != null)
            {
                using (AcApp.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    using (var tr = new OpenCloseTransaction())
                    {
                        foreach (SelectedObject selectedObject in psr.Value)
                        {
                            if (selectedObject.ObjectId == ObjectId.Null)
                            {
                                continue;
                            }
                            var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                            if (obj is Entity entity)
                            {
                                var xData = entity.GetXDataForApplication("ModPlusProduct");
                                if (xData != null)
                                {
                                    detach = false;
                                    break;
                                }
                            }
                        }

                        tr.Commit();
                    }
                }
            }

            if (detach)
            {
                ObjectContextMenu.Detach();
            }
            else
            {
                ObjectContextMenu.Attach();
            }
        }
Example #15
0
        public IList <FeatureItem> ProcessFeatureItems()
        {
            try
            {
                var doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
                using (Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database)
                {
                    var features = new List <FeatureItem>();
                    var pid      = GetPolylineEntityIDs(db);
                    var temp     = new List <Polyline>();

                    foreach (ObjectId item in pid)
                    {
                        using (OpenCloseTransaction tr = db.TransactionManager.StartOpenCloseTransaction())
                        {
                            Polyline pline = (Polyline)tr.GetObject(item, OpenMode.ForWrite);
                            temp.Add(pline);
                            tr.Commit();
                        }
                    }

                    var distpolys = temp.Select(p => p.Layer).Distinct();

                    foreach (var item in distpolys)
                    {
                        var feature = new FeatureItem();
                        feature.active = true;
                        feature.layer  = item;
                        feature.name   = GetShortLayerName(item);
                        feature.count  = temp.Count(p => p.Layer == item);
                        features.Add(feature);
                    }
                    return(features);
                }
            }
            catch (System.Exception ex)
            {
                COMS.MessengerManager.LogException(ex);
            }
            return(null);
        }
        // ReSharper disable once InconsistentNaming
        private static CoordinateSystem3d GetECS(ObjectId entityId)
        {
            var coordinateSystem3D = new CoordinateSystem3d(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis);

            if (!entityId.IsNull)
            {
                using (var openCloseTransaction = new OpenCloseTransaction())
                {
                    var obj = (Entity)openCloseTransaction.GetObject(entityId, OpenMode.ForRead);
                    if (obj != null)
                    {
                        var plane  = obj.GetPlane();
                        var plane1 = new Plane(plane.PointOnPlane, plane.Normal);
                        coordinateSystem3D = plane1.GetCoordinateSystem();
                    }

                    openCloseTransaction.Commit();
                }
            }

            return(coordinateSystem3D);
        }
Example #17
0
        public static void ChangReinText()
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            ed.WriteMessage("\n异常钢筋符号快速替换 2016/10/14");
            Stopwatch sw = new Stopwatch();

            sw.Start();
            using (OpenCloseTransaction acTrams = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                TypedValue[]          typedValue = new TypedValue[] { new TypedValue((int)DxfCode.Start, "TEXT") };
                SelectionFilter       filter     = new SelectionFilter(typedValue);
                PromptSelectionResult result     = ed.SelectAll(filter);
                if (result.Status == PromptStatus.OK)
                {
                    SelectionSet set = result.Value;
                    foreach (SelectedObject text in set)
                    {
                        if (text != null)
                        {
                            DBText acText = acTrams.GetObject(text.ObjectId, OpenMode.ForWrite) as DBText;
                            if (acText != null)
                            {
                                if (acText.TextString.Contains("„"))
                                {
                                    string[] strs = acText.TextString.Split('„');
                                    acText.TextString = acText.TextString.Replace("„", "%%132");
                                }
                            }
                        }
                    }
                }
                acTrams.Commit();
            }
            sw.Stop();
            ed.WriteMessage("\n替换操作,耗时{0}ms", sw.ElapsedMilliseconds);
        }
Example #18
0
        public static IEnumerable <Point3d> GetPointsFromPolylineWithPointWeeding([NotNull] this Database database, ObjectId id, [GreaterThan(.0)] double weeding)
        {
            // Weeding, we only add the point when weeding factor has been satisfied.

            using (OpenCloseTransaction transAction = database.TransactionManager.StartOpenCloseTransaction())
            {
                object objectX = transAction.GetObject(id, OpenMode.ForRead);
                switch (objectX.GetType().ToString())
                {
                case "Autodesk.AutoCAD.DatabaseServices.Polyline3d":
                {
                    //Get a list of 3D points in parameter order
                    using (Polyline3d pl1 = (Polyline3d)objectX)
                    {
                        // We get curve here, its faster to get the
                        // parameters and point on a non database object
                        var curve = pl1.GetGeCurve(new Tolerance(1e-10, 1e-10));

                        // Initialize list with dimensions specified (speed)
                        var       bounds     = (int)Math.Ceiling(pl1.Length / weeding) + 1;
                        Point3d[] arrRes     = new Point3d[bounds];
                        var       arrCounter = 0;

                        for (double i = 0.0; i < pl1.Length; i += weeding)
                        {
                            var x = curve.EvaluatePoint(curve.GetParameterAtLength(0, i, true, 1e-10));
                            arrRes[arrCounter++] = x;
                        }
                        arrRes[arrCounter] = pl1.EndPoint;
                        transAction.Commit();
                        return(arrRes);
                    }
                }

                default: throw new Exception("\r\n\t=> Selected object is not supported for this function.");
                }
            }
        }
Example #19
0
        private static void Document_ImpliedSelectionChanged(object sender, EventArgs e)
        {
            var psr    = AcadUtils.Editor.SelectImplied();
            var detach = true;

            if (psr.Value != null && psr.Value.Count == 1)
            {
                using (AcadUtils.Document.LockDocument())
                {
                    using (var tr = new OpenCloseTransaction())
                    {
                        foreach (SelectedObject selectedObject in psr.Value)
                        {
                            if (selectedObject.ObjectId == ObjectId.Null)
                            {
                                continue;
                            }

                            var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                            if (obj is BlockReference blockReference &&
                                ExtendedDataUtils.IsApplicable(blockReference))
                            {
                                AttachCreateAnalogContextMenu();
                                detach = false;
                            }
                        }

                        tr.Commit();
                    }
                }
            }

            if (detach)
            {
                DetachCreateAnalogContextMenu();
            }
        }
Example #20
0
        public void CreateAnalogCommand()
        {
            var psr = AcadUtils.Editor.SelectImplied();

            if (psr.Value == null || psr.Value.Count != 1)
            {
                return;
            }

            SmartEntity intellectualEntity = null;

            using (AcadUtils.Document.LockDocument())
            {
                using (var tr = new OpenCloseTransaction())
                {
                    foreach (SelectedObject selectedObject in psr.Value)
                    {
                        if (selectedObject.ObjectId == ObjectId.Null)
                        {
                            continue;
                        }

                        var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                        if (obj is BlockReference blockReference)
                        {
                            intellectualEntity = EntityReaderService.Instance.GetFromEntity(blockReference);
                        }
                    }

                    tr.Commit();
                }
            }

            if (intellectualEntity == null)
            {
                return;
            }

            var copyLayer = true;
            var layerActionOnCreateAnalog = MainSettings.Instance.LayerActionOnCreateAnalog;

            if (layerActionOnCreateAnalog == LayerActionOnCreateAnalog.NotCopy)
            {
                copyLayer = false;
            }
            else if (layerActionOnCreateAnalog == LayerActionOnCreateAnalog.Ask)
            {
                var promptKeywordOptions =
                    new PromptKeywordOptions($"\n{Language.GetItem("msg8")}", "Yes No");
                var promptResult = AcadUtils.Editor.GetKeywords(promptKeywordOptions);
                if (promptResult.Status == PromptStatus.OK)
                {
                    if (promptResult.StringResult == "No")
                    {
                        copyLayer = false;
                    }
                }
                else
                {
                    copyLayer = false;
                }
            }

            var function = TypeFactory.Instance.GetEntityFunctionTypes().FirstOrDefault(f =>
            {
                var functionName = $"{intellectualEntity.GetType().Name}Function";
                var fName        = f.GetType().Name;
                return(fName == functionName);
            });

            function?.CreateAnalog(intellectualEntity, copyLayer);
        }
        public void CreateKeyLine()
        {
            bool B = true;

            while (B)
            {
                //#region PRE
                //SelectionSet acSSet = SelectLines();

                //if (acSSet == null)
                //{
                //    B = false;
                //    return;
                //}
                //#endregion

                //#region 폴리라인 선택
                //var selectedPolyLines = new List<Polyline>();
                //var acPolylines = new List<Polyline>();

                //using (Transaction T = AC.DB.TransactionManager.StartTransaction())
                //{
                //    var Lines = from id in acSSet.GetObjectIds()
                //                let acEnt = T.GetObject(id, OpenMode.ForWrite) as Entity
                //                where acEnt is Polyline
                //                let acLine = acEnt as Polyline
                //                select acLine;

                //    if (!Lines.Any())
                //        return;

                //    selectedPolyLines.AddRange(Lines.ToArray());
                //}
                //#endregion

                var Polylines   = select.Objects <Polyline>();
                var acPolylines = new List <Polyline>();

                #region 폴리라인 정리
                Polylines.ForEach(pl =>
                {
                    #region 폴리라인에서 커브 담기
                    var curves = new List <Curve3d>();

                    for (int i = 0; i < pl.NumberOfVertices; i++)
                    {
                        try
                        {
                            var l = pl.GetLineSegmentAt(i).Length;

                            if (l >= Min && l <= Max)
                            {
                                curves.Add(pl.GetLineSegmentAt(i));
                            }
                        }
                        catch (System.Exception)
                        {
                        }
                    }
                    #endregion

                    #region 폴리라인 장축 중심을 읻는 선
                    if (curves.Count == 2)
                    {
                        var cv1 = curves[0];
                        var cv2 = curves[1];

                        var p1 = CADUtil.GetCenterPoint3d(cv1);
                        var p2 = CADUtil.GetCenterPoint3d(cv2);

                        var vec = CADUtil.GetVector(p1, p2);

                        var X = (vec * extend).X;
                        var Y = (vec * extend).Y;

                        var sp = CADUtil.MoveP(p1, -X, -Y, 0);
                        var ep = CADUtil.MoveP(p2, X, Y, 0);

                        var acPolyline = CADUtil.CreatePolyline(sp, ep);

                        acPolylines.Add(acPolyline);
                    }
                    #endregion
                });
                #endregion

                using (DocumentLock DL = AC.Doc.LockDocument())
                {
                    #region 검토 & 연속된 선 연결
                    // 제거할 선들
                    var deletePolylines = new List <Polyline>();

                    acPolylines.ForEach(pl1 =>
                    {
                        var contiPolylines = new List <Polyline>();

                        // 평행하고 같은 선상에 있는 선들
                        var paralPolylines = from pl2 in acPolylines
                                             where !deletePolylines.Contains(pl2)
                                             let line1                         = pl1.GetLineSegmentAt(0)
                                                                     let line2 = pl2.GetLineSegmentAt(0)
                                                                                 where line1.IsParallelTo(line2, new Tolerance(1, 1))
                                                                                 where IsAlmostEqual(line1, line2)
                                                                                 select pl2;

                        // 평행하고 같은 선상에 있는 선들 개수
                        int N = paralPolylines.Count();

                        var paralNearPolylines                                                             = from pl2 in paralPolylines
                                                                         let line1                         = pl1.GetLineSegmentAt(0)
                                                                                                 let line2 = pl2.GetLineSegmentAt(0)
                                                                                                             where CADUtil.getNearDistance(line1, line2) < distance
                                                                                                             select pl2;

                        if (paralNearPolylines.Any())
                        {
                            contiPolylines.AddRange(paralNearPolylines);

                            for (int j = 0; j < N; j++)
                            {
                                contiPolylines.ToList().ForEach(a =>
                                {
                                    var srtPolylines = from pl2 in acPolylines
                                                       where !contiPolylines.Contains(pl2)
                                                       let line1                         = a.GetLineSegmentAt(0)
                                                                               let line2 = pl2.GetLineSegmentAt(0)
                                                                                           where line1.IsParallelTo(line2, new Tolerance(1, 1))
                                                                                           where IsAlmostEqual(line1, line2)
                                                                                           where CADUtil.getNearDistance(line1, line2) < 2 * extend + distance
                                                                                           select pl2;

                                    if (srtPolylines.Any())
                                    {
                                        contiPolylines.AddRange(srtPolylines);
                                    }
                                });
                            }
                        }

                        if (contiPolylines.Any())
                        {
                            var Ps = CADUtil.getFurPoints(contiPolylines.ToList());

                            var acPolyline = CADUtil.CreatePolyline(Ps[0], Ps[1]);

                            deletePolylines.AddRange(contiPolylines);
                        }
                    });

                    #endregion

                    #region 제거
                    using (OpenCloseTransaction T = AC.DB.TransactionManager.StartOpenCloseTransaction())
                    {
                        deletePolylines.ForEach(a =>
                        {
                            var entity = T.GetObject(a.Id, OpenMode.ForWrite) as Entity;

                            if (!entity.IsErased)
                            {
                                entity.Erase(true);
                            }
                        });

                        T.Commit();
                    }
                    #endregion
                }
            }

            AC.Editor.WriteMessage("\n키라인 입력완료 ");
            AC.Editor.PostCommandPrompt();
        }
        public void CreateKeyLine2()
        {
            var selectedPolyLines = new List <Polyline>();
            var acPolylines       = new List <Polyline>();

            #region 폴리라인 선택
            using (Transaction T = AC.DB.TransactionManager.StartTransaction())
            {
                try
                {
                    SelectionSet acSSet = SelectLines();

                    var Lines = from id in acSSet.GetObjectIds()
                                let acEnt = T.GetObject(id, OpenMode.ForWrite) as Entity
                                            where acEnt is Polyline
                                            let acLine = acEnt as Polyline
                                                         select acLine;

                    if (!Lines.Any())
                    {
                        return;
                    }

                    selectedPolyLines.AddRange(Lines.ToArray());
                }
                catch (System.Exception ex)
                {
                    AC.Editor.WriteMessage(Convert.ToString(ex));
                }
            }
            #endregion

            using (DocumentLock DL = AC.Doc.LockDocument())
            {
                #region 입력
                selectedPolyLines.ForEach(pl =>
                {
                    #region 폴리라인에서 커브 담기
                    var curves = new List <Curve3d>();

                    for (int i = 0; i < pl.NumberOfVertices; i++)
                    {
                        try
                        {
                            var l = pl.GetLineSegmentAt(i).Length;

                            if (l >= Min && l <= Max)
                            {
                                curves.Add(pl.GetLineSegmentAt(i));
                            }
                        }
                        catch (System.Exception)
                        {
                        }
                    }
                    #endregion

                    if (curves.Count == 2)
                    {
                        var cv1 = curves[0];
                        var cv2 = curves[1];

                        var p1 = CADUtil.GetCenterPoint3d(cv1);
                        var p2 = CADUtil.GetCenterPoint3d(cv2);

                        var vec = CADUtil.GetVector(p1, p2);

                        var X = (vec * extend).X;
                        var Y = (vec * extend).Y;

                        var sp = CADUtil.MoveP(p1, -X, -Y, 0);
                        var ep = CADUtil.MoveP(p2, X, Y, 0);

                        var acPolyline = CADUtil.CreatePolyline(sp, ep);

                        acPolylines.Add(acPolyline);
                    }
                });
                #endregion

                #region 검토 & 연속된 선 연결
                // 제거할 선들
                var deletePolylines = new List <Polyline>();

                acPolylines.ForEach(pl1 =>
                {
                    var direction = pl1.GetLineSegmentAt(0).Direction;
                    direction     = direction.X < 0 ? -direction : direction;
                    var Ang       = Math.Round(Math.Atan2(direction.Y, direction.X) / Math.PI * 180) % 180;
                    var A         = Math.Abs(Ang) == 90 || Ang == 0 ? 0 : Math.Tan(Ang / 180 * Math.PI);

                    //MessageBox.Show(Ang + "\n" + A.ToString());

                    // 같은 2차 그래프에 존재하는 선들
                    var parallelPolylines = from pl2 in acPolylines
                                            where !deletePolylines.Contains(pl2)
                                            let line1                         = pl1.GetLineSegmentAt(0)
                                                                    let line2 = pl2.GetLineSegmentAt(0)
                                                                                where line1.IsParallelTo(line2, new Tolerance(1, 1))
                                                                                //let b1 = line1.StartPoint.Y - A * line1.StartPoint.X
                                                                                //let b2 = line2.StartPoint.Y - A * line2.StartPoint.X
                                                                                //let sp1 = line1.StartPoint
                                                                                //let sp2 = line2.StartPoint
                                                                                //where (Ang == 0 && IsAlmostEqual(sp1.Y, sp2.Y)) ||
                                                                                //      (Math.Abs(Ang) == 90 && IsAlmostEqual(sp1.X, sp2.X)) ||
                                                                                //      (Ang != 0 && Math.Abs(Ang) != 90 && IsAlmostEqual(line1,line2))
                                                                                where IsAlmostEqual(line1, line2)
                                                                                select pl2;

                    if (parallelPolylines.Any())
                    {
                        var Ps = CADUtil.getFurPoints(parallelPolylines.ToList());

                        var acPolyline = CADUtil.CreatePolyline(Ps[0], Ps[1]);

                        deletePolylines.AddRange(parallelPolylines);
                    }
                });

                #endregion

                #region 제거
                using (OpenCloseTransaction T = AC.DB.TransactionManager.StartOpenCloseTransaction())
                {
                    deletePolylines.ForEach(a =>
                    {
                        var entity = T.GetObject(a.Id, OpenMode.ForWrite) as Entity;

                        if (!entity.IsErased)
                        {
                            entity.Erase(true);
                        }
                    });

                    T.Commit();
                }
                #endregion
            }

            AC.Editor.WriteMessage("\n키라인 입력완료 ");
            AC.Editor.PostCommandPrompt();
        }
        /// <summary>
        /// Добавление пользовательских элементов в палитру в зависимости от выбранных объектов
        /// </summary>
        private void ShowPropertiesControlsBySelection()
        {
            BtCollapseAll.Visibility = Visibility.Hidden;

            // Удаляем контролы свойств
            if (StackPanelProperties.Children.Count > 0)
            {
                StackPanelProperties.Children.Clear();
            }

            var psr = AcadUtils.Editor.SelectImplied();

            if (psr.Value == null || psr.Value.Count == 0)
            {
                // Очищаем панель описания
                ShowDescription(string.Empty);

                // hide message
                StckMaxObjectsSelectedMessage.Visibility = Visibility.Collapsed;
            }
            else
            {
                var maxSelectedObjects = MainSettings.Instance.MaxSelectedObjects;
                if (maxSelectedObjects == 0 || maxSelectedObjects >= psr.Value.Count)
                {
                    StckMaxObjectsSelectedMessage.Visibility = Visibility.Collapsed;

                    var objectIds = new List <ObjectId>();
                    using (AcadUtils.Document.LockDocument())
                    {
                        using (var tr = new OpenCloseTransaction())
                        {
                            foreach (SelectedObject selectedObject in psr.Value)
                            {
                                if (selectedObject.ObjectId == ObjectId.Null)
                                {
                                    continue;
                                }

                                var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                                if (obj is BlockReference blockReference &&
                                    ExtendedDataUtils.IsApplicable(blockReference))
                                {
                                    objectIds.Add(selectedObject.ObjectId);
                                }
                            }

                            tr.Commit();
                        }
                    }

                    if (objectIds.Any())
                    {
                        BtCollapseAll.Visibility = Visibility.Visible;
                        var summaryPropertyCollection = new SummaryPropertyCollection(objectIds);
                        summaryPropertyCollection.OnLockedLayerEventHandler +=
                            (sender, args) => ShowPropertiesControlsBySelection();
                        SetData(summaryPropertyCollection);
                    }
                }
                else
                {
                    StckMaxObjectsSelectedMessage.Visibility = Visibility.Visible;
                }
            }
        }