Author Topic: Selection Set Filters  (Read 2731 times)

0 Members and 1 Guest are viewing this topic.

Offline (gile)

  • C#
  • *
  • Posts: 87
  • Karma: +8/-0
  • Gender: Male
    • prefered language: F
    • Prog expertise: Good
    • View Profile
Selection Set Filters
« on: December 04, 2010, 10:24:53 PM »
In the .NET environment, a SelectionFilter is constructed with a TypedValue array.
A TypedValue can contain various Objects types in its Value property. The Object type is defined in the TypeCode property as an integer (or a DxfCode enum integer) which corresponds to the DXF group code of the Value.
For those who know AutoLISP, a TypedValue looks like a DXF dotted pair (even it is not the same thing, a dotted pair is a LISP specific data).
For the Values which type is String as entity type (DxfCode.Start = 0) or layer (DxfCode.Layer = 8), the Value can contain many patterns separted by commas and use wildcard patterns.
The filter can contain relational tests for the numerical values and logical grouping.

The more complete documentation in the AutoCAD Developer's Help for building sofisticated SelectionFilters is in the AutoLISP Help:
AutoLISP developer's Guide > Using the AutoLISP Language > Using AutoLISP to Manipulate AutoCAD Objects > Selection Set Handling > Selection Set Filter Lists
And the DXF group codes can be found in DXF Reference.

Here's an example to select closed polylines (lw, 2d and 3d) and closed ellipses on layers BASE and CONSTRUCTION

Code: [Select]
TypedValue[] filter =
            {   new TypedValue(-4, "<OR"),
                new TypedValue(-4, "<AND"),
                new TypedValue(0, "*POLYLINE"), // LWPOLYLINE and POLYLINE
                new TypedValue(-4, "&"),
                new TypedValue(70, 1), // Closed
                new TypedValue(-4, "<NOT"),
                new TypedValue(-4, "&"),
                new TypedValue(70, 112),  // Avoid meshes (bit codes: 16 + 32 + 64)
                new TypedValue(-4, "NOT>"),
                new TypedValue(-4, "AND>"),
                new TypedValue(-4, "<AND"),
                new TypedValue(0, "ELLIPSE"),
                new TypedValue(-4, "="),
                new TypedValue(41, 0.0), // Start parameter
                new TypedValue(-4, "="),
                new TypedValue(42, 6.283185307179586), // End parameter
                new TypedValue(-4, "AND>"),
                new TypedValue(-4, "OR>"),
                new TypedValue(8, "BASE,CONSTRUCTION")};
SelectionFilter = new SelectionFilter(filter);

target audience:{beginner}
« Last Edit: December 13, 2010, 08:29:31 PM by (gile) »

Offline frits432

  • Newbie
  • *
  • Posts: 15
  • Karma: +1/-0
  • Gender: Male
    • prefered language: C
    • Prog expertise: Beginner
    • View Profile
Re: Selection Set Filters
« Reply #1 on: November 15, 2011, 12:11:01 PM »
Gile,
Very useful code for complex selecting in large drawings.
However for smaller drawings and easier to maintain code i like the LINQ approach as well, because it enables me to use the same code pattern to use all type of selections.
Selection based on entity type, layer, string contents, location etc.

Some samples.

Code: [Select]
using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                BlockTableRecord ps = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite);
                    LayoutManager layMgr = LayoutManager.Current;
                    Layout lay = (Layout)tr.GetObject(layMgr.GetLayoutId(layMgr.CurrentLayout), OpenMode.ForRead);


//Collect LayerNames to exclude e.q.  Layers OFF or Frozen
List<string> frozenLayerNames= lt
                        .Cast<ObjectId>()
                        .Select(id => (LayerTableRecord)tr.GetObject(id, OpenMode.ForRead))
                        .Where(ly => ly.IsOff)
                        .Where(ly => ly.IsFrozen)
                        .Select(ly => ly.Name)
                        .ToList();

//Same but now from within PaperSpace Viewports
List<string> pvpFrozenLayerNames = lay
                        .GetViewports().Cast<ObjectId>()
                        .Select(id => (Viewport)tr.GetObject(id, OpenMode.ForRead))
                        .SelectMany(pvp => pvp.GetFrozenLayers().Cast<ObjectId>())
                        .Distinct().ToArray()
                        .Select(id => (LayerTableRecord)tr.GetObject(id, OpenMode.ForRead))
                        .Select(ly => ly.Name)
                        .ToList();

// List (visible) Layers named "...~..." and "...TXT..." and NOT "...NOTTOBEINCLUDED..."
var visLayerNames = lt
                    .Cast<ObjectId>()
                    .Select(id => (LayerTableRecord)tr.GetObject(id, OpenMode.ForRead))
                    .Where(ly => ly.Name.Contains('~'))
                    .Where(ly => ly.Name.IndexOf("TXT", StringComparison.CurrentCultureIgnoreCase) > 0)
                    .Where(ly => ly.Name.IndexOf("NOTTOBEINCLUDED", StringComparison.CurrentCultureIgnoreCase) < 0)
                    .Where(ly => !ly.IsOff)
                    .Where(ly => !ly.IsFrozen)
                    .Where(ly => !pvpFrozenLayerNames.Contains(ly.Name))
                    .Select(ly => ly.Name)
                    .ToList();

//select ModelSpace Text from specific layers
               var visTxt = ms.Cast<ObjectId>()
                    .Where(id => id.ObjectClass.DxfName.ToUpper() == "TEXT" || id.ObjectClass.DxfName.ToUpper() == "MTEXT")
                    .Select(id => (Entity)tr.GetObject(id, OpenMode.ForRead))
                    .Where(ent => visLayerNames.Contains(ent.Layer))
                    .ToList();

//select Text from specific layers within specific Blocks
               var visTxtInSpecificBlks = ms.Cast<ObjectId>()
                    .Where(id => id.ObjectClass.DxfName.ToUpper() == "INSERT")
                    .Select(id => (BlockReference)tr.GetObject(id, OpenMode.ForRead))
                    .Where(blkRef => visLayerNames.Contains(blkRef.Layer))
                    .Where(blkRef => blkRef.Name.IndexOf("-xxx-", StringComparison.CurrentCultureIgnoreCase) > 0)
                    .SelectMany(blkRef => ((BlockTableRecord)tr.GetObject(bt[blkRef.Name], OpenMode.ForRead)).Cast<ObjectId>())
                    .Where(id => id.ObjectClass.DxfName.ToUpper() == "TEXT" || id.ObjectClass.DxfName.ToUpper() == "MTEXT")
                    .Select(id => (Entity)tr.GetObject(id, OpenMode.ForRead))
                    .Where(ent => visLayerNames.Contains(ent.Layer))
                    .ToList();

//Join Modelspace and Block Specific text
                visTxt.AddRange(visTxtInSpecificBlks);


// build regular pattern to select certain string contents
// use regex tester to help build the search pattern.
                string searchNrs = @"(^3\(|^)(...)(.*)";
                string returnNrs = "$2";
                var matchNr = new Regex(searchNrs , RegexOptions.IgnoreCase | RegexOptions.Compiled);


//find visible text containing a complex patter
                var textNrs = visTxt
                    .Select(ent => GetType().Name == "MTEXT" ? ((MText)ent).Text : ((DBText)ent).TextString)
                    .Select(txt => matchNr.Replace(txt, searchNrs))
                    .Distinct().ToArray()
                    .ToList();

//List in numeric order
                kabelNrs = kabelNrs
                    .OrderBy(kabelNr => kabelNr.Length)
                    .ThenBy(kabelNr => kabelNr)
                    .ToList();
...




Frits

Offline frits432

  • Newbie
  • *
  • Posts: 15
  • Karma: +1/-0
  • Gender: Male
    • prefered language: C
    • Prog expertise: Beginner
    • View Profile
Re: Selection Set Filters
« Reply #2 on: November 15, 2011, 12:28:24 PM »
In combination with the Kaefer extensions for DBObjects  they can be made even easier

Code: [Select]

  public static class KaeferExtensions
    {
        // Opens a DBObject in ForRead mode (kaefer @ TheSwamp)
        public static T GetObject<T>(this ObjectId id) where T : DBObject
        {
            return id.GetObject<T>(OpenMode.ForRead);
        }

        // Opens a DBObject in the given mode (kaefer @ TheSwamp)
        public static T GetObject<T>(this ObjectId id, OpenMode mode) where T : DBObject
        {
            return id.GetObject(mode) as T;
        }
        // Opens a collection of DBObject in ForRead mode (kaefer @ TheSwamp)       
        public static IEnumerable<T> GetObjects<T>(this IEnumerable ids) where T : DBObject
        {
            return ids.GetObjects<T>(OpenMode.ForRead);
        }

        // Opens a collection of DBObject in the given mode (kaefer @ TheSwamp)
        public static IEnumerable<T> GetObjects<T>(this IEnumerable ids, OpenMode mode) where T : DBObject
        {
            return ids
                .Cast<ObjectId>()
                .Select(id => id.GetObject<T>(mode))
                .Where(res => res != null);
        }

        // Applies the given Action to each element of the collection (mimics the F# Seq.iter function).
        public static void Iterate<T>(this IEnumerable<T> collection, Action<T> action)
        {
            foreach (T item in collection) action(item);
        }

        // Applies the given Action to each element of the collection (mimics the F# Seq.iteri function).
        // The integer passed to the Action indicates the index of element.
        public static void Iterate<T>(this IEnumerable<T> collection, Action<T, int> action)
        {
            int i = 0;
            foreach (T item in collection) action(item, i++);
        }
    }

...

//using KeaderExtensions:
                    pvpFrozenLayerNames = lt.GetObjects<LayerTableRecord>()
                        .Where(ly => ly.IsOff)
                        .Where(ly => ly.IsFrozen)
                        .Select(ly => ly.Name)
                        .ToList();





Frits

Offline (gile)

  • C#
  • *
  • Posts: 87
  • Karma: +8/-0
  • Gender: Male
    • prefered language: F
    • Prog expertise: Good
    • View Profile
Re: Selection Set Filters
« Reply #3 on: November 15, 2011, 10:32:57 PM »
Nice.

Another way is to use the Editor.Selectionadded event
Here's a little example with an extension method for Editor which select only entities derived from Curve.

Code: [Select]
        public static PromptSelectionResult GetCurveSelection(this Editor ed, params TypedValue[] filter)
        {
            ed.SelectionAdded += new SelectionAddedEventHandler(OnCurveSelectionAdded);
            PromptSelectionResult psr = ed.GetSelection(new SelectionFilter(filter));
            ed.SelectionAdded -= new SelectionAddedEventHandler(OnCurveSelectionAdded);
            return psr;
        }

        static void OnCurveSelectionAdded(object sender, SelectionAddedEventArgs e)
        {
            ObjectId[] ids = e.AddedObjects.GetObjectIds();
            for (int i = 0; i < ids.Length; i++)
            {
                if (!ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Curve))))
                    e.Remove(i);
            }
        }
« Last Edit: November 20, 2011, 11:20:21 AM by (gile) »

Offline frits432

  • Newbie
  • *
  • Posts: 15
  • Karma: +1/-0
  • Gender: Male
    • prefered language: C
    • Prog expertise: Beginner
    • View Profile
Re: Selection Set Filters
« Reply #4 on: November 16, 2011, 09:17:39 AM »
Amazing, this gives me even more options to write nicer code.
Thanks.
Frits