Tuesday, January 18, 2011

Mimicking AutoCAD's "AREA" Command With .NET Code

In response to the question asked to me on how to do something similar to AutoCAD's "AREA" command, I spent most my lunch break time and got this simple code that mimicking the AREA" command. Well, just a simple version of "AREA" command.

First, a class does the work - MyAreaCmd:

using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace AreaCommand
{
    public class MyAreaCmd
    {
        private Document _dwg;
        private Editor _editor;

        private double _area = 0.0;
        private double _perimeter = 0.0;

        private Autodesk.AutoCAD.DatabaseServices.Polyline _pline = null;
        private List _points;
        private bool _pickDone;

        public MyAreaCmd(Document dwg)
        {
            _dwg = dwg;
            _editor = _dwg.Editor;
        }

        public double Area
        {
            get { return _area; }
        }

        public double Perimeter
        {
            get { return _perimeter; }
        }

        public bool GetArea()
        {
            _pline=null;

            //Pick first point
            Point3d pt1;
            if (!GetFirstPoint(out pt1)) return false;

            //Pick second point
            Point3d pt2;
            if (!GetSecondPoint(pt1, out pt2)) return false;

            _pickDone = false;

            _points = new List();
            _points.Add(new Point2d(pt1.X,pt1.Y));
            _points.Add(new Point2d(pt2.X, pt2.Y));

            try
            {
                //Handling mouse cursor moving during picking
                _editor.PointMonitor += 
                    new PointMonitorEventHandler(_editor_PointMonitor);

                while (true)
                {
                    if (!PickNextPoint()) break;
                }

                if (_pline != null && _pickDone)
                {
                    _area = _pline.Area;
                    _perimeter = _pline.Length;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                ClearTransientGraphics();

                //Remove PointMonitor handler
                _editor.PointMonitor -= 
                    new PointMonitorEventHandler(_editor_PointMonitor);
            }

            return _pickDone;
        }

        #region private methods

        private bool GetFirstPoint(out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = 
                new PromptPointOptions("\nPick first corner: ");
            PromptPointResult res = _editor.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool GetSecondPoint(Point3d basePt, out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = 
                new PromptPointOptions("\nPick next corner: ");
            opt.UseBasePoint = true;
            opt.BasePoint = basePt;
            PromptPointResult res = _editor.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool PickNextPoint()
        {
            PromptPointOptions opt = 
                new PromptPointOptions("\nPick next corner: ");
            if (_points.Count > 2) 
            {
                opt.Keywords.Add("Undo");
                opt.Keywords.Add("Total");
                opt.AppendKeywordsToMessage = true;
            }
            
            PromptPointResult res = _editor.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                _points.Add(new Point2d(res.Value.X,res.Value.Y));
                return true;
            }
            else if (res.Status == PromptStatus.Keyword)
            {
                if (res.StringResult == "Undo")
                {
                    if (_points.Count > 2)
                    {
                       _points.RemoveAt(_points.Count - 1);
                    }
                    return true;
                }
                else
                {
                    _pickDone = true;
                    return false;
                }
            }
            else
            {
                _pickDone = false;
                return false;
            }
        }

        private void ClearTransientGraphics()
        {
            if (_pline != null)
            {
                TransientManager.CurrentTransientManager.EraseTransients(
                    TransientDrawingMode.DirectTopmost, 
                    128, new IntegerCollection());

                _pline.Dispose();
                _pline = null;
            }
        }

        private void _editor_PointMonitor(object sender, PointMonitorEventArgs e)
        {
            ClearTransientGraphics();

            //Draw polyline
            Point2d pt = new Point2d(e.Context.RawPoint.X, e.Context.RawPoint.Y);

            _pline = new Autodesk.AutoCAD.DatabaseServices.Polyline(_points.Count + 1);

            for (int i = 0; i < _points.Count; i++)
            {
                _pline.AddVertexAt(i, _points[i], 0.0, 0.0, 0.0);
            }

            _pline.AddVertexAt(_points.Count, pt, 0.0, 0.0, 0.0);
            _pline.Closed = true;

            TransientManager.CurrentTransientManager.AddTransient(
                _pline, TransientDrawingMode.DirectTopmost, 
                128, new IntegerCollection());
        }

        #endregion
    }
}
Then, I use MyAreaCmd class in a command method:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;

[assembly: CommandClass(typeof(AreaCommand.MyCommands))]

namespace AreaCommand
{
    public class MyCommands 
    {
        [CommandMethod("MyArea")]
        public static void GetArea()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;

            MyAreaCmd cmd = new MyAreaCmd(dwg);

            if (cmd.GetArea())
            {
                ed.WriteMessage("\nArea = {0}", cmd.Area);
                ed.WriteMessage("\nPerimeter = {0}", cmd.Perimeter);
            }
            else
            {
                ed.WriteMessage("\n*Cancelled*");
            }
        }
    }
}

See this video clip for the action.

Pretty simple, eh? Here are notes:

1. I did not try to give extra options during the picking as the real "Area" command does, such as [Arc/Length...]. if someone is interested in to expend the functionality, fell free to try.

2. The real "Area" command fills the picked polygon with color so that the area enclosed in the polygon is visually stand-out. I did not successfully mimic that. By "did not successfully", I mean I tried to create a hatch as Transient Graphics in the PointMonitor event handler. However, to my surprise, the code to append hatch's loop would fail unless the newly instantiated Hatch object and the loop object (closed Polyline) were appended into the drawing database in a transaction (hope someone would confirm this or confirm that I was wrong on this). Since the polygon has to be cleared and redraw (as Transient Graphics) repeatedly in the PointMonitor event handler, I felt repeatedly adding/erasing the Hatch in/from database within a transaction would be horrible thing to do. So I gave it up (for now).

Monday, January 17, 2011

Picking Points With Visual Aid

Again, this article was prompted with the discussion in the same thread from Autodesk's .NET discussion here.

As we all know, using PromptPointOptions with Editor.GetPoint(), one can use its properties UseBasePoint and BasePoint tp let AutoCAD show a rubber band line while picking points.

Some times, there are many points to pick, and user may want to have certain visual hint showing the points he/she has picked during the picking process. It may also be helpful to show a trace line follow the order of the points being picked.

Here is the code I do it, in a class called "PickPoints":

using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace PickPointWithVisualSpot
{
    public class PickPoints
    {
        private Document _dwg;
        private Editor _editor;
        private List _points = null;
        private List _circles = null;

        private bool _drawPline = false;
        private Polyline _pline = null;

        private int _color = 1;
        private double _radius = 0.1;

        public PickPoints(Document dwg)
        {
            _dwg = dwg;
            _editor = _dwg.Editor;
        }

        public Point3d[] PickedPoints
        {
            get
            {
                if (_points == null)
                    return null;
                else
                    return _points.ToArray();
            }
        }

        public void DoPick(bool drawTraceLine)
        {
            try
            {
                //Pick first point
                Point3d pt;
                if (!PickFirstPoint(out pt)) return;

                _drawPline = drawTraceLine;

                _points = new List();
                _circles = new List();

                _points.Add(pt);

                //Crate visual at the point
                CreateCircle(pt);

                while (true)
                {
                    if (!PickNextPoint()) break;
                }
            }
            catch { }
            finally
            {
                //Clear Transient graphics
                if (_circle != null)
                {
                    if (_circles.Count > 0)
                    {
                        foreach (Circle c in _circles)
                        {
                            TransientManager.CurrentTransientManager.
                                EraseTransient(c, new IntegerCollection());

                            c.Dispose();
                        }
                    }

                    _circles.Clear();
                    _circles = null;
                }

                ClearTraceLine();
            }
        }

        private bool PickFirstPoint(out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = 
                new PromptPointOptions("\nPick start point: ");
            PromptPointResult res = _editor.GetPoint(opt);
            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool PickNextPoint()
        {
            PromptPointOptions opt=
                new PromptPointOptions("\nPick next point: ");
            opt.UseBasePoint=true;
            opt.BasePoint=_points[_points.Count-1];
            if (_points.Count>2)
            {
                opt.Keywords.Add("Close");
                opt.AppendKeywordsToMessage=true;
            }

            PromptPointResult res=_editor.GetPoint(opt);
            if (res.Status==PromptStatus.OK)
            {
                _points.Add(res.Value);

                CreateCircle(res.Value);

                if (_points.Count > 1 && _drawPline )
                {
                    DrawTraceLine();
                }

                return true;
            }
            else if (res.Status==PromptStatus.Keyword)
            {
                return false;
            }
            else
            {
                return false;
            }
        }

        private void CreateCircle(Point3d pt)
        {
            Circle c = new Circle();
            c.Center = pt;
            c.Radius = _radius;
            c.ColorIndex = _color;
            c.Highlight();

            TransientManager.CurrentTransientManager.AddTransient(c, 
                TransientDrawingMode.Highlight,128, new IntegerCollection());

            _circles.Add(c);
        }

        private void DrawTraceLine()
        {
            ClearTraceLine();

            _pline = new Polyline(_points.Count);

            for (int i = 0; i < _points.Count; i++)
            {
                Point2d p = new Point2d(_points[i].X, _points[i].Y);
                _pline.AddVertexAt(i, p, 0.0, 0.0, 0.0);
            }

            _pline.ColorIndex = _color;

            TransientManager.CurrentTransientManager.AddTransient(_pline,
                TransientDrawingMode.Highlight, 128, new IntegerCollection());
        }

        private void ClearTraceLine()
        {
            if (_pline != null)
            {
                TransientManager.CurrentTransientManager.
                        EraseTransient(_pline, new IntegerCollection());

                _pline.Dispose();
                _pline = null;
            }
        }
    }
}
Then the use of the class in custom command. There are 2 commands: one shows trace line, while the other does not:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;

[assembly: CommandClass(typeof(PickPointWithVisualSpot.MyCommand))]

namespace PickPointWithVisualSpot
{
    public class MyCommand 
    {
        [CommandMethod("MyPick1", CommandFlags.Session)]
        public static void RunThisMethod1()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            PickPoints pick = new PickPoints(dwg);

            pick.DoPick(false);
            if (pick.PickedPoints != null)
            {
                dwg.Editor.WriteMessage("\nMyCommand executed: {0} points picked.", pick.PickedPoints.Length);
            }
            else
            {
                dwg.Editor.WriteMessage("\n*Cancelled*");
            }
        }

        [CommandMethod("MyPick2", CommandFlags.Session)]
        public static void RunThisMethod2()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            PickPoints pick = new PickPoints(dwg);

            pick.DoPick(true);
            if (pick.PickedPoints != null)
            {
                dwg.Editor.WriteMessage("\nMyCommand executed: {0} points picked.", pick.PickedPoints.Length);
            }
            else
            {
                dwg.Editor.WriteMessage("\n*Cancelled*");
            }
        }
    }
}

See this video clip for the code's behaviour.

Note: thanks to Irvin who prompted a bug in the "PickPoints" class' DoPick() method in the try...finally{...} block. I have corrected in red.

Sunday, January 16, 2011

Picking Entity Like Picking Point With Rubber Band Line

This article is inspired by this question posted by Irvin in Autodesk .NET discussion forum here.

In a occassion when picking a series of entities, the user may not only wants to have the picked entity highlighted, but also wants a rubber band line drawn from the previously picked point (or point derived from the previously picked entity) to the moving mouse cursor before picking next entity.

As we know, using PromptPointOption in conjunction with Editor.GetPoint(), AutoCAD draws a rubber band line, if PromptPointOptions.UseBasePoint is set true and a base point is supplied. However, to pick an entity, PromptEntityOptions and Editor.GetEntity() do not provide such option as "UseBasePoint".

Here is my way to solve this issue. After the first entity is picked, I handle Editor.PointMonitor event, so that when user moves mouse to pick next entity, a Transient Graphics (Line) is drawn in the event handler. The code is fairly simple, as following.

First, as I usually do, I created a class to encapsulate the wanted functionality: PickEntities.

using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace PickMultiplePoints
{
    public class PickEntities
    {
        private Document _dwg;
        private Editor _editor;

        private List _points = null;
        private List _entities = null;

        private Line _rubberLine = null;

        private Point3d _basePoint;
        private Point3d _currentPoint;

        public PickEntities(Document dwg)
        {
            _dwg = dwg;
            _editor = _dwg.Editor;
        }

        #region public properties 

        public List PickedPoints
        {
            get { return _points; }
        }

        public List PickedEntities
        {
            get { return _entities; }
        }

        #endregion

        public void DoPick(bool unhighlightAtEnd)
        {
            //Pick first entity
            ObjectId id;
            Point3d pt;
            if (!PickFirstEntity(out id, out pt)) return;

            _rubberLine = null;
            _points = new List();
            _entities = new List();

            _points.Add(pt);
            _entities.Add(id);

            SetHighlight(id, true);

            //Start drag rubber band line
            while (true)
            {
                if (!PickNextEntity()) break;
            }

            //Unhighlight all picked entities
            if (unhighlightAtEnd)
            {
                foreach (ObjectId entId in _entities)
                    SetHighlight(entId, false);
            }
        }

        #region private methods

        private bool PickFirstEntity(
            out ObjectId id, out Point3d pt)
        {
            pt = new Point3d();
            id = ObjectId.Null;

            PromptEntityOptions opt = 
                new PromptEntityOptions("\nPick an entity: ");
            PromptEntityResult res = _editor.GetEntity(opt);

            if (res.Status == PromptStatus.OK)
            {
                id = res.ObjectId;

                //if the entity is a BlockRefernece, get Insertion Point
                //otherwise get the picked point
                Point3d p;
                if (GetBlockInsPoint(res.ObjectId, out p))
                    pt = p;
                else
                    pt = res.PickedPoint;

                return true;
            }
            else
            {
                return false;
            }
        }

        private bool GetBlockInsPoint(ObjectId id, out Point3d insPt)
        {
            insPt=new Point3d();
            bool isBlk = false;

            using (Transaction tran = _dwg.Database.
                TransactionManager.StartTransaction())
            {
                BlockReference blk = tran.GetObject(
                    id, OpenMode.ForRead) as BlockReference;

                if (blk != null)
                {
                    insPt = blk.Position;
                    isBlk = true;
                }

                tran.Commit();
            }

            return isBlk;
        }

        private bool PickNextEntity()
        {
            _basePoint = _points[_points.Count - 1];

            string msg = 
                "\n" + _points.Count + " picked. Pick next entity: ";
            PromptEntityOptions opt = new PromptEntityOptions(msg);

            try
            {
                //Create rubber band line
                _rubberLine = new Line(_basePoint, _basePoint);

                //Set line properties, for example
                _rubberLine.SetDatabaseDefaults(_dwg.Database);

                //Create Transient graphics
                IntegerCollection intCol = new IntegerCollection();
                TransientManager.CurrentTransientManager.
                    AddTransient(_rubberLine,
                    TransientDrawingMode.DirectShortTerm, 128, intCol);

                _editor.PointMonitor += 
                    new PointMonitorEventHandler(_editor_PointMonitor);

                PromptEntityResult res =_editor.GetEntity(opt);

                if (res.Status == PromptStatus.OK)
                {
                    bool exists = false;
                    foreach (ObjectId ent in _entities)
                    {
                        if (ent == res.ObjectId)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        //if the entity is a BlockRefernece, 
                        //get Insertion Point.
                        //Otherwise get the picked point
                        Point3d p;
                        if (!GetBlockInsPoint(res.ObjectId, out p))
                        {
                            p = res.PickedPoint;
                        }

                        _points.Add(p);
                        _entities.Add(res.ObjectId);

                        SetHighlight(res.ObjectId, true);
                    }
                    else
                    {
                        _editor.WriteMessage(
                            "\nThe entity has already been picked!");
                    }
                        
                    return true;
                }
                else
                {
                    return false;
                }
            }
            finally
            {
                if (_rubberLine != null)
                {
                    //Clear transient graphics
                    IntegerCollection intCol = new IntegerCollection();
                    TransientManager.CurrentTransientManager.
                        EraseTransient(_rubberLine, intCol);

                    _rubberLine.Dispose();
                    _rubberLine = null;
                }

                _editor.PointMonitor -= 
                    new PointMonitorEventHandler(_editor_PointMonitor);
            }
        }

        private void SetHighlight(ObjectId id, bool highlight)
        {
            using (Transaction tran = _dwg.Database.
                TransactionManager.StartTransaction())
            {
                Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);

                if (highlight)
                    ent.Highlight();
                else
                    ent.Unhighlight();
            }
        }

        private void _editor_PointMonitor(
            object sender, PointMonitorEventArgs e)
        {
            //Get mouse cursor point
            _currentPoint = e.Context.RawPoint;

            //Update line
            _rubberLine.EndPoint = _currentPoint;

            //Update Transient graphics
            IntegerCollection intCol = new IntegerCollection();
            TransientManager.CurrentTransientManager.
                UpdateTransient(_rubberLine, intCol);
        }

        #endregion
    }
}

Then, I use "PickEntities" class in a command method of a command class:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;

[assembly: CommandClass(typeof(PickMultiplePoints.MyCommands))]

namespace PickMultiplePoints
{
    public class MyCommands
    {
        [CommandMethod("MyPick")]
        public static void DoCommand()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;

            Editor ed = dwg.Editor;

            //Do picking
            PickEntities picker = new PickEntities(dwg);
            picker.DoPick(true);

            ObjectId[] ids = picker.PickedEntities.ToArray();

            ed.WriteMessage(
                "\nMy command executed: {0} entities picked.", 
                ids.Length);
        }
    }
}

Here is the video clip of the code in action.

Use the technique presented in this article, one can also makes AutoCAD draw a polyline started from the first picked entity/point along the picked entities dynamically.

Thursday, January 13, 2011

Creating A "Move" Command With .NET API

In AutoCAD VBA era, although programmatic moving an entity with user interaction is fairly easy to do, but there is no way to make it behave like AutoCAD built-in "MOVE" command - the entity to be moved can be dragged with the cursor, which gives user a very good visual hint as where the entity is moving.

With AutoCAD .NET API being available, programming an custom command that allows user to drag entity or entities becomes a hot AutoCAD programming technique that every AutoCAD programmer would like to try out.

There are two ways to do entity dragging: creating a custom Jig class that derived from EntityJig or DrawJig class; or use a delegate (DragCallBack) in Editor.Drag() method. There are quite some discussions on the topic of Jig in various blogs/forums. In this article, I focus on the latter - Editor.Drag() with a delegate.

Kean Walmsly posted an article on this topic here. However, in dragging part of his code, there is no code to show a rubber band and show the entity/entities being dragged in highlight (of course this is because that was not what his post focused on).

The code shown below tries to imitate AutoCAD's "MOVE" command: the entity/entities can be selected before or after the custom command starts; the selected entity/entities being highlighted, a rubber band line being drawn from base point to the mouse cursor; the dragging method can ask user to pick base point; if no base point is required, the code finds the lower left corner of bounding box of all selected entities as base point... Enough explanations. Here are the code snippets following.

First, in the project, add a class "DragMove":

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace InteractiveDrag
{
    public class DragMove
    {
        private Document _dwg;
        private SelectionSet _sset;

        private Point3d _basePoint = new Point3d(0.0, 0.0, 0.0);
        private bool _useBasePoint = false;
        private Line _rubberLine = null;

        public DragMove(Document dwg, SelectionSet ss)
        {
            _dwg = dwg;
            _sset = ss;
        }

        #region public properties

        public bool UseBasePoint
        {
            set { _useBasePoint = value; }
            get { return _useBasePoint; }
        }

        public Point3d BasePoint
        {
            set { _basePoint = value; }
            get { return _basePoint; }
        }

        #endregion

        #region public methods

        public void DoDrag()
        {
            if (_sset.Count == 0) return;

            _rubberLine = null;

            using (Transaction tran = 
                _dwg.Database.TransactionManager.StartTransaction())
            {
                //Highlight entities
                SetHighlight(true, tran);

                if (!_useBasePoint)
                {
                    _basePoint = GetDefaultBasePoint();
                }
                else
                {
                    Point3d pt;
                    if (!PickBasePoint(_dwg.Editor, out pt)) return;

                    _basePoint = pt;
                    _useBasePoint = true;
                }

                PromptPointResult ptRes = _dwg.Editor.Drag
                    (_sset, "\nPick point to move to: ",
                        delegate(Point3d pt, ref Matrix3d mat)
                        {
                            if (pt == _basePoint)
                            {
                                return SamplerStatus.NoChange;
                            }
                            else
                            {
                                if (_useBasePoint)
                                {
                                    if (_rubberLine == null)
                                    {
                                        _rubberLine = new Line(_basePoint, pt);
                                        _rubberLine.SetDatabaseDefaults(_dwg.Database);

                                        IntegerCollection intCol;

                                        //Create transient graphics: rubberband line
                                        intCol = new IntegerCollection();
                                        TransientManager.CurrentTransientManager.
                                            AddTransient(_rubberLine, 
                                            TransientDrawingMode.DirectShortTerm, 128, intCol);
                                    }
                                    else
                                    {
                                        _rubberLine.EndPoint = pt;

                                        //Update the transient graphics
                                        IntegerCollection intCol = new IntegerCollection();
                                        TransientManager.CurrentTransientManager.
                                            UpdateTransient(_rubberLine, intCol);
                                    }
                                }

                                mat = Matrix3d.Displacement(_basePoint.GetVectorTo(pt));
                                return SamplerStatus.OK;
                            }
                        }
                    );

                if (_rubberLine != null)
                {
                    //Clear transient graphics
                    IntegerCollection intCol = new IntegerCollection(); 
                    TransientManager.CurrentTransientManager.
                        EraseTransient(_rubberLine, intCol);

                    _rubberLine.Dispose();
                    _rubberLine = null;
                }

                if (ptRes.Status == PromptStatus.OK)
                {
                    MoveObjects(ptRes.Value, tran);
                }

                //Unhighlight entities
                SetHighlight(false, tran);

                tran.Commit();
            }
        }

        public void DoDrag(bool pickBasePt)
        {
            _useBasePoint = pickBasePt;

            DoDrag();
        }

        public void DoDrag(Point3d basePt)
        {
            _basePoint = basePt;
            _useBasePoint = true;

            DoDrag();
        }

        #endregion

        #region private methods

        private Point3d GetDefaultBasePoint()
        {
            Point3d pt = new Point3d();

            Extents3d exts = new Extents3d(
                new Point3d(0.0, 0.0, 0.0), new Point3d(0.0, 0.0, 0.0));

            using (Transaction tran = 
                _dwg.Database.TransactionManager.StartTransaction())
            {
                ObjectId[] ids=_sset.GetObjectIds();
                for (int i = 0; i < ids.Length; i++ )
                {
                    ObjectId id = ids[i];
                    Entity ent = (Entity)tran.GetObject(id, OpenMode.ForRead);

                    if (i == 0)
                    {
                        exts = ent.GeometricExtents;
                    }
                    else
                    {
                        Extents3d ext = ent.GeometricExtents;
                        exts.AddExtents(ext);
                    }
                }

                tran.Commit();
            }

            return exts.MinPoint;
        }

        private bool PickBasePoint(Editor ed, out Point3d pt)
        {
            pt = new Point3d();

            PromptPointOptions opt = new PromptPointOptions("Pick base point: ");
            PromptPointResult res = ed.GetPoint(opt);
            if (res.Status == PromptStatus.OK)
            {
                pt = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }

        private void MoveObjects(Point3d pt, Transaction tran)
        {
            Matrix3d mat = Matrix3d.Displacement(_basePoint.GetVectorTo(pt));
            foreach (ObjectId id in _sset.GetObjectIds())
            {
                Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);
                ent.TransformBy(mat);
            }
        }

        private void SetHighlight(bool highlight, Transaction tran)
        {
            foreach (ObjectId id in _sset.GetObjectIds())
            {
                Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);

                if (highlight)
                    ent.Highlight();
                else
                    ent.Unhighlight();
            }
        }

        #endregion
    }
}

Here is the Command class:

using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[assembly: CommandClass(typeof(InteractiveDrag.MyCommand))]

namespace InteractiveDrag
{
    public class MyCommand
    {
        [CommandMethod("DragMove", CommandFlags.UsePickSet)]
        public static void DoMove()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;

            Editor ed = dwg.Editor;

            //Get PickFirst SelectionSet
            PromptSelectionResult setRes = ed.SelectImplied();

            if (setRes.Status != PromptStatus.OK)
            {
                //if not PickFirst set, ask user to pick:
                ObjectId[] ids = GetUserPickedObjects(dwg);
                if (ids.Length == 0)
                {
                    ed.WriteMessage("\n*Cancelled*");
                    ed.WriteMessage("\n*Cancelled*");
                    return;
                }

                ed.SetImpliedSelection(ids);
                setRes = ed.SelectImplied();

                if (setRes.Status != PromptStatus.OK)
                {
                    ed.Regen();
                    return;
                }
            }
            
            //Do the dragging with the selectionSet
            DragMove drag = new DragMove(dwg, setRes.Value);
            drag.DoDrag(true);
        }

        private static ObjectId[] GetUserPickedObjects(Document dwg)
        {
            List ids = new List();
            using (Transaction tran = 
                dwg.Database.TransactionManager.StartTransaction())
            {
                bool go = true;
                while (go)
                {
                    go = false;

                    PromptEntityOptions opt = 
                        new PromptEntityOptions("\nPick an entity: ");
                    PromptEntityResult res = dwg.Editor.GetEntity(opt);

                    if (res.Status == PromptStatus.OK)
                    {
                        bool exists = false;
                        foreach (ObjectId id in ids)
                        {
                            if (id == res.ObjectId)
                            {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists)
                        {
                            //Highlight
                            Entity ent = (Entity)tran.GetObject(
                                res.ObjectId, OpenMode.ForWrite);

                            ent.Highlight();

                            ids.Add(res.ObjectId);
                            go = true;
                        }
                    }
                }

                tran.Commit();
            }

            return ids.ToArray();
        }
    }
}

Build the project and "NETLOAD" it into AutoCAD. See this video clip for the behaviuor of the code shown above.

With some slight modification to the code one can easily do a drag-copying, drag-rotating...

Monday, December 27, 2010

Showing Progress Window When Running A Long Process

It is very often a command that does a complicated drawing/entities manipulation could take fair amount of time. During the command execution, it would be desired that something visual shows in AutoCAD to indicate the processing is in progress.

One option to do it is to use AutoCAD's progress meter, of course. However, many programmer would choose to show a small window with a progress bar. With this approach, the window can not only display a progress bar, but also display messages regarding the process execution.

This article presents a reusable progress window component that can be easily plugged into a long-running drawing process execution method.

The basic idea here is to define an interface (ILongProcessCommand) that raises events at beginning, ending and progressing of a process/command. Then the drawing manipulating process would be wrapped in a class that implements the said interface. The progress window component then will contain a reference of the drawing manipulating class (as the type of ILongProcessCommand) and subscribe the events (CommandStarted, CommandEnded and CommandProgress). The actual progress window will be shown, closed and updated in the event handler.

Since the goal is to create a reusable/pluggable progress window component, I created 2 projects in a VS solution:

1. Project "ProgressWindow"

As afore-mentioned, an interface is defined. Along with the interface are delegates and classes used for event raising/handling. Here is the code:

using System;

namespace ProgressWindow
{
    public interface ILongProcessCommand
    {
        event CommandStartedEventHandler CommandStarted;
        event CommandEndedEventHandler CommandEnded;
        event CommandProgressEventHandler CommandProgress;
    }

    public delegate void CommandStartedEventHandler(
        object sender, CommandStartEventArgs e);

    public delegate void CommandEndedEventHandler(
        object sender, EventArgs e);

    public delegate void CommandProgressEventHandler(
        object sender, CommandProgressEventArgs e);

    public class CommandStartEventArgs : System.EventArgs
    {
        public string WindowTitle { set; get; }
        public int ProgressMinValue { set; get; }
        public int ProgressMaxValue { set; get; }
        public int PrograssInitValue { set; get; }
        public System.Windows.Forms.ProgressBarStyle ProgressBarStyle { set; get; }

        public CommandStartEventArgs()
        {
            WindowTitle = "Command in Progress";
            ProgressMinValue = 0;
            ProgressMaxValue = 0;
            ProgressBarStyle = System.Windows.Forms.ProgressBarStyle.Continuous;
        }
    }

    public class CommandProgressEventArgs : System.EventArgs
    {
        public int ProgressValue { set; get; }
        public string ProgressTitle { set; get; }
        public string ProgressMessage { set; get; }

        public CommandProgressEventArgs()
        {
            ProgressValue = 0;
            ProgressTitle = "";
            ProgressMessage = "";
        }
    }
}

Then, a window form is added. It has a progress bar and 2 labels. The form's ControlBox property is set to False, so that it canot be closed by user accidently. See picture below:


Here is the code of the form:

using System.Windows.Forms;

namespace ProgressWindow
{
    public partial class dlgProgress : Form
    {
        public dlgProgress()
        {
            InitializeComponent();
        }

        public string ProgressTitleMessage
        {
            set { lblTitle.Text = value; }
            get { return lblTitle.Text; }
        }

        public string ProgressDetailMessage
        {
            set { lblMessage.Text = value; }
            get { return lblMessage.Text; }
        }

        public int ProgressMinValue
        {
            set { pBar.Minimum = value; }
            get { return pBar.Minimum; }
        }

        public int ProgressMaxValue
        {
            set { pBar.Maximum=value;}
            get { return pBar.Maximum;}
        }

        public int ProgressValue
        {
            set { pBar.Value = value; }
            get { return pBar.Value; }
        }
    }
}

Finally, I added a class "ProgressIndicator", shown as following:

using System;

namespace ProgressWindow
{
    public class ProgressIndicator : IDisposable 
    {
        private ILongProcessCommand _cmdObject = null;
        private dlgProgress _window = null;

        public ProgressIndicator(ILongProcessCommand cmdObj)
        {
            _cmdObject = cmdObj;

            WireCommandEvents();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_window!=null)
            {
                _window.Dispose();
            }
        }

        #endregion

        private void WireCommandEvents()
        {
            if (_cmdObject != null)
            {
                _cmdObject.CommandStarted += 
                    new CommandStartedEventHandler(_cmdObject_CommandStarted);

                _cmdObject.CommandEnded += 
                    new CommandEndedEventHandler(_cmdObject_CommandEnded);

                _cmdObject.CommandProgress +=
                    new CommandProgressEventHandler(_cmdObject_CommandProgress);
            }
        }

        void _cmdObject_CommandStarted(object sender, CommandStartEventArgs e)
        {
            if (_window!=null) _window.Dispose();

            _window = new dlgProgress();
            _window.Text = e.WindowTitle;
            _window.ProgressMinValue = e.ProgressMinValue;
            _window.ProgressMaxValue = e.ProgressMaxValue;
            _window.ProgressValue = e.PrograssInitValue;

            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(_window);

        }

        void  _cmdObject_CommandProgress(object sender, CommandProgressEventArgs e)
        {
            if (_window == null) return;

            _window.ProgressTitleMessage = e.ProgressTitle;
            _window.ProgressDetailMessage = e.ProgressMessage;
            _window.ProgressValue = e.ProgressValue;

            _window.Refresh();
            System.Windows.Forms.Application.DoEvents();
        }

        void _cmdObject_CommandEnded(object sender, EventArgs e)
        {
            if (_window == null) return;

            _window.Close();
        }
    }
}

Notice the constructor of the class take an ILongProcessCommand type as its argument and wire itself to the events of the ILongProcessCommand object. As long as the ILongProcessCommand fires an event (CommandStarted, CommandEnded, or CommandProgress), this class will show/close/update the progress window accordingly.

That is all for the reusable/pluggable progress window component. After building the project, it is ready to be used in drawing manipulating process as progress indicator.

2. Project "ProgressWindowSample"

This project is a regulaer AutoCAD managed DLL project. I added the first project as reference. I created a class "TestProcess". It has a method that is supposed to do some time consuming drawing data manipulating. To make things simple, I simply call Editor.SelectAll() to get ObjectId of all entities in the drawing into an ObjectIdCollection and then loop through each ObjectId to open eacg entity. If the drawing contains tens of thousands entities, the process would take a while. The kind of process would be good candidate process we want to show a progress indicator during the process.

Here is the code of class "TestProcess":

using System;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

using ProgressWindow;

namespace ProgressWindowSample
{
    public class TestProcess : ILongProcessCommand
    {
        private ObjectIdCollection _objIds = null;
        private Document _dwg;

        public TestProcess(Document dwg)
        {
            _dwg = dwg;
        }

        #region ILongProcessCommand Members

        public event CommandStartedEventHandler CommandStarted;

        public event CommandEndedEventHandler CommandEnded;

        public event CommandProgressEventHandler CommandProgress;

        #endregion

        public void DoSomeWork()
        {
            PromptSelectionResult res = _dwg.Editor.SelectAll();
            if (res.Status != PromptStatus.OK) return;

            _objIds = new ObjectIdCollection(res.Value.GetObjectIds());

            using (ProgressIndicator progress=new ProgressIndicator(this))
            {
                //Raise CommandStarted event that causes progress window to show
                if (CommandStarted != null)
                {
                    CommandStartEventArgs args = new CommandStartEventArgs();
                    args.WindowTitle = "Process All Entities in Current Drawing";
                    args.ProgressMaxValue = _objIds.Count;
                    args.ProgressMinValue = 0;
                    args.PrograssInitValue = 0;

                    CommandStarted(this, args);
                }

                ProcessDrawing(_objIds);

                //Raise CommandEnded event that closes progress widow
                if (CommandEnded != null)
                {
                    CommandEnded(this, EventArgs.Empty);
                }
            }
        }

        private void ProcessDrawing(ObjectIdCollection ids)
        {
            int count = 0;
            int total=ids.Count;

            using (DocumentLock lck = _dwg.LockDocument())
            {
                using (Transaction tran = 
                    _dwg.Database.TransactionManager.StartTransaction())
                {
                    foreach (ObjectId id in ids)
                    {
                        count++;
                        string entClass = id.ObjectClass.Name;

                        if (CommandProgress != null)
                        {
                            CommandProgressEventArgs args = new CommandProgressEventArgs();
                            args.ProgressTitle = "Processing entity: " + entClass;
                            args.ProgressMessage = 
                                count + " out of " + total + " entities processed...Please wait...";

                            args.ProgressValue = count;

                            CommandProgress(this, args);
                        }

                        Entity ent = (Entity)tran.GetObject(id, OpenMode.ForRead);

                        //Do something....
                        for (int i = 0; i < 10000; i++)
                        {
                            int x = i + 1000;
                            x = 0;
                        }
                    }

                    tran.Commit();
                }
            }
        }
    }
}

Notice that this class implements ILongProcessCommand interface. It is the resposibility of this class to raise appropriate event using the drawing data process (in this case, in public method "DoSomeWork()"), and pass suitable data to the EventArgs.

Now, let's put everything together in a command method to see the actual effect:

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;

namespace ProgressWindowSample
{
    public class TestCommand
    {
        [CommandMethod("DoWork")]
        public static void RunLongCommand()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;

            try
            {
                TestProcess prog = new TestProcess(dwg);
                prog.DoSomeWork();

                dwg.Editor.WriteMessage("\nProcess completed");
            }
            catch (System.Exception ex)
            {
                dwg.Editor.WriteMessage("\nError: " + ex.Message);
            }
        }
    }
}

Now, build the project, start AutoCAD, netload "ProgressWindowSample.dll". Open a drawing with a lot of entities in it and enter command "DoWork". This video clip shows the progress window's effect.

As you can see, the ProgressIndicator component knows nothing about the actual long processing and only responds to the ILongProcessCommand's events to show/close/update progress window. As long as you wrap the long running CAD operation into a class that implements ILongProcessCommand and fire up appropriate event when needed, the progress window will automatically present the progress.

Thursday, November 18, 2010

Dragging a Line in Certain Angle

This article is inspired by a question posted in the Autodesk's Visual Basic Customization user forum. Baiscally, while drawing a line, after picking the start point, the user wants the ghost line only stretch in certain direction/angle, similar effect as the Ortho-On mode. Well, as a programmer, not a drafter/designer, I am not very sure how often this kind of fuctionality is desired in AutoCAD use. If one wants to draw a line that he knows the line's start/end point, or start point, lenght and direction/angle, he can alway enter them easily at command line. However I can imagine that during designing (nt drafting) process, the designer may want to draw a line, starting at a known point and she'd like it to be stretched at certain angle with undecided length.

Regardless it possible use/benefit an AutoCAD user may find, here is the code to do this. Yes, as you may have guessed, I used TransientGraphics again.

Here is the class that do the dynamic dragging. At the end of AngledDrag() call, the class provides two points (Point3d) - StartPoint and EndPoint as public read-only properties for the calling procedure to use.

using System;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace AngleLockedDrag
{
    public class AngledDrag
    {
        private Document _dwg;
        private Database _db;
        private Editor _editor;

        private Point3d _startPoint = new Point3d(0.0, 0.0, 0.0);
        private Point3d _endPoint = new Point3d(0.0, 0.0, 0.0);

        private double _dragAngle = 45.0;

        private Line _dragLine = null;
        private int _colorIndex = 1;

        public AngledDrag(Document dwg)
        {
            _dwg = dwg;
            _db = dwg.Database;
            _editor = dwg.Editor;
        }

        public Point3d StartPoint
        {
            get { return _startPoint; }
        }

        public Point3d EndPoint
        {
            get { return _endPoint; }
        }

        #region public methods

        public bool DragAtAngle()
        {
            _endPoint = _startPoint;

            _editor.PointMonitor += 
                new PointMonitorEventHandler(Editor_PointMonitor);

            try
            {
                //Get end point
                if (GetEndPoint())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            finally
            {
                ClearTransientGraphics();
                _editor.PointMonitor -= Editor_PointMonitor;
            }
        }

        #endregion

        #region private methods

        private void Editor_PointMonitor(
            object sender, PointMonitorEventArgs e)
        {
            DrawDragLine(e.Context.RawPoint);
            if (_dragLine != null)
            {
                e.AppendToolTipText("Angle: " + 
                    _dragAngle.ToString() + "\nLength: " + 
                    _dragLine.Length.ToString());
            }
            else
            {
                e.AppendToolTipText("");
            }
        }

        private void DrawDragLine(Point3d mousePoint)
        {
            ClearTransientGraphics();

            Point3d pt = CalculateEndPoint(mousePoint);

            _dragLine = new Line(_startPoint, pt);
            _dragLine.SetDatabaseDefaults(_db);
            _dragLine.ColorIndex = _colorIndex;

            IntegerCollection col = new IntegerCollection();
            TransientManager.CurrentTransientManager.AddTransient(
                _dragLine, TransientDrawingMode.Highlight, 128, col);

            //whenever the dragged line updated, reset _endPoint
            _endPoint = pt;
        }

        private void ClearTransientGraphics()
        {
            if (_dragLine != null)
            {
                IntegerCollection col = new IntegerCollection();
                TransientManager.CurrentTransientManager.
                    EraseTransient(_dragLine, col);

                _dragLine.Dispose();
                _dragLine = null;
            }
        }

        private Point3d CalculateEndPoint(Point3d mousePoint)
        {
            Point3d pt = mousePoint;

            if (_dragAngle <= 90.0 || _dragAngle >= 270.0)
            {
                if (mousePoint.X <= _startPoint.X)
                {
                    pt = _startPoint;
                }
                else
                {
                    if (_dragAngle <= 45.0 || _dragAngle >= 315.0)
                    {
                        double y = (mousePoint.X - _startPoint.X) * 
                            Math.Tan(_dragAngle * Math.PI / 180);
                        pt = new Point3d(
                            mousePoint.X, _startPoint.Y + y, 0.0);
                    }
                    else
                    {
                        if (_dragAngle > 45.0 && _dragAngle <= 90.0)
                        {
                            if (mousePoint.Y < _startPoint.Y)
                            {
                                pt = _startPoint;
                            }
                            else
                            {
                                double x = (mousePoint.Y - _startPoint.Y) / 
                                    Math.Tan(_dragAngle * Math.PI / 180);
                                pt = new Point3d(
                                    _startPoint.X + x, mousePoint.Y, 0.0);
                            }
                        }
                        else
                        {
                            if (mousePoint.Y > _startPoint.Y)
                            {
                                pt = _startPoint;
                            }
                            else
                            {
                                double x = (mousePoint.Y - _startPoint.Y) / 
                                    Math.Tan(_dragAngle * Math.PI / 180);
                                pt = new Point3d(
                                    _startPoint.X + x, mousePoint.Y, 0.0);
                            }
                        }
                    }

                    return pt;
                }
            }

            if (_dragAngle >= 90.0 && _dragAngle <= 270.0)
            {
                if (mousePoint.X >= _startPoint.X)
                {
                    pt = _startPoint;
                }
                else
                {
                    if (_dragAngle >= 135.0 && _dragAngle <= 225.0)
                    {
                        double y = (mousePoint.X - _startPoint.X) * 
                            Math.Tan(_dragAngle * Math.PI / 180);
                        pt = new Point3d(
                            mousePoint.X, _startPoint.Y + y, 0.0);
                    }
                    else
                    {
                        if (_dragAngle >=90.0 && _dragAngle < 135.0)
                        {
                            if (mousePoint.Y <= _startPoint.Y)
                            {
                                pt = _startPoint;
                            }
                            else
                            {
                                double x = (mousePoint.Y - _startPoint.Y) / 
                                    Math.Tan(_dragAngle * Math.PI / 180);
                                pt = new Point3d(
                                    _startPoint.X + x, mousePoint.Y, 0.0);
                            }
                        }
                        else
                        {
                            if (mousePoint.Y >= _startPoint.Y)
                            {
                                pt = _startPoint;
                            }
                            else
                            {
                                double x = (mousePoint.Y - _startPoint.Y) / 
                                    Math.Tan(_dragAngle * Math.PI / 180);
                                pt = new Point3d(
                                    _startPoint.X + x, mousePoint.Y, 0.0);
                            }
                        }
                        
                    }

                    return pt;
                }
            }

            return pt;
        }

        private bool GetEndPoint()
        {
            //endPoint = new Point3d();

            bool go = true;
            bool picked = false;

            while (go)
            {
                PromptPointOptions opt = new PromptPointOptions("\nPick point:");
                //opt.BasePoint = _startPoint;
                //opt.UseBasePoint = true;
                opt.Keywords.Add("Start point");
                opt.Keywords.Add("Angle");
                opt.Keywords.Add("End point");
                opt.Keywords.Add("eXit");
                opt.Keywords.Default = "End point";
                opt.AppendKeywordsToMessage = true;
                opt.AllowArbitraryInput = false;
                opt.AllowNone = false;

                PromptPointResult res = _editor.GetPoint(opt);
                if (res.Status == PromptStatus.Cancel)
                {
                    go = false; ;
                }
                else
                {
                    switch (res.Status)
                    {
                        case PromptStatus.Keyword:
                            //_editor.WriteMessage("\n" + res.StringResult);
                            if (res.StringResult.StartsWith("Start"))
                            {
                                SetStartPoint();
                                go = true;
                            }
                            if (res.StringResult.StartsWith("Angle"))
                            {
                                SetAngle();
                                go = true;
                            }
                            if (res.StringResult.StartsWith("eXit"))
                            {
                                go = false;
                            }
                            break;
                        case PromptStatus.OK:
                            //endPoint = res.Value;
                            picked = true;
                            go = false;
                            break;
                        default:
                            go = true;
                            break;
                    }
                }
            }

            return picked;
        }

        private void SetStartPoint()
        {
            ClearTransientGraphics();
            _editor.PointMonitor -= Editor_PointMonitor;

            PromptPointOptions opt = 
                new PromptPointOptions("\nStart point:");
            PromptPointResult res = _editor.GetPoint(opt);
            if (res.Status == PromptStatus.OK)
            {
                _startPoint = res.Value;
            }

            _editor.PointMonitor += 
                new PointMonitorEventHandler(Editor_PointMonitor);
        }

        private void SetAngle()
        {
            ClearTransientGraphics();
            _editor.PointMonitor -= Editor_PointMonitor;

            PromptDoubleOptions opt = 
                new PromptDoubleOptions("\nEnter drag-angle in degree [" + 
                    _dragAngle.ToString() + "]: ");
            opt.AllowNegative = false;
            opt.AllowZero = true;
            opt.AllowNone = true;

            PromptDoubleResult res = _editor.GetDouble(opt);

            if (res.Status == PromptStatus.OK)
            {
                _dragAngle = res.Value;
                if (_dragAngle > 360.0) _dragAngle -= 360.0;
            }

            _editor.PointMonitor += 
                new PointMonitorEventHandler(Editor_PointMonitor);
        }

        #endregion
    }
}

Here is the command class that uses the AngleLockedDrag class to draw a Line in AutoCAD.

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[assembly: CommandClass(typeof(AngleLockedDrag.DragCommand))]

namespace AngleLockedDrag
{
    public class DragCommand
    {
        [CommandMethod("AngledDrag")]
        public void RunThisMethod()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;

            AngledDrag drag = new AngledDrag(dwg);
            try
            {
                if (drag.DragAtAngle())
                {
                    GenerateLine(dwg, drag.StartPoint, drag.EndPoint);

                    dwg.Editor.WriteMessage("\nMyCommand executed.");
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                dwg.Editor.WriteMessage("\nError: {0}\n", ex.Message);
            }
        }

        private static void GenerateLine(
            Document dwg, Point3d startPt, Point3d endPt)
        {
            using (Transaction tran = 
                dwg.Database.TransactionManager.StartTransaction())
            {
                BlockTableRecord br = (BlockTableRecord)tran.GetObject(
                    dwg.Database.CurrentSpaceId, OpenMode.ForWrite);
                
                Line line = new Line(startPt, endPt);
                line.SetDatabaseDefaults(dwg.Database);

                br.AppendEntity(line);
                tran.AddNewlyCreatedDBObject(line, true);
                tran.Commit();
            }
        }
    }
}

Here is the video clip that shows the "angled dragging" effect.

Friday, November 5, 2010

Dynamically Draw An Array Of Entities

One of the exciting things when an AutoCAD VBA programmer moves into AutoCAD .NET API world is that he/she suddenly gain a capability to create dynamic visual hint (ghost image) when the code ask user to interact with the drawing editor, namely the capability to create JIG. Besides, since AutoCAD 2009 introduced TransientGraphics, it is even easier do add visual hint in the code when the user has to interact with AutoCAD editor during code execution.

In this post I am going to show a piece of code that creates an array of entities in following operation steps:

1. User pick an entity he/she wants to create an array of copy of this entity;
2. The user does not know how many entities could fit into a space, but he/she has a desired distance between each 2 entities. Or the user simply does not bother to calculate how many entities could fit in, he/she just want to move the mouse and see how the array of entities fits in a give space. So, the user would enter a desired space increment for the entities in the array;
3. The user pick a base point;
4. The user moves the mouse around, the ghost image of an array of entities shows dynamically, which automatically show the count of entities in the array, depending on how far the mouse pointer is from the base point;
5. If user clicks the mouse again, an array of entity copies is created. If user cancels the pick for the second point, the ghost image is gone, no entity array is created.

There is a link at the bottom of this article that leads you to see a video clip of the result of running the code.

Again, I use TransientGraphics (I just love it!) to achieve my goal. Here is the code.

Firstly, I created an Interface IDynamicDrawTool. It is not a must. Currently, the code only create an array of entities along a straight line. Later I could create the array along an arc, circle...I would like all the later possible tool all implement this interface.

namespace DynamicDrawTool
{
    public interface IDynamicDrawTool
    {
        void DrawEntities();
    }
}

Then here is the command class:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[assembly: CommandClass(typeof(DynamicDrawTool.DynamicDrawCommands))]

namespace DynamicDrawTool
{
    public class DynamicDrawCommands
    {
        [CommandMethod("DynDraw")]
        public static void RunThisMethod()
        {
            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;

            Editor ed = dwg.Editor;

            //Pick and entity
            PromptEntityOptions opt = new PromptEntityOptions
                ("\nPick a source entity:");

            PromptEntityResult res = ed.GetEntity(opt);

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

            IDynamicDrawTool drawTool = new LinearDynamicDrawTool(dwg, res.ObjectId);

            try
            {
                drawTool.DrawEntities();

                dwg.Editor.WriteMessage(
                    "\nMyCommand executed successfully.");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                dwg.Editor.WriteMessage(
                    "\nMyCommand execution failed:\n" + ex.Message);
            }
        }
    }
}

Finally, the code doing the real work:

using System;
using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace DynamicDrawTool
{
    public class LinearDynamicDrawTool : IDynamicDrawTool 
    {
        private Document _dwg;
        private Editor _editor;
        private ObjectId _sourceEntId;

        private Point3d _startPoint;
        private Point3d _endPoint;
        private double _increment = 0.0;

        private Line _guideLine = null;
        private List _clonedEntities = new List();

        private int _colorIndex = 1;
        private int _originalColorIndex = 0;

        public LinearDynamicDrawTool(Document dwg, ObjectId sourceEntId)
        {
            _dwg = dwg;
            _editor = _dwg.Editor;
            _sourceEntId = sourceEntId;
        }

        public int GuideLineColorIndex
        {
            set { _colorIndex = value; }
            get { return _colorIndex; }
        }

        public void DrawEntities()
        {
            //Pick start point
            if (!GetPoint("Pick start point:", out _startPoint)) return;

            //Get incremting distance
            if (!GetIncrement(out _increment)) return;

            //Hook up to PointerMoniter event
            _editor.PointMonitor += 
                new PointMonitorEventHandler(_editor_PointMonitor);

            try
            {
                //Pick end point
                if (GetPoint("Pick end point:", out _endPoint))
                {
                    //Draw real entities exactly as 
                    //the transient graphics shows
                    AddEntities();
                }
            }
            finally
            {
                //Clear transient graphics and remove PointMonitor handler
                ClearTransientGraphics();
                _editor.PointMonitor -= _editor_PointMonitor;
            }
        }

        #region private methods: draw transient graphics

        private void _editor_PointMonitor(
            object sender, PointMonitorEventArgs e)
        {
            DrawTransientGrapgics(e.Context.RawPoint);
        }

        private void DrawTransientGrapgics(Point3d pt)
        {
            //Clear existing transient graphics
            ClearTransientGraphics();

            //Draw guideline
            _guideLine = new Line(_startPoint, pt);
            _guideLine.SetDatabaseDefaults(_dwg.Database);
            _guideLine.ColorIndex = _colorIndex;

            IntegerCollection col = new IntegerCollection();
            TransientManager.CurrentTransientManager.AddTransient(
                _guideLine, TransientDrawingMode.DirectShortTerm, 128, col);

            //Draw cloned entities
            DrawClonedEntityTransientGraphics(pt);
        }

        private void DrawClonedEntityTransientGraphics(Point3d pt)
        {
            //Calculate count of cloned entities
            int count = CalculateCloneCount(pt);
            if (count < 1) return;

            Entity sourceEnt = GetSourceEntity();
            _originalColorIndex = sourceEnt.ColorIndex;

            //Draw cloned entities as transient graphics
            for (int i = 1; i <= count; i++)
            {
                Entity ent = sourceEnt.Clone() as Entity;
                ent.ColorIndex = _colorIndex;

                //Move to target location
                SetClonedEntityPosition(i, ent);

                //Draw as transient graphics
                IntegerCollection col = new IntegerCollection();
                TransientManager.CurrentTransientManager.AddTransient(
                    ent, TransientDrawingMode.DirectShortTerm, 128, col);

                _clonedEntities.Add(ent);
            }
        }

        private int CalculateCloneCount(Point3d pt)
        {
            double dis = _startPoint.DistanceTo(pt);

            if (dis <= _increment)
                return 0;
            else
                return Convert.ToInt32(Math.Floor(dis / _increment));
        }

        private Entity GetSourceEntity()
        {
            Entity ent = null;

            using (Transaction tran = 
                _dwg.Database.TransactionManager.StartTransaction())
            {
                ent = (Entity)tran.GetObject(_sourceEntId, OpenMode.ForRead);
                tran.Commit();
            }

            return ent;
        }

        private void SetClonedEntityPosition(int index, Entity ent)
        {
            double dist = _increment * index;
            Point3d pt = _guideLine.GetPointAtDist(dist);

            ent.TransformBy(
                Matrix3d.Displacement(_startPoint.GetVectorTo(pt)));
        }

        private void ClearTransientGraphics()
        {
            //Clear guide line
            if (_guideLine != null)
            {
                IntegerCollection col = new IntegerCollection();
                TransientManager.CurrentTransientManager.
                    EraseTransient(_guideLine, col);

                _guideLine.Dispose();
                _guideLine = null;
            }

            //Clear cloned entities
            foreach (Entity ent in _clonedEntities)
            {
                if (ent != null)
                {
                    IntegerCollection col = new IntegerCollection();
                    TransientManager.CurrentTransientManager.
                        EraseTransient(ent, col);

                    ent.Dispose();
                }
            }

            _clonedEntities.Clear();
        }

        private void AddEntities()
        {
            using (DocumentLock lk = _dwg.LockDocument())
            {
                using (Transaction tran = 
                    _dwg.Database.TransactionManager.StartTransaction())
                {
                    BlockTableRecord br = 
                        (BlockTableRecord)tran.GetObject(
                        _dwg.Database.CurrentSpaceId, OpenMode.ForWrite);

                    foreach (Entity ent in _clonedEntities)
                    {
                        Entity newEnt = ent.Clone() as Entity;
                        newEnt.SetDatabaseDefaults(_dwg.Database);
                        newEnt.ColorIndex = _originalColorIndex;

                        br.AppendEntity(newEnt);
                        tran.AddNewlyCreatedDBObject(newEnt, true);
                    }

                    tran.Commit();
                }
            }
        }

        #endregion

        #region private methods: miscellaneous

        private bool GetPoint(string prompt, out Point3d point)
        {
            point = new Point3d(0.0, 0.0, 0.0);

            PromptPointOptions opt = 
                new PromptPointOptions("\n" + prompt);
            opt.AllowNone = false;

            PromptPointResult res = _editor.GetPoint(opt);

            if (res.Status == PromptStatus.OK)
            {
                point = res.Value;
                return true;
            }

            return false;
        }

        private bool GetIncrement(out double increment)
        {
            increment = 0.0;

            PromptDoubleOptions opt = 
                new PromptDoubleOptions("\nIncrementing distance:");

            PromptDoubleResult res = _editor.GetDouble(opt);

            if (res.Status == PromptStatus.OK)
            {
                increment = res.Value;
                return true;
            }

            return false;
        }

        #endregion
    }
}

Click here to see the a video clip showing how it works.

Obviously, there are more can be done to improve it. I have exposed ColorIndex as public property so that we can set the color of guide line/ghost image of the entities prior to calling DrawEntities() method. We can also do the similar thing to set LineWeight or line width (if it is polyline), LineType (use dash line would be more in line with AutoCAD standard).

Of course the user input part could also be enhanced to allow user to try different distance increment during mouse move.

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.