public void cmdTestUCS()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                var ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                var ucs = new CoordinateSystem3d(new Point3d(11, 22, 0), Vector3d.XAxis, Vector3d.YAxis);

                //UCS到WCS的转换矩阵
                var matrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis,
                                                            ucs.Origin, ucs.Xaxis, ucs.Yaxis, ucs.Zaxis);

                ed.CurrentUserCoordinateSystem = matrix;

                //API中加进去的都是WCS的坐标,我们构造的时候是通过UCS里的坐标值来构造的,真正加进去之前需要转换到WCS
                var circle = new Autodesk.AutoCAD.DatabaseServices.Circle();
                circle.Center = new Point3d(10, 10, 0);
                circle.Radius = 5;
                circle.TransformBy(matrix);

                ms.AppendEntity(circle);
                tr.AddNewlyCreatedDBObject(circle, true);

                tr.Commit();
            }
        }
        public void cmdImportFromJSON()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            var openFileDialog = new Microsoft.Win32.OpenFileDialog();

            openFileDialog.Filter      = "All files (*.*)|*.*|JSON files (*.json)|*.json";
            openFileDialog.FilterIndex = 2;
            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }
            var filePath = openFileDialog.FileName;

            var        jsonText = File.ReadAllText(filePath);
            RootObject ro       = JsonConvert.DeserializeObject <RootObject>(jsonText);

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt  = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                foreach (var c in ro.circles)
                {
                    var circle = new Autodesk.AutoCAD.DatabaseServices.Circle(new Point3d(c.x, c.y, c.z), Vector3d.ZAxis, c.radius);
                    btr.AppendEntity(circle);
                    tr.AddNewlyCreatedDBObject(circle, true);
                }

                tr.Commit();
            }
        }
Exemple #3
0
        private static void AddCircle(Gem.Point2d pnt, string layer)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.Circle acCircle = new Db.Circle();
                acCircle.SetDatabaseDefaults();
                acCircle.Center = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acCircle.Radius = SettingsParser.getInstance()._Scale.Circle;
                acCircle.Layer  = layer;
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acCircle);
                acTrans.AddNewlyCreatedDBObject(acCircle, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Exemple #4
0
        private PointSet method_3(Autodesk.AutoCAD.DatabaseServices.Circle circle_0, double double_1)
        {
            PointSet result;

            try
            {
                PointSet pointSet = new PointSet();
                ngeometry.VectorGeometry.Circle circle = Conversions.ToCeometricCircle(circle_0);
                if (double_1 > 0.0 && double_1 < circle.Circumference)
                {
                    int    num   = Math.Max((int)Math.Ceiling(circle.Circumference / double_1), 4);
                    double num2  = 6.2831853071795862 / (double)num;
                    Point  point = Conversions.ToCeometricPoint(circle_0.StartPoint);
                    for (int i = 0; i < num; i++)
                    {
                        ngeometry.VectorGeometry.Matrix3d rotationMatrix = ngeometry.VectorGeometry.Matrix3d.RotationArbitraryAxis(circle.NormalVector, (double)i * num2);
                        pointSet.Add(point.Rotate(circle.Center, rotationMatrix));
                    }
                }
                else
                {
                    pointSet.Add(circle.Center);
                }
                result = pointSet;
            }
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Can not subdivide circle (handle: " + circle_0.Handle.ToString() + ")\n");
                result = null;
            }
            return(result);
        }
Exemple #5
0
 /// <summary>
 /// Задание параметров окружности класса Circle.
 /// </summary>
 /// <param name="acadCircle">Редактируемая окружность</param>
 public void Update(ref AcadDS.Circle acadCircle)
 {
     if (acadCircle != null)
     {
         acadCircle.Center = new Point3d(Center.X, Center.Y, Height);
         acadCircle.Radius = Radius;
     }
 }
Exemple #6
0
 public Circle(AcadDS.Circle circle)
 {
     _id     = circle.Id;
     _name   = "circle";
     _center = new Coordinates()
     {
         X = circle.Center.X, Y = circle.Center.Y
     };
     _radius = circle.Radius;
     _height = circle.Center.Z;
 }
        public void cmdImportFromXML()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            var openFileDialog = new Microsoft.Win32.OpenFileDialog();

            openFileDialog.Filter      = "All files (*.*)|*.*|XML files (*.xml)|*.xml";
            openFileDialog.FilterIndex = 2;
            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }
            var filePath = openFileDialog.FileName;

            FileStream    file           = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            XmlSerializer xmlSearializer = new XmlSerializer(typeof(Circles));
            Circles       circles        = (Circles)xmlSearializer.Deserialize(file);

            file.Close();

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt  = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                foreach (var c in circles.CircleList)
                {
                    var circle = new Autodesk.AutoCAD.DatabaseServices.Circle(new Point3d(c.x, c.y, c.z), Vector3d.ZAxis, c.radius);
                    btr.AppendEntity(circle);
                    tr.AddNewlyCreatedDBObject(circle, true);
                }

                tr.Commit();
            }
        }
Exemple #8
0
        /// <summary>
        /// Загружает в документ новые параметры слоев и фигур.
        /// </summary>
        public void Update()
        {
            // Получаем текущий документ, доступ к командной строке и БД.
            Document doc = AcadAS.Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            // Блокируем документ для редактирования из вне.
            using (DocumentLock lc = doc.LockDocument())
            {
                // Начинаем транзакцию.
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        // Создаем список имен слоев.
                        string[] layerNames = new string[Layers.Count];
                        int      i          = 0;
                        foreach (Layer layer in Layers)
                        {
                            layerNames[i] = layer.Name;
                            i++;
                        }

                        i = 0;
                        // Получаем таблицу слоев.
                        LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite);
                        // Задаем временные имена слоев для избежания конфликтов переименовывания.
                        foreach (ObjectId ltrId in lt)
                        {
                            LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite);
                            if (ltr.Name != "0")
                            {
                                ltr.Name = "_temp_" + ltr.Name + "_temp_";
                            }
                        }

                        foreach (Layer layer in Layers)
                        {
                            // Проверяем новое имя слоя на дублирование и присваиваем слоям документа новые параметры.
                            if (Array.IndexOf(layerNames, layer.Name) == Array.LastIndexOf(layerNames, layer.Name))
                            {
                                LayerTableRecord acadLayer = (LayerTableRecord)tr.GetObject(layer.Id, OpenMode.ForWrite);
                                layer.Update(ref acadLayer);
                            }
                            else if (Array.IndexOf(layerNames, layer.Name) == i)
                            {
                                MessageBox.Show("Дублирование имени слоя \"" + layer.Name + "\".");
                            }
                            i++;

                            // Присваиваем фигурам документа новые параметры.
                            foreach (Model.Point point in layer.Points)
                            {
                                AcadDS.DBPoint acadPoint = (AcadDS.DBPoint)tr.GetObject(point.Id, OpenMode.ForWrite);
                                point.Update(ref acadPoint);
                            }

                            foreach (Model.Line line in layer.Lines)
                            {
                                AcadDS.Line acadLine = (AcadDS.Line)tr.GetObject(line.Id, OpenMode.ForWrite);
                                line.Update(ref acadLine);
                            }

                            foreach (Model.Circle circle in layer.Circles)
                            {
                                AcadDS.Circle acadCircle = (AcadDS.Circle)tr.GetObject(circle.Id, OpenMode.ForWrite);
                                circle.Update(ref acadCircle);
                            }
                        }

                        // Если не все слои переименовались удаляем добавочный преффик и суффикс.
                        foreach (ObjectId ltrId in lt)
                        {
                            LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite);
                            ltr.Name = ltr.Name.Replace("_temp_", "");
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception e)
                    {
                        ed.WriteMessage("error. {0}: {1}", e.Message);
                    }
                    tr.Commit();
                    tr.Dispose();
                }
                //lc.Dispose();
            }
            // Обновляем экземпляр класса после изменения документа.
            Reload();
        }
Exemple #9
0
 public static ngeometry.VectorGeometry.Circle ToCeometricCircle(Autodesk.AutoCAD.DatabaseServices.Circle circle /*ng:类型存疑*/)
 {
     ngeometry.VectorGeometry.Point    center       = new ngeometry.VectorGeometry.Point(circle.Center.X, circle.Center.Y, circle.Center.Z);
     ngeometry.VectorGeometry.Vector3d normalVector = new ngeometry.VectorGeometry.Vector3d(circle.Normal.X, circle.Normal.Y, circle.Normal.Z);
     return(new ngeometry.VectorGeometry.Circle(center, circle.Radius, normalVector));
 }
Exemple #10
0
        public static void ComputeMinEnclosingCircle(ObjectId[] idArray, CoordinateSystem actualCS)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter value           = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(value);
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    progressMeter.SetLimit(idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        progressMeter.Start("Computing min. enclosing circle...");
                    }
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), actualCS);
                    CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        coordinateTransformator.Transform(point);
                        pointSet.Add(point);
                    }
                    ConvexHull2d convexHull2d = new ConvexHull2d();
                    convexHull2d.InitialPoints = pointSet;
                    convexHull2d.ComputeHull();
                    PointSet vertices = convexHull2d.Vertices;
                    double   z        = vertices[0].Z;
                    for (int j = 0; j < vertices.Count; j++)
                    {
                        vertices[j].Z = z;
                    }
                    SmallestEnclosingCircle         smallestEnclosingCircle = new SmallestEnclosingCircle(vertices);
                    ngeometry.VectorGeometry.Circle circle = smallestEnclosingCircle.ComputeCircle();
                    Point center = circle.Center;
                    Point point2 = circle.NormalVector.ToPoint();
                    inverseTransformation.Transform(center);
                    inverseTransformation.Transform(point2);
                    Autodesk.AutoCAD.DatabaseServices.Circle circle2 = new Autodesk.AutoCAD.DatabaseServices.Circle(new Autodesk.AutoCAD.Geometry.Point3d(center.X, center.Y, center.Z), new Autodesk.AutoCAD.Geometry.Vector3d(point2.X, point2.Y, point2.Z), circle.Radius);
                    circle2.LayerId = (layerId);
                    blockTableRecord.AppendEntity(circle2);
                    transaction.AddNewlyCreatedDBObject(circle2, true);
                    editor.WriteMessage("\nMinimum enclosing circle properties:");
                    editor.WriteMessage("\n------------------------------------");
                    editor.WriteMessage("\nRadius          : " + circle.Radius.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nArea            : " + circle.Area.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nPerimeter length: " + circle.Circumference.ToString(DBManager.GetFormatFromLUPREC()));
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Exemple #11
0
        private PointSet method_1(ObjectId[] objectId_0, double double_1)
        {
            if (objectId_0 == null)
            {
                return(null);
            }
            Editor        arg_14_0        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            PointSet      pointSet        = new PointSet();
            PointSet      pointSet2       = new PointSet();
            ProgressMeter progressMeter   = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Computing points on entities");
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        if (i % 10000 == 0)
                        {
                            System.Windows.Forms.Application.DoEvents();
                        }
                        Entity entity = (Entity)objectId_0[i].GetObject((OpenMode)0);
                        string text   = entity.ToString();
                        if (text.ToUpper().Contains("POLYLINE"))
                        {
                            text = "PLINE";
                        }
                        string key;
                        switch (key = text)
                        {
                        case "Autodesk.AutoCAD.DatabaseServices.Line":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Line dbl = (Autodesk.AutoCAD.DatabaseServices.Line)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = PointGeneration.SubdivideLine(dbl, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.DBText":
                        {
                            DBText dbtext_ = (DBText)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_2(dbtext_);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Circle":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Circle circle_ = (Autodesk.AutoCAD.DatabaseServices.Circle)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_3(circle_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Ellipse":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Ellipse ellipse_ = (Autodesk.AutoCAD.DatabaseServices.Ellipse)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_4(ellipse_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Arc":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Arc arc_ = (Autodesk.AutoCAD.DatabaseServices.Arc)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_5(arc_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Spline":
                        {
                            Spline spline_ = (Spline)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_6(spline_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Face":
                        {
                            Face face_ = (Face)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_7(face_);
                            break;
                        }

                        case "PLINE":
                        {
                            DBObject @object = transaction.GetObject(objectId_0[i], (OpenMode)0);
                            pointSet2 = PointGeneration.SubdividePolyline(@object, transaction, double_1);
                            break;
                        }
                        }
                        if (pointSet2 != null)
                        {
                            pointSet.Add(pointSet2);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
            progressMeter.Stop();
            if (pointSet.Count == 0)
            {
                return(null);
            }
            pointSet.RemoveMultiplePoints3d();
            return(pointSet);
        }