Monday, June 30, 2014

Open A Viewport From ModelSpace

I posted an article on selecting entities in ModelSpace that are visible from a PaperSpace Viewport a while ago. The key point of that article is to identify an area in ModelSpace that is visible in a "Display-Locked" Viewport in PaperSpace.

While writing that article, I was thinking it would be another topic that I would write on: opening a Viewport based on selected area in ModelSpace.

When presenting content in ModelSpace on a layout, user usually:
  • Set a selected layout current;
  • Open a Viewport;
  • Activate the Viewport into with "MSpace";
  • Twist the view angle if necessary;
  • Scale the view in the Viewport;
  • Pan the view in the Viewport to fit the desired drawing content to be shown in the Viewport;
  • Finally, lock the Viewport's display.
I was thinking that the process can be simplified like this:
  • In ModelSpace, user select an area with a polygon that is to be shown in a PaperSpace Viewport. It would be similar to AutoCAD's polygon selection;
  • User select an angle that the view would be twisted in Viewport;
  • User specify the view scale in Viewport;
  • A Viewport will be opened on given layout that scaled and twisted properly to fit the selected area/polygon, which encloses the drawing content to be shown in the opened Viewport.
As you can see, since the user usually already knows the view scale and the view twist angle when he/she is ready to present drawing content in Viewports on layout, the proposed process means that user just need to specify what area to be shown, a Viewport would be opened with proper size, scale and twist angle.

With this topic hanging in my mind for a few months, I finally found a bit time to actually write some code to see it in action.

First, I defined a class ViewportBoundaryInfo that represents a rectangle Viewport being projected into ModelSpace:

using Autodesk.AutoCAD.Geometry;
 
namespace OpenViewportFromModelSpace
{
    public class ViewportBoundaryInfo
    {
        public Point3d Centre
        {
            get
            {
                double x =
                    (PointLL.X + PointLU.X + PointRL.X + PointRU.X) / 4.0;
                double y =
                    (PointLL.Y + PointLU.Y + PointRL.Y + PointRU.Y) / 4.0;
                double z =
                    (PointLL.Z + PointLU.Z + PointRL.Z + PointRU.Z) / 4.0;
 
                return new Point3d(x, y, z);
            }
        }
        public Point3d PointLL { setget; }
 
        public Point3d PointLU { setget; }
 
        public Point3d PointRU { setget; }
 
        public Point3d PointRL { setget; }
 
        public double Rotation { setget; }
 
        public double Width
        {
            get { return PointLL.DistanceTo(PointRL); }
        }
 
        public double Height
        {
            get { return PointLL.DistanceTo(PointLU); }
        }
 
        public Point3dCollection RectanglePointsInModel
        {
            get
            {
                Point3dCollection points = new Point3dCollection();
                points.Add(PointLL);
                points.Add(PointRL);
                points.Add(PointRU);
                points.Add(PointLU);
                return points;
            }
        }
 
        public double TwistAngle { setget; }
 
        public ViewportBoundaryInfo()
        {
            PointLL = new Point3d();
            PointLU = new Point3d();
            PointRL = new Point3d();
            PointRU = new Point3d();
            TwistAngle = 0.0;
        }
    }
 
}

Then I decided to design a class that collect user input on which drawing area in ModelSpace to be shown in a Viewport. As the result of user input, the boundary of Viewport to be created would be the output. User also get chance to see the boundary rectangle before proceeding to actually create the Viewport. Here is the class OpenViewportVisualHelper:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
 
namespace OpenViewportFromModelSpace
{
    public class OpenViewportVisualHelper : IDisposable 
    {
        private Document _dwg;
        private Editor _ed;
        private Database _db;
        private TransientManager _tsManager;
 
        private ViewportBoundaryInfo _vpBoundaryInfo = null;
 
        private Point3dCollection _polygonPoints = null;
        private CadDb.Polyline _polygon = null;
        private CadDb.Polyline _rectangle = null;
        public OpenViewportVisualHelper(Document dwg)
        {
            _dwg=dwg;
            _ed=dwg.Editor;
            _db=dwg.Database;
            _tsManager = TransientManager.CurrentTransientManager;
        }
 
        public ViewportBoundaryInfo ViewportBoundaryInfo
        {
            get { return _vpBoundaryInfo; }
        }
 
        public bool PickEnclosingPolygon()
        {
            ViewportBoundaryInfo vportInfo = new ViewportBoundaryInfo();
 
            if (!PickEnclosingPoints()) return false;
 
            if (_polygon != null)
            {
                double twistAngle;
                if (PickTwistAngle(_ed, out twistAngle))
                {
                    Point3d pLL, pRL, pRU, pLU;
                    GetTwistedBoundingBox(_polygon, twistAngle,
                        out pLL, out pRL, out pRU, out pLU);
 
                    vportInfo.PointLL = pLL;
                    vportInfo.PointRL = pRL;
                    vportInfo.PointRU = pRU;
                    vportInfo.PointLU = pLU;
 
                    vportInfo.TwistAngle = twistAngle;
                }
 
                _vpBoundaryInfo = vportInfo;
 
                DrawEnclosingPolygon(_polygonPoints);
                DrawViewportRectangle(vportInfo.RectanglePointsInModel);
                _ed.UpdateScreen();
 
                PromptKeywordOptions opt = new PromptKeywordOptions(
                    "\nDraw viewport boundary in ModelSpace permanently?");
                opt.AppendKeywordsToMessage = true;
                opt.Keywords.Add("Yes");
                opt.Keywords.Add("No");
                opt.Keywords.Default = "Yes";
                PromptResult res = _ed.GetKeywords(opt);
                bool ok = true;
                if (res.Status == PromptStatus.OK)
                {
                    if (res.StringResult == "Yes")
                    {
                        AddRectangleToModelSpace(_rectangle);
                    }
                }
                else
                {
                    ok = false;
                }
 
                _tsManager.EraseTransient(
                    _polygon, new IntegerCollection());
                _tsManager.EraseTransient(
                    _rectangle, new IntegerCollection());
 
                _polygon.Dispose();
                _rectangle.Dispose();
 
                return ok;
            }
            else
            {
                return false;
            }
        }
 
        public void Dispose()
        {
            if (_polygon!=null)
            {
                _tsManager.EraseTransient(_polygon, new IntegerCollection());
                _polygon.Dispose();
            }
 
            if (_rectangle!=null)
            {
                _tsManager.EraseTransient(_rectangle, new IntegerCollection());
                _rectangle.Dispose();
            }
        }
 
        #region private methods
 
        private bool PickEnclosingPoints()
        {
            bool ok = true;
            _polygonPoints = new Point3dCollection();
 
            _ed.PointMonitor += MyPointMonitor;
 
            while(true)
            {
                string msg;
                PromptPointOptions opt;
 
                if (_polygonPoints.Count == 0)
                {
                    msg = "Select first point of enclosing polyline:";
                    opt = new PromptPointOptions("\n" + msg);
                }
                else if (_polygonPoints.Count == 1)
                {
                    msg = "Select second point of enclosing polyline:";
                    opt = new PromptPointOptions("\n" + msg);
                    opt.UseBasePoint = true;
                    opt.BasePoint = _polygonPoints[0];
                    opt.UseDashedLine = true;
                }
                else
                {
                    msg = "select next point of enclosing polyline:";
                    opt = new PromptPointOptions("\n" + msg);
                }
 
                if (_polygonPoints.Count > 2)
                {
                    opt.Keywords.Add("Done");
                    opt.Keywords.Default = "Done";
                    opt.AllowNone = true;
                }
 
                PromptPointResult res = _ed.GetPoint(opt);
                if (res.Status==PromptStatus.OK || res.Status==PromptStatus.Keyword)
                {
                    if (res.Status == PromptStatus.OK)
                    {
                        _polygonPoints.Add(res.Value);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    ok = false;
                    break;
                }
            }
 
            _ed.PointMonitor -= MyPointMonitor;
 
            DrawEnclosingPolygon(_polygonPoints);
 
            return ok;
        }
 
        private void MyPointMonitor(object sender, PointMonitorEventArgs e)
        {
            Point3dCollection points = new Point3dCollection();
            foreach (Point3d p in _polygonPoints)
            {
                points.Add(p);
            }
            points.Add(e.Context.RawPoint);
            DrawEnclosingPolygon(points);
        }
 
        private void DrawEnclosingPolygon(Point3dCollection points)
        {
            if (_polygon != null)
            {
                _tsManager.EraseTransient(_polygon, new IntegerCollection());
                _polygon.Dispose();
                _polygon = null;
            }
 
            _polygon = CreatePolygonFromPoints(points);
            _tsManager.AddTransient(
                _polygon, 
                TransientDrawingMode.DirectTopmost, 
                128, 
                new IntegerCollection());
        }
 
        private void DrawViewportRectangle(Point3dCollection points)
        {
            if (_rectangle!=null)
            {
                _tsManager.EraseTransient(_rectangle, new IntegerCollection());
                _rectangle.Dispose();
                _rectangle = null;
            }
 
            _rectangle = CreatePolygonFromPoints(points);
            _tsManager.AddTransient(
                _rectangle, 
                TransientDrawingMode.DirectTopmost, 
                128, 
                new IntegerCollection());
        }
 
        private CadDb.Polyline CreatePolygonFromPoints(Point3dCollection points)
        {
            CadDb.Polyline pl = new CadDb.Polyline(points.Count);
 
            for (int i = 0; i < points.Count; i++ )
            {
                pl.AddVertexAt(
                    i, new Point2d(points[i].X, points[i].Y), 0.0, 0.0, 0.0);
            }
 
            pl.ColorIndex = 2;
            if (pl.NumberOfVertices > 2) pl.Closed = true;
             
            return pl;
        }
 
        private bool PickTwistAngle(Editor ed, out double twistAngle)
        {
            twistAngle = 0.0;
 
            Point3d pt1, pt2;
 
            ed.WriteMessage(
                "\nDetermine viewport twist angle by " +
                "selecting 2 points as a horizontal line in viewport.");
            PromptPointOptions opt = new PromptPointOptions(
                "\nSelect first point:");
 
            PromptPointResult res = ed.GetPoint(opt);
            if (res.Status == PromptStatus.OK)
            {
                pt1 = res.Value;
 
                opt = new PromptPointOptions("\nSelect second point:");
                opt.UseBasePoint = true;
                opt.UseDashedLine = true;
                opt.BasePoint = pt1;
 
                res = ed.GetPoint(opt);
                if (res.Status == PromptStatus.OK)
                {
                    pt2 = res.Value;
 
                    //We can calculate the angle based on the 2 points
                    //Being lazy, I use a line to get the angle
                    using (CadDb.Line line=new CadDb.Line(pt1,pt2))
                    {
                        twistAngle = line.Angle;
                    }
 
                    return true;
                }
            }
 
            return false;
        }
 
        private void GetTwistedBoundingBox(
            CadDb.Polyline pl, double twistAngle,
            out Point3d pointLL, out Point3d pointRL,
            out Point3d pointRU, out Point3d pointLU)
        {
 
            Point3d pt = pl.GetPoint3dAt(0);
            double ang = Math.PI * 2.0 - twistAngle;
            Matrix3d mt = Matrix3d.Rotation(ang, Vector3d.ZAxis, pt);
 
            //Clone the polyline
            CadDb.Polyline clone = pl.Clone() as CadDb.Polyline;
            using (clone)
            {
                clone.TransformBy(mt);
                Extents3d ext = clone.GeometricExtents;
                pointLL = (new Point3d(ext.MinPoint.X, ext.MinPoint.Y, 0.0))
                    .TransformBy(mt.Inverse());
                pointRL = (new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, 0.0))
                    .TransformBy(mt.Inverse());
                pointRU = (new Point3d(ext.MaxPoint.X, ext.MaxPoint.Y, 0.0))
                    .TransformBy(mt.Inverse());
                pointLU = (new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, 0.0))
                    .TransformBy(mt.Inverse());
            }
        }
 
        private void AddRectangleToModelSpace(CadDb.Polyline pl)
        {
            using (Transaction tran=
                _dwg.TransactionManager.StartTransaction())
            {
                BlockTableRecord model = (BlockTableRecord)tran.GetObject(
                    SymbolUtilityServices.GetBlockModelSpaceId(_db),
                    OpenMode.ForWrite);
                model.AppendEntity(pl);
                tran.AddNewlyCreatedDBObject(pl, true);
                tran.Commit();
            }
        }
 
        #endregion
    }
}

Since I used TransientGraphics to show the desired drawing content to be shown in the Viewport (the selecting polygon) and the Viewport boundary rectangle, thus temporary, non-database-residing entity (Polyline) is used. So, I implemented IDispose interface with this class. This way, I can use much simple "using {...}" block to make sure the temporary entity being disposed.

Now that I can correctly capture user input on what portion of drawing content in ModelSpace to be displayed in a Viewport, I can then write some code to open a Viewport on specific layout. The Viewport would show exactly the rectangle Viewport boundary the user wants. Here is the code in class CadHelper:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
namespace OpenViewportFromModelSpace
{ 
 public class CadHelper
 {
  public static string SelectLayout()
  {
   Document dwg = CadApp.DocumentManager.MdiActiveDocument;
   Editor ed = dwg.Editor;
 
   PromptStringOptions opt=new PromptStringOptions(
    "\nEnter the name of a layout, " +
    "where viewport will be created: ");
   opt.AllowSpaces = true;
 
   PromptResult res = ed.GetString(opt);
   if (res.Status == PromptStatus.OK)
   {
    return res.StringResult;
   }
   else
   {
    return null;
   }
  }
 
  public static double GetPaperToModelScale()
  {
   Document dwg = CadApp.DocumentManager.MdiActiveDocument;
   Editor ed = dwg.Editor;
 
   PromptDoubleOptions opt = new PromptDoubleOptions(
    "\nEnter PaperSpace scale for the viewport:");
   opt.AllowNegative = false;
   opt.AllowZero = false;
   opt.AllowNone = false;
   opt.AllowArbitraryInput = false;
   opt.DefaultValue = 1.0;
   opt.UseDefaultValue = true;
 
   PromptDoubleResult res = ed.GetDouble(opt);
   if (res.Status==PromptStatus.OK)
   {
    return res.Value;
   }
   else
   {
    return double.MinValue;
   }
  }
 
  public static ObjectId CreateRectangularViewport(
   string layout, string layer, 
   double paperToModelScale,
   ViewportBoundaryInfo vportInfo)
  {
   //Create a vewport in the center of the layout
   Document dwg=CadApp.DocumentManager.MdiActiveDocument;
   ObjectId vpId = OpenViewport(
    dwg, 
    layout, 
    layer, 
    vportInfo.TwistAngle, 
    paperToModelScale, 
    vportInfo.Centre);
 
   //Resize the viewport
   ResizeViewport(dwg, vpId, vportInfo, paperToModelScale);
 
   return ObjectId.Null;
  }
 
  #region code borrowed from www.theswamp.org
  //**********************************************************************
  //Create coordinate transform matrix 
  //between modelspace and paperspace viewport
 
  //The code is borrowed from
  //http://www.theswamp.org/index.php?topic=34590.msg398539#msg398539
  //*********************************************************************
  public static Matrix3d PaperToModel(Viewport vp)
  {
   Matrix3d mx = ModelToPaper(vp);
   return mx.Inverse();
  }
 
  public static Matrix3d ModelToPaper(Viewport vp)
  {
   Vector3d vd = vp.ViewDirection;
   Point3d vc = new Point3d(vp.ViewCenter.X, vp.ViewCenter.Y, 0);
   Point3d vt = vp.ViewTarget;
   Point3d cp = vp.CenterPoint;
   double ta = -vp.TwistAngle;
   double vh = vp.ViewHeight;
   double height = vp.Height;
   double width = vp.Width;
   double scale = vh / height;
   double lensLength = vp.LensLength;
   Vector3d zaxis = vd.GetNormal();
   Vector3d xaxis = Vector3d.ZAxis.CrossProduct(vd);
   Vector3d yaxis;
 
   if (!xaxis.IsZeroLength())
   {
    xaxis = xaxis.GetNormal();
    yaxis = zaxis.CrossProduct(xaxis);
   }
   else if (zaxis.Z < 0)
   {
    xaxis = Vector3d.XAxis * -1;
    yaxis = Vector3d.YAxis;
    zaxis = Vector3d.ZAxis * -1;
   }
   else
   {
    xaxis = Vector3d.XAxis;
    yaxis = Vector3d.YAxis;
    zaxis = Vector3d.ZAxis;
   }
   Matrix3d pcsToDCS = Matrix3d.Displacement(Point3d.Origin - cp);
   pcsToDCS = pcsToDCS * Matrix3d.Scaling(scale, cp);
   Matrix3d dcsToWcs = Matrix3d.Displacement(vc - Point3d.Origin);
   Matrix3d mxCoords = Matrix3d.AlignCoordinateSystem(
    Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, 
                Vector3d.ZAxis, Point3d.Origin,
    xaxis, yaxis, zaxis);
   dcsToWcs = mxCoords * dcsToWcs;
   dcsToWcs = Matrix3d.Displacement(vt - Point3d.Origin) * dcsToWcs;
   dcsToWcs = Matrix3d.Rotation(ta, zaxis, vt) * dcsToWcs;
 
   Matrix3d perspectiveMx = Matrix3d.Identity;
   if (vp.PerspectiveOn)
   {
    double vSize = vh;
    double aspectRatio = width / height;
    double adjustFactor = 1.0 / 42.0;
    double adjstLenLgth = vSize * lensLength *
     Math.Sqrt(1.0 + aspectRatio * aspectRatio) * adjustFactor;
    double iDist = vd.Length;
    double lensDist = iDist - adjstLenLgth;
                                double[] dataAry = new double[] 
                                        {   
                                            1,0,0,0,0,1,0,0,0,0,
         (adjstLenLgth-lensDist)/adjstLenLgth,
                                            lensDist*(iDist-adjstLenLgth)/adjstLenLgth,
         0,0,-1.0/adjstLenLgth,iDist/adjstLenLgth
                                        };
 
    perspectiveMx = new Matrix3d(dataAry);
   }
 
   Matrix3d finalMx = 
                pcsToDCS.Inverse() * perspectiveMx * dcsToWcs.Inverse();
 
   return finalMx;
  }
 
  #endregion
 
  #region private methods
 
  private static void GetTwistedBoundingBox(
   Polyline pl, double twistAngle,
   out Point3d pointLL, out Point3d pointRL, 
   out Point3d pointRU, out Point3d pointLU)
  {
   
   Point3d pt = pl.GetPoint3dAt(0);
   double ang = Math.PI * 2.0 - twistAngle;
   Matrix3d mt = Matrix3d.Rotation(ang, Vector3d.ZAxis, pt);
 
   //Clone the polyline
   Polyline clone = pl.Clone() as Polyline;
   using (clone)
   {
    clone.TransformBy(mt);
    Extents3d ext = clone.GeometricExtents;
    pointLL = (new Point3d(ext.MinPoint.X, ext.MinPoint.Y, 0.0))
     .TransformBy(mt.Inverse());
    pointRL = (new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, 0.0))
     .TransformBy(mt.Inverse());
    pointRU = (new Point3d(ext.MaxPoint.X, ext.MaxPoint.Y, 0.0))
     .TransformBy(mt.Inverse());
    pointLU = (new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, 0.0))
     .TransformBy(mt.Inverse());
   }
  }
 
  private static ObjectId OpenViewport(
   Document dwg, string layoutName, string layerName, 
   double twistAngle, double pScale, Point3d targetCenter)
  {
   Viewport vport = null;
 
   using (Transaction tran = 
    dwg.Database.TransactionManager.StartTransaction())
   {
    BlockTableRecord layoutBlock = 
     GetLayoutBlock(tran, dwg.Database, layoutName);
 
    double width;
    double height;
    Point3d centre;
    GetLayoutSize(
     dwg, layoutName, out centre, out width, out height);
 
    vport = new Viewport();
 
    vport.CenterPoint = new Point3d(centre.X, centre.Y, 0.0);
    vport.Width = width;
    vport.Height = height;
    vport.Layer = layerName;
 
    layoutBlock.UpgradeOpen();
    layoutBlock.AppendEntity(vport);
    tran.AddNewlyCreatedDBObject(vport, true);
 
    vport.On = true; ;
    vport.ViewDirection = Vector3d.ZAxis;
    vport.ViewTarget = targetCenter;
    vport.ViewCenter = Point2d.Origin;
    vport.TwistAngle = Math.PI * 2 - twistAngle;
    vport.CustomScale = pScale;
    vport.Locked = true;
 
    vport.UpdateDisplay();
 
    tran.Commit();
   }
 
   return vport.ObjectId;
  }
 
  private static void ResizeViewport(
   Document dwg, ObjectId vpId,
   ViewportBoundaryInfo vportInfo,
   double customScale)
  {
   Matrix3d mt = GetModelToPaperTransformMatrix(vpId);
 
   Point3d pt1;
   Point3d pt2;
 
   //Get vport width
   pt1 = vportInfo.PointLL.TransformBy(mt);
   pt2 = vportInfo.PointRL.TransformBy(mt);
 
   double vportW = Math.Abs(pt2.X - pt1.X); ;
 
   //Get vport height
   pt1 = vportInfo.PointLL.TransformBy(mt);
   pt2 = vportInfo.PointLU.TransformBy(mt);
 
   double vportH = Math.Abs(pt2.Y - pt1.Y);
 
   using (Transaction tran = 
    dwg.Database.TransactionManager.StartTransaction())
   {
    Viewport vport = (Viewport)
     tran.GetObject(vpId, OpenMode.ForWrite);
 
    Point3d center = vport.CenterPoint;
 
    vport.Locked = false;
    vport.Width = vportW;
    vport.Height = vportH;
    vport.CenterPoint = center;
    vport.CustomScale = customScale;
    vport.Locked = true;
 
    vport.UpdateDisplay();
 
    tran.Commit();
   }
  }
 
  private static void GetLayoutSize(
   Document dwg, string layoutName, 
   out Point3d centre, out double width, out double height)
  {
   centre = new Point3d();
   width = 0.0;
   height = 0.0;
 
   ObjectId layoutId = LayoutManager.Current.GetLayoutId(layoutName);
 
   using (Transaction tran=dwg.TransactionManager.StartTransaction())
   {
    Layout layout = (Layout)
     tran.GetObject(layoutId, OpenMode.ForRead);
 
    double w = 
     layout.PlotPaperSize.X - 
     layout.PlotPaperMargins.MinPoint.X - 
     layout.PlotPaperMargins.MaxPoint.X;
    double h = layout.PlotPaperSize.Y - 
     layout.PlotPaperMargins.MinPoint.Y - 
     layout.PlotPaperMargins.MaxPoint.Y;
 
    double s = layout.StdScale;
    if (!layout.UseStandardScale)
    {
     s = layout.CustomPrintScale.Denominator / 
      layout.CustomPrintScale.Numerator;
    }
 
    if (layout.PlotRotation==PlotRotation.Degrees090 || 
     layout.PlotRotation==PlotRotation.Degrees270)
    {
     width = h;
     height = w;
    }
    else
    {
     width = w;
     height = h;
    }
 
    width = width * s;
    height = height * s;
 
    if (layout.PlotPaperUnits==PlotPaperUnit.Inches)
    {
     width = width / 25.4;
     height = height / 25.4;
    }
    else if (layout.PlotPaperUnits==PlotPaperUnit.Pixels)
    {
     width = width / 25.4 * 72.0;
     height = height / 25.4 * 72.0;
    }
 
    centre = new Point3d(width / 2.0, height / 2.0, 0.0);
 
    tran.Commit();
   }
  }
 
  private static BlockTableRecord GetLayoutBlock(
   Transaction tran, Database db, string layoutName)
  {
   LayoutManager lmanager = LayoutManager.Current;
   ObjectId layId = lmanager.GetLayoutId(layoutName);
 
   Layout layout = tran.GetObject(layId, OpenMode.ForRead) as Layout;
 
   return tran.GetObject(
    layout.BlockTableRecordId, OpenMode.ForRead) 
    as BlockTableRecord;
  }
 
  private static Matrix3d GetModelToPaperTransformMatrix(
   ObjectId vportId)
  {
   Matrix3d mt;
 
   using (Transaction tran = 
    vportId.Database.TransactionManager.StartTransaction())
   {
    Viewport vp = (Viewport)
     tran.GetObject(vportId, OpenMode.ForRead);
    mt = ModelToPaper(vp);
    tran.Commit();
   }
 
   return mt;
  }
 
  private static void TransformPointsFromModelToPaper(
   ObjectId vpId, 
   Point3dCollection modelPoints1, 
   Point3dCollection modelPoints2,
   out Point3dCollection paperPoints1, 
   out Point3dCollection paperPoints2)
  {
   paperPoints1 = new Point3dCollection();
   paperPoints2 = new Point3dCollection();
   Matrix3d mt;
   using (Transaction tran =
    vpId.Database.TransactionManager.StartTransaction())
   {
    Viewport vp=(Viewport)tran.GetObject(vpId,OpenMode.ForRead);
    mt = ModelToPaper(vp);
    tran.Commit();
   }
 
   foreach (Point3d p in modelPoints1)
   {
    paperPoints1.Add(p.TransformBy(mt));
   }
 
   foreach (Point3d p in modelPoints2)
   {
    paperPoints2.Add(p.TransformBy(mt));
   }
  }
 
  #endregion
 }
}

As the code shows, the Viewport will be opened at the centre of the given layout.

Finally with all the code ready to use, here is the CommandClass MyCadCommands:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(OpenViewportFromModelSpace.MyCadCommands))]
 
namespace OpenViewportFromModelSpace
{
    public class MyCadCommands
    {
        [CommandMethod("OpenVp")]
        public static void CreateRectangularViewport()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            //Make sure start from ModelSpace
            LayoutManager.Current.CurrentLayout = "Model";
            
            //Pick model area to be shown in viewport
            ViewportBoundaryInfo vportInfo = GetUserInput(dwg);
           
            //Ask user for Layout name, exception test is omitted
            string layoutName = CadHelper.SelectLayout();
 
            //layer for the viewport, exception test is omitted
            string layerName = (string)
                Application.GetSystemVariable("CLAYER");
 
            //Viewport's custom scale, exception test is omitted
            double paperToModelScale = CadHelper.GetPaperToModelScale();
 
            if (!string.IsNullOrEmpty(layoutName) &&
                paperToModelScale != double.MinValue)
            {
                //Create viewport on specified layout
                try
                {
                    System.Windows.Forms.Cursor.Current =
                        System.Windows.Forms.Cursors.WaitCursor;
 
                    LayoutManager.Current.CurrentLayout = layoutName;
 
                    CadHelper.CreateRectangularViewport(
                        layoutName, layerName,
                        paperToModelScale, vportInfo);
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage(
                        "\nError: {0}.\n\n{1}", ex.Message, ex.StackTrace);
                }
                finally
                {
                    System.Windows.Forms.Cursor.Current =
                        System.Windows.Forms.Cursors.Default;
                }
            }
            else
            {
                ed.WriteMessage("\n*Cancel*");
            }
 
            Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
        }
 
        [CommandMethod("MyPolygon")]
        public static void DrawVisualPolygon()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            GetUserInput(dwg);
        }
 
        private static ViewportBoundaryInfo GetUserInput(Document dwg)
        {
            ViewportBoundaryInfo vpInfo = null;
            using (OpenViewportVisualHelper helper =
                new OpenViewportVisualHelper(dwg))
            {
                if (helper.PickEnclosingPolygon())
                {
                    vpInfo = helper.ViewportBoundaryInfo;
                }
            }
 
            return vpInfo;
        }
    }
}

Watch this video clip to see how the code works.

In order to make the code shown here more user friendly in real AutoCAD operation, I could give user more options, such as after showing the Viewport boundary rectangle, I could let user drag/rotate the rectangle. so that the Viewport to be created would better fit the drawing content to be shown.

Download source code here.

Friday, June 20, 2014

Finding Polygon Intersection By Using MS SQL Server

When doing AutoCAD programming, especially when the target AutoCAD vertical is AutoCAD Map 3D/Civil 3D, we often need to find out if one polygon intersects with another polygon, and if yes, then we often need to get the derived polygon because of the intersection.

There seems there is no easy, ready to call API support in plain either AutoCAD, or AutoCAD Map/Civil.

There are quite a few well-known algorithms that can be found in the Internet, some even has code implementation, or available as compiled library.

However, if the AutoCAD working environment has a accessible MS SQL Server (2008 or later version), it would be very simple to take advantage of SQL Server's spatial capability to fulfill this task fairly simple and easy.

This article demonstrates how to use MS SQL Server's spatial functionality to calculate polygon intersection.

Since MS SQL Server's spatial capabilities are actually "add-in" to SQL Server. so the spatial capabilities can be used with or without SQL Server being involved. That is, our code can be set to direct reference to related DLLs and do the calculation; or our code can access SQL Server with necessary input and let the SQL Server do the calculation, then obtain the calculation result from the SQL Server.

Firstly, because I need to use 2 different ways to take advantage of SQL Server's spatial functionality, I decide to define an interface for AutoCAD to call. With this interface, if I later decide to use other polygon intersection algorithms to do the calculation, I can simply implement this interface, so that the code on AutoCAD side would not need change no matter what method is used to find polygon intersection. Here is the simple interface code:

using Autodesk.AutoCAD.Geometry;
namespace PolygonIntersection
{
    public interface IPolyIntersecCalculator
    {
        Point2dCollection GetPolygonIntersection(
            Point2dCollection polygonA, Point2dCollection polygonB);
    } 
}

This interface defines an method GetPolygonIntersection(), which effectively says: "Give me 2 collections of 2D points, representing 2 polygons, I'll return either a collection of 2D points, representing the intersection area, if the 2 polygons intersect to each other; or nothing if the 2 polygons do not intersect."

1. Use SQL Server to do the polygon intersection calculation

Now, let's see how to make SQL Server to do the calculation of finding polygon intersection. Here the code uses ADO.NET to directly access SQL Server to call a stored procedure, which is executed inside SQL Server. The input to the stored procedure call is 2 text values, representing 2 polygons (WKT - Well Known Text). Then SQL Server returns calculation result, which is also represented as WKT, back to the code in AutoCAD.

Here is the stored procedure that stored in a SQL Server database:

-- ============================================================================
-- Author:  Norman Yuan
-- Create date: 2014-05-12
-- Description: This stored procedure uses Sql Server's
--  spatial computing capability to find out polygon's intersection. 
--  There is no data involved in an data table.
--  Inputs are 2 polygons described as WKT (Well-known text);
--  Output is WKT of geometry, being POLYGON, POINT, or 
--  GEOMETRYCOLLECTION EMPTY
-- ============================================================================
ALTER PROCEDURE [dbo].[SpatialComputing_GetPolygonIntersection]
 @PolygonWKT1 nvarchar(max), 
 @PolygonWKT2 nvarchar(max)
AS
BEGIN
 
 SET NOCOUNT ON;
 
 --Test data
 /*
 --Intersecting polygons, returns 'POLYGON((...))'
 SET @PolygonWKT1='POLYGON((0 0, 2 0, 3 3, 0 2, 0 0))';
 SET @PolygonWKT2='POLYGON((1 1, 3 1, 3 3, 1 3, 1 1))';
 */
 
 /*
 --polygons that do not intersecting to each other,
 --but has overlapped point, returns 'POINT(...)'
 SET @PolygonWKT1='POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))';
 SET @PolygonWKT2='POLYGON((1 1, 2 1, 2 2, 1 2, 1 1))';
 */
 
 /*
 --polygons that do not intersecting to each other at all,
 --returns 'GEOMETRYCOLLECTION EMPTY'
 SET @PolygonWKT1='POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))';
 SET @PolygonWKT2='POLYGON((2 2, 3 2, 3 3, 2 3, 2 2))';
 */
 
 DECLARE @Polygon1 geometry
 SET @Polygon1 = geometry::STPolyFromText(@polygonWKT1,0)
 
 DECLARE @Polygon2 geometry
 SET @Polygon2 = geometry::STPolyFromText(@polygonWKT2,0)
 
 DECLARE @OutputPolygon geometry
 SET @OutputPolygon = @Polygon1.STIntersection(@Polygon2)
 
 DECLARE @OutputWKT geometry
 SET @OutputWKT = @OutputPolygon.ToString()
 
 SELECT @OutputWKT.ToString() AS OutputWKT
    
END

With the stored procedure created in a SQL Server database (and proper execution permission assigned), I can now write some simple ADO.NET code to access SQL Server and call this stored procedure easily.

Here is class PolyIntersecSqlServerBackEndCalculator, which implements IPolyIntersecCalculator:

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Autodesk.AutoCAD.Geometry;
 
namespace PolygonIntersection
{
    public class PolyIntersecSqlServerBackEndCalculator : 
        IPolyIntersecCalculator
    {
        private string _connectionString;
        private string _procedureName;
        private string _inputParam1;
        private string _inputParam2;
        public PolyIntersecSqlServerBackEndCalculator(
            string connectionString, 
            string procedureName,
            string inputParamName1,
            string inputParamName2)
        {
            _connectionString = connectionString;
            _procedureName = procedureName;
            _inputParam1 = inputParamName1.StartsWith("@") ? 
                inputParamName1 : "@" + inputParamName1;
            _inputParam2 = inputParamName2.StartsWith("@") ? 
                inputParamName2 : "@" + inputParamName2;
        }
 
        public Point2dCollection GetPolygonIntersection(
            Point2dCollection polygonA, Point2dCollection polygonB)
        {
            return FindIntersectionPolygon(polygonA, polygonB);
        }
 
        #region private methods
 
        private Point2dCollection FindIntersectionPolygon(
            Point2dCollection polygonA, Point2dCollection polygonB)
        {
            Point2dCollection points = null;
 
            string wkt1 = GetPolygonWKTFromPoints(polygonA);
            string wkt2 = GetPolygonWKTFromPoints(polygonB);
 
            using (SqlConnection cn = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = cn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = _procedureName;
 
                    cmd.Parameters.AddWithValue(_inputParam1, wkt1);
                    cmd.Parameters.AddWithValue(_inputParam2, wkt2);
 
                    try
                    {
                        cn.Open();
                        string outputWKT = (string)cmd.ExecuteScalar();
                        points = ParseOutputWKT(outputWKT);
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (cn.State == ConnectionState.Open) cn.Close();
                    }
                }
            }
 
            return points;
        }
 
        private string GetPolygonWKTFromPoints(Point2dCollection points)
        {
            StringBuilder coords = new StringBuilder();
            foreach (Point2d p in points)
            {
                coords.Append(p.X.ToString() + " " + p.Y.ToString() + ", ");
            }
 
            //Add the first point as the WKT's last point, indicaating
            //the geometry is a closed polygon
            coords.Append(
                points[0].X.ToString() + " " + points[0].Y.ToString());
 
            return "POLYGON((" + coords.ToString() + "))";
        }
 
        private Point2dCollection ParseOutputWKT(string wkt)
        {
            if (wkt.ToUpper().StartsWith("POLYGON"))
            {
                Point2dCollection points = new Point2dCollection();
 
                int pos = wkt.IndexOf("((");
                string temp = wkt.Substring(pos + 2).Replace("))""");
                string[] coords = temp.Trim().Split(',');
                foreach (var coord in coords)
                {
                    string[] val = coord.Trim().Split(' ');
 
                    Point2d p = new Point2d(
                        Convert.ToDouble(val[0]), Convert.ToDouble(val[1]));
                    points.Add(p);
                }
 
                return points;
            }
            else
            {
                return null;
            }
        }
 
        #endregion
    }
}

As you can see, the code does not do any calculation on polygon intersecting. It simply interprets the input and output to/from SQL Server from WKT into Point2dCollection. Naturally, if the SQL Server access is exposed through a service layer, I can simply swap the ADO.NET data access code with service access code. The point is that the polygon intersection calculation is done on the SQL Server side.

2. Use Microsoft.SqlServer.Types.dll to do polygon intersection calculation

We can directly call a .NET API exposed by Microsoft.SqlServer.Types.dll to calculate polygon intersection without SQL Server involved at all. This is because that SQL Server's spatial functionality is implemented independently from SQL Server. SQL Server uses it as add-in.

To use Microsoft.SqlServer.Types.dll, you need to add reference to it in the Visual Studio project:



More explanation later on setting reference to Microsoft.SqlServer.Types.dll and making it work outside SQL Server.

With Microsoft.SqlServer.Types namespace available, I created another class that implements IPolyIntersecCalculator, called PolyIntersecSqlServerSpatialLibCalculator:

using System;
using Microsoft.SqlServer.Types;
using Autodesk.AutoCAD.Geometry;
 
namespace PolygonIntersection
{
    public class PolyIntersecSqlServerSpatialLibCalculator :
        IPolyIntersecCalculator
    {
        public Point2dCollection GetPolygonIntersection(
            Point2dCollection polygonA, Point2dCollection polygonB)
        {
            return FindIntersectionPolygon(polygonA, polygonB);
        }
 
        #region private methods
 
        private Point2dCollection FindIntersectionPolygon(
            Point2dCollection polygonA, Point2dCollection polygonB)
        {
            Point2dCollection points = new Point2dCollection();
 
            SqlGeometry polygon1 = 
                CreateSqlPolygonGeometryFromPoint2ds(polygonA);
            polygon1.MakeValid();
 
            SqlGeometry polygon2 = 
                CreateSqlPolygonGeometryFromPoint2ds(polygonB);
            polygon2.MakeValid();
 
            //Debugging code
            string wktP1 = polygon1.ToString();
            string wktP2 = polygon2.ToString();
 
            SqlGeometry area = polygon1.STIntersection(polygon2);
            if (!area.IsNull)
            {
                if (area.STGeometryType().ToString().ToUpper() == "POLYGON")
                {
                    for (int i = 1; i <= area.STNumPoints(); i++)
                    {
                        SqlGeometry geoPoint = 
                            area.STPointN(Convert.ToInt32(i));
 
                        double x = geoPoint.STX.Value;
                        double y = geoPoint.STY.Value;
                        Point2d pt = new Point2d(x, y);
                        points.Add(pt);
 
                    }
                }
            }
 
            return points;
        }
 
        private static SqlGeometry CreateSqlPolygonGeometryFromPoint2ds(
            Point2dCollection points)
        {
            SqlGeometry geometry = null;
 
            SqlGeometryBuilder gb = new SqlGeometryBuilder();
            gb.SetSrid(0);
            gb.BeginGeometry(OpenGisGeometryType.Polygon);
 
            gb.BeginFigure(points[0].X, points[0].Y);
 
            for (int i = 1; i <= points.Count; i++)
            {
                if (i < points.Count)
                {
                    gb.AddLine(points[i].X, points[i].Y);
                }
                else
                {
                    gb.AddLine(points[0].X, points[0].Y);
                }
            }
 
            gb.EndFigure();
 
            gb.EndGeometry();
            geometry = gb.ConstructedGeometry;
 
            return geometry;
        }
 
        #endregion
    }
}

Following CommandClass MyCadCommands uses the 2 IPolyIntersecCalculator classes in action:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.GraphicsInterface;
 
[assemblyCommandClass(typeof(PolygonIntersection.MyCadCommands))]
 
namespace PolygonIntersection
{
    public class MyCadCommands
    {
        [CommandMethod("PolyIntersec")]
        public static void GetPolygonIntersection()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            try
            {
                ObjectId polyId1 = PickPolygon(
                    ed, "Select a closed polyline:");
                if (polyId1.IsNull)
                {
                    ed.WriteMessage("\n*Cancel*");
                    return;
                }
 
                ObjectId polyId2 = PickPolygon(
                    ed, "Select another closed polyline:");
                if (polyId2.IsNull)
                {
                    ed.WriteMessage("\n*Cancel*");
                    return;
                }
 
                Point2dCollection polygonA = GetPolylineVertices(polyId1);
                Point2dCollection polygonB = GetPolylineVertices(polyId2);
 
                IPolyIntersecCalculator calculator = null;
 
                //Use SqlServerSpatial110.dll and 
                //its .NET wrapper Microsoft.SqlServer.Types.dll
                calculator = new PolyIntersecSqlServerSpatialLibCalculator();
 
                Point2dCollection interPolygon1 = 
                    calculator.GetPolygonIntersection(polygonA, polygonB);
 
                if (interPolygon1 != null)
                {
                    ShowIntersectionArea(interPolygon1, 
                        "Intersectiion area found by " +
                        "SqlServerSpatialLib calculator.");
                    ed.UpdateScreen();
                }
 
                //Use SqlServer DB backend
                string connection = "User ID=XXXXXX;" +
                    "Password=xxxx;Initial Catalog=" +
                    "[DatabaseName];Data Source=[ServerName]";
                string procedureName = 
                    "SpatialComputing_GetPolygonIntersection";
                string param1 = "PolygonWKT1";
                string param2 = "PolygonWKT2";
                calculator = new PolyIntersecSqlServerBackEndCalculator(
                    connection, procedureName, param1, param2);
 
                Point2dCollection interPolygon2 =
                    calculator.GetPolygonIntersection(polygonA, polygonB);
 
                if (interPolygon2 != null)
                {
                    ShowIntersectionArea(interPolygon2, 
                        "Intersection area found by " +
                        "SqlServerBackEnd calculator.");
                    ed.UpdateScreen();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
            }
        }
 
        #region private methods
 
        private static ObjectId PickPolygon(Editor ed, string message)
        {
            PromptEntityOptions opt = new PromptEntityOptions(
                "\n" + message);
            opt.SetRejectMessage("\nLnvalid pick: must be a polyline.");
            opt.AddAllowedClass(typeof(CadDb.Polyline), true);
            PromptEntityResult res = ed.GetEntity(opt);
            if (res.Status==PromptStatus.OK)
            {
                return res.ObjectId;
            }
            else
            {
                return ObjectId.Null;
            }
        }
 
        private static Point2dCollection GetPolylineVertices(
            ObjectId polylineId)
        {
            Point2dCollection points = new Point2dCollection();
 
            using (Transaction tran=
                polylineId.Database.TransactionManager.
                StartOpenCloseTransaction())
            {
                CadDb.Polyline pl = (CadDb.Polyline)tran.GetObject(
                    polylineId, OpenMode.ForRead);
 
                for (int i = 0; i < pl.NumberOfVertices; i++)
                {
                    points.Add(pl.GetPoint2dAt(i));
                }
                    
                tran.Commit();
            }
 
            return points;
        }
 
        private static void ShowIntersectionArea(
            Point2dCollection points, string msg)
        {
            Editor ed = CadApp.DocumentManager.MdiActiveDocument.Editor;
 
            using (CadDb.Polyline pl = CreatePolyline(points))
            {
                TransientManager ts = TransientManager.CurrentTransientManager;
 
                ts.AddTransient(
                    pl,
                    TransientDrawingMode.DirectTopmost,
                    128,
                    new IntegerCollection());
 
                ed.UpdateScreen();
 
                ed.GetString("\n" + msg + " Press any key to continue...");
 
                ts.EraseTransient(pl, new IntegerCollection());
            }
        }
 
        private static CadDb.Polyline CreatePolyline(Point2dCollection points)
        {
            CadDb.Polyline pl = new CadDb.Polyline(points.Count);
            for (int i=0; i<points.Count; i++)
            {
                pl.AddVertexAt(i, points[i], 0.0, 0.0, 0.0);
            }
 
            pl.Closed = true;
            pl.ColorIndex = 1;  //Show it in red
 
            return pl;
        }
 
        #endregion
    }
}

This video clip shows how the code works.

Now more about how to get Microsoft.SqlServer.Types.dll.

As a developer who does .NET programming, it is very likely the computer has a version of Visual Studio installed, and often also has a version of SQL Server (possible SQL Server Express) installed. In this case, Visual Studio's adding references dialog box should show Microsoft.SqlServer.Types in the list, as the picture above shows. However Microsoft.SqlServer.Types.dll is only a .NET assembly that wraps some native code that does the real heavy lifting work. That means, the second way of calculating polygon intersection works only if the computer has SQL Server (2008 or later) installed. Since Microsoft.SqlServer.Types.dll get installed into GAC due to SQL Server installation, in the Visual Studio project, the reference's "Copy Local" can be set to "False" (it is default to "False" anyway).

In reality, not all CAD computers would have a version of SQL Server installed for sure. In this case, we need to have a copy of Microsoft.SqlServer.Types.dll and the native DLL it wraps. What it is, then? It turned out that SqlServerSpatial.dll (SQL Server2008) or SqlServerSpatial110.dll (SQL Server 2012. I uses SqlServerSpatial110.dll here). To get both Microsoft.SqlServer.Types.dll and SqlServerSpatial110.dll installed to the computer, one can download Microsoft SQL Server 2012 Feature Pack, or find a copy of SqlServerSpatial11.dll in a computer that has SQL Server 2012 installed (in C:\Windows.System32 folder).

As for possible license issue of using these 2 DLLs, it is beyond the technical discussion and I'll leave it to user's discretion.

With these 2 DLLs available, make sure them to be build into the output of the project. That is, for the reference of Microsoft.SqlServer.Types.dll, its "Copy Local" should be set to "True"; and for the SqlServerSpatial110.dll, add it into the project and set "Copy to Output Directory" to "Copy always". See picture below:



So, after building the project, besides the AutoCAD add-in DLL in the bin folder, there are also both Microsoft.SqlServer.Types.dll and SqlServerSpatial110.dll. The 3 DLLs should go together to when used with other AutoCAD computers, no need to install SQL Server.

Download source code here.