Exemple #1
0
        private void ChangeCase(bool upper)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Specifically select an MText object

            var peo = new PromptEntityOptions(string.Format("\nSelect MText to change to {0}case: ", upper ? "upper" : "lower"));

            peo.SetRejectMessage("\nObject must be MText.");
            peo.AddAllowedClass(typeof(MText), false);

            PromptEntityResult per = ed.GetEntity(peo);

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

            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {
                // We only need our MText open for read

                DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead, false);
                MText    mt  = obj as MText;
                if (mt == null)
                {
                    return;
                }

                // Create a text editor object for the MText
                TextEditor te = TextEditor.CreateTextEditor(mt);

                if (te == null)
                {
                    return;
                }

                // Select the entire contents of the MText

                te.SelectAll();
                TextEditorSelection sel = te.Selection;
                if (sel == null)
                {
                    return;
                }

                // Check whether we can change the selection's
                // case, and then do so

                if (sel.CanChangeCase)
                {
                    if (upper)
                    {
                        sel.ChangeToUppercase();
                    }
                    else
                    {
                        sel.ChangeToLowercase();
                    }
                }

                // Be sure to save the results from the editor

                te.Close(TextEditor.ExitStatus.ExitSave);
                tr.Commit();
            }
        }
        public void GetInformation()
        {
            Editor   ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;
            //获得标注样式
            ObjectId curDimstyle = db.Dimstyle;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //下面的操作用来选择实体来显示它的扩展数据
                PromptEntityOptions opt = new PromptEntityOptions("请选择实体来显示它的扩展数据");
                PromptEntityResult  res = ed.GetEntity(opt);
                if (res.Status != PromptStatus.OK)
                {
                    return;
                }
                Entity ent = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                //判断实体的类型 点 线 面
                //点
                if (ent.GetType().Name.ToString() == "DBPoint")
                {
                    DBPoint Selectent = (DBPoint)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    //位置
                    Point3d position = Selectent.Position;
                    double  x        = position.X;
                    double  y        = position.Y;
                    double  z        = position.Z;
                    //厚度
                    double thickness = Selectent.Thickness;
                    //扩展数据
                    ResultBuffer xdata = Selectent.XData;
                    if (xdata != null)
                    {
                        foreach (TypedValue entXData in xdata)
                        {
                            ed.WriteMessage(string.Format("\n扩展数据  类型代码={0},数据值={1}", entXData.TypeCode, entXData.Value));
                        }
                    }
                    ed.WriteMessage(string.Format("\n 点的X坐标={0}", x.ToString()));
                    ed.WriteMessage(string.Format("\n 点的Y坐标={0}", y.ToString()));
                    ed.WriteMessage(string.Format("\n 点的Z坐标={0}", z.ToString()));
                }

                //直线
                if (ent.GetType().Name.ToString() == "Line")
                {
                    Line Selectent = (Line)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    //起点
                    Point3d start = Selectent.StartPoint;
                    //终点
                    Point3d end = Selectent.EndPoint;

                    //线段的中点位置
                    Point3d midpoint = new Point3d((start.X + end.X) / 2, (start.Y + end.Y) / 2, 0);

                    double sx = start.X;
                    double sy = start.Y;
                    double ex = end.X;
                    double ey = end.Y;
                    //扩展数据
                    ResultBuffer xdata = Selectent.XData;
                    if (xdata != null)
                    {
                        foreach (TypedValue entXData in xdata)
                        {
                            ed.WriteMessage(string.Format("\n扩展数据  类型代码={0},数据值={1}", entXData.TypeCode, entXData.Value));
                        }
                    }
                    ed.WriteMessage(string.Format("\n 直线起点X坐标={0}", sx.ToString()));
                    ed.WriteMessage(string.Format("\n 直线起点Y坐标={0}", sy.ToString()));
                    ed.WriteMessage(string.Format("\n 直线终点X坐标={0}", ex.ToString()));
                    ed.WriteMessage(string.Format("\n 直线终点Y坐标={0}", ey.ToString()));

                    PromptPointOptions optPointB = new PromptPointOptions("\n请输入标注终点位置:");
                    optPointB.AllowNone = true;
                    PromptPointResult resPointB = ed.GetPoint(optPointB);
                    Point3d           ptEnd     = resPointB.Value;

                    Point3d pt1 = new Point3d(midpoint[0], midpoint[1], 0);
                    Point3d pt2 = new Point3d(ptEnd[0], ptEnd[1], 0);

                    //标注
                    Point3dCollection ptss = new Point3dCollection();
                    ptss.Add(pt1);
                    ptss.Add(pt2);
                    ModelSpace.AddLeader(ptss, false);
                    //标注内容
                    ModelSpace.AddMtext(pt1, "{\\L引线标注示例\\l}", curDimstyle, AttachmentPoint.BottomLeft, 2.5, 0);
                }

                //多段线
                if (ent.GetType().Name.ToString() == "Polyline")
                {
                    Polyline Selectent = (Polyline)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    //面积
                    double area = Selectent.Area;
                    //长度
                    double  length      = Selectent.Length;
                    Point3d startpoint  = Selectent.StartPoint;
                    double  startpointx = startpoint.X;
                    double  startpointy = startpoint.Y;
                    bool    closed      = Selectent.Closed;
                    //多段线闭合 围成了面积
                    if (closed == true)
                    {
                        ed.WriteMessage(string.Format("多段线闭合: YES"));
                        ed.WriteMessage(string.Format("\n  顶点X坐标={0}", startpointx.ToString()));
                        ed.WriteMessage(string.Format("\n 顶点Y坐标={0}", startpointy.ToString()));
                        ed.WriteMessage(string.Format("\n 多段线面积={0}", area.ToString()));
                        ed.WriteMessage(string.Format("\n 多段线长度={0}", length.ToString()));

                        //扩展数据
                        ResultBuffer xdata = Selectent.XData;
                        if (xdata != null)
                        {
                            foreach (TypedValue entXData in xdata)
                            {
                                ed.WriteMessage(string.Format("\n扩展数据  类型代码={0},数据值={1}", entXData.TypeCode, entXData.Value));
                            }
                        }
                    }
                    else
                    {
                        ed.WriteMessage(string.Format("多段线闭合: NO 无法围成面"));
                        return;
                    }
                }
            }
        }
Exemple #3
0
        public void Bora()
        {
            Editor ed = acDoc.Editor;
            //Prompt options for running line
            PromptEntityOptions peo = new PromptEntityOptions("Select Running Line");

            peo.SetRejectMessage("Please Select Running Line");
            peo.AddAllowedClass(typeof(Polyline), false);

            PromptEntityResult perRunningLine = ed.GetEntity(peo);

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

            while (checkForDriveways())
            {
                //get the selection set from the prompt results
                //SelectionSet acSSetDriveways = psResultDriveways.Value;

                // Start a transaction
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    //open block table record for read
                    BlockTable blkTbl;
                    blkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                    //open table record for write
                    BlockTableRecord blkTblRec;
                    blkTblRec = acTrans.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;



                    _runningLine = acTrans.GetObject(perRunningLine.ObjectId, OpenMode.ForRead) as Polyline;
                    //Polyline drivewayLine = acTrans.GetObject(perDriveways.ObjectId, OpenMode.ForRead) as Polyline;

                    //get all point crossing running line
                    Point3dCollection ptscoll = getIntersectionPoints();

                    // if the points did not intersect the running line return
                    if (ptscoll == null)
                    {
                        return;
                    }



                    if (_runningLine != null)
                    {
                        // we will assume that line only intersect one time for now!!!!! FIX THIS LATER
                        bool isOn = isPointOnRunningLine(_runningLine, ptscoll);

                        //find the polyline segment using distance at point
                        //getRunningLineSegment()


                        //if they intercept then create the offset line and so forth

                        ed.WriteMessage(
                            "Selected point is {0} on the curve.",
                            isOn ? ptscoll[0].ToString() : "not"
                            );

                        if (isOn)
                        {
                            createPolyline2(ptscoll);
                            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                            //foreach (DBObject dbo in createBoreSymbol(ptscoll))
                            //{

                            //  //////////////////////blkTblRec.AppendEntity();
                            //  acTrans.AddNewlyCreatedDBObject(dbo, true);

                            //}
                        }
                    }
                    // Save the changes and dispose of the transaction
                    acTrans.Commit();
                }
            }

            return;
        }
        static public void Plan2CalcFlaSelVolAtts()
        {
            try
            {
                if (Plan2Ext.Flaeche.TheCalcAreaPalette == null)
                {
                    return;
                }


                Document doc = Application.DocumentManager.MdiActiveDocument;
                log.DebugFormat("Dokumentname: {0}.", doc.Name);
                if (doc == null)
                {
                    return;
                }

                using (DocumentLock m_doclock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
                    if (doc == null)
                    {
                        return;
                    }
                    Editor ed = doc.Editor;


#if NEWSETFOCUS
                    Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Window.Focus();
#else
                    Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif

                    PromptEntityResult per = ed.GetNestedEntity("\nHöhenattribut wählen: ");
                    if (per.Status == PromptStatus.OK)
                    {
                        using (Transaction tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }

                            Plan2Ext.Flaeche.TheCalcAreaPalette.SetHeightAttribut(ar.Tag);

                            tr.Commit();
                        }
                    }
                    per = ed.GetNestedEntity("\nVolumsattribut wählen: ");
                    if (per.Status == PromptStatus.OK)
                    {
                        using (Transaction tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }

                            Plan2Ext.Flaeche.TheCalcAreaPalette.SetVolAttribut(ar.Tag);

                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2CalcFlaSelVolAtts aufgetreten! {0}", ex.Message));
            }
        }
        //返回选中对象的扩展数据
        public static List <string> ObjectXData()
        {
            //扩展数据容器
            List <string> XDataList = new List <string>();

            Editor   ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //下面的操作用来选择实体来显示它的扩展数据
                PromptEntityOptions opt = new PromptEntityOptions("请选择实体来显示它的扩展数据");
                PromptEntityResult  res = ed.GetEntity(opt);
                if (res.Status != PromptStatus.OK)
                {
                    return(XDataList);
                }
                Entity ent = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                //判断实体的类型 点 线 面

                //点
                if (ent.GetType().Name.ToString() == "DBPoint")
                {
                    DBPoint Selectent = (DBPoint)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    //扩展数据
                    ResultBuffer xdata = Selectent.XData;
                    if (xdata != null)
                    {
                        foreach (TypedValue entXData in xdata)
                        {
                            string DataItem = entXData.TypeCode + "- - - - - -" + entXData.Value;
                            XDataList.Add(DataItem);
                        }
                    }
                }

                //直线
                if (ent.GetType().Name.ToString() == "Line")
                {
                    Line Selectent = (Line)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    //扩展数据
                    ResultBuffer xdata = Selectent.XData;
                    if (xdata != null)
                    {
                        foreach (TypedValue entXData in xdata)
                        {
                            string DataItem = entXData.TypeCode + "- - - - - -" + entXData.Value;
                            XDataList.Add(DataItem);
                        }
                    }
                }

                //多段线
                if (ent.GetType().Name.ToString() == "Polyline")
                {
                    Polyline Selectent = (Polyline)trans.GetObject(res.ObjectId, OpenMode.ForWrite);
                    bool     closed    = Selectent.Closed;
                    //多段线闭合 围成了面积
                    if (closed == true)
                    {
                        //扩展数据
                        ResultBuffer xdata = Selectent.XData;
                        if (xdata != null)
                        {
                            foreach (TypedValue entXData in xdata)
                            {
                                string DataItem = entXData.TypeCode + "- - - - - -" + entXData.Value;
                                XDataList.Add(DataItem);
                            }
                        }
                    }
                    else
                    {
                        //不能围成面
                        return(XDataList);
                    }
                }
            }
            return(XDataList);
        }
        private void btSelBlo_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();

            Editor   ed  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            PromptEntityOptions optSel = new PromptEntityOptions("\nSelect a block: ");

            optSel.SetRejectMessage("\nMust be a Block...");
            optSel.AddAllowedClass(typeof(BlockReference), true);
            PromptEntityResult ProSelRes = ed.GetEntity(optSel);

            switch (ProSelRes.Status)
            {
            case PromptStatus.OK:
                //Criate Wblock
                Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
                using (db)
                {
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            BlockReference br = (BlockReference)trans.GetObject(ProSelRes.ObjectId, OpenMode.ForRead);
                            objIdColl.Clear();
                            objIdColl.Add(br.ObjectId);
                            BlockTableRecord btr = new BlockTableRecord();
                            if (br.IsDynamicBlock)
                            {
                                btr = (BlockTableRecord)trans.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead);
                            }
                            else
                            {
                                btr = (BlockTableRecord)trans.GetObject(br.BlockTableRecord, OpenMode.ForRead);
                            }


                            //Define LocalDWG
                            _bDbIsInExternalDWG = false;
                            //Define SelectionIsABlock
                            _SelectionIsABlock = true;
                            //Set Thumbnail
                            _objBlockModNew.btmImage = GetBitmap();
                            //Set Selection Text
                            tblObjSelDesc.Text = "Block \"" + btr.Name + "\" selected.";
                            //Set Name
                            _objBlockModNew.Name = btr.Name;
                            //Set Pick Point
                            tbX.Text = btr.Origin.X.ToString();
                            tbY.Text = btr.Origin.Y.ToString();
                            tbZ.Text = btr.Origin.Z.ToString();

                            //Desable fields
                            tbName.IsEnabled = false;
                            tbX.IsEnabled    = false;
                            tbY.IsEnabled    = false;
                            tbZ.IsEnabled    = false;
                            btPick.IsEnabled = false;

                            //Set Properties
                            //Angle
                            _objBlockModNew.LstBlockProp[0].Angle = ArCaUtils.RadianToDegree(br.Rotation);
                            //Scale
                            _objBlockModNew.LstBlockProp[0].SclX = br.ScaleFactors.X;
                            _objBlockModNew.LstBlockProp[0].SclY = br.ScaleFactors.Y;
                            _objBlockModNew.LstBlockProp[0].SclZ = br.ScaleFactors.Z;
                        }
                        catch (System.Exception ex)
                        {
                            trans.Abort();
                        }
                    }
                }

                break;

            case PromptStatus.Cancel:
                //Command Canceled
                break;
            }
            this.Show();
        }
Exemple #7
0
        public override void Add()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            var intensity1 = ed.GetString(new PromptStringOptions("Nhap gia tri luc cua diem dau tien"));

            if (intensity1.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc.");
                return;
            }

            var intensity2 = ed.GetString(new PromptStringOptions("Nhap gia tri luc cua diem sau"));

            if (intensity2.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc.");
                return;
            }

            PromptEntityResult objectId = ed.GetEntity("\nChon vat ma luc phan bo tac dong vao");

            if (objectId.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc phan bo.");
                return;
            }

            PromptPointResult point1 = ed.GetPoint(new PromptPointOptions("\nChon cac diem dat luc dau tien"));

            if (point1.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc phan bo.");
                return;
            }

            PromptPointResult point2 = ed.GetPoint(new PromptPointOptions("\nChon cac diem dat luc thu hai"));

            if (point2.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc phan bo.");
                return;
            }

            PromptAngleOptions pdo = new PromptAngleOptions("\nNhap goc nghieng:");

            pdo.AllowArbitraryInput = true;
            pdo.AllowNone           = true;
            pdo.AllowZero           = true;
            pdo.DefaultValue        = 0;
            pdo.UseDefaultValue     = true;
            PromptDoubleResult angle = ed.GetAngle(pdo);

            if (angle.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nDa huy lenh them luc phan bo. Vi khong lay duoc goc.");
                return;
            }

            string partDwg = @"Drawings\DistributedLoad.dwg";

            ////////////////////////
            Point3d point  = new Point3d((point1.Value.X + point2.Value.X) / 2, (point1.Value.Y + point2.Value.Y) / 2, 0);
            double  length = Math.Sqrt(Math.Pow(point1.Value.X - point2.Value.X, 2) + Math.Pow(point1.Value.Y - point2.Value.Y, 1));

            if (Math.Round(length, Common.numberOfMathRound) == 0)
            {
                ed.WriteMessage("\nDa huy lenh them luc phân bo. Vì kich thuoc khong the trung nhau.");
                return;
            }
            Scale3d scale = new Scale3d(Common.scale, length / Common.lengthOfDistributedLoad, 1);

            if (Common.InsertDrawing(partDwg, scale, point, angle.Value, out ObjectId idDistributedLoad) == false)
            {
                ed.WriteMessage("\nDa huy lenh them luc phân bo. Vi khong the ve duoc ban ve.");
                return;
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Common.AddRegAppTableRecord("Data_MechanicalCalculation");
                TypedValue   typedValue = new TypedValue(1000, intensity1 + "," + intensity2 + "," + objectId.ToString() + "," + point1.Value.X + "," + point1.Value.Y + "," + point2.Value.X + "," + point2.Value.Y);
                ResultBuffer rb         = new ResultBuffer(new TypedValue(1001, "Data_MechanicalCalculation"), typedValue);
                tr.GetObject(idDistributedLoad, OpenMode.ForWrite).XData = rb;
                rb.Dispose();
                tr.Commit();
            }
        }
Exemple #8
0
        private bool GetHeightFromVermBlocks(ref double height)
        {
            DocumentCollection dm  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Document           doc = dm.MdiActiveDocument;
            Editor             ed  = doc.Editor;

#if NEWSETFOCUS
            doc.Window.Focus();
#else
            Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif


            PromptEntityResult per = ed.GetEntity("\nErsten Vermessungsblock wählen: ");

            //DocumentLock loc = dm.MdiActiveDocument.LockDocument();
            //using (loc)
            //{
            //}

            bool   blockFound = false;
            double height1    = 0.0;
            double height2    = 0.0;
            if (per.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);

                    BlockReference br = obj as BlockReference;
                    if (br == null)
                    {
                        return(false);
                    }

                    if (br.Name == "GEOINOVA")
                    {
                        blockFound = true;
                        height1    = br.Position.Z;
                        br.Highlight();
                    }

                    if (blockFound)
                    {
                        blockFound = false;
                        per        = ed.GetEntity("\nZweiten Vermessungsblock wählen: ");
                        if (per.Status == PromptStatus.OK)
                        {
                            obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            BlockReference br2 = obj as BlockReference;
                            if (br2 == null)
                            {
                                return(false);
                            }

                            if (br2.Name == "GEOINOVA")
                            {
                                blockFound = true;
                                height2    = br2.Position.Z;
                            }
                        }

                        if (blockFound)
                        {
                            height = Math.Abs(height1 - height2);
                        }

                        br.Unhighlight();
                    }

                    tr.Commit();
                }

                if (!blockFound)
                {
                    return(false);
                }
                return(true);
            }

            return(false);
        }
        private static void joinPolylines()
        {
            Document document =
                Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Editor   ed = document.Editor;
            Database db = document.Database;

            PromptEntityOptions peo1
                = new PromptEntityOptions("\nSelect source polyline : ");

            peo1.SetRejectMessage("\nInvalid selection...");

            peo1.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline),
                true
            );

            peo1.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline2d),
                true
            );

            peo1.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline3d),
                true
            );

            PromptEntityResult pEntrs = ed.GetEntity(peo1);

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

            ObjectId srcId = pEntrs.ObjectId;

            PromptEntityOptions peo2
                = new PromptEntityOptions("\nSelect polyline to join : ");

            peo2.SetRejectMessage("\nInvalid selection...");
            peo2.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline),
                true
            );

            peo2.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline2d),
                true
            );

            peo2.AddAllowedClass
            (
                typeof(Autodesk.AutoCAD.DatabaseServices.Polyline3d),
                true
            );

            pEntrs = ed.GetEntity(peo2);
            if (PromptStatus.OK != pEntrs.Status)
            {
                return;
            }

            ObjectId joinId = pEntrs.ObjectId;

            try {
                using (Transaction trans
                           = db.TransactionManager.StartTransaction()) {
                    Entity srcPLine
                        = trans.GetObject(
                              srcId,
                              OpenMode.ForRead
                              ) as Entity;

                    Entity addPLine
                        = trans.GetObject(
                              joinId,
                              OpenMode.ForRead
                              ) as Entity;

                    srcPLine.UpgradeOpen();
                    srcPLine.JoinEntity(addPLine);

                    addPLine.UpgradeOpen();
                    addPLine.Erase();

                    trans.Commit();
                }
            } catch (System.Exception ex) {
                ed.WriteMessage(ex.Message);
            }
        }
Exemple #10
0
        public void DimOfCE()
        {
            ObjectId dicId  = CreateCeDic();
            ObjectId IDofL1 = ObjectId.Null;
            ObjectId IDofL2 = ObjectId.Null;

            if (dicId != ObjectId.Null)
            {
                CurrentConfig(dicId);
                //开始选择直线
                PromptEntityOptions opt = new PromptEntityOptions("\n选择第一条直线或[更改设置(S)]:", "S");
                opt.SetRejectMessage("\n只能选择直线哦!");
                opt.AddAllowedClass(typeof(Line), true);     //必须先使用SetRejectMessage设置提示才能使用这个方法,否则会报错。
                opt.AllowObjectOnLockedLayer = true;
                opt.AllowNone = false;
                PromptEntityResult result = ed.GetEntity(opt);
                while (result.Status == PromptStatus.Keyword)
                {
                    ChangeConfig(dicId);
                    result = ed.GetEntity(opt);
                }
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }
                IDofL1 = result.ObjectId;
                IDofL2 = ChooseAnotherLine(IDofL1);
                if (IDofL2 == ObjectId.Null)
                {
                    return;
                }
            }
            //直线选择完毕
            //开始获取交点
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Line L1 = trans.GetObject(IDofL1, OpenMode.ForRead) as Line;
                    Line L2 = trans.GetObject(IDofL2, OpenMode.ForRead) as Line;
                    Point3dCollection intersectionpoints = new Point3dCollection();
                    L1.IntersectWith
                    (
                        L2,
                        Intersect.OnBothOperands,
                        intersectionpoints,
                        0,
                        0
                    );
                    while (intersectionpoints.Count == 0)
                    {
                        ed.WriteMessage("\n两条直线不相交,需要重新选择第二条直线");
                        IDofL2             = ChooseAnotherLine(IDofL1);
                        L1                 = trans.GetObject(IDofL1, OpenMode.ForRead) as Line;
                        L2                 = trans.GetObject(IDofL2, OpenMode.ForRead) as Line;
                        intersectionpoints = new Point3dCollection();
                        L1.IntersectWith
                        (
                            L2,
                            Intersect.OnBothOperands,
                            intersectionpoints,
                            0,
                            0
                        );
                    }
                    Point3d node = intersectionpoints[0];
                    //获取交点结束
                    //开始获取夹角
                    double AngleOfL1 = L1.Angle;
                    double AngleOfL2 = L2.Angle;
                    double angle     = Math.Abs(AngleOfL1 - AngleOfL2);
                    if (angle < Math.PI / 2)
                    {
                        angle = Math.PI - angle;
                    }
                    else if (angle > Math.PI)
                    {
                        angle = angle - Math.PI;
                    }
                    //获取夹角结束
                    Table tb      = (Table)trans.GetObject(CreatCeTable(dicId, node, angle), OpenMode.ForWrite);
                    jigCE jigger  = new jigCE(tb);
                    Line  drgline = new Line(jigger.basePT, jigger.basePT);
                    jigger.Leader = drgline;



                    PromptResult jigresult = ed.Drag(jigger);
                    if (jigresult.Status == PromptStatus.OK)
                    {
                        jigger.TransformEnties();
                        BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        btr.AppendEntity(jigger.Leader);
                        trans.AddNewlyCreatedDBObject(jigger.Leader, true);
                        trans.Commit();
                        //ed.WriteMessage("\n起点坐标,x={0},y={1}", jigger.basePT.X, jigger.basePT.Y);//测试用
                        //ed.WriteMessage("\n终点坐标,x={0},y={1}", jigger.dargPT.X, jigger.dargPT.Y);//测试用
                    }
                    else
                    {
                        trans.Abort();
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception EX)
                {
                    ed.WriteMessage("\n出错了!" + EX.ToString());
                }
            }
        }
        public void ShowTendonInfo()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //1.选择钢束线
                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 tdId = tdLineRes.ObjectId;
                Polyline td   = trans.GetObject(tdId, OpenMode.ForRead) as Polyline;
                //2.获取钢束线的Xrecord
                string info = "";
                #region 1.钢束名称
                if (td.ExtensionDictionary.IsNull || td.ObjectId.GetXrecord("tdName") == null)
                {
                    info += "无钢束名称信息;";
                }
                else//如果存在该键值,采用Xrecord中记录的信息
                {
                    string tdName = (string)td.ObjectId.GetXrecord("tdName")[0].Value;
                    info += "钢束名称:" + tdName + ";";
                }
                #endregion
                #region 2.钢束规格
                if (td.ExtensionDictionary.IsNull || td.ObjectId.GetXrecord("tdStyle") == null)
                {
                    info += "\n无钢束规格信息;";
                }
                else//如果存在该键值,采用Xrecord中记录的信息
                {
                    string tdStyle = (string)td.ObjectId.GetXrecord("tdStyle")[0].Value;
                    info += "\n钢束规格:" + tdStyle + ";";
                }
                #endregion
                #region 3.钢束根数
                if (td.ExtensionDictionary.IsNull || td.ObjectId.GetXrecord("tdNum") == null)
                {
                    info += "\n无钢束根数信息;";
                }
                else//如果存在该键值,采用Xrecord中记录的信息
                {
                    Int16 tdNum = (Int16)td.ObjectId.GetXrecord("tdNum")[0].Value;
                    info += "\n钢束根数:" + tdNum.ToString("F0") + ";";
                }
                #endregion
                #region 4.管道直径
                if (td.ExtensionDictionary.IsNull || td.ObjectId.GetXrecord("tdPipeDia") == null)
                {
                    info += "\n无管道直径信息;";
                }
                else//如果存在该键值,采用Xrecord中记录的信息
                {
                    double tdPipeDia = (double)td.ObjectId.GetXrecord("tdPipeDia")[0].Value;
                    info += "\n管道直径:" + tdPipeDia.ToString("F0") + " mm;";
                }
                #endregion
                #region 5.张拉方式
                if (td.ExtensionDictionary.IsNull || td.ObjectId.GetXrecord("tdDrawStyle") == null)
                {
                    info += "\n无张拉方式信息;";
                }
                else//如果存在该键值,采用Xrecord中记录的信息
                {
                    int tdDrawStyle = (Int16)td.ObjectId.GetXrecord("tdDrawStyle")[0].Value;
                    switch (tdDrawStyle)
                    {
                    case -1:    //左侧张拉
                        info += "\n张拉方式:" + "左侧张拉" + ";";
                        break;

                    case 0:    //两侧张拉
                        info += "\n张拉方式:" + "两端张拉" + ";";
                        break;

                    case 1:    //右侧张拉
                        info += "\n张拉方式:" + "右侧张拉" + ";";
                        break;
                    }
                }
                #endregion
                Application.ShowAlertDialog(info);
                trans.Commit();
            }
        }
        public void DrawingAmounts()
        {
            Document doc      = Application.DocumentManager.MdiActiveDocument;
            Database db       = doc.Database;
            Editor   ed       = doc.Editor;
            int      drwStyle = 0;                                               //张拉方式,0为两端张拉,-1为左端张拉,1为右端张拉

            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();//执行事务处理
            }
        }
        public void TendonAnnotation()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            db.SetDefaultOverallParams();//设置默认总体参数,已有总体参数字典项则无动作
            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("tdDrawStyle") != null) //如果钢束线有扩展记录则取扩展记录数据
                {
                    tdDrawStyle = (Int16)tdLine.ObjectId.GetXrecord("tdDrawStyle")[0].Value;
                }
                //获取工作长度信息
                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 = new TypedValueList();    //根据输入更新钢束线的Xrecord记录
                            values.Add(DxfCode.Int16, tdDrawStyle);
                            tdLine.ObjectId.SetXrecord("tdDrawStyle", values);
                            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 = "工作长度800";
                    //文字高度
                    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, 800);
                    //创建张拉段
                    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 = "工作长度800";
                    //文字高度
                    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();
            }
        }
Exemple #14
0
        public void MyCommand() // This method can have any name
        {
            LayerStateManager LayerState = db.LayerStateManager;
            int      viewnum             = 0;
            ObjectId SaveTableID         = InitialSave();

            if (SaveTableID == ObjectId.Null)
            {
                ed.WriteMessage("\n遇到问题,无法创建存档...");
                return;
            }
            int SaveNum = GetSave(SaveTableID);

            if (SaveNum != InitialNum)
            {
                PromptIntegerOptions InputOption = new PromptIntegerOptions("\n回车继续上次的编号,或者输入新的视图起始编号");
                InputOption.AllowNone    = true;
                InputOption.DefaultValue = SaveNum;
                PromptIntegerResult InputRes = ed.GetInteger(InputOption);
                if (InputRes.Status != PromptStatus.OK)
                {
                    return;
                }
                viewnum = InputRes.Value;
            }
            else
            {
                PromptIntegerResult numres = ed.GetInteger("\n输入视图起始编号");
                if (numres.Status != PromptStatus.OK)
                {
                    return;
                }
                viewnum = numres.Value;
            }
            int counter = 0;

            while (true)
            {
inputstart:
                PromptEntityOptions ops = new PromptEntityOptions("\n选择视图框");
                ops.SetRejectMessage("\n只能选择封闭的矩形!");
                ops.AddAllowedClass(typeof(Polyline), true);
                ops.AllowNone = false;
                ops.AllowObjectOnLockedLayer = true;
                PromptEntityResult res = ed.GetEntity(ops);
                if (res.Status != PromptStatus.OK)
                {
                    if (counter != 0)
                    {
                        UpdateSave(SaveTableID, viewnum);
                    }
                    ed.WriteMessage("\n共创建{0}个视图。", counter);
                    break;
                }
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        Polyline PL = trans.GetObject(res.ObjectId, OpenMode.ForRead) as Polyline;
                        if (PL.NumberOfVertices != 4 && !PL.Closed)
                        {
                            ed.WriteMessage("\n选择的不是封闭的矩形!");
                            goto inputstart;
                        }
                        Point3d  P1 = PL.GetPoint3dAt(0);
                        Point3d  P2 = PL.GetPoint3dAt(1);
                        Point3d  P3 = PL.GetPoint3dAt(2);
                        Point3d  P4 = PL.GetPoint3dAt(3);
                        Vector3d V1 = P1.GetVectorTo(P2);
                        Vector3d V2 = P2.GetVectorTo(P3);
                        Vector3d V3 = P3.GetVectorTo(P4);
                        Vector3d V4 = P4.GetVectorTo(P1);
                        if (!(V1.IsPerpendicularTo(V2) && V2.IsPerpendicularTo(V3) && V3.IsPerpendicularTo(V4)))
                        {
                            ed.WriteMessage("\n选择的不是封闭的矩形!");
                            goto inputstart;
                        }
                        Point2d CT = new Point2d((P1.X + P3.X) / 2, (P1.Y + P3.Y) / 2);
                        double  H  = 1;
                        double  W  = 1;

                        if (V1.Length > V4.Length)
                        {
                            H = V4.Length;
                            W = V1.Length;
                        }
                        else
                        {
                            H = V1.Length;
                            W = V4.Length;
                        }


                        Vector2d UserXaxix  = new Vector2d(db.Ucsxdir.X, db.Ucsxdir.Y);
                        Vector2d WXaxix     = new Vector2d(1, 0);
                        double   TwistAngle = WXaxix.GetAngleTo(UserXaxix);
                        if (db.Ucsxdir.Y > 0)
                        {
                            TwistAngle = Math.PI * 2 - WXaxix.GetAngleTo(UserXaxix);
                        }

                        //Matrix2d WCS2DCS = Matrix2d.Rotation(new Vector2d(1, 0).GetAngleTo(UserXaxix),new Point2d(0,0));
                        Matrix2d WCS2DCS   = Matrix2d.Rotation(TwistAngle, new Point2d(0, 0));
                        Point3d  UcsCenter = db.Ucsorg;
                        //Point2d DcsCenter = new Point2d(UcsCenter.X, UcsCenter.Y).TransformBy(TransWCSToDCS);
                        Point2d DcsCenter = CT.TransformBy(WCS2DCS);

                        /*
                         * ed.WriteMessage("\n计算旋转角:{0}", WXaxix.GetAngleTo(UserXaxix));
                         * ed.WriteMessage("\nTwistAngle:{0}", TwistAngle);
                         * ed.WriteMessage("\nWCS的中点:{0}", CT.ToString());
                         * ed.WriteMessage("\nUCS的中点:{0}", new Point3d(CT.X,CT.Y,0).TransformBy(ed.CurrentUserCoordinateSystem).ToString());
                         * ed.WriteMessage("\nDCS的中点:{0}", DcsCenter.ToString());
                         */


                        SymbolTable VT = trans.GetObject(db.ViewTableId, OpenMode.ForWrite) as SymbolTable;
                        if (VT.Has(viewnum.ToString()))
                        {
                            foreach (ObjectId viewid in VT)
                            {
                                ViewTableRecord VR = trans.GetObject(viewid, OpenMode.ForWrite) as ViewTableRecord;
                                if (VR.Name == viewnum.ToString())
                                {
                                    VR.Erase();
                                    break;
                                }
                            }
                        }
                        ViewTableRecord NewVr = new ViewTableRecord();
                        NewVr.Name = viewnum.ToString();

                        NewVr.CenterPoint = DcsCenter;
                        NewVr.Height      = H;
                        NewVr.Width       = W;
                        NewVr.ViewTwist   = TwistAngle;
                        NewVr.SetUcs(db.Ucsorg, db.Ucsxdir, db.Ucsydir);
                        VT.Add(NewVr);
                        trans.AddNewlyCreatedDBObject(NewVr, true);
                        //添加图层快照属性要在把view添加到数据库里后再操作,要不会报错eNoDataBase...
                        string LayerStateName = string.Format("ACAD_VIEWS_{0}", NewVr.Name);
                        //已有同名那就删掉
                        if (LayerState.HasLayerState(LayerStateName))
                        {
                            LayerState.DeleteLayerState(LayerStateName);
                        }
                        LayerState.SaveLayerState(LayerStateName, LayerStateMasks.None, new ObjectId());
                        NewVr.LayerState = LayerStateName;
                        trans.Commit();
                        ed.WriteMessage("\n成功创建编号为{0}的视图。", viewnum);
                        viewnum++;
                        counter++;
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception EX)
                    {
                        ed.WriteMessage("\n出错了!{0}", EX.ToString());
                    }
                    finally
                    {
                        trans.Dispose();
                    }
                }
            }
        }
Exemple #15
0
        //update in tehran 7/15
        public void DrawDisconnector()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            System.Data.DataTable ParentList = Atend.Global.Acad.UAcad.DetermineParent((int)Atend.Control.Enum.ProductType.Disconnector);

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


            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)
                {
                    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 && Info1.ParentCode == Info2.ParentCode)
                        {
                            DrawDisconnectorJig _DrawDisconnectorJig = new DrawDisconnectorJig(MyScale);
                            List <Entity>       ents = _DrawDisconnectorJig.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)));

                            if (SaveDisConnectorData())
                            {
                                ObjectIdCollection OIC = new ObjectIdCollection();
                                //ed.WriteMessage("go for each\n");
                                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());
                                    Atend.Global.Acad.AcadJigs.MyLine terminal = ent as Atend.Global.Acad.AcadJigs.MyLine;
                                    if (terminal != null)
                                    {
                                        object ProductType = null;
                                        if (terminal.AdditionalDictionary.TryGetValue("ProductType", out ProductType))
                                        {
                                            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);

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

                                ObjectId GOI = Atend.Global.Acad.Global.MakeGroup(DisConnectorPack.Code.ToString(), OIC);

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


                                ObjectId TextOi = Atend.Global.Acad.UAcad.DrawEntityOnScreen(
                                    Atend.Global.Acad.UAcad.WriteNote(eDisConnector.Comment,
                                                                      _DrawDisconnectorJig.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  = DisConnectorPack.Code.ToString();
                                textInfo.NodeType    = (int)Atend.Control.Enum.ProductType.Comment;
                                textInfo.ProductCode = 0;
                                textInfo.Insert();

                                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();

                                Atend.Base.Acad.AT_SUB.AddToAT_SUB(GOI, per.ObjectId);
                                Atend.Base.Acad.AT_SUB.AddToAT_SUB(GOI, per1.ObjectId);
                            }
                        } //if (drs1.Length != 0)
                    }     //if (per1.Status == PromptStatus.OK)
                }         //if (drs.Length != 0)
            }             //if (per.Status == PromptStatus.OK )
        }
Exemple #16
0
        public static void GeneratePolyline3dFromLevels()
        {
            HousingExtensionApplication.Current.Logger.LogCommand(typeof(PolylineCommands), nameof(GeneratePolyline3dFromLevels));

            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            using var trans = db.TransactionManager.StartTransaction();

            var initial = LevelBlockHelper.GetPromptedBlockDetails(Resources.Command_Prompt_SelectInitialBlock, ed, trans);

            if (!initial.IsValid)
            {
                return;
            }

            var points = new List <Point3d> {
                initial.Point3d
            };
            var nextLevel = true;

            var options = new PromptEntityOptions(Resources.Command_Prompt_SelectNextBlock);

            options.SetRejectMessage(Resources.Command_Prompt_RejectBlockReference);
            options.AddAllowedClass(typeof(BlockReference), true);
            options.AppendKeywordsToMessage = true;

            foreach (var keyword in PolylineOptions)
            {
                options.Keywords.Add(keyword);
            }

            PromptEntityResult result = null;

            while (nextLevel)
            {
                nextLevel = false;
                result    = ed.GetEntity(options);

                if (result.Status == PromptStatus.OK)
                {
                    var details = new LevelBlockDetails(LevelBlockHelper.GetBlockReference(result.ObjectId, trans));
                    if (!details.IsValid)
                    {
                        HousingExtensionApplication.Current.Logger.Entry(Resources.Message_Invalid_Level_Block_Selected, Severity.Warning);
                        return;
                    }

                    if (points.Any(p => p.Y.Equals(details.Point3d.Y) && p.X.Equals(details.Point3d.X) && p.Z.Equals(details.Point3d.Z)))
                    {
                        HousingExtensionApplication.Current.Logger.Entry(Resources.Message_Block_Already_Selected, Severity.Information);
                    }
                    else
                    {
                        points.Add(details.Point3d);
                    }

                    nextLevel = true;
                }
            }

            var close = false;

            if (result.Status == PromptStatus.Keyword)
            {
                close = result.StringResult == PolylineOptions[0];
            }

            CreatePolyline3dFromPoints(db, points, close);

            trans.Commit();
        }
Exemple #17
0
 private static void handle_promptEntityResult(object sender, PromptEntityResultEventArgs e)
 {
     useThisEntityResult = e.Result;
 }
Exemple #18
0
        private bool SelectBlock()
        {
            _CurrentBlock = ObjectId.Null;
            Editor ed = _AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions entopts = new PromptEntityOptions("\nRaumblock wählen: ");

            entopts.SetRejectMessage(string.Format(CultureInfo.CurrentCulture, _NoRaumblockMessage, Blockname));
            entopts.AddAllowedClass(typeof(BlockReference), true);
            //entopts.Message = "Pick an entity of your choice from the drawing";
            PromptEntityResult ent = null;
            //ADDED INPUT CONTEXT REACTOR

            bool ret = false;
            var  ok  = false;

            while (!ok)
            {
                //ed.PromptingForEntity += new PromptEntityOptionsEventHandler(handle_promptEntityOptions);
                //ed.PromptedForEntity += new PromptEntityResultEventHandler(handle_promptEntityResult);

                try
                {
                    //ent = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity("Get Object ");
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("\nKein gültiges Elemente gewählt!");
                }
                finally
                {
                    //ed.PromptingForEntity -= new PromptEntityOptionsEventHandler(handle_promptEntityOptions);
                    //ed.PromptedForEntity -= new PromptEntityResultEventHandler(handle_promptEntityResult);
                }

                if (ent.Status != PromptStatus.OK)
                {
                    ok  = true;
                    ret = false;
                }
                else
                {
                    ObjectId entid = ent.ObjectId;
                    using (Transaction myT = _TransMan.StartTransaction())
                    {
                        Entity         entity   = (Entity)_TransMan.GetObject(entid, OpenMode.ForRead);
                        BlockReference blockRef = entity as BlockReference;
                        if (string.Compare(blockRef.Name, Blockname, StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            ed.WriteMessage(string.Format(CultureInfo.CurrentCulture, _NoRaumblockMessage, Blockname));
                        }
                        else
                        {
                            _CurrentBlock = entid;
                            ok            = true;
                            ret           = true;
                        }

                        myT.Commit();
                    }
                }
            }
            return(ret);
        }
        // based on article by Wayne Brill
        // http://adndevblog.typepad.com/autocad/2012/06/use-getclosestpointto-and-onsegat-to-locate-a-polyline-vertex-near-a-point.html
        //[CommandMethod("oseg")]
        public static void TEST_PointOnPoly()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            CoordinateSystem3d cs = ed.CurrentUserCoordinateSystem.CoordinateSystem3d;

            Plane plan = new Plane(Point3d.Origin, cs.Zaxis);

            Application.SetSystemVariable("osmode", 512);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Entity ename;

                    Point3d pt;

                    Point3d ptWcs;

                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect Pline: ");

                    peo.SetRejectMessage("\nYou have to select LWPOLYLINE!");

                    peo.AddAllowedClass(typeof(Polyline), false);

                    PromptEntityResult res = ed.GetEntity(peo);

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

                    ObjectId id = res.ObjectId;

                    // Convert to WCS incase selection was made

                    // while in a UCS.

                    pt = res.PickedPoint;

                    // Transform from UCS to WCS

                    Matrix3d mat =

                        Matrix3d.AlignCoordinateSystem(

                            Point3d.Origin,

                            Vector3d.XAxis,

                            Vector3d.YAxis,

                            Vector3d.ZAxis,

                            cs.Origin,

                            cs.Xaxis,

                            cs.Yaxis,

                            cs.Zaxis

                            );

                    ptWcs = pt.TransformBy(mat);

                    ename = tr.GetObject(id, OpenMode.ForRead) as Entity;

                    Polyline pline = ename as Polyline;

                    if (pline == null)
                    {
                        ed.WriteMessage("\nSelected Entity is not a Polyline");

                        return;
                    }

                    Point3d clickpt = pline.GetClosestPointTo(ptWcs, false);

                    for (int c = 0; c < pline.NumberOfVertices; c++)
                    {
                        double segParam = new double();

                        // This is the test filter here...it uses the

                        // nifty API OnSegmentAt

                        if (pline.OnSegmentAt(c, clickpt.Convert2d(plan), segParam))
                        {
                            ed.WriteMessage("\nSelected Segment: {0} \n", c + 1);

                            break;
                        }
                    }
                }

                catch (System.Exception ex)
                {
                    ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
                }
            }
        }
Exemple #20
0
        public void GenegateUnigineSpline()
        {
            Document adoc = Application.DocumentManager.MdiActiveDocument;

            if (adoc == null)
            {
                return;
            }

            Database db = adoc.Database;

            Editor ed = adoc.Editor;

            try
            {
                //выбрать 3d полилинию
                PromptEntityOptions peo1 = new PromptEntityOptions("\nВыберите 3D полилинию");
                peo1.SetRejectMessage("\nМожно выбрать только 3D полилинию");
                peo1.AddAllowedClass(typeof(Polyline3d), true);
                PromptEntityResult per1 = ed.GetEntity(peo1);
                if (per1.Status != PromptStatus.OK)
                {
                    return;
                }

                //создание данных для сериализации
                UnigineSpline unigineSpline = new UnigineSpline();
                Point3d       center        = Point3d.Origin;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    Polyline3d poly = tr.GetObject(per1.ObjectId, OpenMode.ForRead) as Polyline3d;
                    if (poly == null)
                    {
                        return;
                    }

                    ObjectId[] verts = poly.Cast <ObjectId>().ToArray();

                    List <Point3d> pts = new List <Point3d>(verts.Length);
                    for (int i = 0; i < verts.Length; i++)
                    {
                        PolylineVertex3d vt      = tr.GetObject(verts[i], OpenMode.ForRead) as PolylineVertex3d;
                        Point3d          point3d = vt.Position;
                        pts.Add(point3d);
                    }

                    //найти среднюю точку
                    foreach (Point3d pt in pts)
                    {
                        center = center.Add(new Vector3d(pt.X, pt.Y, pt.Z));
                    }
                    center = center.DivideBy(pts.Count);

                    for (int i = 0; i < pts.Count; i++)
                    {
                        pts[i] = pts[i].Subtract(new Vector3d(center.X, center.Y, center.Z));
                    }


                    List <Vector3d> tangents = new List <Vector3d>(verts.Length);
                    tangents.Add((pts[1] - pts[0]).GetNormal());
                    for (int i = 1; i < verts.Length - 1; i++)
                    {
                        Vector3d tangent = ((pts[i + 1] - pts[i]).GetNormal()
                                            + (pts[i] - pts[i - 1]).GetNormal()).GetNormal();
                        tangents.Add(tangent);
                    }
                    tangents.Add((pts[verts.Length - 1] - pts[verts.Length - 2]).GetNormal());

                    for (int i = 0; i < verts.Length; i++)
                    {
                        unigineSpline.points.Add(new double[] { pts[i].X, pts[i].Y, pts[i].Z });

                        if (i > 0)
                        {
                            //тангенсы должны быть по модулю примерно 1/4 от расстояния между точками
                            double   mult = (pts[i] - pts[i - 1]).Length / 4;
                            Vector3d tan0 = tangents[i - 1] * mult;
                            Vector3d tan1 = -tangents[i] * mult;

                            //сегмент
                            UnigineSegment segment = new UnigineSegment()
                            {
                                start_index   = i - 1,
                                start_tangent = new double[] { tan0.X, tan0.Y, tan0.Z },
                                start_up      = new double[] { 0, 0, 1 },
                                end_index     = i,
                                end_tangent   = new double[] { tan1.X, tan1.Y, tan1.Z },
                                end_up        = new double[] { 0, 0, 1 },
                            };
                            unigineSpline.segments.Add(segment);
                        }
                    }

                    if (poly.Closed || pts[0].IsEqualTo(pts[verts.Length - 1]))
                    {
                        UnigineSegment lastSeg  = unigineSpline.segments.Last();
                        UnigineSegment firstSeg = unigineSpline.segments.First();

                        if (pts[0].IsEqualTo(pts[verts.Length - 1]))
                        {
                            //замыкающий сегмент привязывается к стартовой точке

                            lastSeg.end_index = 0;

                            //тангенсы в стартовой точке
                            Vector3d tan = ((pts[1] - pts[0]).GetNormal()
                                            + (pts[verts.Length - 1] - pts[verts.Length - 2]).GetNormal()).GetNormal();
                            Vector3d tanLast = -tan * (pts[lastSeg.end_index] - pts[lastSeg.start_index]).Length / 4;
                            lastSeg.end_tangent = new double[] { tanLast.X, tanLast.Y, tanLast.Z };


                            Vector3d tanFirst = tan * (pts[firstSeg.end_index] - pts[firstSeg.start_index]).Length / 4;
                            firstSeg.start_tangent = new double[] { tanFirst.X, tanFirst.Y, tanFirst.Z };
                        }
                        else
                        {
                            //тангенсы в стартовой и последней точке
                            Point3d  lastPt   = pts[verts.Length - 1];
                            Point3d  firstPt  = pts[0];
                            Vector3d tanStart = ((pts[1] - firstPt).GetNormal()
                                                 + (firstPt - lastPt).GetNormal()).GetNormal();
                            Vector3d tanEnd = ((firstPt - lastPt).GetNormal()
                                               + (lastPt - pts[verts.Length - 2]).GetNormal()).GetNormal();

                            Vector3d tanLast = -tanEnd * (pts[lastSeg.end_index] - pts[lastSeg.start_index]).Length / 4;
                            lastSeg.end_tangent = new double[] { tanLast.X, tanLast.Y, tanLast.Z };

                            Vector3d tanFirst = tanStart * (pts[firstSeg.end_index] - pts[firstSeg.start_index]).Length / 4;
                            firstSeg.start_tangent = new double[] { tanFirst.X, tanFirst.Y, tanFirst.Z };

                            //замыкающий сегмент
                            double   mult = (firstPt - lastPt).Length / 4;
                            Vector3d tan0 = tanEnd * mult;
                            Vector3d tan1 = -tanStart * mult;

                            UnigineSegment segment = new UnigineSegment()
                            {
                                start_index   = verts.Length - 1,
                                start_tangent = new double[] { tan0.X, tan0.Y, tan0.Z },
                                start_up      = new double[] { 0, 0, 1 },
                                end_index     = 0,
                                end_tangent   = new double[] { tan1.X, tan1.Y, tan1.Z },
                                end_up        = new double[] { 0, 0, 1 },
                            };
                            unigineSpline.segments.Add(segment);
                        }
                    }


                    tr.Commit();
                }


                //сериализация
                //TODO: Сделать выбор папки
                if (unigineSpline.segments.Count > 0)
                {
                    string fileName = Common.Utils.GetNonExistentFileName(Path.GetDirectoryName(adoc.Name),
                                                                          center.ToString().Replace(',', '_').Substring(1, center.ToString().Length - 2), "spl");
                    using (StreamWriter file = System.IO.File.CreateText(fileName))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(file, unigineSpline);
                    }
                }
            }
            catch (System.Exception ex)
            {
                CommonException(ex, "Ошибка при создании сплайна для UNIGINE");
            }
        }
        public static void Break()
        {
            ObjectId LayerOfBreakLine;


            // Get the current document and database
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            LineSegment3d seg1 = new LineSegment3d();
            LineSegment3d seg2 = new LineSegment3d();

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Pick the line/polyline that will be broke
                PromptEntityResult acSSPrompt1 = acDoc.Editor.GetEntity("Pick the line to break");

                // If the prompt status is OK, objects were selected
                if (acSSPrompt1.Status == PromptStatus.OK)
                {
                    ObjectId obj1 = acSSPrompt1.ObjectId;

                    Entity ent1 = acTrans.GetObject(obj1, OpenMode.ForWrite) as Entity;
                    LayerOfBreakLine = ent1.LayerId;
                    switch (obj1.ObjectClass.DxfName)
                    {
                    case "LINE":
                        Line ln1 = new Line();
                        ln1 = (Line)ent1;

                        seg1 = new LineSegment3d(new Point3d(ln1.StartPoint.X, ln1.StartPoint.Y, ln1.StartPoint.Z), new Point3d(ln1.EndPoint.X, ln1.EndPoint.Y, ln1.EndPoint.Z));

                        break;

                    case "LWPOLYLINE":
                        Polyline pln1 = new Polyline();
                        pln1 = (Polyline)ent1;

                        //loops through each segment of the polyline and finds which one our user selected point resides on
                        for (int x = 0; x < pln1.NumberOfVertices; x++)
                        {
                            //converts a 3d point to 2d point that would be on the 2d polyline
                            Point2d temppt = pln1.GetClosestPointTo(acSSPrompt1.PickedPoint, false).Add(pln1.StartPoint.GetAsVector()).Convert2d(pln1.GetPlane());
                            //then checks if that 2d point resides on the current segment being looked at
                            if (pln1.OnSegmentAt(x, temppt, 0.00))
                            {
                                seg1 = pln1.GetLineSegmentAt(x);
                                break;
                            }
                        }
                        break;
                    }
                    // Pick the line/polyline that intersects with the line to be broke
                    PromptEntityResult acSSPrompt2 = acDoc.Editor.GetEntity("Pick the intersecting line");

                    // If the prompt status is OK, objects were selected
                    if (acSSPrompt2.Status == PromptStatus.OK)
                    {
                        ObjectId obj2 = acSSPrompt2.ObjectId;

                        Entity ent2 = acTrans.GetObject(obj2, OpenMode.ForWrite) as Entity;

                        switch (obj2.ObjectClass.DxfName)
                        {
                        case "LINE":
                            Line ln2 = new Line();
                            ln2 = (Line)ent2;

                            seg2 = new LineSegment3d(new Point3d(ln2.StartPoint.X, ln2.StartPoint.Y, ln2.StartPoint.Z), new Point3d(ln2.EndPoint.X, ln2.EndPoint.Y, ln2.EndPoint.Z));

                            break;

                        case "LWPOLYLINE":
                            Polyline pln2 = new Polyline();
                            pln2 = (Polyline)ent2;

                            for (int x = 0; x < pln2.NumberOfVertices; x++)
                            {
                                Point2d temppt = pln2.GetClosestPointTo(acSSPrompt2.PickedPoint, false).Add(pln2.StartPoint.GetAsVector()).Convert2d(pln2.GetPlane());
                                if (pln2.OnSegmentAt(x, temppt, 0.00))
                                {
                                    seg2 = pln2.GetLineSegmentAt(x);
                                    break;
                                }
                            }
                            break;
                        }
                        //checks if the line segments actually intersect
                        //also checks if the line segment are the same
                        //both cases would cause AutoCAD to crash if the code was allowed to run
                        if (seg1.IntersectWith(seg2) != null || (seg1.Equals(seg2)))
                        {
                            //gets the start and endpoint of the segment selected
                            Point2d pt1 = new Point2d(seg1.StartPoint.X, seg1.StartPoint.Y);
                            Point2d pt2 = new Point2d(seg1.EndPoint.X, seg1.EndPoint.Y);

                            //with those two points we can calculate the angle of the first segment
                            double angle1 = pt1.GetVectorTo(pt2).Angle;
                            double angle2 = pt2.GetVectorTo(pt1).Angle;

                            //get the point where the two segments intersect
                            Point3d[] intersectpoint = seg1.IntersectWith(seg2);
                            Point3d   center         = intersectpoint[0];

                            //using the centerpoint and the angle, calculate the vector of where to break the line segment
                            Point3d point1 = new Point3d(center.X + .125 * Math.Cos(angle1), center.Y + .125 * Math.Sin(angle1), 0);
                            Point3d point2 = new Point3d(center.X + .125 * Math.Cos(angle2), center.Y + .125 * Math.Sin(angle2), 0);

                            BlockTable acBlkTbl;
                            acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;
                            BlockTableRecord acBlkTbleRec;
                            acBlkTbleRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                            //ready to replace the original line/polyline with two new entities
                            switch (obj1.ObjectClass.DxfName)
                            {
                            case "LINE":
                                ent1.Erase(true);

                                Line newline1 = new Line(new Point3d(seg1.StartPoint.X, seg1.StartPoint.Y, seg1.StartPoint.Z), point2);
                                Line newline2 = new Line(point1, new Point3d(seg1.EndPoint.X, seg1.EndPoint.Y, seg1.EndPoint.Z));

                                newline1.LayerId = LayerOfBreakLine;
                                newline2.LayerId = LayerOfBreakLine;

                                acBlkTbleRec.AppendEntity(newline1);
                                acBlkTbleRec.AppendEntity(newline2);
                                acTrans.AddNewlyCreatedDBObject(newline1, true);
                                acTrans.AddNewlyCreatedDBObject(newline2, true);


                                break;

                            case "LWPOLYLINE":
                                Polyline oldpl = new Polyline();
                                oldpl = (Polyline)ent1;

                                //create the first polyline on one side of the break
                                Polyline newpl1 = new Polyline();
                                newpl1.LayerId = LayerOfBreakLine;
                                for (int x = 0; seg1.EndPoint != oldpl.GetPoint3dAt(x); x++)
                                {
                                    newpl1.AddVertexAt(x, oldpl.GetPoint2dAt(x), 0, 0, 0);
                                }
                                //add end point
                                newpl1.AddVertexAt(newpl1.NumberOfVertices, new Point2d(point2.X, point2.Y), 0, 0, 0);



                                //create the second polyline at the other side of the break
                                Polyline newpl2 = new Polyline();
                                newpl2.LayerId = LayerOfBreakLine;

                                int i = 0;      //for tracking the index of our new polyline
                                //start at the end of the old polyline and work our way backwards to the break point
                                for (int x = oldpl.NumberOfVertices - 1; seg1.StartPoint != oldpl.GetPoint3dAt(x); x--)
                                {
                                    newpl2.AddVertexAt(i, oldpl.GetPoint2dAt(x), 0, 0, 0);
                                    i++;
                                }
                                //add end point
                                newpl2.AddVertexAt(i, new Point2d(point1.X, point1.Y), 0, 0, 0);

                                //erases the old polyline and adds the new two polylines to the database
                                ent1.Erase(true);
                                acBlkTbleRec.AppendEntity(newpl1);
                                acBlkTbleRec.AppendEntity(newpl2);
                                acTrans.AddNewlyCreatedDBObject(newpl1, true);
                                acTrans.AddNewlyCreatedDBObject(newpl2, true);

                                break;
                            }
                            //commit everything
                            acTrans.Commit();
                        }
                    }
                }
            }
        }
    /// <summary>
    /// Let user select a wall and override one display properties of this wall.
    /// User can see the different display of this wall.
    /// </summary>
    public void DisplayPropertiesWallSample()
    {
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDisplay Properties Wall Sample:\n");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n");

        Database db = Application.DocumentManager.MdiActiveDocument.Database;

        //MaterialUtility.
        TransactionManager tm    = db.TransactionManager;
        Transaction        trans = tm.StartTransaction();
        Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;

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

            PromptEntityResult resEnt = ed.GetEntity(optEnt);
            if (resEnt.Status != PromptStatus.OK)
            {
                throw new System.Exception("Selection error - aborting");
            }

            Wall pickedWall = trans.GetObject(resEnt.ObjectId, OpenMode.ForWrite) as Wall;

            DisplayRepresentationManager displayManager = new DisplayRepresentationManager(db);
            ObjectIdCollection           ids            = displayManager.GetDisplayRepresentationIdsFromCurrentViewport(RXClass.GetClass(typeof(Wall)));

            ObjectId activeDisplayRepId = ids[0];

            DisplayPropertiesWallPlan wallProperties = new DisplayPropertiesWallPlan();

            wallProperties.SubSetDatabaseDefaults(db);
            wallProperties.SetToStandard(db);
            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();

            DisplayComponent[] components = wallProperties.GetDisplayComponents(out sc);
            int index = -1;
            for (int i = 0; i < sc.Count; i++)
            {
                string componentName = sc[i];
                //Here, we override the display properties for "shrink wrap" and display it on the screen.
                if (componentName == "Shrink Wrap")
                {
                    index = i;
                    break;
                }
            }
            if (index == -1)
            {
                throw new System.Exception("Lack of display component.");
            }

            DisplayComponentEntity component = components[index] as DisplayComponentEntity;
            component.IsApplicable  = true;
            component.IsVisible     = true;
            component.ByMaterial    = false;
            component.ColorIndex    = 30;
            component.LinetypeScale = 2;
            component.LineWeight    = LineWeight.LineWeight070;

            ObjectId dispWallId = Override.AddToOverrideExtensionDictionaryAndClose(pickedWall, wallProperties);
            OverrideDisplayProperties overrideProperties = new OverrideDisplayProperties();
            overrideProperties.ViewId            = activeDisplayRepId;
            overrideProperties.DisplayPropertyId = dispWallId;
            pickedWall.Overrides.Add(overrideProperties);

            trans.Commit();
        }
        catch (System.Exception e)
        {
            trans.Abort();
            ed.WriteMessage("\n" + e.Message + "\n");
        }
    }
Exemple #23
0
    public void TestMethod()
    {
        Document activeDoc = Application.DocumentManager.MdiActiveDocument;
        Database db        = activeDoc.Database;
        Editor   ed        = activeDoc.Editor;

        PromptEntityOptions peo = new PromptEntityOptions("Select a polyline : ");

        peo.SetRejectMessage("Not a polyline");
        peo.AddAllowedClass(typeof(Autodesk.AutoCAD.DatabaseServices.Polyline), true);

        PromptEntityResult per = ed.GetEntity(peo);

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

        ObjectId plOid = per.ObjectId;

        PromptPointResult ppr = ed.GetPoint(new PromptPointOptions("Select an internal point : "));

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

        Point3d testPoint = ppr.Value;

        PromptAngleOptions pao

            = new PromptAngleOptions("Specify ray direction");

        pao.BasePoint = testPoint;

        pao.UseBasePoint = true;

        PromptDoubleResult rayAngle = ed.GetAngle(pao);

        if (rayAngle.Status != PromptStatus.OK)
        {
            return;
        }
        Point3d tempPoint = testPoint.Add(Vector3d.XAxis);

        tempPoint = tempPoint.RotateBy(rayAngle.Value, Vector3d.ZAxis, testPoint);

        Vector3d rayDir = tempPoint - testPoint;

        ClearTransientGraphics();
        _markers = new DBObjectCollection();
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            Curve plcurve = tr.GetObject(plOid, OpenMode.ForRead) as Curve;

            for (int cnt = 0; cnt < 2; cnt++)
            {
                if (cnt == 1)
                {
                    rayDir = rayDir.Negate();
                }

                using (Ray ray = new Ray())
                {
                    ray.BasePoint = testPoint;

                    ray.UnitDir = rayDir;
                    Point3dCollection intersectionPts = new Point3dCollection();

                    plcurve.IntersectWith(ray, Intersect.OnBothOperands, intersectionPts, IntPtr.Zero, IntPtr.Zero);

                    foreach (Point3d pt in intersectionPts)
                    {
                        Circle marker = new Circle(pt, Vector3d.ZAxis, 0.2);
                        marker.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(0, 255, 0);
                        _markers.Add(marker);

                        IntegerCollection intCol = new IntegerCollection();

                        TransientManager tm = TransientManager.CurrentTransientManager;
                        tm.AddTransient(marker, TransientDrawingMode.Highlight, 128, intCol);

                        ed.WriteMessage("\n" + pt.ToString());
                    }
                }
            }

            tr.Commit();
        }
    }
        private void btnSelectBlock_Click(object sender, EventArgs e)
        {
            try
            {
                _AcAp.DocumentCollection dm  = _AcAp.Application.DocumentManager;
                _AcAp.Document           doc = dm.MdiActiveDocument;
                Editor ed = doc.Editor;

#if NEWSETFOCUS
                _AcAp.Application.DocumentManager.MdiActiveDocument.Window.Focus();
#else
                Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif

                PromptEntityResult per = ed.GetEntity("\nRaumblock wählen: ");

                //DocumentLock loc = dm.MdiActiveDocument.LockDocument();
                //using (loc)
                //{
                //}

                if (per.Status == PromptStatus.OK)
                {
                    Transaction tr = doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        DBObject       obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                        BlockReference br  = obj as BlockReference;
                        if (br == null)
                        {
                            return;
                        }

                        txtBlockname.Text = Plan2Ext.Globs.GetBlockname(br, tr);
                        tr.Commit();
                    }

                    per = ed.GetNestedEntity("\nFlächen-Attribut wählen: ");
                    if (per.Status == PromptStatus.OK)
                    {
                        tr = doc.TransactionManager.StartTransaction();
                        using (tr)
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }
                            txtAttribute.Text = ar.Tag;
                            tr.Commit();
                        }
                    }

                    txtPeriAtt.Text = "";
                    per             = ed.GetNestedEntity("\nUmfang-Attribut wählen: ");
                    if (per.Status == PromptStatus.OK)
                    {
                        tr = doc.TransactionManager.StartTransaction();
                        using (tr)
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }
                            txtPeriAtt.Text = ar.Tag;
                            tr.Commit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _AcAp.Application.ShowAlertDialog(ex.Message);
            }
        }
Exemple #25
0
        public void PoolExcavation()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

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

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

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

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

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

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

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

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

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

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

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

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

                    tr.Commit();
                }
        }
Exemple #26
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
            TransactionManager tm =
                AcadApp.DocumentManager.MdiActiveDocument.Database.TransactionManager;

            // Get the AutoCAD editor
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.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 = tm.StartTransaction())
                {
                    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 = (Part)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());
                    }
                }
            }
        }
Exemple #27
0
        public static void JigCircle()
        {
            PromptPointResult resultp = ed.GetPoint("\n指定第一个顶点");

            if (resultp.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d basePt = resultp.Value;

            resultp = ed.GetCorner("\n指定另一个顶点", basePt);
            if (resultp.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d  cornerPt = resultp.Value;
            Point2d  point1   = new Point2d(basePt.X, basePt.Y);
            Point2d  point2   = new Point2d(cornerPt.X, cornerPt.Y);
            Polyline polyline = new Polyline();

            Transaction(polyline, point1, point2);

            Point3d point3d2 = new Point3d(basePt.X, cornerPt.Y, 0); //第一个顶点竖下对着的点
            Point3d point3d3 = new Point3d(cornerPt.X, basePt.Y, 0); //第一个顶点横着对着的点


            CreatePL();


            PromptEntityOptions m_peo = new PromptEntityOptions("\n请选择第一条曲线:");
            PromptEntityResult  m_per = ed.GetEntity(m_peo);

            if (m_per.Status != PromptStatus.OK)
            {
                return;
            }
            ObjectId m_objid1 = m_per.ObjectId;

            m_peo = new PromptEntityOptions("\n请选择第二条曲线:");
            m_per = ed.GetEntity(m_peo);
            if (m_per.Status != PromptStatus.OK)
            {
                return;
            }
            ObjectId m_objid2 = m_per.ObjectId;

            using (Transaction m_tr = db.TransactionManager.StartTransaction())
            {
                Curve m_cur1 = (Curve)m_tr.GetObject(m_objid1, OpenMode.ForRead);
                Curve m_cur2 = (Curve)m_tr.GetObject(m_objid2, OpenMode.ForRead);

                Point3dCollection m_ints = new Point3dCollection();
                m_cur1.IntersectWith(m_cur2, Intersect.OnBothOperands, new Plane(), m_ints, IntPtr.Zero, IntPtr.Zero); //得出的所有交点在c1曲线上
                foreach (Point3d m_pt in m_ints)
                {
                    ed.WriteMessage("\n第一条曲线与第二条曲线交点:{0}", m_pt);

                    if (PtInPolygon1(m_pt, polyline) == 0)
                    {
                        ed.WriteMessage($"\n该点在矩形上,{PtInPolygon1(m_pt, polyline)}");
                    }
                    else if (PtInPolygon1(m_pt, polyline) == 1)
                    {
                        ed.WriteMessage($"\n该点在矩形内,{PtInPolygon1(m_pt, polyline)}");
                    }
                    else if (PtInPolygon1(m_pt, polyline) == -1)
                    {
                        ed.WriteMessage($"\n该点在矩形外,{PtInPolygon1(m_pt, polyline)}");
                    }
                }

                m_tr.Commit();
            }


            demo();


            //    ed.WriteMessage($"第一个点:{basePt},第二个点:{point3d3},第三个点:{cornerPt},第四个点:{point3d2}," +
            //    $"第一个交点:{ PLL(basePt, point3d2, ptStart, ptEnd)}" +
            //    $"第二个交点:{PLL(basePt,point3d3,ptStart,ptEnd)}");



            //ed.WriteMessage($"端点:{PLL(basePt, point3d2, ptStart, ptEnd)},夹角:" +
            //    $"{Angle(PLL(basePt, point3d2, ptStart, ptEnd),basePt, PLL(basePt, point3d3, ptStart, ptEnd))}");
        }
Exemple #28
0
        public void ProfileCreator()
        {
            //prompt the user for running line
            PromptEntityOptions promptEntity = new PromptEntityOptions("\nPlease Select Running Line: ");

            promptEntity.SetRejectMessage("Line selected is not a polyline!!");
            promptEntity.AddAllowedClass(typeof(Polyline), true);

            PromptEntityResult entityResult = document.Editor.GetEntity(promptEntity);

            if (entityResult.Status != PromptStatus.OK)
            {
                document.Editor.WriteMessage("Error: Please select a Polyline.");
                return;
            }

            Transaction tr = database.TransactionManager.StartTransaction();
            //Save the polyline
            Polyline runningLine = null;

            using (tr)
            {
                runningLine = tr.GetObject(entityResult.ObjectId, OpenMode.ForRead) as Polyline;
            }

            //create the grid for the profile
            Grid grid = null;

            try
            {
                grid = new Grid(4, runningLine.Length);
                grid.Draw();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                document.Editor.WriteMessage("error creating grid;" + ex.Message);
            }

            if (grid != null)
            {
                grid.SaveGrid();
            }


            Point3d gradeLineInsPt = grid.InsertionPoint;
            //create a vector to generate the starting point for the gradeline..It 80' from -25 to 0
            Point3d  origin = new Point3d(0, 0, 0);
            Matrix3d matrix = Matrix3d.Displacement(origin.GetVectorTo(new Point3d(0, 100, 0)));

            gradeLineInsPt = gradeLineInsPt.TransformBy(matrix);

            Polyline    gradeLine = new Polyline();
            Transaction trans     = database.TransactionManager.StartTransaction();

            using (trans)
            {
                BlockTable       bt  = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;


                gradeLine.AddVertexAt(0, new Point2d(gradeLineInsPt.X, gradeLineInsPt.Y), 0, 0, 0);
                gradeLine.AddVertexAt(1, new Point2d((gradeLineInsPt.X + runningLine.Length), gradeLineInsPt.Y), 0, 0, 0);
                gradeLine.Layer = "PROFILE";

                btr.AppendEntity(gradeLine);
                trans.AddNewlyCreatedDBObject(gradeLine, true);
                trans.Commit();
            }

            //vertice to create selection fence use runningLine
            SelectionSet selectionSet = CreateFenceUsingPolyline(runningLine, false);

            //if any objects selected
            if (selectionSet != null)
            {
                //find objects that intersect with runningLine
                var objCrossingRunningLine = CrossingRunnngLine(selectionSet, runningLine, gradeLineInsPt);

                Point3dCollection bocPoints = new Point3dCollection();

                //draw profile objects if any
                if (objCrossingRunningLine != null)
                {
                    foreach (var obj in objCrossingRunningLine)
                    {
                        //draw profiles objects of Type = boc
                        if (obj.Type == "boc")
                        {
                            bocPoints.Add(obj.Center);
                        }
                        else
                        {
                            DrawProfileObjects(obj);
                        }
                    }
                }

                if (bocPoints.Count != 0)
                {
                    //convert to array to sort
                    Point3d[] point3s = new Point3d[bocPoints.Count];
                    bocPoints.CopyTo(point3s, 0);
                    Array.Sort(point3s, new sort3dByX());

                    Point3dCollection bocPtsSorted = new Point3dCollection(point3s);

                    DrawProfileDriveway(bocPtsSorted, gradeLine.Length);
                }



                //find boc intersect
                //var bocCrossingRunningLine =
            }

            //bore line
            Polyline bore = gradeLine.GetOffsetCurves(14)[0] as Polyline;

            DrawBoreLine(bore);

            //find intercepting profile objects using fence and filter for only ellipses
            SelectionSet utilitiesCrossingBore = CreateFenceUsingPolyline(bore, true);

            //if any profile ellipses selected
            if (utilitiesCrossingBore != null)
            {
                //DrawBoreBelowUtilities(utilitiesCrossingBore, bore.ObjectId);
            }
        }
Exemple #29
0
        public static void testAttributedBlockInsert()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // change block name to your suit

            PromptEntityOptions pEnOpt = new PromptEntityOptions("\nPick Block Reference:");
            pEnOpt.SetRejectMessage("\nObject Not Block Reference");
            pEnOpt.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult pEnRes = ed.GetEntity(pEnOpt);
            ObjectId EntId = pEnRes.ObjectId;
            //PromptResult pr = ed.GetString("\nType Block Name: ");
            //string blockName = pr.StringResult;
            string blockName = null;
            BlockReference UserBlockref = null;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                UserBlockref = (BlockReference)trans.GetObject(EntId, OpenMode.ForRead);
                blockName = UserBlockref.Name;
            }
            Matrix3d ucs = ed.CurrentUserCoordinateSystem;
            //get current UCS matrix
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // to force update drawing screen
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);

                    // if the block table doesn't already exists, exit
                    if (!bt.Has(blockName))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Block " + blockName + " does not exist.");
                        return;
                    }

                    // insert the block in the current space
                    PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                    if (ppr.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    DBObjectCollection dbobjcoll = ed.TraceBoundary(ppr.Value, false);
                    Double area = 0;
                    try
                    {
                        if (dbobjcoll.Count > 0)
                        {
                            BlockTableRecord blockTableRecmSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                            ObjectIdCollection traceObjIds = new ObjectIdCollection();
                            foreach (DBObject obj in dbobjcoll)
                            {
                                Entity EntTrace = obj as Entity;
                                if (EntTrace != null)
                                {
                                    if (EntTrace is Polyline)
                                    {
                                        Polyline p = (Polyline)EntTrace;
                                        if (p.Closed)
                                        {
                                            area = p.Area;
                                        }

                                    }
                                    if (EntTrace is Line)
                                    {
                                        Line Ln = (Line)EntTrace;
                                        if (Ln.Closed)
                                        {
                                            area = Ln.Area;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    string presisi = "#";
                    switch (db.Auprec)
                    {
                        case 0:
                            presisi = "#";
                            break;
                        case 1:
                            presisi = "#0.0";
                            break;
                        case 2:
                            presisi = "#0.00";
                            break;
                        case 3:
                            presisi = "#0.000";
                            break;
                        case 4:
                            presisi = "#0.0000";
                            break;
                        case 5:
                            presisi = "#0.00000";
                            break;
                        default:
                            presisi = "#0.00";
                            break;
                    }

                    valueAreaBoundary = area.ToString(presisi);

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                    List<string> ListTag = new List<string>();
                    List<string> ListString = new List<string>();

                    Point3d pt = ppr.Value;
                    BlockReference bref = new BlockReference(pt, bt[blockName]);

                    Dictionary<string, string> dic = GetAttributDef(bref.BlockTableRecord, tr);
                    foreach (KeyValuePair<string, string> item in dic)
                    {
                        ListTag.Add(item.Key.ToUpper().ToString());
                        // string[] info = item.Value.Split('|');
                    }
                    formUserInputAttribut frmInput = new formUserInputAttribut();
                    IntPtr handle = AcAp.MainWindow.Handle;
                    if (frmInput.ShowDialog(ListTag) == System.Windows.Forms.DialogResult.OK)
                    {
                        ListString.AddRange(frmInput.InputString);
                    }
                    else { return; }

                    bref.Rotation = frmInput.UseRotation ? UserBlockref.Rotation : 0.0;

                    bref.TransformBy(ucs);
                    bref.AddContext(occ.CurrentContext);
                    //add blockreference to current space
                    btr.AppendEntity(bref);
                    tr.AddNewlyCreatedDBObject(bref, true);
                    // set attributes to desired values

                    ApplyAttibutes(db, tr, bref, ListTag, ListString);

                    bref.RecordGraphicsModified(true);
                    // to force updating a block reference
                    tr.TransactionManager.QueueForGraphicsFlush();
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
            }
            finally
            {
                // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Pokey")
            }
        }
Exemple #30
0
 private static void handle_promptEntityResult(object sender, PromptEntityResultEventArgs e)
 {
     useThisEntityResult = e.Result;
 }
Exemple #31
0
        public void Bisector()
        {
            Document            doc = Application.DocumentManager.MdiActiveDocument;
            Database            db  = doc.Database;
            Editor              ed  = doc.Editor;
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect the first line: ");

            peo.SetRejectMessage("Selected object is not a line !");
            peo.AddAllowedClass(typeof(Line), true);
            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d  p1  = per.PickedPoint.TransformBy(ed.CurrentUserCoordinateSystem);
            ObjectId id1 = per.ObjectId;

            peo.Message = "\nSelect the second line: ";
            per         = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d  p2  = per.PickedPoint.TransformBy(ed.CurrentUserCoordinateSystem);
            ObjectId id2 = per.ObjectId;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Line l1 = (Line)tr.GetObject(id1, OpenMode.ForRead);
                Line l2 = (Line)tr.GetObject(id2, OpenMode.ForRead);

                // Checks if lines intersect
                Plane  plane;
                Line3d line1 = new Line3d(l1.StartPoint, l1.EndPoint);
                Line3d line2 = new Line3d(l2.StartPoint, l2.EndPoint);
                if (!line1.IsCoplanarWith(line2, out plane) || line1.IsParallelTo(line2))
                {
                    return;
                }

                // Calculates the bisector
                Point3d  inters = line1.IntersectWith(line2)[0];
                Vector3d vec1   = line1.Direction;
                Vector3d vec2   = line2.Direction;
                // Corrects the vectors direction according to picked points
                if (vec1.DotProduct(inters.GetVectorTo(p1)) < 0)
                {
                    vec1 = vec1.Negate();
                }
                if (vec2.DotProduct(inters.GetVectorTo(p2)) < 0)
                {
                    vec2 = vec2.Negate();
                }
                Vector3d bisectDir = (vec1 + vec2) / 2.0;

                // Draws the bisector (XLine)
                Xline xline = new Xline();
                xline.UnitDir   = bisectDir.GetNormal();
                xline.BasePoint = inters;
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(xline);
                tr.AddNewlyCreatedDBObject(xline, true);
                tr.Commit();
            }
        }