/// <summary>
        /// Get the list of surfaces and search by name
        /// </summary>
        /// <param name="name">Name of surface to search.
        /// Case sensitive.</param>
        /// <returns>ObjectId of the surface</returns>
        public static ObjectId GetSurfaceId(string name)
        {
            Database db = Application.DocumentManager.
                          MdiActiveDocument.Database;

            using (Transaction trans = db.
                                       TransactionManager.StartTransaction())
            {
                CivilDocument      civilDoc   = CivilApplication.ActiveDocument;
                ObjectIdCollection surfaceIds = civilDoc.GetSurfaceIds();
                foreach (ObjectId surfaceId in surfaceIds)
                {
                    CivilSurface surface =
                        trans.GetObject(surfaceId, OpenMode.ForRead)
                        as CivilSurface;
                    if (surface.Name == name)
                    {
                        return(surface.ObjectId);
                    }
                }
            }
            return(ObjectId.Null);
        }
Ejemplo n.º 2
0
 public bool AddStandardBoundary(ObjectId polyId, string name, ObjectId surfaceId)
 {
     try
     {
         PasteSurfaces pasteSurfaces = new PasteSurfaces();
         var           db            = CivilApplicationManager.WorkingDatabase;
         var           doc           = CivilDocument.GetCivilDocument(db);
         using (Transaction tr = db.TransactionManager.StartTransaction())
         {
             C3DLandDb.TinSurface surface = surfaceId.GetObject(OpenMode.ForRead) as C3DLandDb.TinSurface;
             //surface.UpgradeOpen();
             pasteSurfaces.AddStandardBoundary(polyId, name, surface);
             //surface.DowngradeOpen();
             tr.Commit();
         }
         return(true);
     }
     catch (Exception ex)
     {
         MessengerManager.MessengerManager.LogException(ex);
     }
     return(false);
 }
Ejemplo n.º 3
0
        public static Site ByName(string siteName)
        {
            CivilDocument      civilDocument = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            Site               site          = null;
            ObjectIdCollection siteIds       = civilDocument.GetSiteIds();

            //get the current document and database
            AcadApp.Document doc = AcadApp.Application.DocumentManager.MdiActiveDocument;
            Database         db  = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId objectId in siteIds)
                {
                    site = new Site((Autodesk.Civil.DatabaseServices.Entity)trans.GetObject(objectId, OpenMode.ForRead), true);
                    if (site.Name != siteName)
                    {
                        site = null;
                    }
                }
            }
            return(site);
        }
Ejemplo n.º 4
0
        public static Alignment ByName(string alignmentName)
        {
            CivilDocument      civilDocument = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            Alignment          alignment     = null;
            ObjectIdCollection alignIds      = civilDocument.GetAlignmentIds();

            //get the current document and database
            AcadApp.Document doc = AcadApp.Application.DocumentManager.MdiActiveDocument;
            Database         db  = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId objectId in alignIds)
                {
                    alignment = new Alignment((Autodesk.Civil.DatabaseServices.Entity)trans.GetObject(objectId, OpenMode.ForRead), false);
                    if (alignment.Name != alignmentName)
                    {
                        alignment = null;
                    }
                }
            }
            return(alignment);
        }
Ejemplo n.º 5
0
    /// <summary>
    /// Get the ObjectId for the given profile style name
    /// </summary>
    public static ObjectId GetProfileStyleId(Document document, string styleName)
    {
        if (document == null)
        {
            return(ObjectId.Null);
        }
        if (string.IsNullOrEmpty(styleName))
        {
            return(ObjectId.Null);
        }

        var db  = document.AcDocument.Database;
        var doc = CivilDocument.GetCivilDocument(db);

        var styleId = ObjectId.Null;

        if (doc.Styles.ProfileStyles.Contains(styleName))
        {
            styleId = doc.Styles.ProfileStyles[styleName];
        }

        return(styleId);
    }
Ejemplo n.º 6
0
        setPoint(this Point3d pnt3d, string nameLayer = "CPNT-ON")
        {
            ObjectId id = ObjectId.Null;

            Layer.manageLayers(nameLayer);
            CivilDocument civDOC = CivilApplication.ActiveDocument;

            id = civDOC.CogoPoints.Add(pnt3d, true);
            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    CogoPoint cogoPnt = (CogoPoint)id.GetObject(OpenMode.ForWrite);
                    cogoPnt.PointName = cogoPnt.PointNumber.ToString();
                    if (nameLayer != null)
                    {
                        try
                        {
                            cogoPnt.Layer = nameLayer;
                        }
                        catch (System.Exception ex)
                        {
                            BaseObjs.writeDebug(string.Format("{0} Pnt.cs: line: 203", ex.Message));
                        }
                        cogoPnt.RawDescription = nameLayer;
                        cogoPnt.LabelStyleId   = Pnt_Style.getPntLabelStyle(nameLayer);
                        cogoPnt.PointName      = nameLayer + cogoPnt.PointNumber;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(string.Format("{0} Pnt.cs: line: 214", ex.Message));
            }
            return(id);
        }
        public static List <BaseC3dObject> GetAlignmentStyles()
        {
            Document      doc      = Application.DocumentManager.MdiActiveDocument;
            Database      db       = doc.Database;
            CivilDocument civilDoc = CivilApplication.ActiveDocument;

            Autodesk.Civil.DatabaseServices.Styles.AlignmentStyleCollection aliStyles = civilDoc.Styles.AlignmentStyles;
            List <BaseC3dObject> aliStylesList = new List <BaseC3dObject>();

            if (aliStyles.Count == 0)
            {
                return(null);
            }
            else
            {
                using (Transaction ts = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        foreach (ObjectId id in aliStyles)
                        {
                            Autodesk.Civil.DatabaseServices.Styles.AlignmentStyle aliStyle =
                                id.GetObject(OpenMode.ForRead) as Autodesk.Civil.DatabaseServices.Styles.AlignmentStyle;
                            BaseC3dObject bObject = new BaseC3dObject();
                            bObject.Name = aliStyle.Name;
                            bObject.Id   = aliStyle.ObjectId;
                            aliStylesList.Add(bObject);
                        }
                    }
                    catch (System.Exception)
                    {
                        throw;
                    }
                }
                return(aliStylesList);
            }
        }
Ejemplo n.º 8
0
        getProfileStyles()
        {
            List <string> styles = new List <string>();
            CivilDocument civDoc = CivilApplication.ActiveDocument;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    ProfileStyleCollection profileStyles = BaseObjs._civDoc.Styles.ProfileStyles;
                    foreach (ObjectId idProfileStyle in profileStyles)
                    {
                        ProfileStyle profileStyle = (ProfileStyle)tr.GetObject(idProfileStyle, OpenMode.ForRead);
                        styles.Add(profileStyle.Name);
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(string.Format("{0} Prof_Style.cs: line: 250", ex.Message));
            }
            return(styles);
        }
Ejemplo n.º 9
0
        public static ParcelAreaTable ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            ParcelAreaTable retStyle = new ParcelAreaTable(CivilStyle.DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.TableStyles.ParcelAreaTableStyles, index), false);

            return(retStyle);
        }
        public static QTOMaterialTable ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string styleName)
        {
            QTOMaterialTable retStyle = new QTOMaterialTable(CivilStyle.DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.TableStyles.QuantityTakeoffMaterialTableStyles, styleName), false);

            return(retStyle);
        }
Ejemplo n.º 11
0
        public static void ReadICD()
        {
            // CAD指针
            CivilDocument civildoc = CivilApplication.ActiveDocument;
            Document      doc      = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb  = doc.Database;
            Editor        ed       = doc.Editor;


            PromptOpenFileOptions opt = new PromptOpenFileOptions("\n请选择线型文件.");

            opt.Filter = "ICD File (*.icd)|*.icd|All files (*.*)|*.*";
            PromptFileNameResult res = ed.GetFileNameForOpen(opt);

            if (res.Status != PromptStatus.OK)
            {
                return;
            }
            SRBA.PM bill = new SRBA.PM(res.StringResult);

            // 转化平曲线
            ObjectId AlgID = Alignment.Create(civildoc, Path.GetFileNameWithoutExtension(res.StringResult), null, "0", "Basic", "All Labels");

            using (Transaction ts = acCurDb.TransactionManager.StartTransaction())
            {
                Alignment myAg = ts.GetObject(AlgID, OpenMode.ForWrite) as Alignment;
                AddICD(ref myAg, ref bill, ref ed);
                myAg.ReferencePointStation = bill.StartPK;
                //ed.WriteMessage("\n{0}读取成功.", res.StringResult);


                // 竖曲线
                PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("\n是否加载竖曲线?");
                pKeyOpts.Keywords.Add("Y");
                pKeyOpts.Keywords.Add("N");
                pKeyOpts.Keywords.Default = "Y";
                pKeyOpts.AllowNone        = true;
                PromptResult pKeyRes = doc.Editor.GetKeywords(pKeyOpts);
                switch (pKeyRes.Status)
                {
                case PromptStatus.OK:
                    if (pKeyRes.StringResult == "Y")
                    {
                        SRBA.SQX kitty      = new SRBA.SQX(Path.ChangeExtension(res.StringResult, "SQX"));
                        ObjectId layerId    = myAg.LayerId;
                        ObjectId styleId    = civildoc.Styles.ProfileStyles["Basic"];
                        ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"];
                        ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId);
                        Profile  oProfile   = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile;

                        AddSQX(ref oProfile, ref kitty, ref ed);
                    }
                    break;

                default:
                    break;
                }


                // 转化对比JD法
                //pKeyOpts = new PromptKeywordOptions("\n是否加载交点法平曲线?");
                //pKeyOpts.Keywords.Add("Y");
                //pKeyOpts.Keywords.Add("N");
                //pKeyOpts.Keywords.Default = "Y";
                //pKeyOpts.AllowNone = true;
                //pKeyRes = doc.Editor.GetKeywords(pKeyOpts);
                //switch (pKeyRes.Status)
                //{
                //    case PromptStatus.OK:
                //        if (pKeyRes.StringResult == "Y")
                //        {

                //            PQXnew kitty = new PQXnew("Test");
                //            kitty.ReadICDFile(res.StringResult);
                //            ObjectId layerId = myAg.LayerId;
                //            ObjectId styleId = civildoc.Styles.ProfileStyles["Basic"];
                //            ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"];
                //            ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId);
                //            Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile;

                //            AddPQX( 0,24000,500, ref acCurDb, ref kitty, ref ed);
                //        }
                //        break;
                //    default:
                //        break;
                //}



                ts.Commit();
            }
        }
        public static TangentIntersectionLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            TangentIntersectionLabel retLabel = new TangentIntersectionLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.AlignmentLabelStyles.TangentIntersectionLabelStyles, labelStyleName), false);

            return(retLabel);
        }
        public static TangentIntersectionLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            TangentIntersectionLabel retLabel = new TangentIntersectionLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.AlignmentLabelStyles.TangentIntersectionLabelStyles, index), false);

            return(retLabel);
        }
        public static void ExportReport()
        {
            Document      acadDoc = Application.DocumentManager.MdiActiveDocument;
            CivilDocument civDoc  = CivilApplication.ActiveDocument;

            List <MainPoint> mainPointCol = new List <MainPoint>();

            using (Transaction ts = acadDoc.Database.TransactionManager.StartTransaction())
            {
                // JSON に出力した線形名を取得
                dynamic inputParams = JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(".\\AlignmentNameForReport.json"));
                string  alignName   = inputParams.name;

                // 線形を取得
                Alignment align = civDoc.GetAlignmentIds().Cast <ObjectId>()
                                  .Select(item => (Alignment)ts.GetObject(item, OpenMode.ForRead))
                                  .First(item => item.Name == alignName);

                // 線形の測点インデックス増分値を取得
                double stationIndexIncrement = align.StationIndexIncrement;

                // 線形の Entity オブジェクトを取得 -> 測点の順番で並べ替え
                IEnumerable <AlignmentCurve> alignCurveOrderedCol = align.Entities.Cast <AlignmentCurve>().OrderBy(item => item.StartStation);

                // 各測点の MainPoint オブジェクトを mainPointCol に追加
                int lineIndex = 0;
                int scsIndex  = 0;

                foreach (AlignmentCurve alignCurve in alignCurveOrderedCol)
                {
                    switch (alignCurve.EntityType)
                    {
                    case AlignmentEntityType.Line:
                        AlignmentLine alignLine = alignCurve as AlignmentLine;
                        mainPointCol.Add(new MainPoint(alignLine, lineIndex, stationIndexIncrement));
                        lineIndex += 1;
                        break;

                    case AlignmentEntityType.SpiralCurveSpiral:
                        AlignmentSCS alignSCS = alignCurve as AlignmentSCS;
                        mainPointCol.Add(new MainPoint(alignSCS.SpiralIn, scsIndex, stationIndexIncrement)
                        {
                        });
                        mainPointCol.Add(new MainPoint(alignSCS.Arc, scsIndex, stationIndexIncrement)
                        {
                        });
                        mainPointCol.Add(new MainPoint(alignSCS.SpiralOut, scsIndex, stationIndexIncrement)
                        {
                        });
                        scsIndex += 1;
                        break;

                    default:
                        return;
                    }

                    try { _ = alignCurve.EntityAfter; }
                    catch (EntityNotFoundException ex)
                    {
                        AlignmentLine alignLine = alignCurve as AlignmentLine;
                        mainPointCol.Add(new MainPoint(alignLine, -1, stationIndexIncrement)
                        {
                        });
                    }
                }

                ts.Commit();
            }

            List <string> header = new List <string>()
            {
                "主要点名称", "測点", "X 座標", "Y 座標", "要素長", "接線角", "始点半径", "終点半径", "パラメータ A"
            };

            string excelFilePath = ".\\Report.xlsx";

            using (XLWorkbook workbook = new XLWorkbook())
            {
                IXLWorksheet worksheet = workbook.AddWorksheet("Sheet1");
                worksheet.Cell("A1").InsertData(header, true);
                worksheet.Cell("A2").InsertData(mainPointCol);
                workbook.SaveAs(excelFilePath);
            }
        }
Ejemplo n.º 15
0
        public static SurfaceWatershedLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            SurfaceWatershedLabel retLabel = new SurfaceWatershedLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.SurfaceLabelStyles.WatershedLabelStyles, labelStyleName), false);

            return(retLabel);
        }
Ejemplo n.º 16
0
        public static SurveyFigureLineLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            SurveyFigureLineLabel retLabel = new SurveyFigureLineLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.GetSurveyLabelStyles().LineLabelStyles, labelStyleName), false);

            return(retLabel);
        }
Ejemplo n.º 17
0
        public static SectionGradeBreakLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            SectionGradeBreakLabel retLabel = new SectionGradeBreakLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.SectionLabelStyles.GradeBreakLabelStyles, labelStyleName), false);

            return(retLabel);
        }
Ejemplo n.º 18
0
        public static SectionGradeBreakLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            SectionGradeBreakLabel retLabel = new SectionGradeBreakLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.SectionLabelStyles.GradeBreakLabelStyles, index), false);

            return(retLabel);
        }
        public static DesignSpeedLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            DesignSpeedLabel retLabel = new DesignSpeedLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.AlignmentLabelStyles.DesignSpeedLabelStyles, labelStyleName), false);

            return(retLabel);
        }
        public static DesignSpeedLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            DesignSpeedLabel retLabel = new DesignSpeedLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.AlignmentLabelStyles.DesignSpeedLabelStyles, index), false);

            return(retLabel);
        }
Ejemplo n.º 21
0
        public static SurfaceUserDefinedContourTable ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string styleName)
        {
            SurfaceUserDefinedContourTable retStyle = new SurfaceUserDefinedContourTable(CivilStyle.DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.TableStyles.SurfaceUserDefinedContourTableStyles, styleName), false);

            return(retStyle);
        }
Ejemplo n.º 22
0
        public static ParcelAreaTable ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string styleName)
        {
            ParcelAreaTable retStyle = new ParcelAreaTable(CivilStyle.DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.TableStyles.ParcelAreaTableStyles, styleName), false);

            return(retStyle);
        }
Ejemplo n.º 23
0
        public static SurfaceWatershedLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            SurfaceWatershedLabel retLabel = new SurfaceWatershedLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.SurfaceLabelStyles.WatershedLabelStyles, index), false);

            return(retLabel);
        }
        public static GeneralNoteLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            GeneralNoteLabel retLabel = new GeneralNoteLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.GeneralNoteLabelStyles, labelStyleName), false);

            return(retLabel);
        }
Ejemplo n.º 25
0
        public static SurveyFigureLineLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            SurveyFigureLineLabel retLabel = new SurveyFigureLineLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.GetSurveyLabelStyles().LineLabelStyles, index), false);

            return(retLabel);
        }
        public void SurfaceMeshByBoundary()
        {
            Document adoc = Application.DocumentManager.MdiActiveDocument;

            if (adoc == null)
            {
                return;
            }

            Database db = adoc.Database;

            DB = db;

            Editor ed = adoc.Editor;

            ED = ed;

            CivilDocument cdok = CivilDocument.GetCivilDocument(adoc.Database);


            try
            {
                Color currColor = db.Cecolor;
                if (!currColor.IsByLayer)//Если текущий слой не по слою, то расчитать более темный цвет для границ участков
                {
                    Color dimmerColor = Utils.GetDimmerColor(currColor, BORDER_DIM_MULTIPLIER);

                    ColorForBorder = dimmerColor;
                }
                else
                {
                    ColorForBorder = Color.FromColorIndex(ColorMethod.ByAci, 256);
                }


                if (!TinSurfIdIsValid())
                {
                    //Выбрать поверхность
                    if (!PickTinSurf(ed))
                    {
                        return;//Если выбор не успешен, прервать выполнение
                    }
                }
                //Подсветить поверхность
                HighlightTinSurf(true);


                //Запрос ключевых слов
                while (true)
                {
                    const string kw1 = "ПОВерхность";
                    const string kw2 = "ВОЗвышение";
                    const string kw3 = "ОТКлонкниеОтДуг";
                    const string kw4 = "СОЗдаватьГраницы";

                    PromptKeywordOptions pko = new PromptKeywordOptions("\nЗадайте параметры или пустой ввод для продолжения");
                    pko.Keywords.Add(kw1);
                    pko.Keywords.Add(kw2);
                    pko.Keywords.Add(kw3);
                    pko.Keywords.Add(kw4);
                    pko.AllowNone = true;
                    PromptResult pr = ed.GetKeywords(pko);
                    if (pr.Status == PromptStatus.Cancel)
                    {
                        return;
                    }

                    if (String.IsNullOrEmpty(pr.StringResult))
                    {
                        break;
                    }

                    switch (pr.StringResult)
                    {
                    case kw1:
                        if (!PickTinSurf(ed))
                        {
                            return;
                        }
                        break;

                    case kw2:
                        if (!GetMeshElevation(ed))
                        {
                            return;
                        }
                        break;

                    case kw3:
                        if (!GetApproxParam(ed))
                        {
                            return;
                        }
                        break;

                    case kw4:
                        if (!GetCreateBorders(ed))
                        {
                            return;
                        }

                        break;
                    }
                }


                //Проверка текущего набора выбора
                acSSet = null;
                PromptSelectionResult acSSPrompt;
                acSSPrompt = ed.SelectImplied();
                if (acSSPrompt.Status == PromptStatus.OK)
                {
                    acSSet = acSSPrompt.Value;
                }
                else
                {
                    //Множественный выбор блоков
                    TypedValue[] tv = new TypedValue[]
                    {
                        new TypedValue(0, "INSERT")
                    };
                    SelectionFilter flt = new SelectionFilter(tv);


                    PromptSelectionOptions pso = new PromptSelectionOptions();
                    pso.MessageForAdding = "\nВыберите блоки участков";

                    acSSPrompt = adoc.Editor.GetSelection(pso, flt);
                    if (acSSPrompt.Status == PromptStatus.OK)
                    {
                        acSSet = acSSPrompt.Value;
                    }
                }

                if (acSSet != null)
                {
                    Common.Timer timerMain = new Common.Timer();
                    timerMain.Start();
                    foreach (SelectedObject acSSObj in acSSet)
                    {
                        string       blockName = null;
                        Common.Timer timer     = new Common.Timer();
                        timer.Start();
                        try
                        {
                            if (acSSObj != null)
                            {
                                //полилинии внутри блока
                                List <ObjectId> polylines      = new List <ObjectId>();
                                BlockReference  blockReference = null;
                                ObjectId        btrId          = ObjectId.Null;
                                using (Transaction tr = db.TransactionManager.StartTransaction())
                                {
                                    //блок внутри набора выбора
                                    blockReference = tr.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as BlockReference;
                                    tr.Commit();
                                }
                                Matrix3d transform = Matrix3d.Identity;
                                if (blockReference != null)
                                {
                                    //трансформация из системы координат блока в мировую систему координат
                                    transform = blockReference.BlockTransform;

                                    //Перебор всех объектов внутри блока
                                    //Найти все правильные полилинии в блоке
                                    using (Transaction tr = db.TransactionManager.StartTransaction())
                                    {
                                        btrId = blockReference.BlockTableRecord;
                                        BlockTableRecord blockTableRecord = tr.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord;

                                        if (blockTableRecord.XrefStatus == XrefStatus.NotAnXref)
                                        {
                                            blockName = blockTableRecord.Name;
                                            foreach (ObjectId id in blockTableRecord)
                                            {
                                                using (Polyline poly = tr.GetObject(id, OpenMode.ForRead) as Polyline)
                                                {
                                                    if (poly != null &&
                                                        (poly.Closed || poly.GetPoint2dAt(0).Equals(poly.GetPoint2dAt(poly.NumberOfVertices - 1))) &&//Полилиния замкнута
                                                        !Utils.PolylineIsSelfIntersecting(poly) &&//Не имеет самопересечений
                                                        poly.Visible == true &&//Учет многовидовых блоков
                                                        poly.Bounds != null
                                                        )
                                                    {
                                                        polylines.Add(id);
                                                    }
                                                }

                                                AcadDb.Entity ent = tr.GetObject(id, OpenMode.ForRead) as AcadDb.Entity;
                                                if (ent is Polyline)
                                                {
                                                    Polyline poly = ent as Polyline;
                                                }
                                            }


                                            if (polylines.Count > 0)
                                            {
                                                //Проверить все линии на пересечение друг с другом. Удалить из списка те, которые имеют пересечения
                                                HashSet <ObjectId> polylinesWithNoIntersections = new HashSet <ObjectId>(polylines);
                                                //Сделать RBush для всех полилиний
                                                RBush <SpatialEntity> polylinesTree   = new RBush <SpatialEntity>();
                                                List <SpatialEntity>  spatialEntities = new List <SpatialEntity>();
                                                foreach (ObjectId polyId in polylines)
                                                {
                                                    spatialEntities.Add(new SpatialEntity(polyId));
                                                }
                                                polylinesTree.BulkLoad(spatialEntities);

                                                foreach (SpatialEntity se in spatialEntities)
                                                {
                                                    //Нахождение всех объектов, расположенных в пределах BoundingBox для этой полилинии
                                                    IReadOnlyList <SpatialEntity> nearestNeighbors = polylinesTree.Search(se.Envelope);
                                                    if (nearestNeighbors.Count > 1)
                                                    {
                                                        Polyline thisPoly = tr.GetObject(se.ObjectId, OpenMode.ForRead) as Polyline;

                                                        foreach (SpatialEntity n in nearestNeighbors)
                                                        {
                                                            if (!n.Equals(se))//Всегда будет находиться та же самая полилиния
                                                            {
                                                                Polyline          otherPoly = tr.GetObject(n.ObjectId, OpenMode.ForRead) as Polyline;
                                                                Point3dCollection pts       = new Point3dCollection();
                                                                thisPoly.IntersectWith(otherPoly, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);
                                                                if (pts.Count > 0)
                                                                {
                                                                    polylinesWithNoIntersections.Remove(thisPoly.Id);
                                                                    polylinesWithNoIntersections.Remove(otherPoly.Id);
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                //Аппроксимация всех полилиний, которые имеют кривизну
                                                List <Polyline> polylinesToProcess = new List <Polyline>();
                                                foreach (ObjectId polyId in polylinesWithNoIntersections)
                                                {
                                                    using (Polyline poly = tr.GetObject(polyId, OpenMode.ForRead) as Polyline)
                                                    {
                                                        polylinesToProcess.Add(ApproximatePolyBulges(poly, approxParam));//Какой допуск оптимален?
                                                    }
                                                }

                                                //Удалить все повторяющиеся подряд точки полилинии
                                                foreach (Polyline poly in polylinesToProcess)
                                                {
                                                    for (int i = 0; i < poly.NumberOfVertices;)
                                                    {
                                                        Point2d curr      = poly.GetPoint2dAt(i);
                                                        int     nextIndex = (i + 1) % poly.NumberOfVertices;
                                                        Point2d next      = poly.GetPoint2dAt(nextIndex);

                                                        if (next.IsEqualTo(curr, new Tolerance(0.001, 0.001)))//Прореживать точки, расположенные слишком близко//TODO: Учесть масштабирование блока
                                                        {
                                                            poly.RemoveVertexAt(nextIndex);
                                                        }
                                                        else
                                                        {
                                                            i++;
                                                        }
                                                    }
                                                }


                                                //Построение дерева вложенности полилиний
                                                using (TinSurface tinSurf = tr.GetObject(tinSurfId, OpenMode.ForRead) as TinSurface)
                                                {
                                                    using (PolylineNesting polylineNesting = new PolylineNesting(tinSurf))
                                                    {
                                                        foreach (Polyline poly in polylinesToProcess)
                                                        {
                                                            poly.TransformBy(transform);
                                                            polylineNesting.Insert(poly);
                                                        }

                                                        //Расчет полигонов
                                                        polylineNesting.CalculatePoligons();

                                                        //Построение сети
                                                        using (SubDMesh sdm = polylineNesting.CreateSubDMesh())
                                                        {
                                                            List <Line> lines = new List <Line>();
                                                            if (createBorders)
                                                            {
                                                                //Создание 3d линий по границе
                                                                lines = polylineNesting.CreateBorderLines();
                                                            }

                                                            //Объекты постоены в координатах пространства модели
                                                            if (sdm != null)
                                                            {
                                                                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForWrite);
                                                                if (btr.GetBlockReferenceIds(true, false).Count > 1)
                                                                {
                                                                    //Если у блока несколько вхождений, то создавать объекты в пространстве модели
                                                                    BlockTable       bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                                                                    BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                                                                    ms.AppendEntity(sdm);
                                                                    tr.AddNewlyCreatedDBObject(sdm, true);

                                                                    foreach (Line line in lines)
                                                                    {
                                                                        ms.AppendEntity(line);
                                                                        tr.AddNewlyCreatedDBObject(line, true);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    //Если у блока только одно вхождение, то создавать сеть внутри блока
                                                                    sdm.TransformBy(transform.Inverse());
                                                                    btr.AppendEntity(sdm);
                                                                    tr.AddNewlyCreatedDBObject(sdm, true);

                                                                    foreach (Line line in lines)
                                                                    {
                                                                        line.TransformBy(transform.Inverse());
                                                                        btr.AppendEntity(line);
                                                                        tr.AddNewlyCreatedDBObject(line, true);
                                                                    }
                                                                }
                                                            }

                                                            foreach (Line line in lines)
                                                            {
                                                                line.Dispose();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        tr.Commit();
                                    }
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            string message = "Возникла ошибка при обработке одного из выбранных объектов";
                            if (!String.IsNullOrEmpty(blockName))
                            {
                                message = "Возникла ошибка при обработке вхождения блока " + blockName;
                            }
                            Utils.ErrorToCommandLine(ed, message, ex);
                        }
                        timer.TimeOutput(blockName);
                    }

                    ed.WriteMessage("\n" +
                                    timerMain.TimeOutput("Затрачено времени (параметр аппроксимации - " + approxParam + ")")
                                    );

                    ed.Regen();
                }
            }
            catch (System.Exception ex)
            {
                CommonException(ex, "Ошибка при создании сетей по участкам поверхности");
            }
            finally
            {
                HighlightTinSurf(false);
            }
        }
Ejemplo n.º 27
0
        public static SectionViewTotalVolumeTable ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string styleName)
        {
            SectionViewTotalVolumeTable retStyle = new SectionViewTotalVolumeTable(CivilStyle.DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.TableStyles.SectionViewTotalVolumeTableStyles, styleName), false);

            return(retStyle);
        }
        public static SuperelevationCriticalPointsLabel ByName(Autodesk.AutoCAD.DynamoNodes.Document document, string labelStyleName)
        {
            SuperelevationCriticalPointsLabel retLabel = new SuperelevationCriticalPointsLabel(DBObjectByName(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.AlignmentLabelStyles.SuperelevationCriticalPointsLabelStyles, labelStyleName), false);

            return(retLabel);
        }
        public static void ExplodeAecObj(List <BaseC3dObject> oList)
        {
            Document      doc      = Application.DocumentManager.MdiActiveDocument;
            Database      db       = doc.Database;
            CivilDocument civilDoc = CivilApplication.ActiveDocument;
            Editor        ed       = doc.Editor;


            using (Transaction ts = db.TransactionManager.StartTransaction())
            {
                try
                {   //Patlatmaca
                    DBObjectCollection dbObjCol = new DBObjectCollection();
                    foreach (BaseC3dObject item in oList)
                    {
                        //Sadece C3D objelerini patlat
                        if (item.Name.Contains("AECC"))
                        {
                            Autodesk.Civil.DatabaseServices.Entity ent = item.Id.GetObject(OpenMode.ForRead)
                                                                         as Autodesk.Civil.DatabaseServices.Entity;
                            ent.Explode(dbObjCol);
                        }
                    }
                    //open the block table
                    BlockTable acBlkTbl;
                    acBlkTbl = ts.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                    //create the blocktablerecord
                    BlockTableRecord btr = new BlockTableRecord();
                    int    i             = 0;
                    String g             = string.Format("C3D-{0}", i.ToString());
                    //set its name
                    while (acBlkTbl.Has(g))
                    {
                        i++;
                        g = string.Format("C3D-{0}", i.ToString());
                    }

                    btr.Name = g;

                    acBlkTbl.UpgradeOpen();
                    ObjectId btrId = acBlkTbl.Add(btr);
                    ts.AddNewlyCreatedDBObject(btr, true);


                    foreach (Autodesk.AutoCAD.DatabaseServices.Entity obj in dbObjCol)
                    {
                        btr.AppendEntity(obj);
                        ts.AddNewlyCreatedDBObject(obj, true);
                    }
                    BlockTableRecord ms;
                    ms = ts.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    BlockReference br = new BlockReference(Point3d.Origin, btrId);
                    ms.AppendEntity(br);
                    ts.AddNewlyCreatedDBObject(br, true);
                    ts.Commit();
                    ed.WriteMessage("\nCreated a block named {0} from {1} selected C3D entities", g, dbObjCol.Count);
                }
                catch (System.Exception)
                {
                    throw;
                }
            }
        }
        public static GeneralNoteLabel ByIndex(Autodesk.AutoCAD.DynamoNodes.Document document, int index)
        {
            GeneralNoteLabel retLabel = new GeneralNoteLabel(DBObjectByIndex(document, CivilDocument.GetCivilDocument(document.AcDocument.Database).Styles.LabelStyles.GeneralNoteLabelStyles, index), false);

            return(retLabel);
        }