Tuesday, December 27, 2016

Splitting Polyline/Curve With AutoCAD Civil 3D Labels Associated

In the era of using plain AutoCAD, I had written routines in AutoLISP and VBA to split a polyline into individual segment (e.g. breaking polyline at each vertex). After AutoCAD .NET API came, it is even easier to do this splitting: simply calling Curve.GetSplitCurves() will gives you back all the individual segment of a polyline/curve, based in the input points on the polyline/curve; in the case of polyline, most likely these points are the polyline's vertices.

However, once we moved from plain AutoCAD to some of the AutoCAD vertical products, in my case, it was AutoCAD Map, then AutoCAD Civil, thing can get complicated. 

With AutoCAD Map, the polylines, to which we used to do splitting, may have Object Data (a kind of attribute data that can be attached to AutoCAD entity, a bit similar to XData) attached. Once the usual splitting is done the attached data is gone, because the splitting is actually creating the individual segment of the polyline as new entities and the original polyline is erased.

With AutoCAD Civil, the splitting target polyline, besides possible Object Data being attached, may also be annotated with AutoCAD Civil label. In the case of Civil label, if the entity (polyline) being labelled is erased, the label will also be erased automatically. So, when my office moved from AutoCAD Map to AutoCAD Civil a while a go, I was asked to modify our polyline splitting tool (which have already handled the attached Object Data issue as aforementioned) to retain AutoCAD Civil label, if the polyline has been labelled.

Labelling is huge part of AutoCAD Civil 3D in terms of its customization. I am still pretty new on this. It took quite some study for me to figure out a working solution, be it is optimized or not. Since there is not as much programming resources available on AutoCAD Map/Civil3D, as on plain AutoCAD, I thought sharing my solution with fellow programmers would be good thing.

Here are the requirements:

1. Split a polyline (assume it is LWPolyline for the simplicity) into individual segment at each vertices;
2. If the polyline has been annotated with labels (assume the label is general segment line/curve label), the labels in the same label style remain.

Here are the logics of the solution:

1. Determine if the polyline is annotated with labels. If yes, what the 2 label styles (for line and curve segment) are used;
2. Get all individual segments and add them into database; 
3. Erase the polyline (then the labels annotating the polyline are gone);
4. Recreate labels on each individual segment with label style determined in Step 1.

Translating the logics into code:
using System.Collections.Generic;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using CivilApp = Autodesk.Civil.ApplicationServices.CivilApplication;
using Civil = Autodesk.Civil;
using CivilDb = Autodesk.Civil.DatabaseServices;
using Autodesk.Civil.DatabaseServices.Styles;
 
[assemblyCommandClass(typeof(Civil3DLabels.PolylineSplitter))]
 
namespace Civil3DLabels
{
    public class PolylineSplitter
    {
        private const string DXF_LABEL = "AECC_GENERAL_SEGMENT_LABEL";
 
        [CommandMethod("SplitPoly")]
        public void DoSplit()
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            var ed = dwg.Editor;
            try
            {
                Split(dwg);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}", ex.Message);
                ed.WriteMessage("\n*Cancel*");
            }
 
            Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
        }
        public void Split(Document dwg)
        {
            CadDb.ObjectId polyId = SelectPolyline(dwg.Editor);
            if (polyId.IsNull) return;
 
            // If the polyline is annotated with general segmen
            // label, find the label styles (line label and curve label),
            //If not labels, both label styles are ObjectId.Null.
            CadDb.ObjectId lineLabelStyleId;
            CadDb.ObjectId curveLabelStyleId;
            GetCurveGeneralSegmentLabelStyles(
                polyId, out lineLabelStyleId, out curveLabelStyleId);
            bool hasLabel = !lineLabelStyleId.IsNull && !curveLabelStyleId.IsNull;
 
            using (var tran = dwg.TransactionManager.StartTransaction())
            {
                var poly = (CadDb.Polyline)tran.GetObject(
                    polyId, CadDb.OpenMode.ForRead);
 
                //Find current space
                var curSpace = (CadDb.BlockTableRecord)tran.GetObject(
                    poly.OwnerId, CadDb.OpenMode.ForRead);
 
                //Newly created entities because of the splitting
                var newIds = new List<CadDb.ObjectId>();
 
                //Get split segments and add them into current space
                using (var ents = GetSplitCurvesFromPolyline(poly))
                {
                    if (ents.Count > 1)
                    {   
                        curSpace.UpgradeOpen();
                        foreach (CadDb.DBObject ent in ents)
                        {
                            var id = curSpace.AppendEntity(ent as CadDb.Entity);
                            tran.AddNewlyCreatedDBObject(ent, true);
 
                            newIds.Add(id);
                        }
 
                        //Erase the polyline (label would also be gone, if exist
                        poly.UpgradeOpen();
                        poly.Erase(true);
                    }
                    else
                    {
                        ents[0].Dispose();
                    }
                }
 
                //Add label to each newly added entities
                if (newIds.Count>0 && hasLabel)
                {      
                    AddGeneralSegmentLabels(
                        newIds, lineLabelStyleId, curveLabelStyleId);
                }
 
                tran.Commit();
            }         
        }
 
        #region private methods
 
        private CadDb.ObjectId SelectPolyline(Editor ed)
        {
            var opt = new PromptEntityOptions(
                "\nSelect a polyline:");
            opt.SetRejectMessage("\nInvalid: not a polyline.");
            opt.AddAllowedClass(typeof(CadDb.Polyline), true);
 
            var res = ed.GetEntity(opt);
            if (res.Status==PromptStatus.OK)
            {
                return res.ObjectId;
            }
            else
            {
                return CadDb.ObjectId.Null;
            }
        }
 
        private CadDb.DBObjectCollection GetSplitCurvesFromPolyline(
            CadDb.Polyline poly)
        {
            var points = new Point3dCollection();
            for (int i = 0; i < poly.NumberOfVertices; i++)
            {
                points.Add(poly.GetPoint3dAt(i));
            }
 
            var dbObjects = poly.GetSplitCurves(points);
 
            return dbObjects;
        }
 
        private void AddGeneralSegmentLabels(
            IEnumerable<CadDb.ObjectId> featureIds, 
            CadDb.ObjectId lineLabelStyleId, 
            CadDb.ObjectId curveLabelStyleId)
        {
            foreach (var featureId in featureIds)
            {
                var labelId = CivilDb.GeneralSegmentLabel.Create(
                    featureId, 0.5, lineLabelStyleId, curveLabelStyleId);
            }
        }
 
        private void GetCurveGeneralSegmentLabelStyles(
            CadDb.ObjectId curveId,
            out CadDb.ObjectId lineStyleId, 
            out CadDb.ObjectId curveStyleId)
        {
            bool hasLabel = false;
            lineStyleId = CadDb.ObjectId.Null;
            curveStyleId = CadDb.ObjectId.Null;
 
            var id1 = CadDb.ObjectId.Null;
            var id2 = CadDb.ObjectId.Null;
 
            using (var tran = curveId.Database.TransactionManager.StartTransaction())
            {
                var ent = (CadDb.Entity)tran.GetObject(curveId, CadDb.OpenMode.ForRead);
                var space = (CadDb.BlockTableRecord)tran.GetObject(
                    ent.OwnerId, CadDb.OpenMode.ForRead);
 
                foreach (CadDb.ObjectId id in space)
                {
                    if (id.ObjectClass.DxfName.ToUpper() == DXF_LABEL)
                    {
                        var label = tran.GetObject(
                            id, CadDb.OpenMode.ForRead) as CivilDb.Label;
                        if (label != null)
                        {
                            if (label.FeatureId == curveId)
                            {
                                if (!hasLabel) hasLabel = true;
 
                                if (id1.IsNull)
                                {
                                    id1 = label.StyleId;
                                }
                                else if (label.StyleId != id1)
                                {
                                    id2 = label.StyleId;
                                }
                            }
                        }
                    }
 
                    if (!id1.IsNull && !id2.IsNull) break;
                }
 
                //Only go further when at least one style is found
                if (hasLabel)
                {
                    if (!id1.IsNull)
                    {
                        //if it is Line Segment Style or Curve Segment Style
                        var civilDoc = CivilApp.ActiveDocument;
                        var lineStyles = 
                            civilDoc.Styles.LabelStyles.GeneralLineLabelStyles;
                        var curveStyles = 
                            civilDoc.Styles.LabelStyles.GeneralCurveLabelStyles;
 
                        if (IsTheLineSegmentStyle(id1, lineStyles, tran))
                        {
                            lineStyleId = id1;
                            if (!id2.IsNull)
                            {
                                if (IsTheLineSegmentStyle(id2, curveStyles, tran))
                                {
                                    curveStyleId = id2;
                                }
                            }
                        }
                        else
                        {
                            if (IsTheLineSegmentStyle(id1, curveStyles, tran))
                            {
                                curveStyleId = id1;
                                if (!id2.IsNull)
                                {
                                    if (IsTheLineSegmentStyle(id2, lineStyles, tran))
                                    {
                                        lineStyleId = id2;
                                    }
                                }
                            }
                        }
                    }
 
                    // The annotated polyline may only have line label or curve label
                    // So, here is to get default label style (either line label style
                    // or curve label style
                    CadDb.ObjectId defaultLineStyleId;
                    CadDb.ObjectId defaultCurveStyleId;
                    GetSettingsCmdAddSegmentLabelDefaultStyles(
                        out defaultCurveStyleId, out defaultLineStyleId);
 
                    if (lineStyleId.IsNull) lineStyleId = defaultLineStyleId;
                    if (curveStyleId.IsNull) curveStyleId = defaultCurveStyleId;
                }
 
                tran.Commit();
            }
        }
 
        private bool IsTheLineSegmentStyle(
            CadDb.ObjectId styleId, 
            IEnumerable<CadDb.ObjectId> styleCollection, 
            CadDb.Transaction tran)
        {
            bool found = false;
 
            foreach (CadDb.ObjectId id in styleCollection)
            {
                if (styleId == id)
                {
                    found = true;
                }
                else
                {
                    var style = (LabelStyle)tran.GetObject(
                        id, CadDb.OpenMode.ForRead);
                    if (style.ChildrenCount > 0)
                    {
                        var styleIds = new List<CadDb.ObjectId>();
                        for (int i = 0; i < style.ChildrenCount; i++)
                        {
                            styleIds.Add(style[i]);
                        }
 
                        //Recursive call
                        found = 
                            IsTheLineSegmentStyle(styleId, styleIds, tran);
                    }
                }
 
                if (found) break;
            }
 
            return found;
        }
 
        private void GetSettingsCmdAddSegmentLabelDefaultStyles(
            out CadDb.ObjectId curveLabelStyleId, 
            out CadDb.ObjectId lineLabelStyleId)
        {
            var settings = CivilApp.ActiveDocument.Settings;
            var cmdSettings = 
                settings.GetSettings<Civil.Settings.SettingsCmdAddSegmentLabel>();
 
            lineLabelStyleId = cmdSettings.Styles.LineLabelStyleId.Value;
            curveLabelStyleId = cmdSettings.Styles.CurveLabelStyleId.Value;
        }

        #endregion
    }
}

In the code, the critical portion of the code is the private method GetCurveGeneralSegmentLabelStyle(), which does these things:

1. Check if the curve to be split has general segment labels associated or not.
2. If there is general segment labels associated, what the 2 label styles (line label and curve label) are.
3. Since the curve's split-able segments could be only lines, or only curves, we may only find one label style (line label style or curve label style) that is associated to the split-able curve.
4. The reason that I need to find both line and curve label styles, even the split-able curve may only use one label style, is that I need to re-create general segment labels on each split segment with Autodesk.Civil.DatabaseServices.GeneralSegmentLabel.Create(ObjectId, double, ObjectId, ObjectId), instead of Autodesk.Civil.DatabaseServices.GeneralSegmentLabel.Create(ObjectId, double). That is, I use the Create() method with 2 label styles' ObjectId passed in, instead of the Create() method that uses current default general segment label styles, set in Autodesk.Civil.Settings.SettingsCmdAddSegmentLable.Styles, which may be different from the original label styles found with the split-able curve.
5. Each of the 2 possible label styles (line or curve label styles) could have one or more child label styles, and each of the child styles could also have child styles...and so on. So the recursive method in the code to identify label style to be used.

This video clip shows the result of running the code.

The code is just a simplified way to re-label the individual segments after splitting a curve, it may not  re-create the label exactly as the original ones. For example, an original label could have been dragged along the segment from default location (centre of the segment), while the code shown here always create the label at the segment centre (the double argument of the Create() method is passed with value 0.5). So, to make the re-created label locate at exact location as the original one, when searching associated labels to the split-able curve, I would need to save the property value of GeneralSegmentLabel class of each found label of each segment, and use the value later when re-creating the label. It would need quite some extra code. I choose to leave it outside of this post.

Adittion Note

I also realize that a segment of line/curve could be annotated with multiple labels (in different label styles, of course). So, the code I posted here only works with segment being labelled with one label style. Obviously, if I want to retain all the labels in the case of multiple labels used on segments, I would need to identify all the labels that is associated to each segment before the splitting target polyline is erased. I'll see if I can find time to work out that part code later.

4 comments:

Stacy said...

Norman,
When this command is run on a closed polyline, the code fails when the IsOnCurve method tries to calculate the ration. The distance returned from curve.GetDistAtPoint(curve.EndPoint) is 0. Is there a different method to calculate the distance when dealing with a closed curve?

Thank you,
Stacy

Unknown said...
This comment has been removed by the author.
Kevin said...

I'm a civil engineer too. But I am new to AutoCAD .Net API.
May I ask you, do you have any .Net source code that fetches geometry of the certain code name of LINKs inside CorridorSection in every SectionView.
I need that geometry info to turn to Plines and process the later analysis.

Norman Yuan said...

Kevin,
I do not have the code you asked. I suggest you post your question to Autodesk's dedicated user forum here:

https://forums.autodesk.com/t5/civil-3d-customization/bd-p/190

Make sure you describe your situation as detailed as possible, show the basic code you have already worked out (such as, the code how to get to the said alignment/corridor/section...), and if possible, attach a simplified drawing. This way a potential responder would be able to reply more targeted.

Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.