Esempio n. 1
0
		/// <summary>
		/// Загружает интересующие нас компоненты
		/// </summary>
		public void LoadComponents()
		{
			document = Application.DocumentManager.MdiActiveDocument;
			var dataBase = document.Database;

			// Взаимодействие с базой данных автокада происходит только в рамках транзакции
			// После завершения транзакции пользоваться полученными объектами нельзя, ибо Undefinded behavior
			using (var transaction = dataBase.TransactionManager.StartTransaction())
			{
				var layerTable = transaction.GetObject(dataBase.LayerTableId, OpenMode.ForRead) as LayerTable;
				Debug.Assert(layerTable != null, "layerTable != null");
				LoadLayers(transaction, layerTable);

				// Загружаем графические примитивы
				var blockTable = transaction.GetObject(dataBase.BlockTableId, OpenMode.ForRead) as BlockTable;
				Debug.Assert(blockTable != null, "blockTable != null");
				LoadEmptities(transaction, blockTable);

				transaction.Commit();
			}
		}
Esempio n. 2
0
        public void ProfileOnCurve()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            Topography.SurfaceType surface = Topography.PickSurface();
            if (surface == Topography.SurfaceType.None)
            {
                return;
            }
            if (!Topography.EnsureSurfaceNotEmpty(surface))
            {
                return;
            }

            // Pick alignment
            bool     flag    = true;
            ObjectId curveId = ObjectId.Null;

            while (flag)
            {
                PromptEntityOptions entityOpts = new PromptEntityOptions("\nEksen [Seçenekler]: ", "Settings");
                entityOpts.SetRejectMessage("\nSelect a curve.");
                entityOpts.AddAllowedClass(typeof(Curve), false);
                PromptEntityResult entityRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entityOpts);
                if (entityRes.Status == PromptStatus.Keyword)
                {
                    ShowSettings();
                }
                else if (entityRes.Status == PromptStatus.OK)
                {
                    curveId = entityRes.ObjectId;
                    break;
                }
                else if (entityRes.Status == PromptStatus.Cancel)
                {
                    return;
                }
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
                using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                {
                    Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;

                    ObjectId textStyleId = ObjectId.Null;
                    using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead))
                    {
                        if (tt.Has(TextStyleName))
                        {
                            textStyleId = tt[TextStyleName];
                        }
                    }

                    // Project curve onto surface
                    Topography        topo   = Topography.Instance;
                    Curve             curve  = tr.GetObject(curveId, OpenMode.ForRead) as Curve;
                    Point2dCollection points = topo.ProfileOnCurve(curve, surface);

                    // Base point for profile drawing
                    PromptPointResult pointRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nProfil başlangıcı: ");
                    if (pointRes.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    Point3d basePt = pointRes.Value;

                    if (points.Count > 0)
                    {
                        // Limits
                        Extents2d ex = AcadUtility.AcadGeometry.Limits(points);

                        // Base level for profile drawing
                        PromptDoubleOptions levelOpts = new PromptDoubleOptions("\nProfil baz kotu: ");
                        levelOpts.DefaultValue    = Math.Floor(ex.MinPoint.Y / ProfileGridV) * ProfileGridV;
                        levelOpts.UseDefaultValue = true;
                        PromptDoubleResult levelRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(levelOpts);
                        if (pointRes.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        double startLevel = levelRes.Value;
                        double endLevel   = Math.Ceiling(ex.MaxPoint.Y / ProfileGridV + 1) * ProfileGridV;

                        // Base chainage for profile drawing
                        double startCh = 0;
                        flag = true;
                        while (flag)
                        {
                            PromptStringOptions chOpts = new PromptStringOptions("\nProfil baz KM: ");
                            chOpts.DefaultValue    = AcadUtility.AcadText.ChainageToString(0, Precision);
                            chOpts.UseDefaultValue = true;
                            PromptResult chRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetString(chOpts);
                            if (chRes.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            if (AcadUtility.AcadText.TryChainageFromString(chRes.StringResult, out startCh))
                            {
                                break;
                            }
                        }
                        double endCh = Math.Ceiling((startCh + ex.MaxPoint.X) / ProfileGridH) * ProfileGridH;

                        // Draw grid
                        IEnumerable <Entity> entities = DrawProfileFrame(db, basePt, startCh, startLevel, endCh, endLevel, ProfileGridH, ProfileGridV, ProfileVScale, TextHeight, Precision, textStyleId);
                        foreach (Entity ent in entities)
                        {
                            ent.TransformBy(ucs2wcs);
                            btr.AppendEntity(ent);
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }

                        // Draw profile
                        ObjectId          profileLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, "Profil_Eksen", Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 5));
                        Point2dCollection trPoints       = new Point2dCollection(points.Count);
                        foreach (Point2d pt in points)
                        {
                            trPoints.Add(new Point2d(basePt.X + pt.X, basePt.Y + (pt.Y - startLevel) * ProfileVScale));
                        }
                        Polyline pline = AcadUtility.AcadEntity.CreatePolyLine(db, false, trPoints);
                        pline.TransformBy(ucs2wcs);
                        pline.LayerId = profileLayerId;
                        btr.AppendEntity(pline);
                        tr.AddNewlyCreatedDBObject(pline, true);
                    }

                    tr.Commit();
                }
        }
Esempio n. 3
0
        Point3dCollection ReadPoints(IEnumerable <ObjectId> items, double maxSpacing)
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            HashSet <Point3d> points = new HashSet <Point3d>(new Point3dComparer(new Tolerance(maxSpacing, maxSpacing)));

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    foreach (ObjectId id in items)
                    {
                        // Point
                        if (SelectPoints && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBPoint)).UnmanagedObject)
                        {
                            DBPoint item = (DBPoint)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.Position);
                        }
                        // Line
                        else if (SelectLines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Line)).UnmanagedObject)
                        {
                            Line item = (Line)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.StartPoint);
                            points.Add(item.EndPoint);
                        }
                        // LW Polyline
                        else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline)).UnmanagedObject)
                        {
                            Polyline item = (Polyline)tr.GetObject(id, OpenMode.ForRead);
                            for (int i = 0; i < item.NumberOfVertices; i++)
                            {
                                points.Add(item.GetPoint3dAt(i));
                            }
                        }
                        // 2D Polyline
                        else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline2d)).UnmanagedObject)
                        {
                            Polyline2d item = (Polyline2d)tr.GetObject(id, OpenMode.ForRead);
                            foreach (ObjectId vId in item)
                            {
                                Vertex2d vertex = (Vertex2d)tr.GetObject(vId, OpenMode.ForRead);
                                points.Add(vertex.Position);
                            }
                        }
                        // 3D Polyline
                        else if (SelectPolylines && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Polyline3d)).UnmanagedObject)
                        {
                            Polyline3d item = (Polyline3d)tr.GetObject(id, OpenMode.ForRead);
                            foreach (ObjectId vId in item)
                            {
                                PolylineVertex3d vertex = (PolylineVertex3d)tr.GetObject(vId, OpenMode.ForRead);
                                points.Add(vertex.Position);
                            }
                        }
                        // Text
                        else if (SelectTexts && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBText)).UnmanagedObject)
                        {
                            DBText item = (DBText)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.Position);
                        }
                        // Text with Z
                        else if (SelectTextsWithZ && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBText)).UnmanagedObject)
                        {
                            DBText item = (DBText)tr.GetObject(id, OpenMode.ForRead);
                            if (double.TryParse(item.TextString, out double z))
                            {
                                Point3d pt = item.Position;
                                points.Add(new Point3d(pt.X, pt.Y, z));
                            }
                        }
                        // Blocks
                        else if (SelectBlocks && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(BlockReference)).UnmanagedObject)
                        {
                            BlockReference item = (BlockReference)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.Position);
                        }
                        // 3DFace
                        else if (Select3DFace && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Face)).UnmanagedObject)
                        {
                            Face item = (Face)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.GetVertexAt(0));
                            points.Add(item.GetVertexAt(1));
                            points.Add(item.GetVertexAt(2));
                            points.Add(item.GetVertexAt(3));
                        }
                        // PolyFaceMesh
                        else if (SelectPolyfaceMesh && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(PolyFaceMesh)).UnmanagedObject)
                        {
                            PolyFaceMesh item = (PolyFaceMesh)tr.GetObject(id, OpenMode.ForRead);
                            foreach (ObjectId faceId in item)
                            {
                                DBObject obj = tr.GetObject(faceId, OpenMode.ForRead);
                                if (obj is PolyFaceMeshVertex vertex)
                                {
                                    points.Add(vertex.Position);
                                }
                            }
                        }
                        // Solid (2D)
                        else if (SelectSolid && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(Solid)).UnmanagedObject)
                        {
                            Solid item = (Solid)tr.GetObject(id, OpenMode.ForRead);
                            points.Add(item.GetPointAt(0));
                            points.Add(item.GetPointAt(1));
                            points.Add(item.GetPointAt(3));
                            points.Add(item.GetPointAt(2));
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.ToString(), "XCOM", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                tr.Commit();
            }

            if (points.Count == 0)
            {
                return(new Point3dCollection());
            }
            else
            {
                return(new Point3dCollection(points.ToArray()));
            }
        }
Esempio n. 4
0
        private bool ShowSettings()
        {
            using (CoordMainForm form = new CoordMainForm())
            {
                form.TextHeight = TextHeight;

                form.TextRotation   = TextRotation;
                form.AutoRotateText = AutoRotateText;

                form.AutoLineLength = AutoLine;
                form.LineLength     = LineLength;

                form.Precision = Precision;

                form.AutoNumbering  = AutoNumbering;
                form.StartingNumber = CurrentNumber;
                form.Prefix         = Prefix;

                form.ShowZCoordinate = ShowZCoordinate;

                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                form.TextStyleName = TextStyleName;

                if (Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(form) == System.Windows.Forms.DialogResult.OK)
                {
                    TextHeight = form.TextHeight;

                    TextRotation   = form.TextRotation;
                    AutoRotateText = form.AutoRotateText;

                    AutoLine   = form.AutoLineLength;
                    LineLength = form.LineLength;

                    Precision = form.Precision;

                    AutoNumbering = form.AutoNumbering;
                    CurrentNumber = form.StartingNumber;
                    Prefix        = form.Prefix;

                    ShowZCoordinate = form.ShowZCoordinate;

                    TextStyleName = form.TextStyleName;

                    if (form.CoordsFromDWG != null && form.CoordsFromDWG.Length > 0)
                    {
                        bool xy = form.CoordsFromDWG[0].IsXYText;
                        if (xy)
                        {
                            using (Transaction tr = db.TransactionManager.StartTransaction())
                            {
                                foreach (CoordMainForm.CoordItem item in form.CoordsFromDWG)
                                {
                                    string text  = GetCoordText(new Point3d(item.X, item.Y, 0));
                                    MText  mtext = (MText)tr.GetObject(item.ID, OpenMode.ForWrite);
                                    mtext.Contents = text;
                                }

                                tr.Commit();
                            }
                        }
                        else
                        {
                            points.Clear();
                            foreach (CoordMainForm.CoordItem item in form.CoordsFromDWG)
                            {
                                points.Add(new CoordPoint(item.Number, item.X, item.Y, item.Z));
                            }
                        }
                    }

                    init = true;

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Esempio n. 5
0
            private void UpdateText()
            {
                Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                Matrix3d ucs2wcs    = AcadUtility.AcadGraphics.UcsToWcs;
                Matrix3d wcs2ucs    = AcadUtility.AcadGraphics.WcsToUcs;
                Point3d  pBaseWorld = mpBase.TransformBy(ucs2wcs);
                Point3d  pTextWorld = mpText.TransformBy(ucs2wcs);

                MText    mtext = Entity as MText;
                Vector3d dir   = (mpText - mpBase);

                // Text attachment
                mtext.Location = pTextWorld;
                bool singleLine = (mtext.Attachment == AttachmentPoint.BottomLeft || mtext.Attachment == AttachmentPoint.BottomRight);

                // Text rotation and attachment
                if (mAutoRotateText)
                {
                    double lineRotation = mTextRotation * Math.PI / 180 + Vector3d.XAxis.GetAngleTo(dir, Vector3d.ZAxis);
                    double rot          = lineRotation * 180 / Math.PI;

                    if (rot > 90.0 && rot < 270.0)
                    {
                        lineRotation     = lineRotation + Math.PI;
                        mtext.Attachment = (singleLine ? AttachmentPoint.BottomRight : AttachmentPoint.MiddleRight);
                    }
                    else
                    {
                        mtext.Attachment = (singleLine ? AttachmentPoint.BottomLeft : AttachmentPoint.MiddleLeft);
                    }

                    mtext.Rotation = lineRotation;
                }
                else
                {
                    mtext.Rotation = mTextRotation * Math.PI / 180;
                }

                // Text to the right or left
                double textlineAngle = Vector3d.XAxis.RotateBy(mtext.Rotation, Vector3d.XAxis).GetAngleTo(dir) * 180 / Math.PI;

                if (textlineAngle > 90.0 && textlineAngle < 270.0)
                {
                    mtext.Attachment = (singleLine ? AttachmentPoint.BottomRight : AttachmentPoint.MiddleRight);
                }
                else
                {
                    mtext.Attachment = (singleLine ? AttachmentPoint.BottomLeft : AttachmentPoint.MiddleLeft);
                }

                // Create and update line
                IntegerCollection vpNumbers = AcadUtility.AcadGraphics.GetActiveViewportNumbers();

                if (line == null)
                {
                    line = new Line();
                    TransientManager.CurrentTransientManager.AddTransient(line, TransientDrawingMode.DirectShortTerm, 0, vpNumbers);
                }
                line.StartPoint = pBaseWorld;
                line.EndPoint   = pTextWorld;
                TransientManager.CurrentTransientManager.UpdateTransient(line, vpNumbers);
            }
Esempio n. 6
0
        public void Coord()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

            if (!init)
            {
                if (!ShowSettings())
                {
                    return;
                }
            }

            bool flag = true;

            ObjectId textStyleId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
                using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead))
                {
                    if (tt.Has(TextStyleName))
                    {
                        textStyleId = tt[TextStyleName];
                    }
                    tr.Commit();
                }
            Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;

            while (flag)
            {
                PromptPointResult pointRes = null;
                if (AutoNumbering)
                {
                    PromptPointOptions pointOpts = new PromptPointOptions("\n" + CurrentNumber.ToString() + ". Koordinat yeri: [Reset/Liste/Seç]", "Reset List Select");
                    pointRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(pointOpts);
                }
                else
                {
                    PromptPointOptions pointOpts = new PromptPointOptions("\nKoordinat yeri: [Reset/Seç]", "Reset Select");
                    pointRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(pointOpts);
                }

                if (pointRes.Status == PromptStatus.Cancel)
                {
                    return;
                }
                else if (pointRes.Status == PromptStatus.Keyword && pointRes.StringResult == "Reset")
                {
                    Reset();
                    return;
                }
                else if (pointRes.Status == PromptStatus.Keyword && pointRes.StringResult == "List")
                {
                    PromptPointOptions listOpts = new PromptPointOptions("\nListe yeri: ");
                    PromptPointResult  listRes  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(listOpts);
                    ShowList(listRes.Value);
                    return;
                }
                else if (pointRes.Status == PromptStatus.Keyword && pointRes.StringResult == "Select")
                {
                    using (SelectObjectsForm form = new SelectObjectsForm())
                    {
                        if (Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(form) == System.Windows.Forms.DialogResult.OK)
                        {
                            // Select objects
                            List <TypedValue> tvs = new List <TypedValue>();
                            switch (form.SelectObjects)
                            {
                            case SelectObjectsForm.SelectCoordinateObjects.Polyline:
                                tvs.Add(new TypedValue((int)DxfCode.Operator, "<OR"));
                                tvs.Add(new TypedValue((int)DxfCode.Start, "LWPOLYLINE"));
                                tvs.Add(new TypedValue((int)DxfCode.Start, "POLYLINE"));
                                tvs.Add(new TypedValue((int)DxfCode.Operator, "OR>"));
                                break;

                            case SelectObjectsForm.SelectCoordinateObjects.Circle:
                                tvs.Add(new TypedValue((int)DxfCode.Operator, "<OR"));
                                tvs.Add(new TypedValue((int)DxfCode.Start, "CIRCLE"));
                                tvs.Add(new TypedValue((int)DxfCode.Start, "ARC"));
                                tvs.Add(new TypedValue((int)DxfCode.Start, "ELLIPSE"));
                                tvs.Add(new TypedValue((int)DxfCode.Operator, "OR>"));
                                break;

                            case SelectObjectsForm.SelectCoordinateObjects.Block:
                                tvs.Add(new TypedValue((int)DxfCode.Start, "INSERT"));
                                break;

                            case SelectObjectsForm.SelectCoordinateObjects.Point:
                                tvs.Add(new TypedValue((int)DxfCode.Start, "POINT"));
                                break;

                            case SelectObjectsForm.SelectCoordinateObjects.Line:
                                tvs.Add(new TypedValue((int)DxfCode.Start, "LINE"));
                                break;
                            }
                            SelectionFilter filter = new SelectionFilter(tvs.ToArray());

                            PromptSelectionResult selRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetSelection(filter);
                            if (selRes.Status == PromptStatus.OK)
                            {
                                using (Transaction tr = db.TransactionManager.StartTransaction())
                                    using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                                    {
                                        TextPositioner positioner = new TextPositioner(ucs2wcs, TextRotation * Math.PI / 180, LineLength);

                                        // Read object coordinates
                                        List <TextPositioner.SelectedObjectCoordinate> objectPoints = new List <TextPositioner.SelectedObjectCoordinate>();
                                        foreach (ObjectId id in selRes.Value.GetObjectIds())
                                        {
                                            if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.Polyline)))
                                            {
                                                Autodesk.AutoCAD.DatabaseServices.Polyline obj = tr.GetObject(id, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Polyline;

                                                positioner.ClearPoints();
                                                for (int i = 0; i < obj.NumberOfVertices; i++)
                                                {
                                                    positioner.AddPoint(obj.GetPoint3dAt(i));
                                                }
                                                objectPoints.AddRange(positioner.GetPositions());
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.Circle)))
                                            {
                                                Circle obj = tr.GetObject(id, OpenMode.ForRead) as Circle;
                                                objectPoints.Add(positioner.GetPosition(obj.Center));
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.Arc)))
                                            {
                                                Arc obj = tr.GetObject(id, OpenMode.ForRead) as Arc;
                                                objectPoints.Add(positioner.GetPosition(obj.Center));
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.Ellipse)))
                                            {
                                                Ellipse obj = tr.GetObject(id, OpenMode.ForRead) as Ellipse;
                                                objectPoints.Add(positioner.GetPosition(obj.Center));
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.BlockReference)))
                                            {
                                                BlockReference obj = tr.GetObject(id, OpenMode.ForRead) as BlockReference;
                                                objectPoints.Add(positioner.GetPosition(obj.Position));
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.DBPoint)))
                                            {
                                                DBPoint obj = tr.GetObject(id, OpenMode.ForRead) as DBPoint;
                                                objectPoints.Add(positioner.GetPosition(obj.Position));
                                            }
                                            else if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(Autodesk.AutoCAD.DatabaseServices.Line)))
                                            {
                                                Line obj = tr.GetObject(id, OpenMode.ForRead) as Line;
                                                positioner.ClearPoints();
                                                positioner.AddPoint(obj.StartPoint);
                                                positioner.AddPoint(obj.EndPoint);
                                                objectPoints.AddRange(positioner.GetPositions());
                                            }
                                        }
                                        // Sort coordinates
                                        objectPoints.Sort((p1, p2) =>
                                        {
                                            switch (form.Ordering)
                                            {
                                            case SelectObjectsForm.CoordinateOrdering.IncreasingX:
                                                return(p1.BasePoint.X < p2.BasePoint.X ? -1 : 1);

                                            case SelectObjectsForm.CoordinateOrdering.IncreasingY:
                                                return(p1.BasePoint.Y < p2.BasePoint.Y ? -1 : 1);

                                            case SelectObjectsForm.CoordinateOrdering.DecreasingX:
                                                return(p1.BasePoint.X > p2.BasePoint.X ? -1 : 1);

                                            case SelectObjectsForm.CoordinateOrdering.DecreasingY:
                                                return(p1.BasePoint.Y > p2.BasePoint.Y ? -1 : 1);

                                            default:
                                                return(0);
                                            }
                                        });
                                        // Write coordinates
                                        foreach (TextPositioner.SelectedObjectCoordinate coord in objectPoints)
                                        {
                                            MText mtext = CreateText(textStyleId, coord.TextPoint);
                                            btr.AppendEntity(mtext);
                                            tr.AddNewlyCreatedDBObject(mtext, true);

                                            // Rotate text
                                            if (coord.TextToLeft)
                                            {
                                                mtext.Attachment = (AutoNumbering ? AttachmentPoint.BottomRight : AttachmentPoint.MiddleRight);
                                            }
                                            else
                                            {
                                                mtext.Attachment = (AutoNumbering ? AttachmentPoint.BottomLeft : AttachmentPoint.MiddleLeft);
                                            }

                                            Line line = new Line();
                                            line.StartPoint = coord.BasePoint;
                                            line.EndPoint   = coord.TextPoint;
                                            btr.AppendEntity(line);
                                            tr.AddNewlyCreatedDBObject(line, true);

                                            points.Add(new CoordPoint(CurrentNumber, coord.BasePoint));
                                            if (AutoNumbering)
                                            {
                                                CurrentNumber = CurrentNumber + 1;
                                            }
                                        }

                                        tr.Commit();
                                    }
                            }
                        }
                    }
                    return;
                }
                else
                {
                    Point3d pCoord = pointRes.Value.TransformBy(ucs2wcs);

                    using (Transaction tr = db.TransactionManager.StartTransaction())
                        using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                        {
                            MText mtext = CreateText(textStyleId, pCoord);

                            btr.AppendEntity(mtext);
                            tr.AddNewlyCreatedDBObject(mtext, true);

                            if (CoordinateJig.Jig(pointRes.Value, mtext, AutoLine, LineLength, AutoRotateText, TextRotation))
                            {
                                points.Add(new CoordPoint(CurrentNumber, pCoord));
                                if (AutoNumbering)
                                {
                                    CurrentNumber = CurrentNumber + 1;
                                }

                                Line line = new Line();
                                line.StartPoint = pCoord;
                                line.EndPoint   = mtext.Location;

                                btr.AppendEntity(line);
                                tr.AddNewlyCreatedDBObject(line, true);

                                tr.Commit();
                            }
                            else
                            {
                                mtext.Dispose();
                                tr.Abort();
                                return;
                            }
                        }
                }
            }
        }
Esempio n. 7
0
        //public void ExplodeBlocksWithNoAttributes(Database db) =>
        //  Wrappers.ExecuteActionInTransaction(db, tr => Wrappers.ExplodeBlocksWithNoAttributes(db, tr));

        //public void ExplodeBlocksByPredicate(Database db, Predicate<BlockReference> predicate) =>
        //  Wrappers.ExecuteActionInTransaction(db, tr => Wrappers.ExplodeBlocksByPredicate(db, tr, predicate));

        public void SendCommand(Autodesk.AutoCAD.ApplicationServices.Document doc, params string[] commandParts) => Wrappers.SendCommand(doc, commandParts);
Esempio n. 8
0
        public void MultiplyTextValues()
        {
            PromptSelectionResult selRes = SelectWithPickFirst();

            if (selRes.Status != PromptStatus.OK)
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                double sum = 1.0;
                foreach (ObjectId id in selRes.Value.GetObjectIds())
                {
                    DBText text = tr.GetObject(id, OpenMode.ForRead) as DBText;
                    if (text != null)
                    {
                        string str = text.TextString;
                        if (double.TryParse(str, out double val))
                        {
                            sum *= val;
                        }
                    }
                }

                PromptEntityResult entRes;
                while (true)
                {
                    PromptEntityOptions opts = new PromptEntityOptions("\nSonucun yazılacağı yazı (" + sum.ToString("F" + Precision) + ") [Basamak sayısı]: ", "Precision");
                    entRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(opts);

                    if (entRes.Status == PromptStatus.Keyword && entRes.StringResult == "Precision")
                    {
                        PromptIntegerOptions intOpts = new PromptIntegerOptions("\nBasamak sayısı: ");
                        intOpts.AllowNone       = true;
                        intOpts.AllowZero       = true;
                        intOpts.AllowNegative   = false;
                        intOpts.LowerLimit      = 0;
                        intOpts.UpperLimit      = 16;
                        intOpts.DefaultValue    = Precision;
                        intOpts.UseDefaultValue = true;
                        PromptIntegerResult res = doc.Editor.GetInteger(intOpts);
                        if (res.Status == PromptStatus.Cancel)
                        {
                            return;
                        }
                        else if (res.Status == PromptStatus.OK)
                        {
                            Precision = res.Value;
                        }
                    }
                    else if (entRes.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    else
                    {
                        break;
                    }
                }

                DBText restext = tr.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBText;
                if (restext != null)
                {
                    restext.TextString = sum.ToString("F" + Precision.ToString());
                }

                tr.Commit();
            }
        }
Esempio n. 9
0
        public void PoolExcavation()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            Topography.SurfaceType surface = Topography.PickSurface();
            if (surface == Topography.SurfaceType.None)
            {
                return;
            }
            if (!Topography.EnsureSurfaceNotEmpty(surface))
            {
                return;
            }
            Topography topo = Topography.Instance;

            TriangleNet.Mesh mesh = (surface == Topography.SurfaceType.Original ? topo.OriginalTIN : topo.ProposedTIN);

            // Pick polyline
            bool     flag         = true;
            ObjectId centerlineId = ObjectId.Null;

            while (flag)
            {
                PromptEntityOptions entityOpts = new PromptEntityOptions("\nKazı tabanı [Seçenekler]:", "Settings");
                entityOpts.SetRejectMessage("\nSelect a curve.");
                entityOpts.AddAllowedClass(typeof(Curve), false);
                PromptEntityResult entityRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entityOpts);
                if (entityRes.Status == PromptStatus.Keyword && entityRes.StringResult == "Settings")
                {
                    ShowSettings();
                    continue;
                }
                if (entityRes.Status != PromptStatus.OK)
                {
                    return;
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                    using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead))
                    {
                        Curve centerline = tr.GetObject(entityRes.ObjectId, OpenMode.ForRead) as Curve;
                        if (centerline != null)
                        {
                            if (centerline.Closed)
                            {
                                centerlineId = entityRes.ObjectId;

                                tr.Commit();
                                break;
                            }
                            else
                            {
                                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nCurve must be closed.");
                                tr.Commit();
                            }
                        }
                    }
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
                using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                {
                    Curve centerline = tr.GetObject(centerlineId, OpenMode.ForRead) as Curve;

                    // Excavate
                    PadExcavation     ex    = new PadExcavation(mesh, centerline, ExcavationStepSize);
                    ExcavationSection slope = new ExcavationSection();
                    slope.AddSlope(ExcavationH, ExcavationV);
                    ex.AddSection(0, slope);
                    ex.Excavate();

                    // Draw excavation boundries
                    Point3dCollection bounds = new Point3dCollection();
                    bool closed = true;
                    foreach (ExcavationSection section in ex.OutputSections)
                    {
                        if (section.Elements[section.Elements.Count - 1].HasTopPoint)
                        {
                            bounds.Add(section.Elements[section.Elements.Count - 1].TopPoint);

                            Line line = AcadUtility.AcadEntity.CreateLine(db, section.Elements[0].BottomPoint, section.Elements[section.Elements.Count - 1].TopPoint);
                            line.ColorIndex = 11;
                            btr.AppendEntity(line);
                            tr.AddNewlyCreatedDBObject(line, true);
                        }
                        else
                        {
                            if (bounds.Count > 1)
                            {
                                Polyline3d pline = AcadUtility.AcadEntity.CreatePolyLine3d(db, bounds);
                                btr.AppendEntity(pline);
                                tr.AddNewlyCreatedDBObject(pline, true);
                            }

                            closed = false;
                            bounds = new Point3dCollection();
                        }
                    }
                    if (bounds.Count > 1)
                    {
                        Polyline3d pline = AcadUtility.AcadEntity.CreatePolyLine3d(db, closed, bounds);
                        btr.AppendEntity(pline);
                        tr.AddNewlyCreatedDBObject(pline, true);
                    }

                    tr.Commit();
                }
        }
Esempio n. 10
0
        public void MakeCoordGrid()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

            ObjectId textStyleId = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
                using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead))
                {
                    if (tt.Has(TextStyleName))
                    {
                        textStyleId = tt[TextStyleName];
                    }
                    tr.Commit();
                }

            ObjectId textLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, TextLayerName, Color.FromColorIndex(ColorMethod.ByAci, 1));
            ObjectId lineLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, LineLayerName, Color.FromColorIndex(ColorMethod.ByAci, 3));

            ObjectId blockId = GetOrCreateBlock(db, BlockName, textLayerId, lineLayerId, textStyleId);

            Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;
            Matrix3d wcs2ucs = AcadUtility.AcadGraphics.WcsToUcs;

            // Pick polyline
            PromptPointResult ptRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nKöşe noktası: ");

            if (PolylineJig.Jig(ptRes.Value, out Point3dCollection points))
            {
                int xmin = int.MaxValue;
                int xmax = int.MinValue;
                int ymin = int.MaxValue;
                int ymax = int.MinValue;
                for (int i = 0; i < 4; i++)
                {
                    Point3d pt = points[i];
                    xmin = Math.Min(xmin, (int)pt.X); xmax = Math.Max(xmax, (int)pt.X);
                    ymin = Math.Min(ymin, (int)pt.Y); ymax = Math.Max(ymax, (int)pt.Y);
                }

                // Interval
                PromptIntegerOptions intOpts = new PromptIntegerOptions("\nAralık: ");
                intOpts.AllowNegative   = false;
                intOpts.AllowZero       = false;
                intOpts.AllowNone       = false;
                intOpts.DefaultValue    = Properties.Settings.Default.Command_COORDGRID_Interval;
                intOpts.UseDefaultValue = true;
                PromptIntegerResult intRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(intOpts);
                if (intRes.Status == PromptStatus.OK)
                {
                    Interval = intRes.Value;
                }
                else
                {
                    return;
                }

                // Round limits to multiples of the interval
                xmin = (int)Math.Floor((double)xmin / Interval) * Interval;
                xmax = (int)Math.Ceiling((double)xmax / Interval) * Interval;
                ymin = (int)Math.Floor((double)ymin / Interval) * Interval;
                ymax = (int)Math.Ceiling((double)ymax / Interval) * Interval;

                // Text height
                PromptDoubleOptions thOpts = new PromptDoubleOptions("\nYazı yüksekliği: ");
                thOpts.AllowNegative   = false;
                thOpts.AllowZero       = false;
                thOpts.AllowNone       = false;
                thOpts.DefaultValue    = Properties.Settings.Default.Command_COORDGRID_TextHeight;
                thOpts.UseDefaultValue = true;
                PromptDoubleResult thRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(thOpts);
                if (thRes.Status == PromptStatus.OK)
                {
                    TextHeight = thRes.Value;
                }
                else
                {
                    return;
                }

                // Save settings
                Properties.Settings.Default.Command_COORDGRID_TextHeight = TextHeight;
                Properties.Settings.Default.Command_COORDGRID_Interval   = Interval;
                Properties.Settings.Default.Save();

                // Print grid
                NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
                nfi.NumberGroupSeparator = " ";
                nfi.NumberDecimalDigits  = 0;

                using (Transaction tr = db.TransactionManager.StartTransaction())
                    using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead))
                        using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                        {
                            BlockTableRecord blockDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);

                            for (int x = xmin; x <= xmax; x += Interval)
                            {
                                for (int y = ymin; y <= ymax; y += Interval)
                                {
                                    Point3d v = new Point3d(x, y, 0);
                                    if (!PolylineContains(points, v))
                                    {
                                        continue;
                                    }

                                    BlockReference blockRef = AcadUtility.AcadEntity.CreateBlockReference(db, blockId, v, TextHeight, 0);

                                    btr.AppendEntity(blockRef);
                                    tr.AddNewlyCreatedDBObject(blockRef, true);

                                    // Set attributes
                                    foreach (ObjectId id in blockDef)
                                    {
                                        AttributeDefinition attDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition;
                                        if (attDef != null)
                                        {
                                            using (AttributeReference attRef = new AttributeReference())
                                            {
                                                attRef.SetDatabaseDefaults(db);
                                                attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform);
                                                blockRef.AttributeCollection.AppendAttribute(attRef);
                                                tr.AddNewlyCreatedDBObject(attRef, true);
                                                attRef.TextString = attDef.Tag == "X" ? x.ToString("n", nfi) : y.ToString("n", nfi);
                                                attRef.AdjustAlignment(db);
                                            }
                                        }
                                    }
                                }
                            }

                            tr.Commit();
                        }
            }
        }