### Author Topic: How to detect a line near a Point? And then get the distance between them?  (Read 3489 times)

0 Members and 1 Guest are viewing this topic.

#### 闻仲

• Newt
• Posts: 94
##### How to detect a line near a Point? And then get the distance between them?
« on: February 10, 2012, 02:20:06 am »
Hello,everyone? Is it possible to "detect" a line near a point? Let's suppose it is the nearest line to be detected.If yes, then return the distance.
If a point is not enough,what about a line? "Detect" the nearest parallel line,and then return the distance?
Any suggestion or code is helpful.
Need lots of stupid stuffs when you are young, or you will regret it when you are too old to do it.

#### Kerry

• Mesozoic relic
• Seagull
• Posts: 11653
• class keyThumper<T>:ILazy<T>
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #1 on: February 10, 2012, 03:42:03 am »

I've done this using a multisided polygon as a fence for a selection set.
loop through, minutely increasing the size of the polygon untill a suitable object gets caught in the selection.

Perhaps not really elegant but seemed to work fine.

Regards

Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

#### 闻仲

• Newt
• Posts: 94
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #2 on: February 10, 2012, 07:37:25 am »
Need lots of stupid stuffs when you are young, or you will regret it when you are too old to do it.

#### Kerry

• Mesozoic relic
• Seagull
• Posts: 11653
• class keyThumper<T>:ILazy<T>
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #3 on: February 10, 2012, 06:20:44 pm »

I'll be away for a few hours ... will have a look at a sample when I come back, unless someone else pops up a solution in the meantime.

Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

#### gile

• Water Moccasin
• Posts: 1999
• Marseille, France
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #4 on: February 11, 2012, 01:27:06 pm »
Hi,

Here's another way, certainly slower if there're many entities in the current space, but much more easy to code.

Code - C#: [Select]
`using System.Linq;using Autodesk.AutoCAD.ApplicationServices;using Autodesk.AutoCAD.DatabaseServices;using Autodesk.AutoCAD.EditorInput;using Autodesk.AutoCAD.Geometry;using Autodesk.AutoCAD.Runtime; namespace ClosestLineSample{    public class Commands    {        [CommandMethod("Test")]        public void Test()        {            Document doc = Application.DocumentManager.MdiActiveDocument;            Database db = doc.Database;            Editor ed = doc.Editor;            PromptPointResult ppr = ed.GetPoint("\nSpecify a point: ");            if (ppr.Status != PromptStatus.OK) return;            Point3d pt = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);            using (Transaction tr = db.TransactionManager.StartTransaction())            {                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);                var closest = btr                    .Cast<ObjectId>()                    .Select(id => tr.GetObject(id, OpenMode.ForRead) as Line)                    .Where(ent => ent != null)                    .Select(line => new { Line = line, Dist = pt.DistanceTo(line.GetClosestPointTo(pt, false)) })                    .Aggregate((l1, l2) => l1.Dist < l2.Dist ? l1 : l2);                if (closest != null)                {                    closest.Line.Highlight();                    ed.WriteMessage("\nDistance = {0}", closest.Dist);                }                tr.Commit();            }        }    }} `
Speaking English as a French Frog

#### Kerry

• Mesozoic relic
• Seagull
• Posts: 11653
• class keyThumper<T>:ILazy<T>
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #5 on: February 11, 2012, 06:00:28 pm »

Looks like a fun solution gile.

Querying the complete database may take a little longer, yes, but thankfully doesn't have to deal with the requirement that selections must be in the current view.

The linq makes for a nice solution.

I haven't ananlysed the code, but the distance will be in the WCS, yes ? as will the Point parameter.

Regards,

Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

#### Gasty

• Newt
• Posts: 85
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #6 on: February 11, 2012, 09:27:51 pm »
Hi,

The distance is invariant under CS changes if all the points are in the same CS.

Gaston Nunez

#### gile

• Water Moccasin
• Posts: 1999
• Marseille, France
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #7 on: February 12, 2012, 03:58:47 am »
Thanks Kerry.
Right Gaston.

In the example, the point got with Editor.GetPoint() is defined in current UCS and have to be transformed from current UCS to WCS to get the distance to the point returned by Line.GetClosestPointTo() which is always WCS defined.

Linq allows to write code in a more 'LISPy' way.
Speaking English as a French Frog

#### gile

• Water Moccasin
• Posts: 1999
• Marseille, France
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #8 on: February 12, 2012, 04:30:44 am »
Maybe some aren't very comfortable with the Linq functional style, so, here's a more traditional impertive implementation.

Code - C#: [Select]
`using Autodesk.AutoCAD.ApplicationServices;using Autodesk.AutoCAD.DatabaseServices;using Autodesk.AutoCAD.EditorInput;using Autodesk.AutoCAD.Geometry;using Autodesk.AutoCAD.Runtime;using System.Collections.Generic; namespace ClosestLineSample{    public class Commands    {        [CommandMethod("Test")]        public void Test()        {            Document doc = Application.DocumentManager.MdiActiveDocument;            Database db = doc.Database;            Editor ed = doc.Editor;            PromptPointResult ppr = ed.GetPoint("\nSpecify a point: ");            if (ppr.Status != PromptStatus.OK) return;            Point3d pt = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);            using (Transaction tr = db.TransactionManager.StartTransaction())            {                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);                Line closest = null;                double shortest = 0.0;                foreach (ObjectId id in btr)                {                    Line line = tr.GetObject(id, OpenMode.ForRead) as Line;                    if (line != null)                    {                        double dist = pt.DistanceTo(line.GetClosestPointTo(pt, false));                        if (closest == null)                        {                            closest = line;                            shortest = dist;                        }                        else if (shortest > dist)                        {                            closest = line;                            shortest = dist;                        }                    }                }                if (closest != null)                {                    closest.Highlight();                    ed.WriteMessage("\nDistance = {0}", shortest);                }                tr.Commit();            }        }    }} `
« Last Edit: February 12, 2012, 06:25:47 am by gile »
Speaking English as a French Frog

#### 闻仲

• Newt
• Posts: 94
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #9 on: February 12, 2012, 06:52:44 am »
Hi,gile.If I want to rule out the case which distance is 0(The point lays in the straight line).I should change your great code liks this?
Code: [Select]
`foreach (ObjectId id in btr)                {                    Line line = tr.GetObject(id, OpenMode.ForRead) as Line;                    if (line != null)                    {                        double dist = pt.DistanceTo(line.GetClosestPointTo(pt, false));                      [b]if (dist == 0)                            continue;[/b]                                           if (closest == null)                        {                            closest = line;                            shortest = dist;                        }                        else if (shortest > dist)                        {                            closest = line;                            shortest = dist;                        }                    }                }`
By the way.The codes in your If...else if ... are the same.Why this?
« Last Edit: February 12, 2012, 06:59:19 am by waterharbin »
Need lots of stupid stuffs when you are young, or you will regret it when you are too old to do it.

#### gile

• Water Moccasin
• Posts: 1999
• Marseille, France
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #10 on: February 12, 2012, 07:15:57 am »
Quote
By the way.The codes in your If...else if ... are the same.Why this?
You're right.
The first if will only occur for the first iteration, the else if for the following ones.

It might have bee written:
(if (closest == null || shortest > dist) { ... }

(if (closest == null || (dist != 0.0 && shortest > dist)) { ... }
Speaking English as a French Frog

#### 闻仲

• Newt
• Posts: 94
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #11 on: February 12, 2012, 09:31:55 am »
Thanks to gile and Kerry.Job is done! This is the codes.Using a SelectCrossingWindow to reduse the number of entitier.
Code: [Select]
`public static void UseCrossingWindow()        {            Document doc = Application.DocumentManager.MdiActiveDocument;            Database db = doc.Database;            Editor ed = doc.Editor;            using (Transaction trans = db.TransactionManager.StartTransaction())            {                PromptPointResult ppr = ed.GetPoint("\n Sepecify the first Point:");                if (ppr.Status != PromptStatus.OK) return;                Point3d pt1 = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);                                //Get another point to form a SeltectCrossingWindow                ppr = ed.GetPoint("\n Sepecify the second Point:");                if (ppr.Status != PromptStatus.OK) return;                Point3d pt2 = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);                                // Create a crossing window based on the two selected points                PromptSelectionResult acSSPrompt;                                acSSPrompt = ed.SelectCrossingWindow(pt1, pt2);                                // If the prompt status is not OK, do nothing.                if (acSSPrompt.Status != PromptStatus.OK)                    return;                SelectionSet acSSet = acSSPrompt.Value;                ObjectId[] ids = acSSet.GetObjectIds();                Line closest = null;                double shortest = 0.0;                foreach (ObjectId id in ids)                {                    Line line = trans.GetObject(id, OpenMode.ForRead) as Line;                    if (line != null)                    {                                                double dist = pt1.DistanceTo(line.GetClosestPointTo(pt1, false));                        if (dist == 0)                            continue;                        if (closest == null)                        {                            closest = line;                            shortest = dist;                        }                        else if (shortest > dist)                        {                            closest = line;                            shortest = dist;                        }                    }                }                if (closest != null)                {                    closest.Highlight();                    ed.WriteMessage("\nDistance = {0}", shortest);                }                /*                double shortest = 0.0;                foreach (ObjectId id in ids)                {                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForWrite);                    if (ent.GetType().Name == "Line")                    {                        Line myLine = (Line)trans.GetObject(id, OpenMode.ForWrite);                        double dist = pt1.DistanceTo(myLine.GetClosestPointTo(pt1,false));                        if (dist!=0 && shortest > dist)                        {                            shortest = dist;                        }                    }                }     //End of foreach loop                ed.WriteMessage("\nDistance = {0}", shortest);                */                                                trans.Commit();            }             }`By the way.The codes which have be commented out don't work. The result is "0".
And another question,how to rule out other kinds of entities when define the SelectCrossingWindow?

Hoping it will be helpful someone else!
Need lots of stupid stuffs when you are young, or you will regret it when you are too old to do it.

#### gile

• Water Moccasin
• Posts: 1999
• Marseille, France
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #12 on: February 12, 2012, 11:53:41 am »
1_ The Editor selection methods require current UCS defined points, so you do not have to use TransformBy(ed.CurrentUserCoordinateSystem); on the points returned by Editor.GetPoint().

2_ The commented code you posted do not work because the 'shortest' variable is assign to 0.0 and will never change because it will always be lower than dist. Look at the code I gave, in the first iteration 'dist' value is assigned to 'shortest'.

3_ You can use SelectionFilter to select only Line objects. One constructor of the SelectionFilter  type take a TypedValue array as parameter.
Code - C#: [Select]
`TypedValue[] filter = new TypedValue[1]{ new TypedValue(0, "LINE") };acSSPrompt = ed.SelectCrossingWindow(pt1, pt2, new SelectionFilter(filter));`
Have a look at the AutoCAD .NET Developper's Guide > Create and Edit AutoCAD Entities > Work with Selection Sets > Define Rules for Selection Filters (and the sub topics).
Speaking English as a French Frog

• Bull Frog
• Posts: 267
• Crash Test Dummy
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #13 on: April 23, 2015, 07:20:00 pm »
This is a variation on Giles' post above that is looking for coincident objects with a tolerance in the Y direction.

Code - C#: [Select]
`/// <summary> how far apart the X positions can be before declaring them totally related. </summary>double XoffsetCloseEnough = 5; /// <summary> how far apart the Y positions can be before declaring them unrelated. </summary>double YoffsetTooFarAway  = 1; /// <summary> Random number that just happens to be 500. </summary>double shortest = 500; /// <summary> This is the same Type as a thing in things </summary>TypeOfThing closestThing = null; foreach (TypeOfThing thing in things){  if (Math.Abs(thing.Position.Y - otherThing.Position.Y) > YoffsetTooFarAway) continue;   double distance = Math.Abs(thing.Position.X - otherThing.Position.X);   if (distance < shortest)  {    closestThing = thing;    shortest = distance;    if (distance < XoffsetCloseEnough) break; // That'll do, Pig, that'll do.  }} `

Notice I omitted the null check in the loop because there is a null check after the loop anyway. Null checks are cheap anyway so it won't kill you.

I also added a break; to bail out of the loop when it gets close enough,  just a premature optimi[zs]ation (hello Regex fans) based on where I expect these objects to be. In my case the objects were AttributeReferences.

#### BKSpurgeon

• Mosquito
• Posts: 2
##### Re: How to detect a line near a Point? And then get the distance between them?
« Reply #14 on: December 21, 2016, 06:20:28 am »
Mr Gilles thank you this code is very nice.  As I understand it, if applied with the GetObjects then you can string things together with to get whittle down to a super filtered set of entities?

e.g.

Code: [Select]
`using (Transaction tr = doc.Database.TransactionManager.StartTransaction())            {                IEnumerable<Entities> filteredEntities = objectIDs.GetObjects<Entity>(OpenMode.ForRead, false, true).Where( predicate).Select(predicate) etc. etc. ;            }`

Where GetObjects is:

Code: [Select]
`        public static IEnumerable<T> GetObjects<T>(            this IEnumerable<ObjectId> ids,            OpenMode mode = OpenMode.ForRead,            bool openErased = false,            bool forceOpenOnLockedLayers = false) where T : DBObject        {            if (ids.Any())            {                TransactionManager tm = ids.First().Database.TransactionManager;                RXClass rxclass = RXClass.GetClass(typeof(T));                if (typeof(T) == typeof(DBObject))                {                    foreach (ObjectId id in ids)                    {                        yield return (T)tm.GetObject(id, mode, openErased,                           forceOpenOnLockedLayers);                    }                }                else if (rxclass.GetHasChildren())                {                    foreach (ObjectId id in ids)                    {                        if (id.ObjectClass.IsDerivedFrom(rxclass))                            yield return (T)tm.GetObject(id, mode, openErased,                               forceOpenOnLockedLayers);                    }                }                else                {                    foreach (ObjectId id in ids)                    {                        if (id.ObjectClass == rxclass)                            yield return (T)tm.GetObject(id, mode, openErased,                               forceOpenOnLockedLayers);                    }                }            }        }        // Returns true if at least one RXClass is derived from        // the given RXClass:        public static bool GetHasChildren(this RXClass rxclass)        {            foreach (DictionaryEntry e in SystemObjects.ClassDictionary)            {                if (rxclass == ((RXClass)e.Value).MyParent)                    return true;            }            return false;        }`

Hi,

Here's another way, certainly slower if there're many entities in the current space, but much more easy to code.

Code - C#: [Select]
`using System.Linq;using Autodesk.AutoCAD.ApplicationServices;using Autodesk.AutoCAD.DatabaseServices;using Autodesk.AutoCAD.EditorInput;using Autodesk.AutoCAD.Geometry;using Autodesk.AutoCAD.Runtime; namespace ClosestLineSample{    public class Commands    {        [CommandMethod("Test")]        public void Test()        {            Document doc = Application.DocumentManager.MdiActiveDocument;            Database db = doc.Database;            Editor ed = doc.Editor;            PromptPointResult ppr = ed.GetPoint("\nSpecify a point: ");            if (ppr.Status != PromptStatus.OK) return;            Point3d pt = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);            using (Transaction tr = db.TransactionManager.StartTransaction())            {                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);                var closest = btr                    .Cast<ObjectId>()                    .Select(id => tr.GetObject(id, OpenMode.ForRead) as Line)                    .Where(ent => ent != null)                    .Select(line => new { Line = line, Dist = pt.DistanceTo(line.GetClosestPointTo(pt, false)) })                    .Aggregate((l1, l2) => l1.Dist < l2.Dist ? l1 : l2);                if (closest != null)                {                    closest.Line.Highlight();                    ed.WriteMessage("\nDistance = {0}", closest.Dist);                }                tr.Commit();            }        }    }} `