Example #1
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 #2
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 #3
0
        public static IEnumerable <Point3d> Select3dPolyline([NotNull] this Editor editor, [NotEmpty] string message, out ObjectId id)
        {
            IEnumerable <Point3d> arrRes = null;

            //' Start a transaction
            using (OpenCloseTransaction transAction = editor.Document.Database.TransactionManager.StartOpenCloseTransaction())
            {
                //Setting some options
                PromptEntityOptions mypromptOption = new PromptEntityOptions(message)
                {
                    AllowNone = false,
                    AllowObjectOnLockedLayer = true
                };
                mypromptOption.SetRejectMessage("\r\n\t=>Only objects of type <Polyline 3D> are allowed.");
                mypromptOption.AddAllowedClass(typeof(Polyline3d), false);

                //Making a new result and adding options to it
                PromptEntityResult res = editor.GetEntity(mypromptOption);

                if (res.Status == PromptStatus.OK)
                {
                    arrRes = editor.Document.Database.GetPointsFromPolyline(res.ObjectId);
                }
                if (arrRes != null && arrRes.Any())
                {
                    editor.WriteMessage("\r\n\t=>Polyline3d has been selected with " + arrRes.Count() + " vertices's.");
                }

                id = res.ObjectId;
                return(arrRes);
            }

            throw new InvalidOperationException("Something went wrong when handling the selection.");
        }
Example #4
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();
            }
        }
        /// <summary>
        /// Проверка не заблокирован ли слой
        /// </summary>
        /// <param name="layerName">Имя слоя</param>
        public static bool IsLockedLayer(string layerName)
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            using (doc.LockDocument())
            {
                using (OpenCloseTransaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {
                    var lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    if (lt == null)
                    {
                        return(false);
                    }
                    foreach (var layerId in lt)
                    {
                        var layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                        if (layer != null && layer.Name.Equals(layerName))
                        {
                            return(layer.IsLocked);
                        }
                    }
                }
            }

            return(false);
        }
Example #6
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 #7
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 #8
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.");
                }
            }
        }
        /// <summary>
        /// Возвращает имя текущего слоя
        /// </summary>
        public static string GetCurrentLayerName()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            using (doc.LockDocument())
            {
                using (OpenCloseTransaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {
                    var lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    if (lt != null)
                    {
                        foreach (var layerId in lt)
                        {
                            if (layerId == db.Clayer)
                            {
                                var layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                                if (layer != null)
                                {
                                    return(layer.Name);
                                }
                            }
                        }
                    }
                }
            }

            return(string.Empty);
        }
        private void BtCreateStyleFromEntity_OnClick(object sender, RoutedEventArgs e)
        {
            /* Созданный стиль нужно еще найти в TreeView и выбрать его, раскрыв дерево
             * для этого можно искать по гуиду, а сам поиск взять в плагине mpDwgBase
             */
            try
            {
                Hide();
                var promptEntityOptions =
                    new PromptEntityOptions($"\n{ModPlusAPI.Language.GetItem(Invariables.LangItem, "msg3")}");
                promptEntityOptions.SetRejectMessage("\nWrong entity");
                promptEntityOptions.AllowNone = false;
                promptEntityOptions.AddAllowedClass(typeof(BlockReference), true);
                promptEntityOptions.AllowObjectOnLockedLayer = true;
                var selectionResult = AcadUtils.Document.Editor.GetEntity(promptEntityOptions);
                if (selectionResult.Status == PromptStatus.OK)
                {
                    var newStyleGuid = string.Empty;
                    using (var tr = new OpenCloseTransaction())
                    {
                        var obj = tr.GetObject(selectionResult.ObjectId, OpenMode.ForRead);
                        if (obj is BlockReference blockReference)
                        {
                            var entity   = EntityReaderService.Instance.GetFromEntity(blockReference);
                            var newStyle = new IntellectualEntityStyle(entity.GetType())
                            {
                                Name      = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h13"),
                                StyleType = StyleType.User,
                                Guid      = Guid.NewGuid().ToString()
                            };
                            newStyle.GetPropertiesFromEntity(entity, blockReference);
                            newStyleGuid = newStyle.Guid;
                            foreach (var entityStyles in _styles)
                            {
                                if (entityStyles.EntityType == entity.GetType())
                                {
                                    entityStyles.Styles.Add(newStyle);
                                    StyleManager.AddStyle(newStyle);
                                    break;
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(newStyleGuid))
                    {
                        SearchInTreeViewByGuid(newStyleGuid);
                    }
                }
            }
            catch (Exception exception)
            {
                ExceptionBox.Show(exception);
            }
            finally
            {
                Show();
            }
        }
Example #11
0
        public static Dictionary <string, string> GetAttribs(string blockName, string tag)
        {
            // create a new instance of Dictionary<string, string>
            var attribs = new Dictionary <string, string>();

            // get the documents collection
            var docs = Application.DocumentManager;

            // use an OpenCloseTransaction which is not related to a document or database
            using (var tr = new OpenCloseTransaction())
            {
                // iterate through the documents
                foreach (Document doc in docs)
                {
                    // get the document database
                    var db = doc.Database;

                    // get the database block table
                    var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    // if the block table contains a block definitions named 'blockName'...
                    if (bt.Has(blockName))
                    {
                        // open the block definition
                        var btr = (BlockTableRecord)tr.GetObject(bt[blockName], OpenMode.ForRead);

                        // get the inserted block references ObjectIds
                        var ids = btr.GetBlockReferenceIds(true, true);

                        // if any...
                        if (0 < ids.Count)
                        {
                            // open the first block reference
                            var br = (BlockReference)tr.GetObject(ids[0], OpenMode.ForRead);

                            // iterate through the attribute collection
                            foreach (ObjectId id in br.AttributeCollection)
                            {
                                // open the attribute reference
                                var attRef = (AttributeReference)tr.GetObject(id, OpenMode.ForRead);

                                // if the attribute tag is equal to 'tag'
                                if (attRef.Tag.Equals(tag, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    // add an entry to the dictionary
                                    attribs[doc.Name] = attRef.TextString;
                                    // break the loop
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            // return the dictionary
            return(attribs);
        }
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
0
        public static IEnumerable <Point3d> Select3dPoints([NotNull] this Editor editor, out List <ObjectId> ids)
        {
            List <Point3d> myPLlist = new List <Point3d>();

            ids = new List <ObjectId>();
            //' Start a transaction
            using (OpenCloseTransaction transAction = editor.Document.Database.TransactionManager.StartOpenCloseTransaction())
            {
                //Setting some options
                PromptSelectionOptions mypromptOption = new PromptSelectionOptions()
                {
                    AllowDuplicates = false,
                    RejectObjectsFromNonCurrentSpace = true,
                    AllowSubSelections          = false,
                    RejectObjectsOnLockedLayers = false,
                };

                //Making a new result and adding options to it
                var res = editor.GetSelection(mypromptOption);

                if (res.Status == PromptStatus.OK)
                {
                    var selectedObjects = res.Value;
                    if (selectedObjects.Count == 0)
                    {
                        throw new Exception("\r\n\t=> No objects were selected.");
                    }

                    foreach (var id in selectedObjects.GetObjectIds())
                    {
                        var objectX = transAction.GetObject(id, OpenMode.ForRead);
                        if (objectX is DBPoint)
                        {
                            DBPoint dBPoint = objectX as DBPoint;
                            myPLlist.Add(dBPoint.Position);
                            ids.Add(dBPoint.ObjectId);
                        }
                    }
                }
                if (myPLlist != null && myPLlist.Any())
                {
                    editor.WriteMessage("\r\n\t=>A set has been selected with " + myPLlist.Count + " points.");
                }
                return(myPLlist);
            }

            throw new InvalidOperationException("Something went wrong when handling the selection.");
        }
Example #18
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 #19
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 #21
0
        public override void TransformBy(Entity e, Matrix3d mat)
        {
            DBPoint pt = e as DBPoint;

            if (pt != null)
            {
                Database db = HostApplicationServices.WorkingDatabase;

                bool found = false;

                OpenCloseTransaction tr =
                    db.TransactionManager.StartOpenCloseTransaction();
                using (tr)
                {
                    foreach (ObjectId curId in _curves)
                    {
                        DBObject obj = tr.GetObject(curId, OpenMode.ForRead);
                        Polyline cur = obj as Polyline;
                        if (cur != null)
                        {
                            Point3d ptOnCurve =
                                cur.GetClosestPointTo(pt.Position, false);
                            Vector3d dist = ptOnCurve - pt.Position;
                            if (dist.IsZeroLength(Tolerance.Global))
                            {
                                Point3d pos =
                                    cur.GetClosestPointTo(
                                        pt.Position.TransformBy(mat),
                                        false
                                        );
                                pt.Position = pos;
                                found       = true;
                                break;
                            }
                        }
                        if (!found)
                        {
                            base.TransformBy(e, mat);
                        }
                    }
                }
            }
        }
Example #22
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 #24
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 #25
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 #26
0
        public static void GetAllObject()
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (OpenCloseTransaction trans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable       bt  = trans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                int count            = 0;
                acDoc.Editor.WriteMessage("\nModel space object:");

                foreach (var acObjId in btr)
                {
                    acDoc.Editor.WriteMessage("\n" + acObjId.ObjectClass.DxfName);
                    count += 1;
                }
                if (count == 0)
                {
                    acDoc.Editor.WriteMessage("\n0 Object Fount");
                }
            }
        }
Example #27
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 #28
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();
        }