示例#1
0
文件: Class1.cs 项目: guchanghai/Cut
        public void GetType()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("���ݿ���������ʶ���ת��\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�򿪵Ķ���");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity;
                ed.WriteMessage("ent.GetRXClass().Name :" + ent.GetRXClass().Name + "\n");

                if (ent is Line)
                {
                    Line aLine = ent as Line;
                    aLine.ColorIndex = 1;
                }
                else if (ent.GetType() == typeof(Circle))
                {
                    Circle cir = (Circle)ent;
                    cir.ColorIndex = 2;
                }

                trans.Commit();
            }
        }
        public static void ZoomToEntity()
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // Get the entity to which we'll zoom

            PromptEntityOptions peo = new PromptEntityOptions("\nSelect an entity:");

            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status != PromptStatus.OK)
                return;

            // Extract its extents

            Extents3d ext;

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                Entity ent = (Entity)tr.GetObject(per.ObjectId, OpenMode.ForRead);
                ext = ent.GeometricExtents;
                tr.Commit();
            }

            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
        }
示例#3
0
        public void XDataShowCommand()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
             if (doc == null) return;
             Editor ed = doc.Editor;

             var opt = new PromptEntityOptions("Выбери приметив:");
             var res = ed.GetEntity(opt);
             if (res.Status == PromptStatus.OK)
             {
            TypedValue[] typedValues = null;
            string entName = string.Empty;
            using (var ent = res.ObjectId.Open(OpenMode.ForRead) as Entity)
            {
               if (ent.XData == null)
               {
                  ed.WriteMessage("\nНет расширенных данных у {0}", ent);
                  return;
               }
               else
               {
                  typedValues = ent.XData.AsArray();
                  entName = ent.ToString();
               }
            }
            FormXDataView formXdataView = new FormXDataView(typedValues, entName);
            Application.ShowModalDialog(formXdataView);
             }
        }
示例#4
0
        private void selectButton_Click(object sender, EventArgs e)
        {
            if (xdata != null)
            {
                xdata.UpdateXData();
            }

            //SetFocus(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Window.Handle); 

            this.Visible = false;
            this.Hide();//先隐藏窗体

            PromptEntityOptions prEnt = new PromptEntityOptions("\n请选择一个实体 ");
            PromptEntityResult prEntRes = Tools.Editor.GetEntity(prEnt);
            if (prEntRes.Status != PromptStatus.OK)
            {
                this.Visible = true;
                this.Show();
                return;
            }

            if (xdata == null || xdata.Id != prEntRes.ObjectId)
            {
                xdata = new XData(prEntRes.ObjectId);
                updateData();
            }

            this.Visible = true;
            this.Show();

            //SetFocus(this.Handle);

        }
示例#5
0
        private PromptEntityOptions GetReferenceSelectionPrompt()
        {
            PromptEntityOptions selectionOptions =
                new PromptEntityOptions(Environment.NewLine + "Wskaż kotę z poprawną wysokością: ");
            selectionOptions.AllowNone = false;

            return selectionOptions;
        }
示例#6
0
        private void CopyPos()
        {
            PromptEntityOptions opts = new PromptEntityOptions("Select source object: ");
            opts.AllowNone = false;
            PromptEntityResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(opts);
            if (result.Status != PromptStatus.OK) return;

            PromptEntityOptions destopts = new PromptEntityOptions("Select destination object: ");
            destopts.AllowNone = false;
            PromptEntityResult destresult = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(destopts);
            if (destresult.Status != PromptStatus.OK) return;
            if (result.ObjectId == destresult.ObjectId) return;

            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    RebarPos source = tr.GetObject(result.ObjectId, OpenMode.ForRead) as RebarPos;
                    if (source == null) return;
                    if (source.Detached) return;

                    RebarPos dest = tr.GetObject(destresult.ObjectId, OpenMode.ForWrite) as RebarPos;
                    if (dest != null)
                    {
                        if (dest.Detached)
                        {
                            dest.Pos = source.Pos;
                        }
                        else
                        {
                            dest.Pos = source.Pos;
                            dest.Count = source.Count;
                            dest.Diameter = source.Diameter;
                            dest.Spacing = source.Spacing;
                            dest.Shape = source.Shape;
                            dest.A = source.A;
                            dest.B = source.B;
                            dest.C = source.C;
                            dest.D = source.D;
                            dest.E = source.E;
                            dest.F = source.F;
                            dest.Display = source.Display;
                            dest.Note = source.Note;
                            dest.Multiplier = source.Multiplier;
                        }
                    }

                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
示例#7
0
 public void BeginTriangulate()
 {
     buildTriangulations buildT = new buildTriangulations();
     AC_Transactions tr = new AC_Transactions();
     PromptEntityOptions options = new PromptEntityOptions("Pick a Line to Triangulate");
     options.SetRejectMessage("not valid Object \n");
     options.AddAllowedClass(typeof(Line), true);
     PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options);
     if (sel.Status == PromptStatus.OK)
     {
         tr.AC_Doc.Editor.WriteMessage("Line " + sel.ObjectId.ToString() + " Selected \n");
         buildT.Create((AC_Line)tr.openObjectErased(sel.ObjectId));
     }
 }
示例#8
0
        private void selectButton_Click(object sender, EventArgs e)
        {
            if (xdata != null)
            {
                if (xdata.HasXData())
                {
                    if (!xdata.IsXDataUpdate)
                    {
                        DialogResult res = MessageBox.Show("请确认是否保存数据?", "保存数据", MessageBoxButtons.YesNo);

                        if (res == DialogResult.Yes)
                        {
                            checkChanged();//检查修改,并更新
                            xdata.UpdateXData();

                            appNamesComboBox.Items.Clear();
                            xdataListView.Items.Clear();
                            appNamesComboBox.Text = null;
                        }
                    }
                }

                //xdata.UpdateXData();
            }

            //TestPalettes.SetPaletteFocus(false);
            SetFocus(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Window.Handle); 

            PromptEntityOptions prEnt = new PromptEntityOptions("\n请选择一个实体 ");
            PromptEntityResult prEntRes = Tools.Editor.GetEntity(prEnt);
            if (prEntRes.Status != PromptStatus.OK)
            {
                return;
            }

            //TestPalettes.SetPaletteFocus(true);
            if (xdata == null || xdata.Id != prEntRes.ObjectId)
            {
                appNamesComboBox.Items.Clear();
                xdataListView.Items.Clear();
                appNamesComboBox.Text = null;

                xdata = new XData(prEntRes.ObjectId);
                updateData();
                MessageBox.Show("该实体没有扩展数据,请注册应用程序名称");
            }

            SetFocus(TestPalettes.ps.Handle);

        }
示例#9
0
        public void GetXData()
        {
            PromptEntityOptions opt = new PromptEntityOptions("\nSelect entity: ");
            PromptEntityResult res = editor.GetEntity(opt);

            if (res.Status == PromptStatus.OK)
            {
                Transaction trans = doc.TransactionManager.StartTransaction();
                using (trans)
                {

                    DBObject obj = trans.GetObject(res.ObjectId, OpenMode.ForRead);
                    ResultBuffer rb = obj.XData;
                    if (rb == null)
                    {
                        editor.WriteMessage("\nEntity does not have XData attached.");
                    }
                    else
                    {
                        int n = 0;
                        foreach (TypedValue tv in rb)
                        {
                            editor.WriteMessage("\nTypedValue {0} - type: {1}, value: {2}",
                              n++,
                              tv.TypeCode,
                              tv.Value
                            );
                        }
                        rb.Dispose();
                    }
                    editor.WriteMessage($"\nObjectId : {obj.ObjectId}");
                    if (obj is BlockReference)
                    {
                        editor.WriteMessage($"\nObject attibutes collection:");
                        AttributeCollection atc = ((BlockReference)obj).AttributeCollection;
                        foreach (ObjectId item in atc)
                        {
                            AttributeReference atr = trans.GetObject(item, OpenMode.ForRead) as AttributeReference;
                            editor.WriteMessage("\n" + atr.Tag.ToString());
                        }
                    }
                }
            }
        }
示例#10
0
文件: Class1.cs 项目: guchanghai/Cut
        public void AddExtDict()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("����������չ�ʵ�\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�����չ���ݵĿ�\n");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject obj = trans.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBObject;
                BlockReference blkRef;
                if (obj is BlockReference)
                {
                    blkRef = obj as BlockReference;
                }
                else
                {
                    return;
                }

                // �����������չ�ʵ�
                blkRef.CreateExtensionDictionary();
                DBDictionary extensionDict = (DBDictionary)trans.GetObject(blkRef.ExtensionDictionary, OpenMode.ForWrite, false);

                // ͨ��Xrecord׼��������������
                Xrecord xRec = new Xrecord();
                xRec.Data = new ResultBuffer(
                  new TypedValue((int)DxfCode.Text, "����"),// ����
                  new TypedValue((int)DxfCode.Real, 1200.0),//нˮ
                  new TypedValue((int)DxfCode.Text, "������"));// ����
               // ����չ�ʵ��������չ��¼
                extensionDict.SetAt("EmployeeInfomation", xRec);
                trans.AddNewlyCreatedDBObject(xRec, true);

                trans.Commit();
            }
        }
示例#11
0
        public static void View()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            if (doc == null) return;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            var opt = new PromptEntityOptions("\nВыбери приметив:");
            var res = ed.GetEntity(opt);
            if (res.Status == PromptStatus.OK)
            {
                StringBuilder sbInfo = new StringBuilder();
                string entName = string.Empty;
                using (var t = db.TransactionManager.StartTransaction())
                {
                    var ent = res.ObjectId.GetObject(OpenMode.ForRead, false, true) as Entity;
                    entName = ent.ToString();
                    if (ent.XData != null)
                    {
                        sbInfo.AppendLine("XData:");
                        foreach (var item in ent.XData)
                        {
                            sbInfo.AppendLine($"    {getTypeCodeName(item.TypeCode)} = {item.Value}");
                        }
                    }
                    if (!ent.ExtensionDictionary.IsNull)
                    {
                        sbInfo.AppendLine("\nExtensionDictionary:");
                        exploreDictionary(ent.ExtensionDictionary, ref sbInfo);
                    }

                    if (sbInfo.Length==0)
                    {
                        ed.WriteMessage("\nНет расширенных данных у {0}", ent);
                        return;
                    }
                    t.Commit();
                }
                FormXDataView formXdataView = new FormXDataView(sbInfo.ToString(), entName);
                Application.ShowModalDialog(formXdataView);
            }
        }
示例#12
0
        private void button1_Click(object sender, EventArgs e)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            this.Hide();
            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    PromptEntityOptions  prEnt = new PromptEntityOptions("ѡ��һ��Բ��\n");
                    PromptEntityResult  prEntRes = ed.GetEntity(prEnt);
                    if (prEntRes.Status != PromptStatus.OK)
                        throw new System.Exception("������û�ȡ��");

                    ObjectId id = prEntRes.ObjectId;
                    DBObject obj = trans.GetObject(id, OpenMode.ForRead) ;
                    Circle cir;
                    if (obj is Circle)
                    {
                        cir = obj as Circle;
                    }
                    else
                    {
                        throw new System.Exception("ѡ��������");
                    }
                    tb_layer.Text = cir.Layer ;
                    tb_center.Text = cir.Center.ToString();
                    tb_radius.Text = cir.Radius .ToString();

                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("����: " + ex.Message);
            }
            finally
            {
                this.Show();
            }
        }
示例#13
0
文件: Class1.cs 项目: guchanghai/Cut
        public void EntPro()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("ʵ����������\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�򿪵Ķ���\n");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�\n");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity;
                ed.WriteMessage("��ȡ������ʵ�������\n");
                ed.WriteMessage("ʵ���ԭ�ȵ�����Ϊ :" + ent.Linetype + "\n");
                // ��ȡ���ͱ��¼
                LinetypeTable lineTypeTbl = trans.GetObject(db.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;
                // ȷ��DOT�������Ѿ����ص���ǰ���ݿ�
                LinetypeTableRecord lineTypeTblRec = trans.GetObject(lineTypeTbl["DOT"], OpenMode.ForRead) as LinetypeTableRecord;
                // ����ʵ�������
                ent.LinetypeId = lineTypeTblRec.ObjectId;

                // ����ʵ������ͱ���
                ed.WriteMessage("����ʵ������ͱ���Ϊ2.0\n");
                ent.LinetypeScale = 2.0;

                //����ʵ��Ŀɼ���
                ent.Visible = true;

                 //����ʵ�����ڵIJ�
                ed.WriteMessage("ʵ���ԭ�����ڵIJ�Ϊ :" + ent.Layer + "\n");
                ent.Layer = "layer0";
                trans.Commit();
            }
        }
 public void filer()
 {
     Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
     PromptEntityOptions opt = new PromptEntityOptions("Select an object to dump");
     PromptEntityResult res ;
     do
     {
         res = ed.GetEntity(opt);
         opt.Message = "\nNo object selected. Select an object to dump";
     }
     while (res.Status == PromptStatus.Error);
     if (res.Status == PromptStatus.OK)
     {
         using (Transaction t = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
         {
             Entity ent = (Entity)t.GetObject(res.ObjectId,OpenMode.ForRead);
             MyFiler filer = new MyFiler();
             ent.DwgOut(filer);
             t.Commit();
         }
     }
 }
示例#15
0
        public void TestWEdding()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            var selOpt = new PromptEntityOptions("\nВыбери полилинию для прополки");
            selOpt.SetRejectMessage("\nТолько полилинию");
            selOpt.AddAllowedClass(typeof(Polyline), true);
            var selRes = ed.GetEntity(selOpt);
            if (selRes.Status != PromptStatus.OK) return;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var pl = selRes.ObjectId.GetObject(OpenMode.ForWrite) as Polyline;
                pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Green));

                pl.Wedding(new Autodesk.AutoCAD.Geometry.Tolerance (0.02,0.1));

                pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Red));
                t.Commit();
            }
        }
示例#16
0
文件: Class1.cs 项目: guchanghai/Cut
        public void GetExtDict()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("��ȡ������չ�ʵ���Ϣ\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ���������չ���ݵĿ�\n");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject obj = trans.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBObject;
                BlockReference blkRef;
                if (obj is BlockReference)
                {
                    blkRef = obj as BlockReference;
                }
                else
                {
                    ed.WriteMessage("ѡ������ǿ飬�˳�\n");
                    return;
                }

                // �����������չ�ʵ�
                DBDictionary extensionDict = (DBDictionary)trans.GetObject(blkRef.ExtensionDictionary, OpenMode.ForWrite, false);
                // ��ȡAuthorInfo��չ��¼Xrecord
                Xrecord EmpXRec = (Xrecord)trans.GetObject(extensionDict.GetAt("EmployeeInfomation"), OpenMode.ForRead);
                ResultBuffer resBuf = EmpXRec.Data;
                TypedValue val = resBuf.AsArray()[0];
                ed.WriteMessage("��Ա������:{0}\n", val.Value);
                val = resBuf.AsArray()[1];
                ed.WriteMessage("��Ա����нˮ:{0}\n", val.Value);
                val = resBuf.AsArray()[2];
                ed.WriteMessage("��Ա������:{0}\n", val.Value);

                trans.Commit();
            }
        }
示例#17
0
文件: Class1.cs 项目: guchanghai/Cut
        public void GETXDATA()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("��ȡ��������XDATA\n");

            PromptEntityOptions entOps = new PromptEntityOptions("ѡ�����չ���ݵĶ���");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {

                Entity ent = (Entity)trans.GetObject(entRes.ObjectId, OpenMode.ForRead);
                ResultBuffer resBuf = ent.XData;
                if (resBuf != null)
                {
                    //
                    IEnumerator iter = resBuf.GetEnumerator();
                    while (iter.MoveNext())
                    {
                        TypedValue tmpVal = (TypedValue)iter.Current;
                        ed.WriteMessage(tmpVal.TypeCode.ToString() + ":");
                        ed.WriteMessage(tmpVal.Value.ToString() + "\n");
                    }
                }
            }
        }
示例#18
0
 public void ModifyTriangulate()
 {
     Triangulations triangulation = new Triangulations();
     AC_Transactions tr = new AC_Transactions();
     PromptEntityOptions options = new PromptEntityOptions("Pick a Line to modify Triangulations");
     options.SetRejectMessage("not valid Object \n");
     options.AddAllowedClass(typeof(Line), true);
     PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options);
     if (sel.Status == PromptStatus.OK)
     {
         triangulation.Modify((AC_Line)tr.openObjectErased(sel.ObjectId));
     }
 }
示例#19
0
 private static void handle_promptEntityOptions(object sender, PromptEntityOptionsEventArgs e)
 {
     useThisEntityOption = e.Options;
 }
示例#20
0
        void wallSpaceDraw()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a space ");
                entopts.SetRejectMessage("Must select a space, please!");
                entopts.AddAllowedClass(typeof(Space), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

                if (ent.Status == PromptStatus.OK)
                {
                    ObjectId entId = ent.ObjectId;

                    Space space = trans.GetObject(entId, OpenMode.ForRead, false) as Space;
                    if (space != null)
                    {
                        Manager mgr = new Manager(db);
                    }
                    else
                    {
                        ed.WriteMessage("\nSomething bad has happened...");
                    }
                }

                trans.Commit();
                Point3d centerPt = new Point3d(0.0, 0.0, 0.0);

                using (Transaction trans1 = tm.StartTransaction())
                {
                    BlockTable       bt    = (BlockTable)(trans1.GetObject(db.BlockTableId, OpenMode.ForWrite));
                    BlockTableRecord btr   = (BlockTableRecord)trans1.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    double           distX = 4800;
                    double           distY = 2400;

                    Point3d[] pts = new Point3d[5];
                    pts[0] = centerPt + new Vector3d(-(distX / 2), -(distY / 2), 0);
                    pts[1] = centerPt + new Vector3d((distX / 2), -(distY / 2), 0);
                    pts[2] = centerPt + new Vector3d((distX / 2), (distY / 2), 0);
                    pts[3] = centerPt + new Vector3d(-(distX / 2), (distY / 2), 0);
                    pts[4] = pts[0];


                    for (int i = 0; i < 4; i++)
                    {
                        Wall wall = new Wall();
                        wall.SetDatabaseDefaults(db);
                        wall.SetToStandard(db);
                        wall.SetDefaultLayer();
                        wall.Normal = new Vector3d(0, 0, 1);
                        wall.Set(pts[i], pts[i + 1], Vector3d.ZAxis);

                        btr.AppendEntity(wall);
                        trans1.AddNewlyCreatedDBObject(wall, true);
                    }
                    trans1.Commit();
                }
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
示例#21
0
        public void DrawKhazan()
        {
            Editor ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            bool   conti = true;

            //ObjectId ConsolElseOI, ConnectionOI, KhazanOI, ELse1OI, Else2OI;
            double MyScale        = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.BankKhazan).Scale;
            double MyCommentScale = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.BankKhazan).CommentScale;
            //ed.WriteMessage("AccessSelectBySoftwareCode:{0}:{1}", MyScale, MyCommentScale);

            ObjectIdCollection  NewDrawnCollection = new ObjectIdCollection();
            DrawKhazanJig       drawKhazan;
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect Container:");
            PromptEntityResult  per = ed.GetEntity(peo);

            if (per.Status == PromptStatus.OK)
            {
                Atend.Base.Acad.AT_INFO at_info = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(per.ObjectId);
                if (at_info.ParentCode != "NONE" && (at_info.NodeType == (int)Atend.Control.Enum.ProductType.Pole || at_info.NodeType == (int)Atend.Control.Enum.ProductType.PoleTip))
                {
                    Entity entContainer = Atend.Global.Acad.UAcad.GetEntityByObjectID(per.ObjectId);
                    if (entContainer != null)
                    {
                        drawKhazan = new DrawKhazanJig(entContainer, MyScale);
                        //ed.WriteMessage("current scale : {0} : {1} \n", MyScale, (int)Atend.Control.Enum.ProductType.BankKhazan);
                        while (conti)
                        {
                            PromptResult pr = ed.Drag(drawKhazan);
                            if (pr.Status == PromptStatus.OK && drawKhazan.PartOneIsActive)
                            {
                                drawKhazan.PartOneIsActive = false;
                                pr = ed.Drag(drawKhazan);
                                if (pr.Status == PromptStatus.OK && !drawKhazan.PartOneIsActive)
                                {
                                    conti = false;
                                    #region Save Data Here

                                    List <Entity> Entities = drawKhazan.GetEntities();
                                    //ed.WriteMessage("2 \n");
                                    if (SaveKhazanData(at_info.NodeCode))
                                    {
                                        //ed.WriteMessage("3 \n");
                                        ObjectId ConsolElseOI = ObjectId.Null;
                                        foreach (Entity ent in Entities)
                                        {
                                            //ed.WriteMessage("1001\n");
                                            ObjectId newDrawnoi = Atend.Global.Acad.UAcad.DrawEntityOnScreen(ent, Atend.Control.Enum.AutoCadLayerName.MED_AIR.ToString());
                                            Atend.Global.Acad.AcadJigs.MyPolyLine mPoly = ent as Atend.Global.Acad.AcadJigs.MyPolyLine;
                                            if (mPoly != null)
                                            {
                                                //ed.WriteMessage("POLY LINE FOUND\n");
                                                if (mPoly.AdditionalDictionary.ContainsKey("ProductType"))
                                                {
                                                    object ProductType = null;
                                                    mPoly.AdditionalDictionary.TryGetValue("ProductType", out ProductType);
                                                    if (ProductType != null)
                                                    {
                                                        if (Convert.ToInt32(ProductType) == (int)Atend.Control.Enum.ProductType.ConsolElse)
                                                        {
                                                            //ed.WriteMessage("1002\n");
                                                            ConsolElseOI = newDrawnoi;
                                                            Atend.Base.Acad.AT_INFO ConsolElseInfo = new Atend.Base.Acad.AT_INFO(newDrawnoi);
                                                            ConsolElseInfo.ParentCode  = at_info.NodeCode;
                                                            ConsolElseInfo.NodeCode    = KhazanPack.Code.ToString();
                                                            ConsolElseInfo.NodeType    = Convert.ToInt32(ProductType);
                                                            ConsolElseInfo.ProductCode = 0;
                                                            ConsolElseInfo.Insert();
                                                        }
                                                    }
                                                }
                                            }
                                            NewDrawnCollection.Add(newDrawnoi);
                                        }

                                        //ed.WriteMessage("ConsolElseOI:{0}\n", ConsolElseOI);
                                        if (ConsolElseOI != ObjectId.Null)
                                        {
                                            Atend.Base.Acad.AT_SUB ConsolElseSub = new Atend.Base.Acad.AT_SUB(ConsolElseOI);
                                            foreach (ObjectId oi in NewDrawnCollection)
                                            {
                                                if (oi != ConsolElseOI)
                                                {
                                                    //ed.WriteMessage("ConsolElseSubOI:{0}\n", oi);
                                                    ConsolElseSub.SubIdCollection.Add(oi);
                                                }
                                            }
                                            ConsolElseSub.SubIdCollection.Add(per.ObjectId);
                                            ConsolElseSub.Insert();
                                        }

                                        foreach (ObjectId oi in NewDrawnCollection)
                                        {
                                            if (oi != ConsolElseOI)
                                            {
                                                Atend.Base.Acad.AT_INFO a = new Atend.Base.Acad.AT_INFO(oi);
                                                a.ParentCode  = at_info.NodeCode;
                                                a.NodeCode    = KhazanPack.Code.ToString();
                                                a.NodeType    = (int)Atend.Control.Enum.ProductType.BankKhazan;
                                                a.ProductCode = KhazanPack.ProductCode;
                                                a.Insert();
                                            }
                                        }


                                        //ed.WriteMessage("Number of Entity : {0} \n", NewDrawnCollection.Count);

                                        ObjectId NewCreatedGroup =
                                            Atend.Global.Acad.Global.MakeGroup(KhazanPack.Code.ToString(), NewDrawnCollection);


                                        ObjectId txtOI = Atend.Global.Acad.UAcad.DrawEntityOnScreen(
                                            Atend.Global.Acad.UAcad.WriteNote(eKhazanTip.Description, drawKhazan.GetCommentPoSition(), MyCommentScale),
                                            Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());

                                        Atend.Base.Acad.AT_INFO GroupInfo1 = new Atend.Base.Acad.AT_INFO(txtOI);
                                        GroupInfo1.ParentCode  = KhazanPack.Code.ToString();
                                        GroupInfo1.NodeCode    = "";
                                        GroupInfo1.NodeType    = (int)Atend.Control.Enum.ProductType.Comment;
                                        GroupInfo1.ProductCode = 0;
                                        GroupInfo1.Insert();

                                        Atend.Base.Acad.AT_INFO GroupInfo = new Atend.Base.Acad.AT_INFO(NewCreatedGroup);
                                        GroupInfo.ParentCode  = at_info.NodeCode;
                                        GroupInfo.NodeCode    = KhazanPack.Code.ToString();
                                        GroupInfo.NodeType    = (int)Atend.Control.Enum.ProductType.BankKhazan;
                                        GroupInfo.ProductCode = KhazanPack.ProductCode;
                                        GroupInfo.Insert();

                                        Atend.Base.Acad.AT_SUB.AddToAT_SUB(NewCreatedGroup, per.ObjectId);
                                        //ed.WriteMessage("PoleOI for KHazan:{0}", per.ObjectId);
                                        Atend.Base.Acad.AT_SUB GroupSub = new Atend.Base.Acad.AT_SUB(NewCreatedGroup);
                                        GroupSub.SubIdCollection.Add(per.ObjectId);
                                        //ed.WriteMessage("TXTOI for KHazan:{0}", txtOI);
                                        GroupSub.SubIdCollection.Add(txtOI);
                                        GroupSub.Insert();
                                    }

                                    #endregion
                                }
                                else
                                {
                                    conti = false;
                                }
                            }
                            else
                            {
                                conti = false;
                            }
                        }
                    }
                }//if it was pole
            }
        }
示例#22
0
        public void Cmd_DimExtend()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var prEntOpt = new PromptEntityOptions("\nSelect a dimension system to extend: ");

            prEntOpt.SetRejectMessage("\nOnly linear dimensions may be selected.");
            prEntOpt.AllowNone = false;
            prEntOpt.AddAllowedClass(typeof(RotatedDimension), false);

            var prEntRes = acCurEd.GetEntity(prEntOpt);

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

            var objId    = prEntRes.ObjectId;
            var matrix3d = acCurEd.GetAlignedMatrix();

            var eqPoint = CalcTol.ReturnCurrentTolerance();

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var acEnt = acTrans.GetObject(objId, OpenMode.ForWrite) as Entity;
                if (acEnt != null)
                {
                    acEnt.Unhighlight();

                    var acRotDim = acEnt as RotatedDimension;
                    if (acRotDim != null)
                    {
                        var dimSys = DimSystem.GetSystem(acRotDim, eqPoint, eqPoint);

                        dimSys.Highlight();

                        var promptPointOption2 =
                            new PromptPointOptions(
                                "\nSelect a dimension line to extend or press CTRL to start crossing line:");

                        while (true)
                        {
                            if (dimSys.Count == 0)
                            {
                                break;
                            }

                            dimSys.Highlight();

                            var nArray    = DimSystem.GetActiveViewCount();
                            var ctManager = TransientManager.CurrentTransientManager;

                            var acCirc = new Circle();
                            var acLine = new Line(new Point3d(0, 0, 0), new Point3d(0, 0, 0));

                            acCirc.Color  = SettingsUser.DynPreviewColor;
                            acCirc.Normal = acRotDim.Normal;

                            acLine.Color = SettingsUser.DynPreviewColor;

                            var intCol = new IntegerCollection(nArray);

                            ctManager.AddTransient(acCirc, TransientDrawingMode.Highlight, 128,
                                                   intCol);
                            ctManager.AddTransient(acLine, TransientDrawingMode.Highlight, 128,
                                                   intCol);

                            var sysPts = dimSys.GetSystemPoints(eqPoint);

                            void Handler(object sender, PointMonitorEventArgs e)
                            {
                                var cPt     = dimSys.GetNearest(e.Context.ComputedPoint, eqPoint);
                                var sysPt   = sysPts[cPt];
                                var dlPt    = sysPt.DimLinePoint;
                                var scrSize = ScreenReader.GetSreenSize();

                                acCirc.Radius = scrSize / 200;

                                var point3d = sysPt.Dim1PointIndex != 1
                                    ? sysPt.Dim1.XLine2Point
                                    : sysPt.Dim1.XLine1Point;

                                if (Math.Abs(point3d.DistanceTo(dlPt)) <= eqPoint)
                                {
                                    acCirc.Center     = dlPt;
                                    acLine.StartPoint = dlPt;
                                    acLine.EndPoint   = dlPt;
                                    ctManager.UpdateTransient(acCirc, intCol);
                                    ctManager.UpdateTransient(acLine, intCol);
                                    return;
                                }

                                var point = new Line3d(dlPt, point3d).GetClosestPointTo(e.Context.ComputedPoint).Point;

                                acLine.StartPoint = dlPt;
                                acLine.EndPoint   = point;
                                acCirc.Center     = point;
                                ctManager.UpdateTransient(acCirc, intCol);
                                ctManager.UpdateTransient(acLine, intCol);
                            }

                            acCurEd.PointMonitor += Handler;

                            PromptPointResult ptRes;
                            try
                            {
                                ptRes = acCurDoc.Editor.GetPoint(promptPointOption2);
                            }
                            finally
                            {
                                acCurEd.PointMonitor -= Handler;
                                ctManager.EraseTransient(acCirc, intCol);
                                ctManager.EraseTransient(acLine, intCol);
                                acCirc.Dispose();
                                acLine.Dispose();
                            }

                            var cntrlPressed = (Control.ModifierKeys & Keys.Control) > Keys.None;

                            PromptPointResult ctrlRes = null;
                            if (cntrlPressed)
                            {
                                var promptPointOption3 =
                                    new PromptPointOptions("\nSelect second point of crossing line:")
                                {
                                    UseBasePoint  = true,
                                    UseDashedLine = true,
                                    BasePoint     = ptRes.Value
                                };

                                ctrlRes = acCurDoc.Editor.GetPoint(promptPointOption3);
                                if (ctrlRes.Status != PromptStatus.OK)
                                {
                                    break;
                                }
                            }

                            if (ptRes.Status != PromptStatus.OK)
                            {
                                break;
                            }

                            if (cntrlPressed)
                            {
                                var point3d6 = ptRes.Value.TransformBy(matrix3d);
                                var point3d7 = ctrlRes.Value.TransformBy(matrix3d);
                                var nums     = dimSys.GetSystemByLine(point3d6, point3d7, eqPoint);

                                if (nums.Count <= 0)
                                {
                                    continue;
                                }

                                var sysPoints2 = dimSys.GetSystemPoints(eqPoint);
                                foreach (var num3 in nums)
                                {
                                    var point3d8 = DimSystem.GetCrossing(dimSys, sysPoints2, num3, point3d6,
                                                                         point3d7, eqPoint);
                                    if (point3d8.X != -99999 || point3d8.Y != -99999 || point3d8.Z != -99999)
                                    {
                                        dimSys.Extend(num3, 0, point3d8, eqPoint);
                                    }
                                    else
                                    {
                                        acCurEd.WriteMessage("\nCannot extend lines with zero length.");
                                    }
                                }

                                acTrans.TransactionManager.QueueForGraphicsFlush();
                            }
                            else
                            {
                                var point3d9  = ptRes.Value.TransformBy(matrix3d);
                                var num4      = dimSys.GetNearest(point3d9, eqPoint);
                                var sysPoint  = dimSys.GetSystemPoints(eqPoint)[num4];
                                var point3d10 = sysPoint.DimLinePoint;
                                var point3d11 = sysPoint.Dim1PointIndex != 1
                                    ? sysPoint.Dim1.XLine2Point
                                    : sysPoint.Dim1.XLine1Point;
                                if (Math.Abs(point3d10.DistanceTo(point3d11)) >= eqPoint)
                                {
                                    dimSys.Extend(num4, 0, point3d9, eqPoint);
                                    acTrans.TransactionManager.QueueForGraphicsFlush();
                                }
                                else
                                {
                                    acCurEd.WriteMessage("\nCannot extend lines with zero length.");
                                }
                            }
                        }

                        dimSys.Unhighlight();
                        acTrans.Commit();
                    }
                }
            }
        }
示例#23
0
        public void CMD_PosEdit()
        {
            if (!CheckLicense()) return;

            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            // Edit entity if there is a pickset
            PromptSelectionResult selectionRes = ed.SelectImplied();
            if (selectionRes.Status != PromptStatus.Error && selectionRes.Value.Count > 0)
            {
                ObjectId id = selectionRes.Value[0].ObjectId;
                ed.SetImpliedSelection(new ObjectId[0]);
                ItemEdit(id, MonitoredPoint);
                return;
            }

            PromptEntityOptions opts = new PromptEntityOptions("Select entity: ");
            opts.AllowNone = false;
            PromptEntityResult result = ed.GetEntity(opts);
            if (result.Status == PromptStatus.OK)
            {
                ItemEdit(result.ObjectId, result.PickedPoint);
            }
        }
示例#24
0
        public static void getLineGroup()
        {
            // Get the TransactionManager
            TransactionManager tm =
                AcadApp.DocumentManager.MdiActiveDocument.Database.TransactionManager;

            // Get the AutoCAD editor
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;

            //
            PromptEntityOptions pmtEntOpts = new PromptEntityOptions("Select a LineSegment: ");
            PromptEntityResult  pmtEntRes  = ed.GetEntity(pmtEntOpts);

            if (pmtEntRes.Status == PromptStatus.OK)
            {
                ObjectId entId = pmtEntRes.ObjectId;

                // 2.1 Use the using statement and start a transaction
                // Use the transactionManager created above (tm)
                // Note: Put the closing curly brace after step 2.14
                using (Transaction tr = tm.StartTransaction())
                {
                    // 2.2 Declare a variable as a LineSegment. Instantiate
                    // it by making it equal to the GetObject method of the transaction
                    // from step 2.1. Cast it is a (LineSegment) and open it for read
                    // use the ObjectId from above (entID) for the ObjectId parameter.
                    LineSegment sline = (LineSegment)tm.GetObject(entId, OpenMode.ForRead);

                    // 2.3 Test to see if the LineSegment from step 2.2 is null. If it
                    // is null return.
                    if (sline == null)
                    {
                        return;
                    }

                    // 2.4 Declare a variable as a LineStyle. Instantiate
                    // it by making it equal to the GetOjbect method of the transaction
                    // from step 2.1. Cast it is a (LineStyle). Use the StyleID property
                    // of the LineSegment from step 2.2 and open it for read
                    LineStyle linestyle = (LineStyle)tm.GetObject(sline.StyleID, OpenMode.ForRead, true);

                    // 2.5 Create a string variable make it equal to this:
                    // "\nLineStyle: " +
                    // linestyle.Name; sMsg += "\n   " +
                    // linestyle.FlagType; sMsg += "\n   " +
                    // linestyle.GapPriority; sMsg += "\n   " +
                    // linestyle.ShowFlowDirection ;  sMsg  += "\n";
                    // Note: change "lineStyle" to the variable used in step 2.4
                    string sMsg = "\nLineStyle: " +
                                  linestyle.Name; sMsg += "\n   " +
                                                          linestyle.FlagType; sMsg += "\n   " +
                                                                                      linestyle.GapPriority; sMsg += "\n   " +
                                                                                                                     linestyle.ShowFlowDirection; sMsg += "\n";

                    // 2.6 Use the WriteMessage of the Editor declared above (ed)
                    // to put the string from step 2.5 on the command line
                    // pass in the string
                    ed.WriteMessage(sMsg);


                    // 2.7 Declare a variable as a LineGroupManager and get the line group id
                    // and assign it to variable lineGroupId.
                    LineGroupManager lineGroupMgr = new LineGroupManager();
                    int lineGroupId = lineGroupMgr.GroupId(entId);

                    // 2.8 use the string variable from step 2.5, make it equal to this:
                    // "\nLineGroup: " + lineGroupId.ToString() + " (" + type.ToString() + ")";
                    // Create the type variable first and assign it.
                    GroupType type = lineGroupMgr.Type(lineGroupId);
                    sMsg = "\nLineGroup: " + lineGroupId.ToString() + " (" + type.ToString() + ")";

                    // 2.9 Add to the string variable from step 2.8. (use +=)
                    // add the string "\n   LineSegments: " plus the Count property
                    // of the LineSegments of the LineGroup from step 2.7
                    sMsg += "\n   LineSegments: " + lineGroupMgr.Count(lineGroupId);

                    // 2.10 Use the WriteMessage of the Editor declared above (ed)
                    // to put the string from step 2.8 and 2.9 on the command line
                    // pass in the string
                    ed.WriteMessage(sMsg);

                    // 2.11 use a foreach loop and iterate through the ObjectId of the
                    // LineSegments of the LineGroup from step 2.7 (use the LineDbIds
                    // property)
                    // Note: Put the closing curly brace after step 2.14
                    foreach (ObjectId lsId in lineGroupMgr.LineDbIds(lineGroupId))
                    {
                        // 2.12 Declare a LineSegment variable and instantiate it using
                        // the transaction from step 1.4. Use the ObjectId from the
                        // loop (step 2.11) Open it for read.
                        LineSegment ls = (LineSegment)tm.GetObject(lsId, OpenMode.ForRead);

                        // 2.13 make the string variable from step 2.5 equal to this string:
                        // "\n   LineSegment: " plus the ClassName property of the LineSegment
                        // from step 2.12 plus this string " ,Vertices 0 - x,y,z "  plus
                        // the Vertices(0).ToString()
                        sMsg = "\n   LineSegment: " + ls.ClassName + " ,Vertices 0 - x,y,z " + ls.Vertices[0].ToString();

                        // 2.14 Use the WriteMessage of the Editor declared above (ed)
                        // to put the string from steps 2.13 the command line
                        // pass in the string
                        ed.WriteMessage(sMsg);

                        // Build and test the code. (run command "LineGroup", you should see
                        // details about the Line Segments on the command line.
                        // Continue to step 2.15 in the lineObjectsAndStylesAccess function
                    }
                }
            }
        }
示例#25
0
        public void CreateSectionFromPolylineCommand()
        {
#if !DEBUG
            Statistic.SendCommandStarting("mpSectionFromPolyline", ModPlusConnector.Instance.AvailProductExternalVersion);
#endif
            try
            {
                // Выберите полилинию:
                var peo = new PromptEntityOptions($"\n{Language.GetItem(Invariables.LangItem, "msg6")}")
                {
                    AllowNone = false,
                    AllowObjectOnLockedLayer = true
                };
                peo.SetRejectMessage($"\n{Language.GetItem(Invariables.LangItem, "wrong")}");
                peo.AddAllowedClass(typeof(Polyline), true);

                var per = AcadUtils.Editor.GetEntity(peo);
                if (per.Status != PromptStatus.OK)
                {
                    return;
                }

                /* Регистрация ЕСКД приложения должна запускаться при запуске
                 * функции, т.к. регистрация происходит в текущем документе
                 * При инициализации плагина регистрации нет!
                 */
                ExtendedDataUtils.AddRegAppTableRecord(SectionDescriptor.Instance.Name);

                var style = StyleManager.GetCurrentStyle(typeof(Section));
                var sectionLastLetterValue  = string.Empty;
                var sectionLastIntegerValue = string.Empty;
                FindLastSectionValues(ref sectionLastLetterValue, ref sectionLastIntegerValue);
                var section = new Section(sectionLastIntegerValue, sectionLastLetterValue);

                MainFunction.CreateBlock(section);
                section.ApplyStyle(style, true);

                var plineId = per.ObjectId;

                using (AcadUtils.Document.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, true))
                {
                    using (var tr = AcadUtils.Document.TransactionManager.StartOpenCloseTransaction())
                    {
                        var dbObj = tr.GetObject(plineId, OpenMode.ForRead);
                        if (dbObj is Polyline pline)
                        {
                            for (int i = 0; i < pline.NumberOfVertices; i++)
                            {
                                if (i == 0)
                                {
                                    section.InsertionPoint = pline.GetPoint3dAt(i);
                                }
                                else if (i == pline.NumberOfVertices - 1)
                                {
                                    section.EndPoint = pline.GetPoint3dAt(i);
                                }
                                else
                                {
                                    section.MiddlePoints.Add(pline.GetPoint3dAt(i));
                                }
                            }

                            section.UpdateEntities();
                            section.BlockRecord.UpdateAnonymousBlocks();

                            var ent = (BlockReference)tr.GetObject(section.BlockId, OpenMode.ForWrite, true, true);
                            ent.Position = pline.GetPoint3dAt(0);
                            ent.XData    = section.GetDataForXData();
                        }

                        tr.Commit();
                    }

                    AcadUtils.Document.TransactionManager.QueueForGraphicsFlush();
                    AcadUtils.Document.TransactionManager.FlushGraphics();

                    // "Удалить исходную полилинию?"
                    if (MessageBox.ShowYesNo(Language.GetItem(Invariables.LangItem, "msg7"), MessageBoxIcon.Question))
                    {
                        using (var tr = AcadUtils.Document.TransactionManager.StartTransaction())
                        {
                            var dbObj = tr.GetObject(plineId, OpenMode.ForWrite, true, true);
                            dbObj.Erase(true);
                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception exception)
            {
                ExceptionBox.Show(exception);
            }
        }
示例#26
0
        public void DrawingAmounts()
        {
            Document doc      = Application.DocumentManager.MdiActiveDocument;
            Database db       = doc.Database;
            Editor   ed       = doc.Editor;
            int      drwStyle = 0;//张拉方式,0为两端张拉,-1为左端张拉,1为右端张拉
            //钢束总体参数
            double kii        = TendonGeneralParameters.Kii;
            double miu        = TendonGeneralParameters.Miu;
            double Ep         = TendonGeneralParameters.Ep;
            double ctrlStress = TendonGeneralParameters.CtrlStress;

            using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理
            {
                //1.选择钢束线
                PromptEntityOptions tdLineOpt = new PromptEntityOptions("\n选择钢束或[张拉方式(D)/管道偏差系数(K)/摩阻系数(U)/张拉控制应力(C)]");
                tdLineOpt.SetRejectMessage("\n钢束应为多段线");
                tdLineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线
                tdLineOpt.Keywords.Add("D");
                tdLineOpt.Keywords.Add("K");
                tdLineOpt.Keywords.Add("U");
                tdLineOpt.Keywords.Add("C");
                tdLineOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字
                for (;;)                                   //无限循环,直到选中钢束线为止
                {
                    PromptEntityResult tdLineRes = ed.GetEntity(tdLineOpt);
                    //2.各关键字下分别设置钢束张拉参数
                    if (tdLineRes.Status == PromptStatus.Keyword)
                    {
                        switch (tdLineRes.StringResult)
                        {
                        case "D":
                            PromptIntegerOptions drwOpt = new PromptIntegerOptions($"\n输入张拉方式[两端张拉(0)/左端张拉(-1)/右端张拉(1)<{drwStyle}>");
                            drwOpt.AllowNone = true;
                            PromptIntegerResult drwRes = ed.GetInteger(drwOpt);
                            if (drwRes.Value == 0)
                            {
                                drwStyle = 0;
                            }
                            else if (drwRes.Value == -1)
                            {
                                drwStyle = -1;
                            }
                            else if (drwRes.Value == 1)
                            {
                                drwStyle = 1;
                            }
                            break;

                        case "K":
                            PromptDoubleOptions kiiOpt = new PromptDoubleOptions($"\n设置管道偏差系数(1/m)<{kii}>");
                            kiiOpt.AllowNone     = true;
                            kiiOpt.AllowNegative = false;
                            kiiOpt.AllowZero     = false;
                            PromptDoubleResult kiiRes = ed.GetDouble(kiiOpt);
                            if (kiiRes.Status == PromptStatus.OK)
                            {
                                kii = kiiRes.Value;
                            }
                            break;

                        case "U":
                            PromptDoubleOptions miuOpt = new PromptDoubleOptions($"\n设置摩阻系数<{miu}>");
                            miuOpt.AllowNone     = true;
                            miuOpt.AllowNegative = false;
                            miuOpt.AllowZero     = false;
                            PromptDoubleResult miuRes = ed.GetDouble(miuOpt);
                            if (miuRes.Status == PromptStatus.OK)
                            {
                                miu = miuRes.Value;
                            }
                            break;

                        case "C":
                            PromptDoubleOptions ctrOpt = new PromptDoubleOptions($"\n设置张拉控制应力(MPa)<{ctrlStress}>");
                            ctrOpt.AllowNone = true;
                            PromptDoubleResult ctrRes = ed.GetDouble(ctrOpt);
                            if (ctrRes.Status == PromptStatus.OK)
                            {
                                ctrlStress = ctrRes.Value;
                            }
                            break;
                        }
                    }
                    //3.输出引伸量
                    else if (tdLineRes.Status == PromptStatus.OK)
                    {
                        ObjectId tdLineId = tdLineRes.ObjectId;
                        Polyline tdLine   = trans.GetObject(tdLineId, OpenMode.ForRead) as Polyline;
                        if (drwStyle == 0)//两端张拉
                        {
                            double[] drawAmounts = tdLine.BothDrawAmount(ctrlStress, kii, miu, Ep);
                            ed.WriteMessage("\n左侧引伸量:" + drawAmounts[0].ToString("F0") + "; " +
                                            "右侧引伸量:" + drawAmounts[1].ToString("F0") + "。");
                        }
                        else if (drwStyle == -1)//左侧张拉
                        {
                            double drawAmount = tdLine.SingleDrawAmount(ctrlStress, kii, miu, -1, Ep);
                            ed.WriteMessage("\n左侧引伸量:" + drawAmount.ToString("F0") + "。");
                        }
                        else if (drwStyle == 1)//右侧张拉
                        {
                            double drawAmount = tdLine.SingleDrawAmount(ctrlStress, kii, miu, 1, Ep);
                            ed.WriteMessage("\n右侧引伸量:" + drawAmount.ToString("F0") + "。");
                        }
                        break;
                    }
                    else
                    {
                        ed.WriteMessage("输入有误!");
                        return;
                    }
                }
                trans.Commit();//执行事务处理
            }
        }
示例#27
0
        public void TendonAnnotation()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            db.SyncDwgToTdGenParas();//设置默认总体参数,已有总体参数字典项则无动作
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                #region 1.选择梁顶缘线
                PromptEntityOptions tpLineOpt = new PromptEntityOptions("\n选择梁顶缘线");
                tpLineOpt.SetRejectMessage("\n顶缘线应为直线、圆弧或多段线");
                tpLineOpt.AddAllowedClass(typeof(Line), true);     //可以选择直线
                tpLineOpt.AddAllowedClass(typeof(Polyline), true); //可以选择多段线
                tpLineOpt.AddAllowedClass(typeof(Arc), true);      //可以选择圆弧线
                PromptEntityResult tpLineRes = ed.GetEntity(tpLineOpt);
                if (tpLineRes.Status != PromptStatus.OK)
                {
                    return;
                }
                ObjectId tpLineId = tpLineRes.ObjectId;
                Curve    tpLine   = trans.GetObject(tpLineId, OpenMode.ForRead) as Curve;
                #endregion
                #region 2.选择钢束线
                PromptEntityOptions tdLineOpt = new PromptEntityOptions("\n选择钢束");
                tdLineOpt.SetRejectMessage("\n钢束应为多段线");
                tdLineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线
                PromptEntityResult tdLineRes = ed.GetEntity(tdLineOpt);
                if (tdLineRes.Status != PromptStatus.OK)
                {
                    return;
                }
                ObjectId tdLineId = tdLineRes.ObjectId;
                Polyline tdLine   = trans.GetObject(tdLineId, OpenMode.ForRead) as Polyline;

                //判断钢束线是否在顶缘线以内,否则报错返回
                if (tdLine.StartPoint.X < tpLine.StartPoint.X || tdLine.EndPoint.X > tpLine.EndPoint.X)
                {
                    Application.ShowAlertDialog("钢束线超出顶缘线,请检查!");
                    return;
                }
                tdLine.SetDefaultTendonParams();//设置钢束默认参数,如已有Xrecord信息则无动作
                #endregion
                #region 3.设置绘图参数(包括张拉方式和工作长度设置)
                //3.1 尺寸标注绘图位置及张拉方式和工作长度设置
                Point3d            pos    = new Point3d();//初始化标注点
                PromptPointOptions posOpt = new PromptPointOptions("\n设置标注线位置或设置[张拉方式(D)/工作长度(W)]");
                posOpt.Keywords.Add("D");
                posOpt.Keywords.Add("W");
                posOpt.AppendKeywordsToMessage = false;                                                     //提示信息中不显示关键字
                //获取钢束张拉方式
                int tdDrawStyle = 0;                                                                        //默认为两端张拉
                if (!tdLine.ExtensionDictionary.IsNull && tdLine.ObjectId.GetXrecord("DA_Tendons") != null) //如果钢束线有扩展记录则取扩展记录数据
                {
                    tdDrawStyle = (Int16)tdLine.ObjectId.GetXrecord("DA_Tendons")[4].Value;
                }
                //获取工作长度信息
                double       workLen = 800;
                DBDictionary dicts   = db.NamedObjectsDictionaryId.GetObject(OpenMode.ForWrite) as DBDictionary;
                if (dicts.Contains("DA_Tendons"))//如果字典中含DA_Tendons的字典项
                {
                    ObjectId       tdsDictId = dicts.GetAt("DA_Tendons");
                    DBDictionary   tdsDict   = tdsDictId.GetObject(OpenMode.ForRead) as DBDictionary; //获取DA_Tendons字典
                    ObjectId       xrecId    = tdsDict.GetAt("workLen");                              //获取字典中的工作长度项
                    Xrecord        xrec      = xrecId.GetObject(OpenMode.ForRead) as Xrecord;         //获取工作长度项中的Xrecird
                    TypedValueList vls       = xrec.Data;                                             //获取Xrecord中的TypedValueList数据
                    workLen = (double)vls[0].Value;                                                   //根据TypedValueList数据中的数值更新工作长度workLen
                }
                for (;;)
                {
                    PromptPointResult posRes = ed.GetPoint(posOpt);
                    if (posRes.Status == PromptStatus.Keyword)
                    {
                        switch (posRes.StringResult)
                        {
                        case "D":                    //选择修改张拉方式
                            PromptIntegerOptions drwOpt = new PromptIntegerOptions($"\n输入张拉方式[两端张拉(0)/左端张拉[-1]/右端张拉[1]<{tdDrawStyle}>");
                            drwOpt.AllowNone = true; //允许ESC退出
                            PromptIntegerResult drwRes = ed.GetInteger(drwOpt);
                            if (drwRes.Value == 0)
                            {
                                tdDrawStyle = 0;
                            }
                            else if (drwRes.Value == -1)
                            {
                                tdDrawStyle = -1;
                            }
                            else if (drwRes.Value == 1)
                            {
                                tdDrawStyle = 1;
                            }
                            TypedValueList values = tdLine.ObjectId.GetXrecord("DA_Tendons");    //根据输入更新钢束线的Xrecord记录
                            values.RemoveAt(4);
                            values.Add(DxfCode.Int16, tdDrawStyle);
                            break;

                        case "W":                    //修改工作长度
                            PromptDoubleOptions wklOpt = new PromptDoubleOptions($"\n输入工作长度<{workLen.ToString("F0")}>");
                            wklOpt.AllowNone = true; //允许ESC退出
                            PromptDoubleResult wklRes = ed.GetDouble(wklOpt);
                            if (wklRes.Status == PromptStatus.OK)
                            {
                                workLen = wklRes.Value;
                                ObjectId       tdsDictId = dicts.GetAt("DA_Tendons");//更新DA_Tendons字典中的钢束总体参数
                                DBDictionary   tdsDict   = tdsDictId.GetObject(OpenMode.ForRead) as DBDictionary;
                                ObjectId       xrecId    = tdsDict.GetAt("workLen");
                                Xrecord        xrec      = xrecId.GetObject(OpenMode.ForWrite) as Xrecord;
                                TypedValueList vls       = new TypedValueList();
                                vls.Add(DxfCode.Real, workLen);
                                xrec.Data = vls;
                                xrec.DowngradeOpen();
                            }
                            break;
                        }
                    }
                    else if (posRes.Status == PromptStatus.OK)
                    {
                        pos = posRes.Value;
                        break;
                    }
                }
                //3.2 绘图比例
                PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale}>");
                scaleOpt.AllowNone     = true;                        //允许回车,则采用前次比例
                scaleOpt.AllowNegative = false;                       //不允许负值
                scaleOpt.AllowZero     = false;                       //不允许零值
                PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例
                if (scaleRes.Status != PromptStatus.OK && scaleRes.Status != PromptStatus.None)
                {
                    return;
                }
                else if (scaleRes.Status == PromptStatus.OK)
                {
                    scale = scaleRes.Value;
                }
                #endregion
                #region 4.建立各类标注
                List <Point3d>   ptsH = new List <Point3d>();   //创建水平标注点集
                List <Dimension> dims = new List <Dimension>(); //创建标注集,存放各类标注
                for (int i = 0; i < tdLine.NumberOfVertices - 1; i++)
                {
                    //4.1 水平点集
                    ptsH.Add(tdLine.GetPoint3dAt(i));

                    //4.2 每段钢束线的长度
                    //4.3 直线标注角度
                    //4.4 圆弧线标注半径
                    if (tdLine.GetSegmentType(i) == SegmentType.Line)
                    {
                        LineSegment3d lineSeg = tdLine.GetLineSegmentAt(i);
                        //4.2 每段钢束线的长度
                        db.LineLengthDim(lineSeg, scale);
                        //4.3 直线标注角度
                        if (tdLine.StartPoint.X < tdLine.EndPoint.X)
                        {
                            db.LineAngelDim(lineSeg, !(i == tdLine.NumberOfVertices - 2), scale);
                        }
                        else
                        {
                            db.LineAngelDim(lineSeg, (i == tdLine.NumberOfVertices - 2), scale);
                        }
                    }
                    else if (tdLine.GetSegmentType(i) == SegmentType.Arc)
                    {
                        CircularArc3d arcSeg = tdLine.GetArcSegmentAt(i);
                        //4.2 每段钢束线的长度
                        db.ArcLengthDim(arcSeg, scale);
                        //4.3 圆弧标注半径
                        db.ArrowRadiusDim(arcSeg, scale);
                    }
                    //4.5 竖直距离标注
                    Ray vRay = new Ray();//建立竖直射线
                    vRay.BasePoint = tdLine.GetPoint3dAt(i);
                    vRay.UnitDir   = new Vector3d(0, 1, 0);
                    Point3dCollection ptIntersects = new Point3dCollection();
                    tpLine.IntersectWith(vRay, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero);
                    Point3d          ptIntersect = ptIntersects[0];
                    RotatedDimension dimV        = new RotatedDimension();
                    dimV.XLine1Point    = tdLine.GetPoint3dAt(i); //第一条尺寸边线
                    dimV.XLine2Point    = ptIntersect;            //第二条尺寸边线
                    dimV.DimLinePoint   = tdLine.GetPoint3dAt(i); //尺寸线位置
                    dimV.Rotation       = Math.PI / 2;            //标注旋转90度
                    dimV.DimensionStyle = db.Dimstyle;            //尺寸样式为当前样式
                    dimV.Dimscale       = scale;                  //设置尺寸全局比例
                    dims.Add(dimV);
                }
                //4.1 节点间距点集缺钢束最后一个点、梁顶缘线端点
                ptsH.Add(tdLine.EndPoint);
                ptsH.Add(tpLine.StartPoint);
                ptsH.Add(tpLine.EndPoint);
                db.ContinuedHorizontalDims(ptsH, pos, scale);//建立水平连续标注

                //4.5 竖直距离标注缺最后一个点
                Ray vRayLast = new Ray();//建立竖直射线
                vRayLast.BasePoint = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1);
                vRayLast.UnitDir   = new Vector3d(0, 1, 0);
                Point3dCollection ptIntersectsLast = new Point3dCollection();
                tpLine.IntersectWith(vRayLast, Intersect.OnBothOperands, ptIntersectsLast, IntPtr.Zero, IntPtr.Zero);
                Point3d          ptIntersectLast = ptIntersectsLast[0];
                RotatedDimension dimVLast        = new RotatedDimension();
                dimVLast.XLine1Point    = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1); //第一条尺寸边线
                dimVLast.XLine2Point    = ptIntersectLast;                                  //第二条尺寸边线
                dimVLast.DimLinePoint   = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1); //尺寸线位置
                dimVLast.Rotation       = Math.PI / 2;                                      //标注旋转90度
                dimVLast.DimensionStyle = db.Dimstyle;                                      //尺寸样式为当前样式
                dimVLast.Dimscale       = scale;                                            //设置尺寸全局比例
                dims.Add(dimVLast);
                #endregion
                #region 5 绘制张拉端
                //5.1 获取张拉端几何特征
                //获取钢束线真实的起点和终点
                Point3d tdStart = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.StartPoint : tdLine.EndPoint;
                Point3d tdEnd   = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.EndPoint : tdLine.StartPoint;
                //获取钢束线真实的起终点角度
                double iclStart = (tdLine.StartPoint.X < tdLine.EndPoint.X) ?
                                  tdLine.GetLineSegmentAt(0).GetAngleOfLineSeg() : tdLine.GetLineSegmentAt(tdLine.NumberOfVertices - 2).GetAngleOfLineSeg();
                double iclEnd = (tdLine.StartPoint.X < tdLine.EndPoint.X) ?
                                tdLine.GetLineSegmentAt(tdLine.NumberOfVertices - 2).GetAngleOfLineSeg() : tdLine.GetLineSegmentAt(0).GetAngleOfLineSeg();
                //初始化张拉端图元
                Polyline leftDraw  = new Polyline();
                Polyline rightDraw = new Polyline();
                MText    lengthL   = new MText();
                MText    lengthR   = new MText();
                //5.2 左侧张拉端
                //5.2.1 两侧张拉或左侧张拉时左端绘制工作长度线
                if (tdDrawStyle == 0 || tdDrawStyle == -1)
                {
                    //创建张拉端几何点
                    Point3d tdDrawL = GeTools.PolarPoint(tdStart, iclStart, -workLen);
                    //创建张拉段
                    leftDraw = new Polyline();
                    leftDraw.AddVertexAt(0, tdStart.ToPoint2d(), 0, 0, 0);
                    leftDraw.AddVertexAt(1, tdDrawL.ToPoint2d(), 0, 0, 0);
                    leftDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层
                    //标注左侧张拉段
                    lengthL = new MText();
                    //长度
                    lengthL.Contents = "工作长度" + workLen.ToString("F0");
                    //文字高度
                    lengthL.TextHeight = 3 * scale;
                    //样式为当前样式
                    lengthL.TextStyleId = db.Textstyle;
                    //旋转角度同直线段倾角
                    lengthL.Rotation = iclStart;
                    //对齐位置为右上
                    lengthL.Attachment = AttachmentPoint.TopRight;
                    //位置为中点垂线以下0.5个单位
                    lengthL.Location = GeTools.PolarPoint(GeTools.MidPoint(leftDraw.StartPoint,
                                                                           leftDraw.EndPoint), iclStart - Math.PI / 2, 0.5 * scale);
                }
                //5.2.2 右侧张拉时绘制P锚标识
                else
                {
                    //创建P锚起终点
                    Point3d tdDrawL1 = GeTools.PolarPoint(tdStart, iclStart + Math.PI / 2, 0.75 * scale);
                    Point3d tdDrawL2 = GeTools.PolarPoint(tdStart, iclStart + Math.PI / 2, -0.75 * scale);
                    //创建P锚标志
                    leftDraw = new Polyline();
                    leftDraw.AddVertexAt(0, tdDrawL1.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale);
                    leftDraw.AddVertexAt(1, tdDrawL2.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale);
                    leftDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层
                    //标注左侧P锚
                    lengthL = new MText();
                    //长度
                    lengthL.Contents = "P锚";
                    //文字高度
                    lengthL.TextHeight = 3 * scale;
                    //样式为当前样式
                    lengthL.TextStyleId = db.Textstyle;
                    //旋转角度同直线段倾角
                    lengthL.Rotation = iclStart;
                    //对齐位置为右中
                    lengthL.Attachment = AttachmentPoint.MiddleRight;
                    //位置为P锚标志右侧0.5个单位
                    lengthL.Location = GeTools.PolarPoint(GeTools.MidPoint(leftDraw.StartPoint,
                                                                           leftDraw.EndPoint), iclStart, -2 * scale);
                }
                //5.3 右侧张拉端绘制
                //5.3.1 两侧张拉或右侧张拉时右端绘制工作长度线
                if (tdDrawStyle == 0 || tdDrawStyle == 1)
                {
                    //创建张拉端几何点
                    Point3d tdDrawR = GeTools.PolarPoint(tdEnd, iclEnd, workLen);
                    //创建张拉段
                    rightDraw = new Polyline();
                    rightDraw.AddVertexAt(0, tdEnd.ToPoint2d(), 0, 0, 0);
                    rightDraw.AddVertexAt(1, tdDrawR.ToPoint2d(), 0, 0, 0);
                    rightDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层
                    //标注右侧张拉段
                    lengthR = new MText();
                    //长度
                    lengthR.Contents = "工作长度" + workLen.ToString("F0");
                    //文字高度
                    lengthR.TextHeight = 3 * scale;
                    //样式为当前样式
                    lengthR.TextStyleId = db.Textstyle;
                    //旋转角度同直线段倾角
                    lengthR.Rotation = iclEnd;
                    //对齐位置为左上
                    lengthR.Attachment = AttachmentPoint.TopLeft;
                    //位置为中点垂线以下0.5个单位
                    lengthR.Location = GeTools.PolarPoint(GeTools.MidPoint(rightDraw.StartPoint,
                                                                           rightDraw.EndPoint), iclEnd - Math.PI / 2, 0.5 * scale);
                }
                //5.2.2 左侧张拉时绘制P锚标识
                else//绘制P锚
                {
                    //创建P锚起终点
                    Point3d tdDrawR1 = GeTools.PolarPoint(tdEnd, iclEnd + Math.PI / 2, 0.75 * scale);
                    Point3d tdDrawR2 = GeTools.PolarPoint(tdEnd, iclEnd + Math.PI / 2, -0.75 * scale);
                    //创建P锚标志
                    rightDraw = new Polyline();
                    rightDraw.AddVertexAt(0, tdDrawR1.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale);
                    rightDraw.AddVertexAt(1, tdDrawR2.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale);
                    rightDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层
                    //标注左侧P锚
                    lengthR = new MText();
                    //长度
                    lengthR.Contents = "P锚";
                    //文字高度
                    lengthR.TextHeight = 3 * scale;
                    //样式为当前样式
                    lengthR.TextStyleId = db.Textstyle;
                    //旋转角度同直线段倾角
                    lengthR.Rotation = iclEnd;
                    //对齐位置为左中
                    lengthR.Attachment = AttachmentPoint.MiddleLeft;
                    //位置为P锚标志右侧0.5个单位
                    lengthR.Location = GeTools.PolarPoint(GeTools.MidPoint(rightDraw.StartPoint,
                                                                           rightDraw.EndPoint), iclEnd, 2 * scale);
                }
                #endregion
                #region 6 在截面顶缘标识“梁顶缘线”
                Point3d midPt     = GeTools.MidPoint(tpLine.StartPoint, tpLine.EndPoint);  //顶缘线起终点中点
                Point3d midPtInTp = tpLine.GetClosestPointTo(midPt, Vector3d.YAxis, true); //顶缘线上靠近中点的点
                MText   tpAnno    = new MText();
                tpAnno.Contents = "梁顶缘线";
                //文字高度
                tpAnno.TextHeight = 3 * scale;
                //样式为当前样式
                tpAnno.TextStyleId = db.Textstyle;
                //对齐位置为右上
                tpAnno.Attachment = AttachmentPoint.BottomLeft;
                //位置为中点以上0.5个单位
                tpAnno.Location = GeTools.PolarPoint(midPtInTp, Math.PI / 2, 0.5 * scale);
                #endregion
                db.AddToModelSpace(dims.ToArray());                        //添加各类标注
                db.AddToModelSpace(leftDraw, rightDraw, lengthL, lengthR); //添加张拉段线
                db.AddToModelSpace(tpAnno);                                //添加梁顶缘线标识
                trans.Commit();
            }
        }
示例#28
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();
                }
        }
示例#29
0
    ////////////////////////////
    //// Display Props
    //// list all the disp reps for the door for the current view port
    ////////////////////////////

    private void DisplayProps()
    {
        Database             db    = Application.DocumentManager.MdiActiveDocument.Database;
        TransactionManager   tm    = db.TransactionManager;
        Transaction          trans = db.TransactionManager.StartTransaction();
        BlockTable           bt    = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
        BlockTableRecord     btr   = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
        DictionaryDisplaySet dds   = new DictionaryDisplaySet(db, false);

        try
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions optEnt = new PromptEntityOptions("Select an AEC door entity");
            optEnt.SetRejectMessage("Selected entity is NOT an AEC door entity, try again...");
            optEnt.AddAllowedClass(typeof(Autodesk.Aec.Arch.DatabaseServices.Door), false);  // Geo is the base class of AEC entities.

            PromptEntityResult resEnt = ed.GetEntity(optEnt);
            if (resEnt.Status != PromptStatus.OK)
            {
                ed.WriteMessage("Selection error - aborting" + "\n");
                return;
            }

            Autodesk.Aec.Arch.DatabaseServices.Door door = trans.GetObject(resEnt.ObjectId, OpenMode.ForRead) as Door;
            ed.WriteMessage("You have selected an " + door.GetRXClass().Name + "\n");

            //  get its style
            Autodesk.Aec.Arch.DatabaseServices.DoorStyle doorstyle = trans.GetObject(door.StyleId, OpenMode.ForRead) as DoorStyle;

            ObjectId doorId = door.ObjectId;
            DisplayRepresentationManager drm = new DisplayRepresentationManager(db);

            ObjectIdCollection    ids = drm.GetDisplayRepresentationIdsFromCurrentViewport(door.GetRXClass());
            DisplayRepresentation dr  = null;
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Get all the Display Representations work with the door for current view port\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n");
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("door disp rep count = " + ids.Count + "\n");

            foreach (ObjectId id in ids)
            {
                dr = trans.GetObject(id, OpenMode.ForRead) as DisplayRepresentation;

                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Representation Name: " + dr.Name + " Display Name: " + dr.DisplayName + "\n");

                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Representation Name: " + dr.Name + "Display Name" + dr.DisplayName + "\n");
                DisplayProperties dps     = null;
                RXClass           rcProps = dr.DisplayPropertiesClass;
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Props Class: " + rcProps.Name + "\n");

                //  find override at instance level.
                ObjectId overId = dr.FindDisplayPropertiesOverride(door);
                if (overId != ObjectId.Null)
                {
                    dps = trans.GetObject(overId, OpenMode.ForRead) as DisplayProperties;
                    Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Element override Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n");
                    continue;
                }
                ObjectId overstyleId = dr.FindDisplayPropertiesOverride(doorstyle);
                if (overstyleId != ObjectId.Null)
                {
                    dps = trans.GetObject(overstyleId, OpenMode.ForRead) as DisplayProperties;
                    Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Style override Style Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n");
                    continue;
                }
                ObjectId defaultDpsId = dr.DefaultDisplayPropertiesId;
                if (!defaultDpsId.IsNull)
                {
                    dps = trans.GetObject(defaultDpsId, OpenMode.ForRead) as DisplayProperties;
                    Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Default Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n");
                }
            }
            trans.Commit();
        }
        catch (System.Exception)
        {
            trans.Abort();
        }
        finally
        {
            trans.Dispose();
        }
        return;
    }
示例#30
0
        public void pipeWalk()
        {
            // 4.1 Declare a variable as a PlantProject. Instantiate it using
            // the CurrentProject of PlantApplication
            PlantProject mainPrj = PlantApplication.CurrentProject;

            // 4.2 Declare a Project and instantiate it using 
            // ProjectParts[] of the PlantProject from step 4.1
            // use "Piping" for the name. This will get the Piping project
            Project prj = mainPrj.ProjectParts["Piping"];

            // 4.3 Declare a variable as a DataLinksManager. Instantiate it using
            // the DataLinksManager property of the Project from 4.2.
            DataLinksManager dlm = prj.DataLinksManager;

            //  PipingProject pipingPrj = (PipingProject) mainPrj.ProjectParts["Piping"];
            //  DataLinksManager dlm = pipingPrj.DataLinksManager;


            // Get the TransactionManager
            // Autodesk.AutoCAD.DatabaseServices.TransactionManager tm =
            //AcadApp.DocumentManager.MdiActiveDocument.Database.TransactionManager;

            // Get the AutoCAD editor
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;


            // Prompt the user to select a pipe entity
            PromptEntityOptions pmtEntOpts = new PromptEntityOptions("Select a Pipe : ");
            PromptEntityResult  pmtEntRes  = ed.GetEntity(pmtEntOpts);

            if (pmtEntRes.Status == PromptStatus.OK)
            {
                // Get the ObjectId of the selected entity
                ObjectId entId = pmtEntRes.ObjectId;

                // Use the using statement and start a transaction
                // Use the transactionManager created above (tm)
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    //#region transaction
                    //try
                    //{

                    //    // 4.4 Declare a variable as a Part. Instantiate it using
                    //    // the GetObject Method of the Transaction created above (tr)
                    //    // for the ObjectId argument use the ObjectId from above (entId)
                    //    // Open it for read. (need to cast it to Part)
                    //Part pPart = tr.GetObject(entId, OpenMode.ForRead);

                    //    // 4.5 Declare a variable as a PortCollection. Instantiate it
                    //    // using the GetPorts method of the Part from step 4.4.
                    //    // use PortType.All for the PortType.
                    //    PortCollection portCol = pPart.GetPorts(PortType.All); // (PortType.Both);

                    //    // 4.6 Use the WriteMessage function of the Editor created above (ed)
                    //    // print the Count property of the PortCollection from step 4.5.
                    //    // use a string similar to this: "\n port collection count = "
                    //    ed.WriteMessage("\n port collection count = " + portCol.Count);

                    //    // 4.7 Declare a ConnectionManager variable.
                    //    // (Autodesk.ProcessPower.PnP3dObjects.ConnectionManager)
                    //    // Instantiate the ConnectionManager variable by making it
                    //    // equal to a new Autodesk.ProcessPower.PnP3dObjects.ConnectionManager();
                    //    ConnectionManager conMgr = new Autodesk.ProcessPower.PnP3dObjects.ConnectionManager();

                    //    // 4.8 Declare a bool variable named bPartIsConnected and make it false
                    //    bool bPartIsConnected = false;


                    //    // 4.9 Use a foreach loop and iterate through all of the Port in
                    //    // the PortCollection from step 4.5.
                    //    // Note: Put the closing curly brace below step 4.18
                    //    foreach (Port pPort in portCol)
                    //    {
                    //        // 4.10 Use the WriteMessage function of the Editor created above (ed)
                    //        // print the Name property of the Port (looping through the ports)
                    //        // use a string similar to this: "\nName of this Port = " +
                    //        ed.WriteMessage("\nName of this Port = " + pPort.Name);

                    //        // 4.11 Use the WriteMessage function of the Editor created above (ed)
                    //        // print the X property of the Position from the Port
                    //        // use a string similar to this: "\nX of this Port = " +
                    //        ed.WriteMessage("\nX of this Port = " + pPort.Position.X.ToString());

                    //        // 4.12 Declare a variable as a Pair and make it equal to a
                    //        // new Pair().
                    //        Pair pair1 = new Pair();

                    //        // 4.13 Make the ObjectId property of the Pair created in step 4.10
                    //        // equal to the ObjectId of the selected Part (entId)
                    //        pair1.ObjectId = entId;

                    //        // 4.14 Make the Port property of the Pair created in step 4.10
                    //        // equal to the port from the foreach cycle (step 4.7)
                    //        pair1.Port = pPort;


                    //        // 4.15 Use an if else and the IsConnected method of the ConnectionManager
                    //        // from step 4.7. Pass in the Pair from step 4.12
                    //        // Note: Put the else statement below step 4.17 and the closing curly
                    //        // brace for the else below step 4.18
                    //        if (conMgr.IsConnected(pair1))
                    //        {
                    //            // 4.16 Use the WriteMessage function of the Editor (ed)
                    //            // and put this on the command line:
                    //            // "\n Pair is connected "
                    //            ed.WriteMessage("\n Pair is connected ");

                    //            // 4.17 Make the bool from step 4.8 equal to true.
                    //            // This is used in an if statement in step 4.19.
                    //            bPartIsConnected = true;
                    //        }
                    //        else
                    //        {
                    //            // 4.18 Use the WriteMessage function of the Editor (ed)
                    //            // and put this on the command line:
                    //            // "\n Pair is NOT connected "
                    //            ed.WriteMessage("\n Pair is NOT connected ");
                    //        }

                    //    }


                    //    // 4.19 Use an If statement and the bool from step 4.8. This will be
                    //    // true if one of the pairs tested in loop above loop was connected.
                    //    // Note: Put the closing curly brace after step 4.26
                    //    if (bPartIsConnected)
                    //    {

                    //        // 4.20 Declare an ObjectId named curObjID make it
                    //        // equal to ObjectId.Null
                    //        ObjectId curObjId = ObjectId.Null;


                    //        // 4.21 Declare an int name it rowId
                    //        int rowId;

                    //        // 4.22 Declare a variable as a  ConnectionIterator instantiate it
                    //        // using the NewIterator method of ConnectionIterator (Autodesk.ProcessPower.PnP3dObjects.)
                    //        // Use the ObjectId property of the Part from step 4.4
                    //        ConnectionIterator connectIter = ConnectionIterator.NewIterator(pPart.ObjectId);                       //need PnP3dObjectsMgd.dll

                    //        // You could Also use this, need to ensure that pPort is connected
                    //        // Use the ConnectionManager and a Pair as in the example above.
                    //        // conIter = ConnectionIterator.NewIterator(pPart.ObjectId, pPort);

                    //        // 4.23 Use a for loop and loop through the connections in the
                    //        // ConnectionIterator from step 4.22. The initializer can be empty.
                    //        // Use !.Done for the condition. use .Next for the iterator. 
                    //        // Note: Put the closing curly brace after step 4.26
                    //        for (; !connectIter.Done(); connectIter.Next())
                    //        {

                    //            // 4.24 Make the ObjectId from step 4.20 equal to the ObjectId
                    //            // property of the ConnectionIterator
                    //            curObjId = connectIter.ObjectId;

                    //            // 4.25 Make the integer from step 4.21 equal to the return from
                    //            // FindAcPpRowId method of the DataLinksManager from step 4.3.
                    //            // pass in the ObjectId from step 4.24
                    //            rowId = dlm.FindAcPpRowId(curObjId);

                    //            //4.26 Use the WriteMessage function of the Editor (ed)
                    //            // and pring the integer from step 4.25. Use a string similar to this
                    //            // this on the command line:
                    //            // "\n PnId = " +
                    //            ed.WriteMessage("\n PnId = " + rowId);

                    //        }

                    //    }
                    //}
                    //catch (System.Exception ex)
                    //{

                    //    ed.WriteMessage(ex.ToString());
                    //}
                    //#endregion
                }
            }
        }
示例#31
0
        public void SetXData()
        {
            PromptEntityOptions opt = new PromptEntityOptions("\nSelect entity: ");
            PromptEntityResult res = editor.GetEntity(opt);
            if (res.Status == PromptStatus.OK)
            {
                Transaction trans = doc.TransactionManager.StartTransaction();
                using (trans)
                {
                    DBObject obj =
                      trans.GetObject(
                        res.ObjectId,
                        OpenMode.ForWrite
                      );

                    AddRegAppTableRecord("skd");
                    AddRegAppTableRecord("l2p");
                    AddRegAppTableRecord("l1p");
                    AddRegAppTableRecord("g_d");
                    AddRegAppTableRecord("kom");
                    AddRegAppTableRecord("dds");
                    AddRegAppTableRecord("typ");
                    AddRegAppTableRecord("ilp");
                    AddRegAppTableRecord("ilw");
                    AddRegAppTableRecord("sko");
                    AddRegAppTableRecord("sre");
                    AddRegAppTableRecord("np-69");
                    AddRegAppTableRecord("el-100");
                    AddRegAppTableRecord("pro");
                    AddRegAppTableRecord("nop");
                    AddRegAppTableRecord("npo");
                    AddRegAppTableRecord("zn1");
                    AddRegAppTableRecord("zna");

                    ResultBuffer rb =

                      new ResultBuffer(

                        new TypedValue(1001, "skd"),
                        new TypedValue(1040, 0),
                        new TypedValue(1001, "l2p"),
                        new TypedValue(1040, 9),
                        new TypedValue(1001, "l1p"),
                        new TypedValue(1040, 9),
                        new TypedValue(1001, "g_d"),
                        new TypedValue(1000, "glo"),
                        new TypedValue(1001, "kom"),
                        new TypedValue(1000, "\u0020"),
                        new TypedValue(1001, "dds"),
                        new TypedValue(1040, 0.4),
                        new TypedValue(1001, "typ"),
                        new TypedValue(1070, 1),
                        new TypedValue(1001, "ilp"),
                        new TypedValue(1070, 7),
                        new TypedValue(1001, "ilw"),
                        new TypedValue(1070, 8),
                        new TypedValue(1001, "sko"),
                        new TypedValue(1040, 0.21),
                        new TypedValue(1001, "sre"),
                        new TypedValue(1040, 0.016),
                        new TypedValue(1001, "np-69"),
                        new TypedValue(1000, "bw"),
                        new TypedValue(1001, "el-100"),
                        new TypedValue(1000, "bw"),
                        new TypedValue(1001, "pro"),
                        new TypedValue(1000, "sys01-v4"),
                        new TypedValue(1001, "nop"),
                        new TypedValue(1070, 9999),
                        new TypedValue(1001, "npo"),
                        new TypedValue(1070, 30),
                        new TypedValue(1001, "zn1"),
                        new TypedValue(1000, "bw"),
                        new TypedValue(1001, "zna"),
                        new TypedValue(1000, "zn1")
                      );

                    obj.XData = rb;
                    rb.Dispose();
                    trans.Commit();
                }
            }
        }
        public static void StartFunction()
        {
#if !DEBUG
            Statistic.SendCommandStarting(ModPlusConnector.Instance);
#endif
            try
            {
                var doc      = Application.DocumentManager.MdiActiveDocument;
                var db       = doc.Database;
                var ed       = doc.Editor;
                var workType = "Tangent";
                while (true)
                {
                    var peo = new PromptEntityOptions($"\n{Language.GetItem(PlinesEditFunction.LangItem, "k16")}:")
                    {
                        AllowNone = false,
                        AllowObjectOnLockedLayer = true
                    };
                    peo.SetRejectMessage($"\n{Language.GetItem(PlinesEditFunction.LangItem, "wrong")}");
                    peo.AddAllowedClass(typeof(Polyline), true);

                    var per = ed.GetEntity(peo);
                    if (per.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    var polylineId = per.ObjectId;
                    var pickedPt   = ModPlus.Helpers.AutocadHelpers.UcsToWcs(per.PickedPoint);

                    using (doc.LockDocument())
                    {
                        using (var tr = db.TransactionManager.StartTransaction())
                        {
                            var dbObj = tr.GetObject(polylineId, OpenMode.ForWrite);

                            if (dbObj is Polyline polyline)
                            {
                                var p         = polyline.GetClosestPointTo(pickedPt, false);
                                var param     = polyline.GetParameterAtPoint(p);
                                var vx        = Convert.ToInt32(Math.Truncate(param));
                                var jig       = new LineToArcSegment();
                                var jigResult = jig.StartJig(polyline, polyline.GetPoint3dAt(vx), vx, workType);
                                if (jigResult.Status != PromptStatus.OK)
                                {
                                    return;
                                }

                                workType = jig.WorkType();
                            }

                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception exception)
            {
                ExceptionBox.Show(exception);
            }
        }
示例#33
0
        void getConnectionsWithSelection()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a wall ");
                entopts.SetRejectMessage("Must select a wall, please!");
                entopts.AddAllowedClass(typeof(Wall), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

                if (ent.Status == PromptStatus.OK)
                {
                    ObjectId entId = ent.ObjectId;

                    Wall     wall     = trans.GetObject(entId, OpenMode.ForRead, false) as Wall;
                    Manager  mgr      = new Manager(db);
                    Graph    theGraph = mgr.FindGraph(wall);
                    Matrix3d mat      = theGraph.WcsToEcsMatrix.Inverse();
                    for (int i = 0; i < theGraph.WallJointCount; i++)
                    {
                        Joint joint = theGraph.GetWallJoint(i);
                        ConnectionCollection connections = joint.Connections;
                        foreach (Connection connection in connections)
                        {
                            ed.WriteMessage("\nConnection in wall system for wall id: " + connection.Section.WallId.ToString());
                            ed.WriteMessage("\n  Direction from here: " + connection.DirectionFromHere.ToString());
                            foreach (double elevation in connection.ElevationVariations)
                            {
                                ed.WriteMessage("\n  Elevation Variations: " + elevation.ToString());
                            }
                            ed.WriteMessage("\n  Start Elevation: " + connection.StartElevation.ToString());
                            ed.WriteMessage("\n  End Elevation: " + connection.EndElevation.ToString());
                            ed.WriteMessage("\n  Section Starts Here: " + connection.SectionStartsHere.ToString());
                        }
                    }
                }

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
示例#34
0
        public void Cmd_DimLt()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var prEntOpt = new PromptEntityOptions("\nSelect an extension line to convert to line-type <" +
                                                   SettingsUser.RcDimLt + "> : ");

            prEntOpt.SetRejectMessage("\nOnly dimensions may be selected.");
            prEntOpt.AllowNone = false;
            prEntOpt.AddAllowedClass(typeof(AlignedDimension), false);
            prEntOpt.AddAllowedClass(typeof(RotatedDimension), false);
            prEntOpt.AddAllowedClass(typeof(ArcDimension), false);

            var prEntRes    = acCurEd.GetEntity(prEntOpt);
            var prPickPoint = prEntRes.PickedPoint;

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

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var acDim = acTrans.GetObject(prEntRes.ObjectId, OpenMode.ForWrite) as Entity;
                if (acDim != null)
                {
                    try
                    {
                        // Open the Linetype table for read
                        var acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
                                                             OpenMode.ForRead) as LinetypeTable;

                        if (acLineTypTbl != null)
                        {
                            var sLineTypName = SettingsUser.RcDimLt;

                            if (acLineTypTbl.Has(sLineTypName) == false)
                            {
                                acCurDb.LoadLineTypeFile(sLineTypName, "acad.lin");
                            }

                            Point3d xPt1;
                            Point3d xPt2;

                            var ltId = acLineTypTbl[sLineTypName];

                            switch (acDim)
                            {
                            case AlignedDimension alDim:
                            {
                                xPt1 = alDim.XLine1Point;
                                xPt2 = alDim.XLine2Point;

                                if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                                {
                                    alDim.Dimltex1 = ltId;
                                }
                                else
                                {
                                    alDim.Dimltex2 = ltId;
                                }

                                break;
                            }

                            case RotatedDimension roDim:
                            {
                                xPt1 = roDim.XLine1Point;
                                xPt2 = roDim.XLine2Point;

                                if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                                {
                                    roDim.Dimltex1 = ltId;
                                }
                                else
                                {
                                    roDim.Dimltex2 = ltId;
                                }

                                break;
                            }

                            case ArcDimension arDim:
                            {
                                xPt1 = arDim.XLine1Point;
                                xPt2 = arDim.XLine2Point;

                                if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                                {
                                    arDim.Dimltex1 = ltId;
                                }
                                else
                                {
                                    arDim.Dimltex2 = ltId;
                                }

                                break;
                            }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        MailAgent.Report(e.Message);
                    }
                }

                acTrans.Commit();
            }
        }
示例#35
0
        public void intersectEntities()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            Line   firstLine  = null;
            Line   secondLine = null;
            Circle cir        = null;
            Entity ent        = null;
            State  st         = State.LineType;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    //Select first polyline
                    PromptEntityOptions ptEntityOpt = new PromptEntityOptions("Select firtst line:");
                    PromptEntityResult  ptEntityRes = ed.GetEntity(ptEntityOpt);
                    if (ptEntityRes.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    //Get the polyline entity
                    ent = (Entity)trans.GetObject(ptEntityRes.ObjectId, OpenMode.ForRead);
                    if (ent is Line)
                    {
                        firstLine = ent as Line;
                    }

                    //Select 2nd polyline
                    ptEntityOpt = new PromptEntityOptions("\n Select the second line or the circle:");
                    ptEntityRes = ed.GetEntity(ptEntityOpt);
                    if (ptEntityRes.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    ent = (Entity)trans.GetObject(ptEntityRes.ObjectId, OpenMode.ForRead);
                    if (ent is Line)
                    {
                        secondLine = ent as Line;
                    }
                    else if (ent is Circle)
                    {
                        cir = ent as Circle;
                        st  = State.CircleType;
                    }

                    Point3dCollection pts3D = new Point3dCollection();

                    //Get the intersection Points.
                    switch (st)
                    {
                    case State.LineType:
                        firstLine.IntersectWith(secondLine, Intersect.OnBothOperands, pts3D, IntPtr.Zero, IntPtr.Zero);
                        break;

                    case State.CircleType:
                        firstLine.IntersectWith(cir, Intersect.OnBothOperands, pts3D, IntPtr.Zero, IntPtr.Zero);
                        break;

                    default:
                        break;
                    }

                    foreach (Point3d pt in pts3D)
                    {
                        ed.WriteMessage("Point number: " + pt.X + " " + pt.Y + " " + pt.Z);
                        //Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("\n Intersection Point: " + "\nX = " + pt.X + "\nY = " + pt.Y + "\nZ = " + pt.Z);
                    }

                    trans.Commit();
                }
                catch (System.Exception)
                {
                    trans.Abort();
                    throw;
                }
            }
        }
示例#36
0
        public void DrawRod()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            bool               conti = true;
            ObjectIdCollection NewDrawnCollection = new ObjectIdCollection();
            //ObjectId ConsolElseOI = ObjectId.Null, ConnectionOI = ObjectId.Null, RodOI = ObjectId.Null, RodTriangeOI = ObjectId.Null;

            double MyScale        = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.Rod).Scale;
            double MyCommentScale = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.Rod).CommentScale;

            PromptEntityOptions peo = new PromptEntityOptions("\nSelect Container :");
            PromptEntityResult  per = ed.GetEntity(peo);

            if (per.Status == PromptStatus.OK)
            {
                DrawRodJig drawRod;
                Atend.Base.Acad.AT_INFO at_info = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(per.ObjectId);
                if (at_info.ParentCode != "NONE" && (at_info.NodeType == (int)Atend.Control.Enum.ProductType.Pole || at_info.NodeType == (int)Atend.Control.Enum.ProductType.PoleTip))
                {
                    drawRod = new DrawRodJig(Atend.Global.Acad.UAcad.GetEntityByObjectID(per.ObjectId), MyScale);
                    while (conti)
                    {
                        PromptResult pr = ed.Drag(drawRod);

                        if (pr.Status == PromptStatus.OK && drawRod.PartOneIsActive)
                        {
                            drawRod.PartOneIsActive = false;
                            pr = ed.Drag(drawRod);

                            if (pr.Status == PromptStatus.OK && !drawRod.PartOneIsActive)
                            {
                                conti = false;
                                //ed.WriteMessage("1 \n");
                                #region Save Data Here

                                List <Entity> Entities = drawRod.GetEntities();
                                //ed.WriteMessage("2 \n");
                                if (SaveRodData(at_info.NodeCode))
                                {
                                    // ed.WriteMessage("3 \n");

                                    //foreach (Entity ent in Entities)
                                    //{
                                    //    NewDrawnCollection.Add(DrawEntityOnScreen(ent, Atend.Control.Enum.AutoCadLayerName.MID_AIR.ToString()));
                                    //}

                                    //---------------------
                                    ObjectId ConsolElseOI = ObjectId.Null;
                                    foreach (Entity ent in Entities)
                                    {
                                        ObjectId newDrawnoi = Atend.Global.Acad.UAcad.DrawEntityOnScreen(ent, Atend.Control.Enum.AutoCadLayerName.MED_AIR.ToString());
                                        Atend.Global.Acad.AcadJigs.MyPolyLine mPoly = ent as Atend.Global.Acad.AcadJigs.MyPolyLine;
                                        if (mPoly != null)
                                        {
                                            //ed.WriteMessage("POLY LINE FOUND\n");
                                            if (mPoly.AdditionalDictionary.ContainsKey("ProductType"))
                                            {
                                                object ProductType = null;
                                                mPoly.AdditionalDictionary.TryGetValue("ProductType", out ProductType);
                                                if (ProductType != null)
                                                {
                                                    if (Convert.ToInt32(ProductType) == (int)Atend.Control.Enum.ProductType.ConsolElse)
                                                    {
                                                        ConsolElseOI = newDrawnoi;
                                                        Atend.Base.Acad.AT_INFO ConsolElseInfo = new Atend.Base.Acad.AT_INFO(newDrawnoi);
                                                        ConsolElseInfo.ParentCode  = at_info.NodeCode;
                                                        ConsolElseInfo.NodeCode    = RodPack.Code.ToString();
                                                        ConsolElseInfo.NodeType    = Convert.ToInt32(ProductType);
                                                        ConsolElseInfo.ProductCode = 0;
                                                        ConsolElseInfo.Insert();
                                                    }
                                                }
                                            }
                                        }
                                        NewDrawnCollection.Add(newDrawnoi);
                                    }

                                    //NewDrawnCollection.Add(Atend.Global.Acad.UAcad.DrawEntityOnScreen(
                                    //Atend.Global.Acad.Global.WriteNoteMText(
                                    //    Atend.Base.Equipment.ERod.SelectByCode(Atend.Base.Acad.AcadGlobal.dPackageForRod.ProductCode).Comment,
                                    //    new Point3d(drawRod.CenterPoint02.X + 10, drawRod.CenterPoint02.Y, 0)),
                                    //    Atend.Control.Enum.AutoCadLayerName.MID_AIR.ToString()));


                                    if (ConsolElseOI != ObjectId.Null)
                                    {
                                        Atend.Base.Acad.AT_SUB ConsolElseSub = new Atend.Base.Acad.AT_SUB(ConsolElseOI);
                                        foreach (ObjectId oi in NewDrawnCollection)
                                        {
                                            if (oi != ConsolElseOI)
                                            {
                                                //ed.WriteMessage("ConsolElseSubOI:{0}\n", oi);
                                                ConsolElseSub.SubIdCollection.Add(oi);
                                            }
                                        }
                                        ConsolElseSub.SubIdCollection.Add(per.ObjectId);
                                        ConsolElseSub.Insert();
                                    }
                                    //---------------------



                                    foreach (ObjectId oi in NewDrawnCollection)
                                    {
                                        if (oi != ConsolElseOI)
                                        {
                                            Atend.Base.Acad.AT_INFO a = new Atend.Base.Acad.AT_INFO(oi);
                                            a.ParentCode  = at_info.NodeCode;
                                            a.NodeCode    = RodPack.Code.ToString();
                                            a.NodeType    = (int)Atend.Control.Enum.ProductType.Rod;
                                            a.ProductCode = RodPack.ProductCode;;
                                            a.Insert();
                                        }
                                    }

                                    //for (int i = 1; i <= 4; i++)
                                    //{

                                    //    ed.WriteMessage("4 \n");
                                    //    switch (i)
                                    //    {

                                    //        case 1:
                                    //            ed.WriteMessage("5 \n");
                                    //            #region Draw & Save ConsolElse Here
                                    //            ConsolElseOI = DrawAndSaveConsolElse(Entities);
                                    //            #endregion
                                    //            break;
                                    //        case 2:
                                    //            ed.WriteMessage("6 \n");
                                    //            #region Draw & Save Connection Here
                                    //            ConnectionOI = DrawAndSaveConnection(Entities);
                                    //            #endregion
                                    //            break;
                                    //        case 3:
                                    //            ed.WriteMessage("7 \n");
                                    //            #region Draw & Save Rod Here
                                    //            RodOI = DrawAndSaveRod(Entities);
                                    //            #endregion
                                    //            break;
                                    //        case 4:
                                    //            ed.WriteMessage("8 \n");
                                    //            #region Draw & Save RodTriangle Here
                                    //            RodTriangeOI = DrawAndSaveRodTriangle(Entities);
                                    //            #endregion
                                    //            break;
                                    //    }

                                    //}

                                    //save additional data here

                                    //ed.WriteMessage("9 \n");
                                    //Atend.Base.Acad.AT_INFO ConsolElseInfo = new Atend.Base.Acad.AT_INFO(ConsolElseOI);
                                    //ConsolElseInfo.ParentCode = at_info.NodeCode;
                                    //ConsolElseInfo.NodeCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.Code.ToString();
                                    //ConsolElseInfo.NodeType = (int)Atend.Control.Enum.ProductType.Rod;
                                    //ConsolElseInfo.ProductCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.ProductCode;
                                    //ConsolElseInfo.Insert();


                                    //ed.WriteMessage("10 \n");
                                    //Atend.Base.Acad.AT_SUB ConsolElseSub = new Atend.Base.Acad.AT_SUB(ConsolElseOI);
                                    //ConsolElseSub.SubIdCollection.Add(ConnectionOI);
                                    //ConsolElseSub.Insert();


                                    //``````````````````````````
                                    //ed.WriteMessage("11 \n");
                                    //ConsolElseInfo = new Atend.Base.Acad.AT_INFO(ConnectionOI);
                                    //ConsolElseInfo.ParentCode = at_info.NodeCode;
                                    //ConsolElseInfo.NodeCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.Code.ToString();
                                    //ConsolElseInfo.NodeType = (int)Atend.Control.Enum.ProductType.Rod;
                                    //ConsolElseInfo.ProductCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.ProductCode;
                                    //ConsolElseInfo.Insert();


                                    //ed.WriteMessage("12 \n");
                                    //ConsolElseSub = new Atend.Base.Acad.AT_SUB(ConnectionOI);
                                    //ConsolElseSub.SubIdCollection.Add(ConsolElseOI);
                                    //ConsolElseSub.SubIdCollection.Add(RodOI);
                                    //ConsolElseSub.Insert();

                                    //```````````````````````````````````````````

                                    //ed.WriteMessage("13 \n");
                                    //ConsolElseInfo = new Atend.Base.Acad.AT_INFO(RodOI);
                                    //ConsolElseInfo.ParentCode = at_info.NodeCode;
                                    //ConsolElseInfo.NodeCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.Code.ToString();
                                    //ConsolElseInfo.NodeType = (int)Atend.Control.Enum.ProductType.Rod;
                                    //ConsolElseInfo.ProductCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.ProductCode;
                                    //ConsolElseInfo.Insert();


                                    //ed.WriteMessage("14 \n");
                                    //ConsolElseSub = new Atend.Base.Acad.AT_SUB(RodOI);
                                    //ConsolElseSub.SubIdCollection.Add(ConnectionOI);
                                    //ConsolElseSub.SubIdCollection.Add(RodTriangeOI);
                                    //ConsolElseSub.Insert();

                                    //```````````````````````````````````````````
                                    //ed.WriteMessage("15 \n");
                                    //ConsolElseInfo = new Atend.Base.Acad.AT_INFO(RodTriangeOI);
                                    //ConsolElseInfo.ParentCode = at_info.NodeCode;
                                    //ConsolElseInfo.NodeCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.Code.ToString();
                                    //ConsolElseInfo.NodeType = (int)Atend.Control.Enum.ProductType.Rod;
                                    //ConsolElseInfo.ProductCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.ProductCode;
                                    //ConsolElseInfo.Insert();

                                    //--------------------------
                                    //ed.WriteMessage("Number of Entity : {0} \n", NewDrawnCollection.Count);

                                    ObjectId NewCreatedGroup =
                                        Atend.Global.Acad.Global.MakeGroup(RodPack.Code.ToString(), NewDrawnCollection);


                                    //Atend.Base.Equipment.ERod ERodForComment = Atend.Base.Equipment.ERod.SelectByCode(RodPack.ProductCode);

                                    //ed.WriteMessage("scale:{0} comment:{1}\n",MyCommentScale,ERod.Comment);
                                    ObjectId txtOI = Atend.Global.Acad.UAcad.DrawEntityOnScreen(Atend.Global.Acad.UAcad.WriteNote(ERod.Comment, new Point3d(drawRod.CenterPoint02.X, drawRod.CenterPoint02.Y, 0), MyCommentScale), Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());
                                    //ed.WriteMessage("text was writen\n");

                                    Atend.Base.Acad.AT_INFO GroupInfo1 = new Atend.Base.Acad.AT_INFO(txtOI);
                                    GroupInfo1.ParentCode  = RodPack.Code.ToString();
                                    GroupInfo1.NodeCode    = "";
                                    GroupInfo1.NodeType    = (int)Atend.Control.Enum.ProductType.Comment;
                                    GroupInfo1.ProductCode = 0;
                                    GroupInfo1.Insert();


                                    //Atend.Base.Acad.AT_INFO GroupInfo = new Atend.Base.Acad.AT_INFO(NewCreatedGroup);
                                    //GroupInfo.ParentCode = at_info.NodeCode;
                                    //GroupInfo.NodeCode = Atend.Base.Acad.AcadGlobal.dPackageForRod.Code.ToString();
                                    //GroupInfo.NodeType = (int)Atend.Control.Enum.ProductType.BankKhazan;
                                    //GroupInfo.ProductCode = Atend.Base.Acad.AcadGlobal.dPackageForKhazanTip.ProductCode;
                                    //GroupInfo.Insert();



                                    //    Atend.Base.Equipment.EKhazanTip khazanTip = Atend.Base.Equipment.EKhazanTip.SelectByCode(
                                    //        Atend.Base.Acad.AcadGlobal.dPackageForKhazanTip.ProductCode);


                                    //    ObjectId txtOI = DrawEntityOnScreen(
                                    //    Atend.Global.Acad.UAcad.WriteNote(khazanTip.Description, drawKhazan.GetCommentPoSition()),
                                    //    Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());


                                    Atend.Base.Acad.AT_INFO GroupInfo = new Atend.Base.Acad.AT_INFO(NewCreatedGroup);
                                    GroupInfo.ParentCode  = at_info.NodeCode;
                                    GroupInfo.NodeCode    = RodPack.Code.ToString();
                                    GroupInfo.NodeType    = (int)Atend.Control.Enum.ProductType.Rod;
                                    GroupInfo.ProductCode = RodPack.ProductCode;
                                    GroupInfo.Insert();


                                    Atend.Base.Acad.AT_SUB.AddToAT_SUB(NewCreatedGroup, per.ObjectId);
                                    //ed.WriteMessage("PoleOI for KHazan:{0}", per.ObjectId);
                                    Atend.Base.Acad.AT_SUB GroupSub = new Atend.Base.Acad.AT_SUB(NewCreatedGroup);
                                    GroupSub.SubIdCollection.Add(per.ObjectId);
                                    //ed.WriteMessage("TXTOI for KHazan:{0}", txtOI);
                                    GroupSub.SubIdCollection.Add(txtOI);
                                    GroupSub.Insert();


                                    //    Atend.Base.Acad.AT_SUB.AddToAT_SUB(NewCreatedGroup, per.ObjectId);

                                    //    Atend.Base.Acad.AT_SUB GroupSub = new Atend.Base.Acad.AT_SUB(NewCreatedGroup);
                                    //    GroupSub.SubIdCollection.Add(per.ObjectId);
                                    //    GroupSub.SubIdCollection.Add(txtOI);
                                    //    GroupSub.Insert();
                                }


                                #endregion
                            }
                            else
                            {
                                conti = false;
                            }
                        }
                        else
                        {
                            conti = false;
                        }
                    }
                }
            }
        }
        public void GetPointsAtEqualDists()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;
            //初始化各标注图元
            Vector3d drvt = new Vector3d();                                      //标注点切线
            double   len  = 10 * scale_GPAD;                                     //标注点长度,为10单位
            Point3d  pt1  = new Point3d();                                       //标准线起点
            Point3d  pt2  = new Point3d();                                       //标准线终点
            Line     line = new Line();                                          //标注线

            using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理
            {
                //1.选择多段线
                PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线");
                plineOpt.SetRejectMessage("\n并非多段线!");
                plineOpt.AddAllowedClass(typeof(Polyline), true);
                PromptEntityResult plineRes = ed.GetEntity(plineOpt);
                if (plineRes.Status != PromptStatus.OK)
                {
                    return;
                }
                Polyline pline = plineRes.ObjectId.GetObject(OpenMode.ForRead) as Polyline;

                //2.选择绘图比例
                PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale_GPAD}>");
                scaleOpt.AllowNone     = true;                        //允许回车,则采用默认比例
                scaleOpt.AllowNegative = false;                       //不允许负值
                scaleOpt.AllowZero     = false;                       //不允许零值
                PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例
                if (scaleRes.Status == PromptStatus.OK)
                {
                    scale_GPAD = scaleRes.Value;  //获取绘图比例
                    len        = 10 * scale_GPAD; //重设标注线长度
                }

                //3.选择起点
                PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点");
                PromptPointResult  startPtRes = ed.GetPoint(startPtOpt);
                if (startPtRes.Status != PromptStatus.OK)
                {
                    return;
                }
                Point3d startPt = pline.GetClosestPointTo(startPtRes.Value, false);//选择点到多段线的最近点

                //4.选择终点
                PromptPointOptions endPtOpt = new PromptPointOptions("\n选择曲线上的点作为终点");
                PromptPointResult  endPtRes = ed.GetPoint(endPtOpt);
                if (endPtRes.Status != PromptStatus.OK)
                {
                    return;
                }
                Point3d endPt = pline.GetClosestPointTo(endPtRes.Value, false);//选择点到多段线的最近点

                //5.是否标注距离
                PromptKeywordOptions kwOpt = new PromptKeywordOptions($"\n是否标注沿曲线长度[Y/N]<{isDistDenote}>");
                kwOpt.Keywords.Add("Y");
                kwOpt.Keywords.Add("N");
                kwOpt.AllowNone               = true;  //可回车
                kwOpt.AllowArbitraryInput     = false; //不可随意输入
                kwOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字
                PromptResult kwRes = ed.GetKeywords(kwOpt);
                if (kwRes.Status == PromptStatus.OK)
                {
                    isDistDenote = kwRes.StringResult;
                }

                //6.输入分段数量
                PromptIntegerOptions intOpt = new PromptIntegerOptions("\n输入分段数");
                intOpt.AllowNegative = false;         //不予许负值
                intOpt.AllowZero     = false;         //不允许0
                PromptIntegerResult intRes = ed.GetInteger(intOpt);
                if (intRes.Status == PromptStatus.OK) //输入成功
                {
                    int nSegs = intRes.Value;

                    Double distOfStPt = pline.GetDistanceToStartPt(startPt); //获取起点距曲线起点的距离
                    //绘制起点线
                    drvt = pline.GetFirstDerivative(startPt);                //获取切线
                    pt1  = startPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                    pt2  = startPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                    line = new Line(pt1, pt2);
                    db.AddToModelSpace(line);

                    double distOfEdPt = pline.GetDistanceToStartPt(endPt); //获取终点距曲线起点的距离
                    //绘制终点线
                    drvt = pline.GetFirstDerivative(endPt);                //获取切线
                    pt1  = endPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                    pt2  = endPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                    line = new Line(pt1, pt2);
                    db.AddToModelSpace(line);


                    List <double> dists = new List <double>();
                    for (int i = 1; i <= nSegs; i++)
                    {
                        dists.Add((distOfEdPt - distOfStPt) / nSegs);
                    }
                    CreateSpanLines(pline, startPt, dists, isDistDenote, scale_GPAD); //绘制分跨线
                }
                trans.Commit();                                                       //执行事务处理
            }
        }
示例#38
0
        private void SelEntBtn_Click(object sender, EventArgs e)
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            ed.WriteMessage("添加扩充数据 XDATA\n");
            PromptEntityOptions entOps = new PromptEntityOptions("选择实体对象");
            PromptEntityResult  entRes;

            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("选择对象失败,退出");
                return;
            }

            ObjectId objId = entRes.ObjectId;
            Database db    = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                RegAppTable appTbl     = trans.GetObject(db.RegAppTableId, OpenMode.ForWrite) as RegAppTable;
                string      DateStr    = DateTime.Now.ToString("yyyyMMddHHmmssms"); //日期
                Random      rd         = new Random();                              //用于生成随机数
                string      AppNamestr = DateStr + rd.Next(10, 99);                 //带日期的随机数
                Entity      ent        = trans.GetObject(objId, OpenMode.ForWrite) as Entity;

                if (!appTbl.Has(AppNamestr))
                {
                    RegAppTableRecord appTblRcd = new RegAppTableRecord();
                    appTblRcd.Name = AppNamestr;
                    appTbl.Add(appTblRcd);
                    trans.AddNewlyCreatedDBObject(appTblRcd, true);
                }

                ResultBuffer resBuf = new ResultBuffer(new TypedValue((int)DxfCode.ExtendedDataRegAppName, AppNamestr));

                if (this.DataInt16TextBox.Text != null)
                {
                    int addint16data = int.Parse(this.DataInt16TextBox.Text);
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataInteger16, addint16data));
                }
                if (this.DataInt32TextBox.Text != null)
                {
                    int addint32data = int.Parse(this.DataInt32TextBox.Text);
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataInteger32, addint32data));
                }

                //比例
                if (this.DataScaleTextBox.Text != null)
                {
                    int addscaledata = int.Parse(this.DataScaleTextBox.Text);
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataScale, addscaledata));
                }
                //ASCII字符串
                if (this.DataStringTextBox.Text != null)
                {
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, this.DataStringTextBox.Text));
                }
                //图层名称
                if (this.LayerNameTextBox.Text != null)
                {
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataLayerName, this.LayerNameTextBox.Text));
                }
                //坐标
                if (this.WorldXCoordinateXTextBox.Text != null && this.WorldXCoordinateYTextBox.Text != null && this.WorldXCoordinateZTextBox.Text != null)
                {
                    double  pointx        = double.Parse(this.WorldXCoordinateXTextBox.Text);
                    double  pointy        = double.Parse(this.WorldXCoordinateYTextBox.Text);
                    double  pointz        = double.Parse(this.WorldXCoordinateZTextBox.Text);
                    Point3d PointLoaction = new Point3d(pointx, pointy, pointz);
                    resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataWorldXCoordinate, PointLoaction));
                }

                if (ent.XData != null)
                {
                    ed.WriteMessage("该对象已有扩展记录,不需要再次添加,只需在原有记录进行修改");
                    return;
                }
                ent.XData = resBuf;
                trans.Commit();
            }
        }
示例#39
0
        public void EntityTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions entopts = new PromptEntityOptions("Pick an entity of your choice from the drawing");
            entopts.Message = "Pick an entity of your choice from the drawing";
            PromptEntityResult ent=null;
            //ADDED INPUT CONTEXT REACTOR
            ed.PromptingForEntity += new PromptEntityOptionsEventHandler(handle_promptEntityOptions);
            ed.PromptedForEntity += new PromptEntityResultEventHandler(handle_promptEntityResult);

            try
            {
                ent = ed.GetEntity(entopts);
            }
            catch
            {
                ed.WriteMessage("You did not select a valid entity");
                ed.PromptingForEntity -= new PromptEntityOptionsEventHandler(handle_promptEntityOptions);
                ed.PromptedForEntity -= new PromptEntityResultEventHandler(handle_promptEntityResult);

            }
            ed.PromptingForEntity -= new PromptEntityOptionsEventHandler(handle_promptEntityOptions);
            ed.PromptedForEntity -= new PromptEntityResultEventHandler(handle_promptEntityResult);

            if(ent.Status != PromptStatus.Error)
            {
                ObjectId entid = ent.ObjectId;
                Database db = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    Entity entity = (Entity)tm.GetObject(entid,OpenMode.ForRead,true);
                    ed.WriteMessage("You selected: "+entity.GetType().FullName);
                    myT.Commit();
                }
            }
        }
示例#40
0
        public void Cmd_DimArrow()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var prEntOpt = new PromptEntityOptions("\nSelect a dimensions arrow to convert to arrow-type <" +
                                                   EnumAgent.GetNameOf(SettingsUser.ArwHead) + "> : ");

            prEntOpt.SetRejectMessage("\nOnly dimensions may be selected.");
            prEntOpt.AllowNone = false;
            prEntOpt.AddAllowedClass(typeof(AlignedDimension), false);
            prEntOpt.AddAllowedClass(typeof(RotatedDimension), false);
            prEntOpt.AddAllowedClass(typeof(ArcDimension), false);

            var prEntRes    = acCurEd.GetEntity(prEntOpt);
            var prPickPoint = prEntRes.PickedPoint;

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

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                var acDim = acTrans.GetObject(prEntRes.ObjectId, OpenMode.ForWrite) as Entity;
                if (acDim != null)
                {
                    try
                    {
                        Point3d xPt1;
                        Point3d xPt2;
                        var     arwString = EnumAgent.GetNameOf(SettingsUser.ArwHead);

                        var arwId = DimSystem.GetArrowId(arwString);

                        switch (acDim)
                        {
                        case AlignedDimension alDim:
                        {
                            alDim.Dimsah = true;
                            xPt1         = alDim.XLine1Point;
                            xPt2         = alDim.XLine2Point;

                            if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                            {
                                alDim.Dimblk1 = arwId;
                            }
                            else
                            {
                                alDim.Dimblk2 = arwId;
                            }
                            alDim.RecomputeDimensionBlock(true);
                            break;
                        }

                        case RotatedDimension roDim:
                        {
                            roDim.Dimsah = true;
                            xPt1         = roDim.XLine1Point;
                            xPt2         = roDim.XLine2Point;

                            if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                            {
                                roDim.Dimblk1 = arwId;
                            }
                            else
                            {
                                roDim.Dimblk2 = arwId;
                            }
                            roDim.RecomputeDimensionBlock(true);
                            break;
                        }

                        case ArcDimension arDim:
                        {
                            arDim.Dimsah = true;
                            xPt1         = arDim.XLine1Point;
                            xPt2         = arDim.XLine2Point;

                            if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2))
                            {
                                arDim.Dimblk1 = arwId;
                            }
                            else
                            {
                                arDim.Dimblk2 = arwId;
                            }

                            arDim.RecomputeDimensionBlock(true);
                            break;
                        }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        MailAgent.Report(e.Message);
                    }
                }

                acTrans.Commit();
            }
        }
示例#41
0
文件: Class1.cs 项目: guchanghai/Cut
        public void AddXData()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("�����������XDATA\n");
            PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�򿪵Ķ���\n");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity ;
                ent.ColorIndex = 1;

                RegAppTable appTbl = trans.GetObject(db.RegAppTableId, OpenMode.ForWrite) as RegAppTable ;
                if (!appTbl.Has("MyAppName"))
                {
                    RegAppTableRecord appTblRcd = new RegAppTableRecord();
                    appTblRcd.Name = "MyAppName";
                    appTbl.Add(appTblRcd);
                    trans.AddNewlyCreatedDBObject(appTblRcd, true);
                }
                ResultBuffer resBuf = new ResultBuffer();//new TypedValue(1001, "MyAppName"), new TypedValue(1000, "��������"));

                resBuf.Add(new TypedValue(1001, "MyAppName"));//ע���������
                resBuf.Add(new TypedValue(1000 , " ����"));//����
                resBuf.Add(new TypedValue(1000 , " ���̲�"));//����
                resBuf.Add(new TypedValue(1040, 2000.0));//нˮ
                ent.XData =  resBuf;
                trans.Commit();
            }
        }
        public void getang()
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            string filepath = "D:\\tdoc.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ Ф"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость углов поворотов"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                        new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Обозначение точки")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Координаты точки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Пикетаж")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Угол")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прямая вставка, м"))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("Y")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("X")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Лево")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Право")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 7 });

                    while (true)
                    {
                        double dist = 0, paste = 0;

                        table.AppendChild(new TableRow(
                            new TableCell(
                                new TableCellProperties(
                                    new GridSpan() { Val = 7 }),
                                    new Paragraph(
                                        new ParagraphProperties(
                                            new ParagraphMarkRunProperties(new Bold()),
                                            new Justification() { Val = JustificationValues.Center }),
                                            new Run(new RunProperties(
                                                new Bold()),
                                                new Text("Трасса"))))));

                        PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline: ");
                        peo.SetRejectMessage("Можно только polyline.");
                        peo.AddAllowedClass(typeof(Polyline), true);
                        PromptEntityResult per = ed.GetEntity(peo);
                        if (per.Status != PromptStatus.OK) { break; }

                        PromptPointResult pPtRes;
                        PromptPointOptions pPtOpts = new PromptPointOptions("");
                        // Prompt for the start point
                        pPtOpts.Message = "\nВведи начало: ";
                        pPtRes = doc.Editor.GetPoint(pPtOpts);

                        PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                        PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);
                        dist = 100 * getpikRes.Value;

                        /*
                        PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");
                        pStrOpts.AllowSpaces = true;
                        PromptResult pStrRes = doc.Editor.GetString(pStrOpts);
                        Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult);
                         */

                        Point3d curr = pPtRes.Value, next = pPtRes.Value;
                        try
                        {
                            using (Transaction tr = db.TransactionManager.StartTransaction())
                            {
                                Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead);
                                if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                    for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВТ" + (i + 1).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                                else
                                    for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВУ" + (pline.NumberOfVertices - 2 - i).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                            }
                        }
                        catch
                        {
                            ed.WriteMessage("\nInvalid polyline.");
                        }
                    }

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\tdoc.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
        public void GetPointsAtDists()
        {
            Document doc        = Application.DocumentManager.MdiActiveDocument;
            Database db         = doc.Database;
            Editor   ed         = doc.Editor;
            Polyline pline      = new Polyline();                                //初始化多段线
            Point3d  startPt    = new Point3d();                                 //初始化起点
            double   distOfStPt = 0;                                             //初始化起点距
            //初始化各标注图元
            Vector3d drvt = new Vector3d();                                      //标注点切线
            double   len  = 10 * scale_GPAD;                                     //标注点长度,为10单位
            Point3d  pt1  = new Point3d();                                       //标准线起点
            Point3d  pt2  = new Point3d();                                       //标准线终点
            Line     line = new Line();                                          //标注线

            using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理
            {
                //1.选择多段线
                PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线");
                plineOpt.SetRejectMessage("\n并非多段线!");
                plineOpt.AddAllowedClass(typeof(Polyline), true);
                PromptEntityResult plineRes = ed.GetEntity(plineOpt);
                if (plineRes.Status != PromptStatus.OK)
                {
                    return;
                }
                pline = plineRes.ObjectId.GetObject(OpenMode.ForRead) as Polyline;

                //2.选择绘图比例
                PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale_GPAD}>");
                scaleOpt.AllowNone     = true;                        //允许回车,则采用默认比例
                scaleOpt.AllowNegative = false;                       //不允许负值
                scaleOpt.AllowZero     = false;                       //不允许零值
                PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例
                if (scaleRes.Status == PromptStatus.OK)
                {
                    scale_GPAD = scaleRes.Value;  //获取绘图比例
                    len        = 10 * scale_GPAD; //重设标注线长度
                }

                //3.选择起点
                PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点");
                PromptPointResult  startPtRes = ed.GetPoint(startPtOpt);
                if (startPtRes.Status != PromptStatus.OK)
                {
                    return;
                }
                startPt    = pline.GetClosestPointTo(startPtRes.Value, false); //选择点到多段线的最近点
                distOfStPt = pline.GetDistanceToStartPt(startPt);              //获取起点距曲线起点的距离
                //绘制起点线
                drvt = pline.GetFirstDerivative(startPt);                      //获取切线
                pt1  = startPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                pt2  = startPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis);
                line = new Line(pt1, pt2);
                db.AddToModelSpace(line);

                //4.是否标注距离
                PromptKeywordOptions kwOpt = new PromptKeywordOptions($"\n是否标注沿曲线长度[Y/N]<{isDistDenote}>");
                kwOpt.Keywords.Add("Y");
                kwOpt.Keywords.Add("N");
                kwOpt.AllowNone               = true;  //可回车
                kwOpt.AllowArbitraryInput     = false; //不可随意输入
                kwOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字
                PromptResult kwRes = ed.GetKeywords(kwOpt);
                if (kwRes.Status == PromptStatus.OK)
                {
                    isDistDenote = kwRes.StringResult;
                }

                trans.Commit();//执行事务处理
            }

            //5.输入沿曲线距离
            //无限循环
            double  distCum    = distOfStPt; //初始化累计长度
            Point3d newStartPt = startPt;    //初始化当前前进起始点

            for (;;)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理
                {
                    PromptStringOptions distsOpt = new PromptStringOptions("\n输入分段距离或按ESC退出(各段长度以空格分隔,等间距采用N@d格式)");
                    distsOpt.AllowSpaces = true;            //允许输入空格
                    PromptResult distsRes = ed.GetString(distsOpt);
                    if (distsRes.Status == PromptStatus.OK) //输入正确
                    {
                        List <double> dists = new List <double>();
                        if (ReadSegsInput(ref dists, distsRes.StringResult))//读入距离数据成功
                        {
                            if (distCum + dists.Sum() > pline.Length)
                            {
                                ed.WriteMessage("超出多段线范围,请重新输入!");
                                trans.Abort();
                                continue;
                            }

                            CreateSpanLines(pline, newStartPt, dists, isDistDenote, scale_GPAD);
                            distCum   += dists.Sum();                   //重置前进距离
                            newStartPt = pline.GetPointAtDist(distCum); //重置当前前进起始点
                            trans.Commit();                             //执行事务处理
                        }
                        else//读入距离数据有误
                        {
                            ed.WriteMessage("\n输入有误,请重新输入!");
                            trans.Abort();
                            continue;
                        }
                    }
                    else
                    {
                        trans.Abort();
                        break;//输入回车、ESC等则退出
                    }
                }
            }
        }
        public void LineSegs2d()
        {
            Document doc     = Application.DocumentManager.MdiActiveDocument;
            Database db      = doc.Database;
            Editor   ed      = doc.Editor;
            Polyline pline   = new Polyline();                                   //初始化钢束线
            Point3d  startPt = new Point3d();                                    //初始化起点

            using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理
            {
                //1.选择空间多段线
                PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线");
                plineOpt.SetRejectMessage("\n并非多段线!");
                plineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线
                PromptEntityResult plineRes = ed.GetEntity(plineOpt);
                if (plineRes.Status != PromptStatus.OK)
                {
                    return;
                }
                ObjectId plineId = plineRes.ObjectId;
                pline = trans.GetObject(plineId, OpenMode.ForWrite) as Polyline;
                //2.选择起始点
                PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点");
                PromptPointResult  startPtRes = ed.GetPoint(startPtOpt);
                if (startPtRes.Status != PromptStatus.OK)
                {
                    return;
                }
                startPt = pline.GetClosestPointTo(startPtRes.Value, false); //选择点到多段线的最近点
                trans.Commit();                                             //执行事务处理
            }
            //3.输入分段距离并节线化
            Point3d newStartPt = startPt;                             //初始化每次绘制起点
            double  distOfStPt = pline.GetDistanceToStartPt(startPt); //获取起点距曲线起点的距离

            for (;;)
            {
                PromptStringOptions segsOpt = new PromptStringOptions("\n输入分段距离或按ESC退出(各段长度以空格分隔,等间距采用N@d格式)");
                segsOpt.AllowSpaces = true;                          //允许输入空格
                PromptResult segsRes = ed.GetString(segsOpt);
                if (segsRes.Status == PromptStatus.OK)               //如果输入正确且不为回车
                {
                    string        input      = segsRes.StringResult; //获得输入字符串
                    List <double> segLengths = new List <double>();  //初始化节段长List
                    if (ReadSegsInput(ref segLengths, input))        //读入距离数据成功
                    {
                        distOfStPt += segLengths.Sum();              //计算累计距离
                        if (distOfStPt > pline.Length)               //累计距离已超过多段线长
                        {
                            ed.WriteMessage("\n输入间距值已超出多段线范围,请重新输入!");
                            continue;
                        }
                        CreateLineSegs(pline, newStartPt, segLengths);//绘制直线段
                        newStartPt = pline.GetPointAtDist(distOfStPt);
                    }
                    else//读入距离数据有误
                    {
                        ed.WriteMessage("\n输入有误,请重新输入!");
                        continue;
                    }
                }
                else
                {
                    break; //输入回车、ESC等则退出
                }
            }
        }
        public void LineSegs3d()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理
            {
                //1.选择空间轴线的平面视图多段线
                PromptEntityOptions plxyOpt = new PromptEntityOptions("\n选择空间轴线的平面视图多段线");
                plxyOpt.SetRejectMessage("\n并非多段线!");
                plxyOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线
                PromptEntityResult plxyRes = ed.GetEntity(plxyOpt);
                if (plxyRes.Status != PromptStatus.OK)
                {
                    return;
                }
                ObjectId plxyId = plxyRes.ObjectId;
                Polyline plxy   = trans.GetObject(plxyId, OpenMode.ForWrite) as Polyline;

                //2.选择空间轴线的立面视图多段线
                PromptEntityOptions plxzOpt = new PromptEntityOptions("\n选择空间轴线的立面视图多段线");
                plxzOpt.SetRejectMessage("\n并非多段线!");
                plxzOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线
                PromptEntityResult plxzRes = ed.GetEntity(plxzOpt);
                if (plxzRes.Status != PromptStatus.OK)
                {
                    return;
                }
                ObjectId plxzId = plxzRes.ObjectId;
                Polyline plxz   = trans.GetObject(plxzId, OpenMode.ForWrite) as Polyline;

                //3.判断平面视图和立面视图中的长度是否一致
                double lenXY = plxy.Length;
                double lenXZ = Math.Abs(plxz.StartPoint.X - plxz.EndPoint.X);
                if (Math.Abs(lenXY - lenXZ) > 10)
                {
                    ed.WriteMessage("\n轴线平面长度与立面长度不一致,请检查!");
                    return;
                }
                double totalLen = lenXY;//记录轴线总长

                //4.输入拟合直线段的长度
                PromptDoubleOptions slOpt = new PromptDoubleOptions("\n输入拟合直线段的长度<1000>");
                slOpt.AllowNegative = false; //不允许负值
                slOpt.AllowZero     = false; //不允许零值
                slOpt.DefaultValue  = 1000;  //默认值为1000
                PromptDoubleResult slRes = ed.GetDouble(slOpt);
                if (slRes.Status != PromptStatus.OK)
                {
                    return;
                }
                double segLen = slRes.Value;  //或得拟合线段长度
                if (segLen > (totalLen - 10)) //节段过长(仅比总长小1cm或更长)
                {
                    ed.WriteMessage("\n节段长度过长!");
                    return;
                }

                //5.获取每个节段点的坐标
                //节段需要包括所有平面曲线节点、立面曲线节点和节段长度端点
                List <Point3d> verts = new List <Point3d>();//初始化节段点List
                //5.1 添加平面曲线节点
                for (int i = 0; i < plxy.NumberOfVertices; i++)
                {
                    Point3d vertInPlxy = plxy.GetPoint3dAt(i);                                                //平面图节点
                    double  prmt       = plxy.GetParameterAtPoint(vertInPlxy);                                //该节点参数
                    double  distance   = plxy.GetDistanceAtParameter(prmt);                                   //该节点到起点距离,即为立面图上到起点的横坐标差
                    Point3d xlBase     = plxz.StartPoint + new Vector3d(distance, 0, 0);                      //立面图起点偏移distance后,作为Xline基点
                    Xline   xl         = new Xline();                                                         //新建xline
                    xl.BasePoint = xlBase;                                                                    //基点如前所述
                    xl.UnitDir   = new Vector3d(0, 1, 0);                                                     //竖直方向
                    Point3dCollection ptIntersects = new Point3dCollection();                                 //建立交点组
                    plxz.IntersectWith(xl, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero); //与立面轴线相交
                    Point3d vertInPlxz = ptIntersects[0];                                                     //获得交点
                    //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定
                    Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y);
                    verts.Add(vert);
                    xl.Dispose();
                }
                //5.2 添加立面曲线节点
                for (int i = 1; i < plxz.NumberOfVertices - 1; i++)
                {
                    Point3d vertInPlxz = plxz.GetPoint3dAt(i);             //立面图节点
                    double  distance   = vertInPlxz.X - plxz.StartPoint.X; //该节点到起点距离,即为立面图上到起点的横坐标差
                    Point3d vertInPlxy = plxy.GetPointAtDist(distance);    //获取该点在平面图上的对应点
                    //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定
                    Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y);
                    if (!IsPtInList(vert, verts, 10))//如果该点尚不在点群中
                    {
                        verts.Add(vert);
                    }
                }
                //5.3 节段端点
                double dist = segLen;
                do
                {
                    Point3d vertInPlxy = plxy.GetPointAtDist(dist);                                           //平面图节点
                    //立面图节点
                    Point3d xlBase = plxz.StartPoint + new Vector3d(dist, 0, 0);                              //立面图起点偏移dist后,作为Xline基点
                    Xline   xl     = new Xline();                                                             //新建xline
                    xl.BasePoint = xlBase;                                                                    //基点如前所述
                    xl.UnitDir   = new Vector3d(0, 1, 0);                                                     //竖直方向
                    Point3dCollection ptIntersects = new Point3dCollection();                                 //建立交点组
                    plxz.IntersectWith(xl, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero); //与立面轴线相交
                    Point3d vertInPlxz = ptIntersects[0];                                                     //获得交点
                    //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定
                    Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y);
                    if (!IsPtInList(vert, verts, 10))//如果该点尚不在点群中
                    {
                        verts.Add(vert);
                    }
                    dist += segLen;
                }while (dist < totalLen - 10);//前进长度小于总长度

                //6.对所有节点进行排序
                var sortedPts = (from pt in verts
                                 let p = plxy.GetParameterAtPoint(pt)
                                         let d = plxy.GetDistanceAtParameter(p)
                                                 orderby d
                                                 select pt).ToList();

                //7.指定插入点
                Point3d insertPt = new Point3d();
                for (;;)
                {
                    PromptPointOptions ptOpt = new PromptPointOptions("\n指定空间拟合段插入点");
                    PromptPointResult  ptRes = ed.GetPoint(ptOpt);
                    if (ptRes.Status == PromptStatus.OK)
                    {
                        insertPt = ptRes.Value;
                        break;
                    }
                }
                Vector3d vect = insertPt - plxy.StartPoint;  //建立平移向量,从曲线平面图起点至选择的插入点
                Matrix3d mt   = Matrix3d.Displacement(vect); //建立对应的变换矩阵

                //7.依次建立线段
                for (int i = 0; i < sortedPts.Count - 1; i++)
                {
                    Line line = new Line(sortedPts[i], sortedPts[i + 1]);
                    line.TransformBy(mt);     //平移到位
                    db.AddToModelSpace(line); //添加至模型空间
                }

                trans.Commit();//执行事务处理
            }
        }
 public PromptEntityArgument(PromptEntityOptions options)
 {
     _options = options;
 }
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
示例#48
0
        public void DrawCatout()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            System.Data.DataTable ParentList = Atend.Global.Acad.UAcad.DetermineParent((int)Atend.Control.Enum.ProductType.CatOut);
            double V1 = 0;
            double V2 = 0;

            double MyScale        = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.CatOut).Scale;
            double MyCommentScale = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.CatOut).CommentScale;

            try
            {
                PromptEntityOptions peo1 = new PromptEntityOptions("Select first node:");
                PromptEntityResult  per  = ed.GetEntity(peo1);
                if (per.Status == PromptStatus.OK)
                {
                    Atend.Base.Acad.AT_INFO Info1 = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(per.ObjectId);
                    DataRow[] drs = ParentList.Select(string.Format("SoftwareCode={0}", Info1.NodeType));
                    if (drs.Length != 0)
                    {
                        switch (((Atend.Control.Enum.ProductType)drs[0]["SoftwareCode"]))
                        {
                        case Atend.Control.Enum.ProductType.HeaderCabel:
                            //V1 = Atend.Base.Equipment.EHeaderCabel.AccessSelectByCode(Info1.ProductCode);
                            V1 = 0;
                            break;

                        case Atend.Control.Enum.ProductType.Consol:
                            V1 = Atend.Base.Equipment.EConsol.AccessSelectByCode(Info1.ProductCode).VoltageLevel;
                            break;

                        case Atend.Control.Enum.ProductType.KablSho:
                            //V1 = Atend.Base.Equipment.EKablsho.AccessSelectByCode(Info1.ProductCode);
                            V1 = 0;
                            break;

                        case Atend.Control.Enum.ProductType.Kalamp:
                            V1 = Atend.Base.Equipment.EClamp.AccessSelectByCode(Info1.ProductCode).VoltageLevel;
                            break;
                        }
                        PromptEntityOptions peo2 = new PromptEntityOptions("Select second node:");
                        PromptEntityResult  per1 = ed.GetEntity(peo2);
                        if (per1.Status == PromptStatus.OK)
                        {
                            Atend.Base.Acad.AT_INFO Info2 = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(per1.ObjectId);
                            DataRow[] drs1 = ParentList.Select(string.Format("SoftwareCode={0}", Info2.NodeType));
                            if (drs1.Length != 0)
                            {
                                switch (((Atend.Control.Enum.ProductType)drs1[0]["SoftwareCode"]))
                                {
                                case Atend.Control.Enum.ProductType.HeaderCabel:
                                    //V1 = Atend.Base.Equipment.EHeaderCabel.AccessSelectByCode(Info1.ProductCode);
                                    V2 = 0;
                                    break;

                                case Atend.Control.Enum.ProductType.Consol:
                                    V2 = Atend.Base.Equipment.EConsol.AccessSelectByCode(Info2.ProductCode).VoltageLevel;
                                    break;

                                case Atend.Control.Enum.ProductType.KablSho:
                                    //V1 = Atend.Base.Equipment.EKablsho.AccessSelectByCode(Info1.ProductCode);
                                    V2 = 0;
                                    break;

                                case Atend.Control.Enum.ProductType.Kalamp:
                                    V2 = Atend.Base.Equipment.EClamp.AccessSelectByCode(Info2.ProductCode).VoltageLevel;
                                    break;
                                }

                                if (V1 == V2 && Info1.ParentCode == Info2.ParentCode)
                                {
                                    //ed.WriteMessage("Voltage was same \n");
                                    DrawCatOutJig _DrawBreakerJig = new DrawCatOutJig(MyScale);
                                    List <Entity> ents            = _DrawBreakerJig.GetDemo(
                                        Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(per.ObjectId)),
                                        Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(per1.ObjectId)));
                                    //ed.WriteMessage("COUNT OF ENTITY :{0}\n",ents.Count);
                                    if (SaveCatOutData())
                                    {
                                        //ed.WriteMessage("data saved {0} \n",ents.Count);
                                        ObjectIdCollection OIC = new ObjectIdCollection();
                                        foreach (Entity ent in ents)
                                        {
                                            ObjectId TerminalOI = ObjectId.Null;
                                            ObjectId KetOI      = ObjectId.Null;
                                            ObjectId NOI        = Atend.Global.Acad.UAcad.DrawEntityOnScreen(ent, Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());
                                            //ed.WriteMessage("111 \n");
                                            Atend.Global.Acad.AcadJigs.MyLine terminal = ent as Atend.Global.Acad.AcadJigs.MyLine;
                                            //ed.WriteMessage("112 \n");
                                            object ProductType = null;
                                            //ed.WriteMessage("changed \n");
                                            if (terminal != null)
                                            {
                                                if (terminal.AdditionalDictionary.TryGetValue("ProductType", out ProductType))
                                                {
                                                    //ed.WriteMessage("113 \n");
                                                    if (Convert.ToInt32(ProductType) == (int)Atend.Control.Enum.ProductType.Terminal)
                                                    {
                                                        //ed.WriteMessage("terminal aws found\n");
                                                        if (ProductType != null)
                                                        {
                                                            TerminalOI = NOI;
                                                        }
                                                    }
                                                    else if (Convert.ToInt32(ProductType) == (int)Atend.Control.Enum.ProductType.Key)
                                                    {
                                                        //ed.WriteMessage("Key aws found\n");
                                                        if (ProductType != null)
                                                        {
                                                            KetOI = NOI;
                                                        }
                                                    }
                                                }
                                            }
                                            OIC.Add(NOI);
                                            //ed.WriteMessage("entity added \n");

                                            if (TerminalOI == ObjectId.Null)
                                            {
                                                if (KetOI == ObjectId.Null)
                                                {
                                                    //ed.WriteMessage("KEYOI == null\n");
                                                    Atend.Base.Acad.AT_INFO groupInfo = new Atend.Base.Acad.AT_INFO(NOI);
                                                    groupInfo.NodeCode    = CatOutPack.Code.ToString();
                                                    groupInfo.ParentCode  = "";
                                                    groupInfo.NodeType    = (int)Atend.Control.Enum.ProductType.CatOut;
                                                    groupInfo.ProductCode = CatOutPack.ProductCode;
                                                    groupInfo.Insert();
                                                }
                                                else
                                                {
                                                    //ed.WriteMessage("KEYOI != null\n");
                                                    Atend.Base.Acad.AT_INFO groupInfo = new Atend.Base.Acad.AT_INFO(NOI);
                                                    groupInfo.NodeCode    = CatOutPack.Code.ToString();
                                                    groupInfo.ParentCode  = "";
                                                    groupInfo.NodeType    = (int)Atend.Control.Enum.ProductType.Key;
                                                    groupInfo.ProductCode = CatOutPack.ProductCode;
                                                    groupInfo.Insert();
                                                }
                                            }
                                            else
                                            {
                                                //ed.WriteMessage("terminal != null\n");
                                                Atend.Base.Acad.AT_INFO groupInfo = new Atend.Base.Acad.AT_INFO(NOI);
                                                groupInfo.NodeCode    = CatOutPack.Code.ToString();
                                                groupInfo.ParentCode  = "";
                                                groupInfo.NodeType    = (int)Atend.Control.Enum.ProductType.Terminal;
                                                groupInfo.ProductCode = CatOutPack.ProductCode;
                                                groupInfo.Insert();
                                            }
                                        }

                                        ObjectId GOI = Atend.Global.Acad.Global.MakeGroup(CatOutPack.Code.ToString(), OIC);
                                        //ed.WriteMessage("----<<<<<----GOI:{0}\n", GOI);

                                        Atend.Base.Acad.AT_INFO groupInfo1 = new Atend.Base.Acad.AT_INFO(GOI);
                                        groupInfo1.NodeCode    = CatOutPack.Code.ToString();
                                        groupInfo1.ParentCode  = "";
                                        groupInfo1.NodeType    = (int)Atend.Control.Enum.ProductType.CatOut;
                                        groupInfo1.ProductCode = CatOutPack.ProductCode;
                                        groupInfo1.Insert();


                                        ObjectId TextOi = Atend.Global.Acad.UAcad.DrawEntityOnScreen(Atend.Global.Acad.UAcad.WriteNote(ECatOut.Comment, _DrawBreakerJig.MyCenterPoint, MyCommentScale), Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());

                                        Atend.Base.Acad.AT_INFO textInfo = new Atend.Base.Acad.AT_INFO(TextOi);
                                        textInfo.NodeCode    = "";
                                        textInfo.ParentCode  = CatOutPack.Code.ToString();
                                        textInfo.NodeType    = (int)Atend.Control.Enum.ProductType.Comment;
                                        textInfo.ProductCode = 0;
                                        textInfo.Insert();
                                        //ed.WriteMessage("text info inserted \n");

                                        Atend.Base.Acad.AT_SUB groupSub = new Atend.Base.Acad.AT_SUB(GOI);
                                        groupSub.SubIdCollection.Add(per.ObjectId);
                                        groupSub.SubIdCollection.Add(per1.ObjectId);
                                        groupSub.SubIdCollection.Add(TextOi);
                                        groupSub.Insert();
                                        //ed.WriteMessage("group info inserted \n");

                                        Atend.Base.Acad.AT_SUB.AddToAT_SUB(GOI, per.ObjectId);
                                        Atend.Base.Acad.AT_SUB.AddToAT_SUB(GOI, per1.ObjectId);
                                        //ed.WriteMessage("other nodes info inserted \n");
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("Voltage was not ok \n");
                                }
                            } //if (drs1.Length != 0)
                        }     //if (per1.Status == PromptStatus.OK)
                    }         //if (drs.Length != 0)
                }             //if (per.Status == PromptStatus.OK )
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("DRAW ING FAILED :{0} \n", ex.Message);
            }
        }
示例#49
0
        public void OU()
        {
            //need editor to prompt user
            Editor ed = doc.Editor;

            while (true)
            {
                //Prompt options for utility line
                PromptEntityOptions promptUtilityLineOpt = new PromptEntityOptions("Select Utility Line: \n");
                PromptEntityResult  utilityLineResults   = ed.GetEntity(promptUtilityLineOpt);

                if (utilityLineResults.Status != PromptStatus.OK)
                {
                    //ed.WriteMessage("\nThe selected object is not utility line");
                    return;
                }

                Transaction trans = database.TransactionManager.StartTransaction();
                using (trans)
                {
                    //access block table and create block table record
                    BlockTable       bt            = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr           = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    LinetypeTable    linetypeTable = trans.GetObject(database.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;

                    if (!linetypeTable.Has("BLDG"))
                    {
                        ed.WriteMessage("Please load Linetype:BLDG \n");
                        return;
                    }

                    //get the running line
                    Type type = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead).GetType();

                    String   resultString;
                    Line     line;
                    Polyline polyline;
                    double   offset;

                    if (type == typeof(Line))
                    {
                        line = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead) as Line;

                        resultString = Regex.Match(line.Linetype, @"\d+").Value;

                        if (resultString != "")
                        {
                            offset = Double.Parse(resultString);
                        }
                        else
                        {
                            ed.WriteMessage("Line has no width. Utility linetype with size must be used.");
                            break;
                        }

                        offset = (offset / 12) / 2;

                        DBObjectCollection objCollection = line.GetOffsetCurves(offset);

                        foreach (Entity entity in objCollection)
                        {
                            Line newLine = (Line)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            newLine.ReverseCurve();
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }

                        DBObjectCollection objCollection2 = line.GetOffsetCurves(-offset);

                        foreach (Entity entity in objCollection2)
                        {
                            Line newLine = (Line)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }
                    }
                    else if (type == typeof(Polyline))
                    {
                        polyline = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead) as Polyline;

                        resultString = Regex.Match(polyline.Linetype, @"\d+").Value;

                        if (resultString != "")
                        {
                            offset = Double.Parse(resultString);
                        }
                        else
                        {
                            ed.WriteMessage("Line has no width. Utility linetype with size must be used.\n");
                            break;
                        }

                        offset = (offset / 12) / 2;

                        DBObjectCollection objCollection = polyline.GetOffsetCurves(offset);

                        foreach (Entity entity in objCollection)
                        {
                            Polyline newLine = (Polyline)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }

                        DBObjectCollection objCollection2 = polyline.GetOffsetCurves(-offset);

                        foreach (Entity entity in objCollection2)
                        {
                            Polyline newLine = (Polyline)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            newLine.ReverseCurve();
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }
                    }
                    else
                    {
                        ed.WriteMessage("Must me Line or Polyline. \n");
                    }

                    trans.Commit();
                }
            }
        }
        public void AdjustAlign()
        {
            Document doc = GetDocument();
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    PromptEntityOptions peo = new PromptEntityOptions(
                        "\nSelect a base line or a polyline: ")
                    {
                        AllowNone = false
                    };
                    peo.SetRejectMessage("\n>>>Select either a line or a polyline: ");
                    peo.AddAllowedClass(typeof(Polyline), true);
                    peo.AddAllowedClass(typeof(Line), true);
                    PromptEntityResult per = ed.GetEntity(peo);
                    if (per.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    var baseCurve  = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Curve;
                    var basePickPt = baseCurve.GetClosestPointTo(per.PickedPoint, true);
                    peo = new PromptEntityOptions("\nSelect a polyline: ")
                    {
                        AllowNone = false
                    };
                    peo.SetRejectMessage("\n>>>This is not a polyline, Select a polyline: ");
                    peo.AddAllowedClass(typeof(Polyline), true);
                    per = ed.GetEntity(peo);
                    if (per.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    var pline  = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Polyline;
                    var pickPt = pline.GetClosestPointTo(per.PickedPoint, true);

                    var baseStartParam = (int)baseCurve.GetParameterAtPoint(basePickPt);
                    var baseEndParam   = baseStartParam + 1;
                    var baseStartPt    = baseCurve.GetPointAtParameter(baseStartParam);
                    var baseEndPt      = baseCurve.GetPointAtParameter(baseEndParam);

                    double par  = (int)pline.GetParameterAtPoint(pickPt);
                    double pre1 = par > 0 ? par - 1 : pline.EndParam - 1;
                    double pos1 = par + 1 == pline.EndParam ? 0 : par + 1;
                    double pos2 = pos1 == pline.EndParam ? 1 : pos1 + 1;

                    // get the the surrounding points
                    var p1 = pline.GetPointAtParameter(pre1);
                    var p2 = pline.GetPointAtParameter(par);
                    var p3 = pline.GetPointAtParameter(pos1);
                    var p4 = pline.GetPointAtParameter(pos2);
                    var l  = p2.DistanceTo(p3);

                    var alp1  = p1.GetAngleTo(p2);
                    var alp2  = p2.GetAngleTo(p3);
                    var alp3  = p3.GetAngleTo(p4);
                    var theta = baseStartPt.GetAngleTo(baseEndPt);

                    var theta1 = theta - alp2;
                    var theta2 = alp2 - alp1;
                    var theta3 = theta - alp1;
                    var theta4 = alp2 - alp3;
                    var theta5 = theta - alp3;

                    var f1 = Math.Sin(theta1) * Math.Sin(theta2) / Math.Sin(theta3);
                    var f2 = Math.Sin(theta1) * Math.Sin(theta4) / Math.Sin(theta5);
                    var f  = f1 / f2;

                    var l1 = l / (1 + Math.Sqrt(f));
                    var l2 = l - l1;

                    var l3 = l1 * Math.Sin(theta1) / Math.Sin(theta3);
                    var l4 = l2 * Math.Sin(theta1) / Math.Sin(theta5);

                    var pt2 = p2.Polar(alp1, l3);
                    var pt3 = p3.Polar(alp3, -l4);

                    pline.UpgradeOpen();
                    pline.SetPointAt((int)par, pt2.GetPoint2d());
                    pline.SetPointAt((int)pos1, pt3.GetPoint2d());
                    trans.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage(ex.Message);
            }
            finally
            {
            }
        }
示例#51
0
        public void CMD_Pos()
        {
            if (!CheckLicense()) return;

            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            // Edit entity if there is a pickset
            PromptSelectionResult selectionRes = ed.SelectImplied();
            if (selectionRes.Status != PromptStatus.Error && selectionRes.Value.Count > 0)
            {
                ObjectId id = selectionRes.Value[0].ObjectId;
                ed.SetImpliedSelection(new ObjectId[0]);
                ItemEdit(id, MonitoredPoint);
                return;
            }

            bool cont = true;
            while (cont)
            {
                PromptEntityOptions opts = new PromptEntityOptions("Poz secin veya [Yeni/Numaralandir/Kopyala/kOntrol/Metraj/bul Degistir/numara Sil/Acilimlar/Tablo stili/ayaRlar]: ",
                    "New Numbering Copy Check BOQ Find Empty Shapes Table Preferences");
                opts.AllowNone = false;
                PromptEntityResult result = ed.GetEntity(opts);

                if (result.Status == PromptStatus.Keyword)
                {
                    switch (result.StringResult)
                    {
                        case "New":
                            NewPos();
                            break;
                        case "Numbering":
                            NumberPos();
                            break;
                        case "Empty":
                            EmptyBalloons();
                            break;
                        case "Copy":
                            CopyPos();
                            break;
                        case "Check":
                            PosCheck();
                            break;
                        case "BOQ":
                            DrawBOQ();
                            break;
                        case "Find":
                            FindReplace(false);
                            break;
                        case "Shapes":
                            PosShapes();
                            break;
                        case "Table":
                            TableStyles();
                            break;
                        case "Preferences":
                            PosGroups();
                            break;
                    }
                    cont = false;
                }
                else if (result.Status == PromptStatus.OK)
                {
                    ItemEdit(result.ObjectId, result.PickedPoint);
                    cont = true;
                }
                else
                {
                    cont = false;
                }
            }
        }
示例#52
0
        static public void GetFieldLink()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor   ed = doc.Editor;

            // Ask the user to select an attribute or an mtext
            PromptEntityOptions opt =
                new PromptEntityOptions(
                    "\nSelect an MText object containing field(s): "
                    );

            opt.SetRejectMessage(
                "\nObject must be MText."
                );
            opt.AddAllowedClass(typeof(MText), false);
            PromptEntityResult res =
                ed.GetEntity(opt);

            if (res.Status == PromptStatus.OK)
            {
                Transaction tr =
                    doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    // Check the entity is an MText object
                    DBObject obj =
                        tr.GetObject(
                            res.ObjectId,
                            OpenMode.ForRead
                            );

                    if (obj is MText mt)
                    {
                        if (!mt.HasFields)
                        {
                            ed.WriteMessage(
                                "\nMText object does not contain fields."
                                );
                        }
                        else
                        {
                            // Open the extension dictionary
                            DBDictionary extDict =
                                (DBDictionary)tr.GetObject(
                                    mt.ExtensionDictionary,
                                    OpenMode.ForRead
                                    );

                            const string fldDictName  = "ACAD_FIELD";
                            const string fldEntryName = "TEXT";
                            // Get the field dictionary
                            if (extDict.Contains(fldDictName))
                            {
                                ObjectId fldDictId =
                                    extDict.GetAt(fldDictName);
                                if (fldDictId != ObjectId.Null)
                                {
                                    DBDictionary fldDict =
                                        (DBDictionary)tr.GetObject(
                                            fldDictId,
                                            OpenMode.ForRead
                                            );

                                    // Get the field itself
                                    if (fldDict.Contains(fldEntryName))
                                    {
                                        ObjectId fldId =
                                            fldDict.GetAt(fldEntryName);
                                        if (fldId != ObjectId.Null)
                                        {
                                            obj =
                                                tr.GetObject(
                                                    fldId,
                                                    OpenMode.ForRead
                                                    );
                                            if (obj is Field fld)
                                            {
                                                // And finally get the string
                                                // including the field codes
                                                string fldCode = fld.GetFieldCode();
                                                ed.WriteMessage(
                                                    "\nField code: "
                                                    + fldCode
                                                    );

                                                // Loop, using our helper function
                                                // to find the object references
                                                do
                                                {
                                                    fldCode =
                                                        FindObjectId(
                                                            fldCode,
                                                            out ObjectId objId
                                                            );
                                                    if (fldCode != "")
                                                    {
                                                        // Print the ObjectId
                                                        ed.WriteMessage(
                                                            "\nFound Object ID: "
                                                            + objId.ToString()
                                                            );
                                                        obj =
                                                            tr.GetObject(
                                                                objId,
                                                                OpenMode.ForRead
                                                                );
                                                        // ... and the type of the object
                                                        ed.WriteMessage(
                                                            ", which is an object of type "
                                                            + obj.GetType().ToString()
                                                            );
                                                    }
                                                } while (fldCode != "");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#53
0
        private void CopyPosNumber()
        {
            PromptEntityOptions opts = new PromptEntityOptions("Select source object: ");
            opts.AllowNone = false;
            PromptEntityResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(opts);
            if (result.Status != PromptStatus.OK) return;

            PromptEntityOptions destopts = new PromptEntityOptions("Select destination object: ");
            destopts.AllowNone = false;
            PromptEntityResult destresult = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(destopts);
            if (destresult.Status != PromptStatus.OK) return;
            if (result.ObjectId == destresult.ObjectId) return;

            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    RebarPos source = tr.GetObject(result.ObjectId, OpenMode.ForRead) as RebarPos;
                    if (source == null) return;
                    if (source.Detached) return;

                    RebarPos dest = tr.GetObject(destresult.ObjectId, OpenMode.ForWrite) as RebarPos;
                    if (dest != null)
                    {
                        dest.Pos = source.Pos;
                        dest.Detached = true;
                    }

                    DBText text = tr.GetObject(destresult.ObjectId, OpenMode.ForWrite) as DBText;
                    if (text != null)
                    {
                        text.TextString = source.Pos;
                    }
                    MText mtext = tr.GetObject(destresult.ObjectId, OpenMode.ForWrite) as MText;
                    if (mtext != null)
                    {
                        mtext.Contents = source.Pos;
                    }

                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
示例#54
0
        public void DrawMafsal()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //ed.WriteMessage("aaaaa\n");
            PromptKeywordOptions PSO = new PromptKeywordOptions("\nترسیم مفصل");

            PSO.Keywords.Add("New", "New", "New");
            PSO.Keywords.Add("Break", "Break", "Break Cabel");
            PSO.Keywords.Default = "New";
            PromptResult psr = ed.GetKeywords(PSO);

            double MyScale = Atend.Base.Design.DProductProperties.AccessSelectBySoftwareCode((int)Atend.Control.Enum.ProductType.Mafsal).Scale;


            DrawMafsalJig DCP = new DrawMafsalJig(MyScale);

            if (psr.Status == PromptStatus.OK)
            {
                switch (psr.StringResult)
                {
                case "New":

                    bool         Conti = true;
                    PromptResult pr;
                    while (Conti)
                    {
                        pr = ed.Drag(DCP);

                        if (pr.Status == PromptStatus.OK)
                        {
                            Conti = false;
                            Entity entity = DCP.GetEntity();
                            if (SaveMafsalData())
                            {
                                Atend.Global.Acad.UAcad.DrawEntityOnScreen(entity, Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());
                                Atend.Base.Acad.AT_INFO at_info = new Atend.Base.Acad.AT_INFO(entity.ObjectId);
                                at_info.ParentCode  = "";
                                at_info.NodeCode    = MafsalInfo.Code.ToString();
                                at_info.NodeType    = (int)Atend.Control.Enum.ProductType.Mafsal;
                                at_info.ProductCode = Convert.ToInt32(MafsalInfo.ProductCode);
                                at_info.Insert();
                            }
                        }
                        else
                        {
                            Conti = false;
                        }
                    }
                    break;

                case "Break":

                    PromptEntityOptions peo = new PromptEntityOptions("\nمحل برش کابل را انتخاب نمایید");
                    PromptEntityResult  per = ed.GetEntity(peo);
                    if (per.Status == PromptStatus.OK)
                    {
                        Polyline SelectedCable = Atend.Global.Acad.UAcad.GetEntityByObjectID(per.ObjectId) as Polyline;
                        if (SelectedCable != null)
                        {
                            //////SelectedCable.UpgradeOpen();
                            //////SelectedCable.SetField("Name",new Field("Parisa", true));
                            int     NearestSegmentIndex    = 0;
                            double  NearestSegmentDistance = 100000;
                            Point3d NearestPoint           = Point3d.Origin;
                            for (int counter = 0; counter < SelectedCable.NumberOfVertices - 1; counter++)
                            {
                                LineSegment3d ls1           = new LineSegment3d(SelectedCable.GetPoint3dAt(counter), SelectedCable.GetPoint3dAt(counter + 1));
                                Point3d       SelectedPoint = ls1.GetClosestPointTo(per.PickedPoint).Point;
                                //ed.WriteMessage("SP:{0}\n", SelectedPoint);

                                if (SelectedPoint.DistanceTo(per.PickedPoint) < NearestSegmentDistance)
                                {
                                    NearestSegmentDistance = SelectedPoint.DistanceTo(per.PickedPoint);
                                    NearestSegmentIndex    = counter;
                                    NearestPoint           = SelectedPoint;
                                }
                            }
                            //ed.WriteMessage("SINDEX:{0}\n", NearestSegmentIndex);
                            //seprate Cable

                            Polyline Part1 = new Polyline();
                            Polyline Part2 = new Polyline();
                            for (int counter = 0; counter <= NearestSegmentIndex; counter++)
                            {
                                Part1.AddVertexAt(Part1.NumberOfVertices, SelectedCable.GetPoint2dAt(counter), 0, 0, 0);
                                //ed.WriteMessage("POINT:{0}\n", SelectedCable.GetPoint2dAt(counter));
                            }
                            Part1.AddVertexAt(Part1.NumberOfVertices, new Point2d(NearestPoint.X, NearestPoint.Y), 0, 0, 0);

                            Part2.AddVertexAt(Part2.NumberOfVertices, new Point2d(NearestPoint.X, NearestPoint.Y), 0, 0, 0);
                            for (int counter = NearestSegmentIndex + 1; counter <= SelectedCable.NumberOfVertices - 1; counter++)
                            {
                                Part2.AddVertexAt(Part2.NumberOfVertices, SelectedCable.GetPoint2dAt(counter), 0, 0, 0);
                            }
                            if (SaveMafsalData())
                            {
                                try
                                {
                                    Atend.Base.Acad.AT_INFO LastCableInfo = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(per.ObjectId);
                                    Atend.Base.Acad.AT_SUB  LastCableSub  = Atend.Base.Acad.AT_SUB.SelectBySelectedObjectId(per.ObjectId);
                                    //ed.WriteMessage("-3\n");
                                    //determine header belong to part1 or part2
                                    ObjectIdCollection Blong1 = new ObjectIdCollection();
                                    ObjectIdCollection Blong2 = new ObjectIdCollection();
                                    foreach (ObjectId oi in LastCableSub.SubIdCollection)
                                    {
                                        Atend.Base.Acad.AT_INFO oiInfo = Atend.Base.Acad.AT_INFO.SelectBySelectedObjectId(oi);
                                        Point3d FirstPoint             = SelectedCable.GetPoint3dAt(0);
                                        //ed.WriteMessage("-3.1\n");
                                        if (oiInfo.ParentCode != "NONE" && FirstPoint != null)
                                        {
                                            //ed.WriteMessage("-3.2\n");
                                            switch ((Atend.Control.Enum.ProductType)oiInfo.NodeType)
                                            {
                                            case Atend.Control.Enum.ProductType.Mafsal:
                                                //ed.WriteMessage("-3.3\n");
                                                if (Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(oi)) == FirstPoint)
                                                {
                                                    //ed.WriteMessage("-3.4\n");
                                                    Blong1.Add(oi);
                                                }
                                                else
                                                {
                                                    //ed.WriteMessage("-3.5\n");
                                                    Blong2.Add(oi);
                                                }
                                                break;

                                            case Atend.Control.Enum.ProductType.HeaderCabel:
                                                //ed.WriteMessage("-3.6\n");
                                                //ed.WriteMessage("color:{0}\n",curv.ColorIndex);
                                                //ed.WriteMessage("-3.6.1\n");
                                                if (Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(oi)) == FirstPoint)
                                                {
                                                    //ed.WriteMessage("-3.7\n");
                                                    Blong1.Add(oi);
                                                }
                                                else
                                                {
                                                    //ed.WriteMessage("-3.8\n");
                                                    Blong2.Add(oi);
                                                }
                                                break;

                                            case Atend.Control.Enum.ProductType.ConnectionPoint:
                                                if (Atend.Global.Acad.UAcad.CenterOfEntity(Atend.Global.Acad.UAcad.GetEntityByObjectID(oi)) == FirstPoint)
                                                {
                                                    Blong1.Add(oi);
                                                }
                                                else
                                                {
                                                    Blong2.Add(oi);
                                                }

                                                break;
                                            }
                                        }
                                    }

                                    Entity   MafsalEntiyt     = DCP.GetDemo(NearestPoint);
                                    ObjectId NewDrawnMafsalOI = Atend.Global.Acad.UAcad.DrawEntityOnScreen(MafsalEntiyt, Atend.Control.Enum.AutoCadLayerName.GENERAL.ToString());

                                    Atend.Base.Acad.AT_INFO newinfo1 = new Atend.Base.Acad.AT_INFO(NewDrawnMafsalOI);
                                    newinfo1.ParentCode  = "";
                                    newinfo1.NodeCode    = MafsalInfo.Code.ToString();
                                    newinfo1.NodeType    = (int)Atend.Control.Enum.ProductType.Mafsal;
                                    newinfo1.ProductCode = MafsalInfo.ProductCode;
                                    newinfo1.Insert();



                                    //ed.WriteMessage("-4\n");
                                    Atend.Global.Acad.AcadRemove.DeleteEntityByObjectId(SelectedCable.ObjectId);
                                    //ed.WriteMessage("1\n");
                                    Atend.Global.Acad.UAcad.DrawEntityOnScreen(Part1, Atend.Control.Enum.AutoCadLayerName.MED_GROUND.ToString());
                                    //ed.WriteMessage("2\n");
                                    Atend.Global.Acad.UAcad.DrawEntityOnScreen(Part2, Atend.Control.Enum.AutoCadLayerName.MED_GROUND.ToString());
                                    //ed.WriteMessage("3\n");

                                    Atend.Base.Acad.AT_SUB mafsalsub = new Atend.Base.Acad.AT_SUB(NewDrawnMafsalOI);
                                    mafsalsub.SubIdCollection.Add(Part1.ObjectId);
                                    mafsalsub.SubIdCollection.Add(Part2.ObjectId);
                                    mafsalsub.Insert();
                                    //ed.WriteMessage("4\n");

                                    LastCableInfo.SelectedObjectId = Part1.ObjectId;
                                    LastCableInfo.Insert();
                                    ///ed.WriteMessage("5\n");

                                    LastCableInfo.SelectedObjectId = Part2.ObjectId;
                                    LastCableInfo.Insert();
                                    //ed.WriteMessage("6\n");

                                    Atend.Base.Acad.AT_SUB.AddToAT_SUB(NewDrawnMafsalOI, Part1.ObjectId);

                                    foreach (ObjectId oi in Blong1)
                                    {
                                        Atend.Base.Acad.AT_SUB.AddToAT_SUB(oi, Part1.ObjectId);
                                    }

                                    Atend.Base.Acad.AT_SUB.AddToAT_SUB(NewDrawnMafsalOI, Part2.ObjectId);

                                    foreach (ObjectId oi in Blong2)
                                    {
                                        Atend.Base.Acad.AT_SUB.AddToAT_SUB(oi, Part2.ObjectId);
                                    }
                                }
                                catch (System.Exception ex)
                                {
                                    ed.WriteMessage("~~~{0}~~~~~~\n", ex.Message);
                                }
                            }    //catch ended here
                        }
                    }


                    break;
                }
            }
        }
示例#55
0
        /// <summary>
        /// Execute the command. Requires Civil3D.
        /// </summary>
        private static void CommandCutSolidFromSurface()
        {
            Editor ed = Application.DocumentManager.
                        MdiActiveDocument.Editor;

            // select a solid
            PromptEntityOptions opSelSolid = new PromptEntityOptions(
                "\nSelect a solid: ");

            opSelSolid.SetRejectMessage("\nOnly solids allowed");
            opSelSolid.AddAllowedClass(typeof(Solid3d), true);
            PromptEntityResult resSelSolid = ed.GetEntity(opSelSolid);

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

            // select a surface
            PromptEntityOptions opSelSurface = new PromptEntityOptions(
                "\nSelect a TIN surface or : ");

            opSelSurface.SetRejectMessage("\nOnly TIN surface allowed");
            opSelSurface.AddAllowedClass(typeof(TinSurface), true);
            opSelSurface.Keywords.Add("None");
            opSelSurface.AppendKeywordsToMessage = true;
            PromptEntityResult resSelSurface = ed.GetEntity(opSelSurface);
            ObjectId           surfaceId;

            switch (resSelSurface.Status)
            {
            case PromptStatus.OK:
                surfaceId = resSelSurface.ObjectId; break;

            case PromptStatus.Keyword:
                surfaceId = ObjectId.Null; break;

            default:
                return;
            }

            // specify new surface name
            PromptResult resSurfName       = null;
            bool         keepAskingForName = true;

            while (keepAskingForName)
            {
                PromptStringOptions opSpecifySurfName = new
                                                        PromptStringOptions("\nSpecify new surface name: ");
                opSpecifySurfName.AllowSpaces  = true;
                opSpecifySurfName.DefaultValue =
                    "Surface<[Next Counter(CP)]>";
                opSpecifySurfName.UseDefaultValue = true;
                resSurfName = ed.GetString(opSpecifySurfName);
                if (resSurfName.Status != PromptStatus.OK)
                {
                    return;
                }

                keepAskingForName = !Util.GetSurfaceId(
                    resSurfName.StringResult).IsNull;
                if (keepAskingForName)
                {
                    // replace points or not
                    PromptKeywordOptions opReplace = new
                                                     PromptKeywordOptions(
                        "\nSurface name already exist. Replace all points? ");
                    opReplace.Keywords.Add("Yes");
                    opReplace.Keywords.Add("No");
                    opReplace.AppendKeywordsToMessage = true;
                    PromptResult resReplace = ed.GetKeywords(opReplace);
                    if (resReplace.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    switch (resReplace.StringResult)
                    {
                    case "Yes":
                        keepAskingForName = false;
                        Application.ShowAlertDialog(
                            "ATTENTION:\nManually remove/disable " +
                            "previous unwanted\noperations of this surface.");
                        break;

                    case "No":
                        keepAskingForName = true;
                        break;
                    }
                }
            }

            // specify the density of point per unit of length
            PromptIntegerOptions opSpecifyDensity = new
                                                    PromptIntegerOptions(
                "\nSpecify number of surface points per " +
                "AutoCAD unit of drawing: ");

            opSpecifyDensity.AllowZero       = false;
            opSpecifyDensity.AllowNegative   = false;
            opSpecifyDensity.DefaultValue    = 5;
            opSpecifyDensity.UseDefaultValue = true;
            PromptIntegerResult resDensity = ed.GetInteger(
                opSpecifyDensity);

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

            // simplify surface (using Civil 3D built-in operation)
            PromptKeywordOptions opSimplify = new PromptKeywordOptions(
                "\nSimplify points? (Recommended, operation can be undone): ");

            opSimplify.Keywords.Add("Yes");
            opSimplify.Keywords.Add("No");
            opSimplify.AppendKeywordsToMessage = true;
            PromptResult resSimplify = ed.GetKeywords(opSimplify);

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

            GenerateSurfaceByScan(resSelSolid.ObjectId,
                                  surfaceId, resSurfName.StringResult,
                                  resDensity.Value, (resSimplify.StringResult == "Yes"));
        }
示例#56
0
        public void DrawGroupLeader()
        {
            Editor ed = dwg.Editor;
            PromptEntityOptions prmtEntityOpts = new PromptEntityOptions("Укажите линию");
            prmtEntityOpts.AllowNone = false;
            prmtEntityOpts.SetRejectMessage("Должна быть линия или полилиния!");
            prmtEntityOpts.AddAllowedClass(typeof(Line), true);
            prmtEntityOpts.AddAllowedClass(typeof(Polyline), true);
            PromptEntityResult entRes = ed.GetEntity(prmtEntityOpts);
            if (entRes.Status!= PromptStatus.OK)
            {
                return;
            }
            using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction())
            {
                GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase);
                List<string> groupList = groupEntities.GetGroupsOfObject(entRes.ObjectId);
                if (groupList == null)
                {
                    ed.WriteMessage("За указанным объектом не значится никаких групп!");
                    return;
                }
                PromptPointOptions pointOpts = new PromptPointOptions("\nУкажите точку вставки блока: ");
                PromptPointResult pointRes = ed.GetPoint(pointOpts);
                if (pointRes.Status!= PromptStatus.OK)
                {
                    return;
                }
                BlockTable bt = (BlockTable)CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead);
                BlockTableRecord btrSpace = (BlockTableRecord)CurrentDatabase.CurrentSpaceId
                    .GetObject(OpenMode.ForWrite);
                if (!bt.Has("group_vinoska"))
                {
                    ed.WriteMessage("\nВ файле не определён блок выноски!!");
                    return;
                }
                BlockTableRecord gleaderBtr = (BlockTableRecord)bt["group_vinoska"].GetObject(OpenMode.ForRead);
                BlockReference gleader = new BlockReference(pointRes.Value, gleaderBtr.ObjectId);
                btrSpace.AppendEntity(gleader);
                tr.AddNewlyCreatedDBObject(gleader, true);

                //Если блок аннотативный - добавляем в таблицу аннотативных масштабов блока текущий масштаб
                ObjectContextManager ocm = CurrentDatabase.ObjectContextManager;
                ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES");
                if (gleaderBtr.Annotative == AnnotativeStates.True)
                {
                    ObjectContexts.AddContext(gleader, occ.CurrentContext);
                }

                gleader.SetDatabaseDefaults();
                if (gleaderBtr.HasAttributeDefinitions)
                {
                    var attDefs = gleaderBtr.Cast<ObjectId>()
                        .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition")
                        .Select(n => (AttributeDefinition)n.GetObject(OpenMode.ForRead));
                    foreach (AttributeDefinition attdef in attDefs)
                    {
                        AttributeReference attref = new AttributeReference();
                        attref.SetAttributeFromBlock(attdef, gleader.BlockTransform);
                        gleader.AttributeCollection.AppendAttribute(attref);
                        tr.AddNewlyCreatedDBObject(attref, true);
                        if (gleaderBtr.Annotative == AnnotativeStates.True)
                        {
                            ObjectContexts.AddContext(attref, occ.CurrentContext);
                        }
                        int attCount = int.Parse(attref.Tag.Remove(0,10));
                        if (attCount<=groupList.Count)
                        {
                            attref.TextString = groupList[attCount-1];
                        }
                    }
                }

                if (gleaderBtr.IsDynamicBlock)
                {
                    DynamicBlockReferencePropertyCollection dynBRefColl = gleader.DynamicBlockReferencePropertyCollection;
                    foreach (DynamicBlockReferenceProperty prop in dynBRefColl)
                    {
                        if (prop.PropertyName == "Lookup1")
                        {
                            prop.Value = prop.GetAllowedValues()[groupList.Count-1];
                        }
                    }
                }
                tr.Commit();
            }
        }
示例#57
0
文件: Class1.cs 项目: guchanghai/Cut
 public void OpenEnt()
 {
     Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
     PromptEntityOptions entOps = new PromptEntityOptions("ѡ��Ҫ�򿪵Ķ���");
     PromptEntityResult entRes;
     entRes = ed.GetEntity(entOps);
     if (entRes.Status != PromptStatus.OK)
     {
         ed.WriteMessage("ѡ�����ʧ�ܣ��˳�");
         return;
     }
     ObjectId objId = entRes.ObjectId;
     Database db = HostApplicationServices.WorkingDatabase;
     using (Transaction trans = db.TransactionManager.StartTransaction())
     {
         Entity ent = trans.GetObject(objId, OpenMode.ForWrite);
         ent.ColorIndex = 1;
         trans.Commit();
     }
 }
示例#58
0
 public void GetGroupsOfObject()
 {
     Editor editor = dwg.Editor;
     List<string> groupList = null;
     PromptEntityOptions selectionOptions = new PromptEntityOptions("\nВыберите объект");
     selectionOptions.AllowNone = false;
     PromptEntityResult selectionResult = editor.GetEntity(selectionOptions);
     if (selectionResult.Status == PromptStatus.OK)
     {
         using (Transaction transaction = CurrentDatabase.TransactionManager.StartTransaction())
         {
             GroupsInformation groupEntities = new GroupsInformation(transaction, CurrentDatabase);
             groupList = groupEntities.GetGroupsOfObject(selectionResult.ObjectId);
         }
         if (groupList!=null)
         {
             editor.WriteMessage("\nГруппы, к которым принадлежат объекты: ");
             foreach (string group in groupList)
                 editor.WriteMessage("\n{0}", group);
         }
         else
         {
             editor.WriteMessage("\nОбъект не принадлежит никаким группам!");
         }
     }
 }
示例#59
0
        static public void MeshFromSolid()
        {
            Utils.Utils.Init();

            Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            while (true)
            {
                // Ask the user to select a solid
                PromptEntityOptions peo = new PromptEntityOptions("Select a 3D solid");
                peo.SetRejectMessage("\nA 3D solid must be selected.");
                peo.AddAllowedClass(typeof(Solid3d), true);
                PromptEntityResult per = ed.GetEntity(peo);

                if (per.Status == PromptStatus.Cancel || per.Status == PromptStatus.Error)
                {
                    Utils.Utils.End(); return;
                }

                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // Open the Block table for read
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    // Open the Block table record Model space for write
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                    Solid3d sol = acTrans.GetObject(per.ObjectId, OpenMode.ForWrite) as Solid3d;

                    try
                    {
                        // Set mesh/faces properties
                        MeshFaceterData mfd = new MeshFaceterData();
                        mfd.FaceterMeshType      = 2;
                        mfd.FaceterDevNormal     = 40;
                        mfd.FaceterDevSurface    = 0.05;
                        mfd.FaceterGridRatio     = 0;
                        mfd.FaceterMaxEdgeLength = 0;

                        MeshDataCollection md = SubDMesh.GetObjectMesh(sol, mfd);

                        // Create mesh
                        SubDMesh mesh = new SubDMesh();
                        mesh.SetDatabaseDefaults();
                        mesh.SetSubDMesh(md.VertexArray, md.FaceArray, 0);
                        mesh.Layer = sol.Layer;

                        // Add mesh to DB
                        acBlkTblRec.AppendEntity(mesh);
                        acTrans.AddNewlyCreatedDBObject(mesh, true);

                        // Delete solid object
                        sol.Erase(true);

                        acTrans.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        ed.WriteMessage("Exception: {0}", ex.Message);
                    }
                }
            }
        }
示例#60
0
        public static void InterpolatePoint()
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PromptEntityOptions peoXref = new PromptEntityOptions("\nSelect Grading Xref.")
            {
                AllowObjectOnLockedLayer = true,
                AllowNone = false
            };
            PromptEntityOptions peoPolyLine1 = new PromptEntityOptions("\nSelect polyline 1.");
            PromptEntityOptions peoPolyLine2 = new PromptEntityOptions("\nSelect polyline 2.");
            PromptPointOptions  ppo          = new PromptPointOptions("\nSelect Point of intrest.");

            PromptPointResult ppr = ed.GetPoint(ppo);

            if (ppr.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    try
                    {
                        Point3d            pt      = ppr.Value;
                        BlockTable         bt      = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                        PromptEntityResult perXref = ed.GetEntity(peoXref);
                        if (perXref.Status == PromptStatus.OK)
                        {
                            BlockReference xrefRef = (BlockReference)tr.GetObject(perXref.ObjectId, OpenMode.ForRead);
                            if (xrefRef != null)
                            {
                                // If so, we check whether the block table record to which it refers is actually from an XRef

                                ObjectId         xrefId  = xrefRef.BlockTableRecord;
                                BlockTableRecord xrefBTR = (BlockTableRecord)tr.GetObject(xrefId, OpenMode.ForRead);
                                if (xrefBTR != null)
                                {
                                    if (xrefBTR.IsFromExternalReference)
                                    {
                                        // If so, then we prigrammatically select the object underneath the pick-point already used
                                        PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("")
                                        {
                                            NonInteractivePickPoint    = perXref.PickedPoint,
                                            UseNonInteractivePickPoint = true
                                        };
                                        PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);
                                        if (pner.Status == PromptStatus.OK)
                                        {
                                            try
                                            {
                                                ObjectId selId = pner.ObjectId;

                                                // Let's look at this programmatically-selected object, to see what it is
                                                DBObject obj = tr.GetObject(selId, OpenMode.ForRead);

                                                // If it's a polyline vertex, we need to go one level up to the polyline itself

                                                if (obj is PolylineVertex3d || obj is Vertex2d)
                                                {
                                                    selId = obj.OwnerId;
                                                }

                                                // We don't want to do anything at all for textual stuff, let's also make sure we are
                                                // dealing with an entity (should always be the case)

                                                if (obj is MText || obj is DBText || !(obj is Entity))
                                                {
                                                    return;
                                                }

                                                // Now let's get the name of the layer, to use later

                                                Entity           ent = (Entity)obj;
                                                LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ent.LayerId, OpenMode.ForRead);

                                                ed.WriteMessage("\nObject Selected is {0} on layer {1} in xref {2}.", selId.GetType(), ltr.Name, xrefBTR.Name);
                                            }
                                            catch
                                            {
                                                // A number of innocuous things could go wrong
                                                // so let's not worry about the details

                                                // In the worst case we are simply not trying
                                                // to replace the entity, so OFFSET will just
                                                // reject the selected Xref
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        ed.WriteMessage("\nFailed in xrefSelect");
                    }
                    //BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                }
                tr.Commit();
            }
            else
            {
                ed.WriteMessage("Failed to find point of intrest.");
            }
        }