.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Restore hatch boundaries if they have been lost with .NET

8 REPLIES 8
SOLVED
Reply
Message 1 of 9
Alexander.Rivilis
3329 Views, 8 Replies

Restore hatch boundaries if they have been lost with .NET

First attempt:

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

[assembly: CommandClass(typeof(Rivilis.HatchUtils))]

namespace Rivilis
{
  public class HatchUtils
  {
    [CommandMethod("RHB", CommandFlags.Modal)]
    public void RHB()
    {
      Document doc = Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;
      PromptEntityOptions prOps = new PromptEntityOptions("\nSelect Hatch: ");
      prOps.SetRejectMessage("\nNot a Hatch");
      prOps.AddAllowedClass(typeof(Hatch),false);
      PromptEntityResult prRes = ed.GetEntity(prOps);
      if (prRes.Status != PromptStatus.OK) return;
      using (Transaction tr = doc.TransactionManager.StartTransaction()) {
        Hatch hatch = tr.GetObject(prRes.ObjectId, OpenMode.ForRead) as Hatch;
        if (hatch != null) {
          BlockTableRecord btr = tr.GetObject(hatch.OwnerId, OpenMode.ForWrite) as BlockTableRecord;
          if (btr == null) return;
          int nLoops = hatch.NumberOfLoops;
          for (int i = 0; i < nLoops; i++) {
            HatchLoop loop = hatch.GetLoopAt(i);
            if (loop.IsPolyline)  {
              Polyline poly = new Polyline();
              int iVertex = 0;
              foreach (BulgeVertex bv in loop.Polyline) {
                poly.AddVertexAt(iVertex++, bv.Vertex, bv.Bulge, 0.0, 0.0);
              }
              btr.AppendEntity(poly);
              tr.AddNewlyCreatedDBObject(poly, true);
            } else {
              int iCurve = 0;
              Plane plane = hatch.GetPlane();
              foreach (Curve2d cv in loop.Curves) {
                LineSegment2d l2d = cv as LineSegment2d;
                CircularArc2d c2d = cv as CircularArc2d;
                EllipticalArc2d e2d = cv as EllipticalArc2d;
                NurbCurve2d n2d = cv as NurbCurve2d;
                if (l2d != null) {
                  Line ent = new Line();
                  ent.StartPoint = new Point3d(plane, l2d.StartPoint);
                  ent.EndPoint   = new Point3d(plane, l2d.EndPoint);
                  btr.AppendEntity(ent);
                  tr.AddNewlyCreatedDBObject(ent, true);
                }  else if (c2d != null) {
                  if (Math.Abs(c2d.StartAngle - c2d.EndAngle) < 1e-5) {
                    Circle ent = new Circle(new Point3d(plane, c2d.Center), plane.Normal, c2d.Radius);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  } else {
                    Arc ent = new Arc(new Point3d(plane, c2d.Center),c2d.Radius,c2d.StartAngle,c2d.EndAngle);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }
                } else if (e2d != null) {
                  Ellipse ent = new Ellipse(new Point3d(plane, e2d.Center), plane.Normal, 
                        new Vector3d(plane,e2d.MajorAxis) * e2d.MajorRadius,
                        e2d.MinorRadius / e2d.MajorRadius, e2d.StartAngle, e2d.EndAngle);
                  btr.AppendEntity(ent);
                  tr.AddNewlyCreatedDBObject(ent, true);
                } else if (n2d != null) {
                  if (n2d.HasFitData) {
                    NurbCurve2dFitData n2fd = n2d.FitData;
                    Point3dCollection p3ds = new Point3dCollection();
                    foreach (Point2d p in n2fd.FitPoints) p3ds.Add(new Point3d(plane,p));
                    Spline ent = new Spline(p3ds, new Vector3d(plane,n2fd.StartTangent), new Vector3d(plane,n2fd.EndTangent),
                           n2fd.KnotParam, n2fd.Degree, n2fd.FitTolerance.EqualPoint);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }  else {
                    NurbCurve2dData n2fd = n2d.DefinitionData;
                    Point3dCollection p3ds = new Point3dCollection();
                    DoubleCollection knots = new DoubleCollection(n2fd.Knots.Count);
                    foreach (Point2d p in n2fd.ControlPoints) p3ds.Add(new Point3d(plane,p));
                    foreach (double k in n2fd.Knots) knots.Add(k);
                    double period = 0;
                    Spline ent = new Spline(n2fd.Degree, n2fd.Rational, 
                             n2d.IsClosed(), n2d.IsPeriodic(out period), 
                             p3ds, knots, n2fd.Weights, n2fd.Knots.Tolerance, n2fd.Knots.Tolerance);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                   }
                }
              }
            }
          }
        }
        tr.Commit();
      }
    }
  }
}

 

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

8 REPLIES 8
Message 2 of 9
Hallex
in reply to: Alexander.Rivilis

I could not get it to work dy reason of the folleing error (in A2010):

'Autodesk.AutoCAD.Geometry.NurbCurve2dFitData' does not contain a definition for 'KnotParam' and no extension method 'KnotParam' accepting a first argument of type 'Autodesk.AutoCAD.Geometry.NurbCurve2dFitData' could be found (are you missing a using directive or an assembly reference?)

on this line:

Spline ent = new Spline(p3ds, new Vector3d(plane, n2fd.StartTangent), new Vector3d(plane, n2fd.EndTangent),
                                               n2fd.KnotParam, n2fd.Degree, n2fd.FitTolerance.EqualPoint);

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 3 of 9
Alexander.Rivilis
in reply to: Hallex

Second attempt:

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

[assembly: CommandClass(typeof(Rivilis.HatchUtils))]

namespace Rivilis
{
  public class HatchUtils
  {
    [CommandMethod("RHB", CommandFlags.Modal)]
    public void RHB()
    {
      Document doc = Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;
      PromptEntityOptions prOps = new PromptEntityOptions("\nSelect Hatch: ");
      prOps.SetRejectMessage("\nNot a Hatch");
      prOps.AddAllowedClass(typeof(Hatch),false);
      PromptEntityResult prRes = ed.GetEntity(prOps);
      if (prRes.Status != PromptStatus.OK) return;
      using (Transaction tr = doc.TransactionManager.StartTransaction()) {
        Hatch hatch = tr.GetObject(prRes.ObjectId, OpenMode.ForRead) as Hatch;
        if (hatch != null) {
          BlockTableRecord btr = tr.GetObject(hatch.OwnerId, OpenMode.ForWrite) as BlockTableRecord;
          if (btr == null) return;
          Plane plane = hatch.GetPlane();
          int nLoops = hatch.NumberOfLoops;
          for (int i = 0; i < nLoops; i++) {
            HatchLoop loop = hatch.GetLoopAt(i);
            if (loop.IsPolyline)  {
              using (Polyline poly = new Polyline()) {
                int iVertex = 0;
                foreach (BulgeVertex bv in loop.Polyline) {
                  poly.AddVertexAt(iVertex++, bv.Vertex, bv.Bulge, 0.0, 0.0);
                }
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
              }
            } else {
              foreach (Curve2d cv in loop.Curves) {
                LineSegment2d   line2d    = cv as LineSegment2d;
                CircularArc2d   arc2d     = cv as CircularArc2d;
                EllipticalArc2d ellipse2d = cv as EllipticalArc2d;
                NurbCurve2d     spline2d  = cv as NurbCurve2d;
                if (line2d != null) {
                  using (Line ent = new Line()) {
                    ent.StartPoint = new Point3d(plane, line2d.StartPoint);
                    ent.EndPoint = new Point3d(plane, line2d.EndPoint);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }
                }  else if (arc2d != null) {
                  if (Math.Abs(arc2d.StartAngle - arc2d.EndAngle) < 1e-5) {
                    using (Circle ent = new Circle(new Point3d(plane, arc2d.Center), plane.Normal, arc2d.Radius)) {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  } else {
                    double angle =  new Vector3d(plane,arc2d.ReferenceVector).AngleOnPlane(plane);
                    using (Arc ent = new Arc(new Point3d(plane, arc2d.Center), arc2d.Radius, arc2d.StartAngle + angle, arc2d.EndAngle + angle)) {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  }
                } else if (ellipse2d != null) {
                  //-------------------------------------------------------------------------------------------
                  // Bug: Can not assign StartParam and EndParam of Ellipse:
                  // Ellipse ent = new Ellipse(new Point3d(plane, e2d.Center), plane.Normal, 
                  //      new Vector3d(plane,e2d.MajorAxis) * e2d.MajorRadius,
                  //      e2d.MinorRadius / e2d.MajorRadius, e2d.StartAngle, e2d.EndAngle);
                  // ent.StartParam = e2d.StartAngle; 
                  // ent.EndParam = e2d.EndAngle;
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.StartParam' cannot be assigned to -- it is read only
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.EndParam' cannot be assigned to -- it is read only
                  // So trying other method which compatible with AutoCAD 2012+:
                  using (EllipticalArc3d e3d = new EllipticalArc3d(new Point3d(plane, ellipse2d.Center), new Vector3d(plane, ellipse2d.MajorAxis),
                         new Vector3d(plane, ellipse2d.MinorAxis), ellipse2d.MajorRadius, ellipse2d.MinorRadius, ellipse2d.StartAngle, ellipse2d.EndAngle)) {
                      using (Curve ent = Curve.CreateFromGeCurve(e3d)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                  }
                  //---------------------------------------------------------------------------------------------
                } else if (spline2d != null) {
                  if (spline2d.HasFitData) {
                    NurbCurve2dFitData n2fd = spline2d.FitData;
                    using (Point3dCollection p3ds = new Point3dCollection()) {
                      foreach (Point2d p in n2fd.FitPoints) p3ds.Add(new Point3d(plane, p));
                      using (Spline ent = new Spline(p3ds, new Vector3d(plane, n2fd.StartTangent), new Vector3d(plane, n2fd.EndTangent),
                        /* n2fd.KnotParam, */  n2fd.Degree, n2fd.FitTolerance.EqualPoint)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                    }
                  }
                  else {
                    NurbCurve2dData n2fd = spline2d.DefinitionData;
                    using (Point3dCollection p3ds = new Point3dCollection()) {
                        DoubleCollection knots = new DoubleCollection(n2fd.Knots.Count);
                        foreach (Point2d p in n2fd.ControlPoints) p3ds.Add(new Point3d(plane, p));
                        foreach (double k in n2fd.Knots) knots.Add(k);
                        double period = 0;
                        using (Spline ent = new Spline(n2fd.Degree, n2fd.Rational,
                                 spline2d.IsClosed(), spline2d.IsPeriodic(out period),
                                 p3ds, knots, n2fd.Weights, n2fd.Knots.Tolerance, n2fd.Knots.Tolerance)) {
                          btr.AppendEntity(ent);
                          tr.AddNewlyCreatedDBObject(ent, true);
                        }
                    }
                  }
                }
              }
            }
          }
        }
        tr.Commit();
      }
    }
  }
}

 Oleg! Previous version was tested with AutoCAD 2013.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 4 of 9

Hello to both of you "Swamprats",

thanks for your effort.

I'm using AutoCAD 2012 with VS2010.

 

in:

using (Curve ent = Curve.CreateFromGeCurve(e3d)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }

 

 

I can't find .CreateFromGeCurve() in the

Autodesk.AutoCAD.DatabaseServices.Curve class ...

 

Error 1 'CreateFromGeCurve' is not a member of 'Autodesk.AutoCAD.DatabaseServices.Curve'.

 

Any hint?

 

René

Message 5 of 9


@ReneRamirez wrote:

Hello to both of you "Swamprats",

thanks for your effort.

I'm using AutoCAD 2012 with VS2010.

 

in:

using (Curve ent = Curve.CreateFromGeCurve(e3d)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }

 

 

I can't find .CreateFromGeCurve() in the

Autodesk.AutoCAD.DatabaseServices.Curve class ...

 

Error 1 'CreateFromGeCurve' is not a member of 'Autodesk.AutoCAD.DatabaseServices.Curve'.

 

Any hint?

 

René


Third attempt:

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

[assembly: CommandClass(typeof(Rivilis.HatchUtils))]

namespace Rivilis
{
  public class HatchUtils
  {
    [CommandMethod("RHB", CommandFlags.Modal)]
    public void RHB()
    {
      Document doc = Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;
      PromptEntityOptions prOps = new PromptEntityOptions("\nSelect Hatch: ");
      prOps.SetRejectMessage("\nNot a Hatch");
      prOps.AddAllowedClass(typeof(Hatch), false);
      PromptEntityResult prRes = ed.GetEntity(prOps);
      if (prRes.Status != PromptStatus.OK) return;
      using (Transaction tr = doc.TransactionManager.StartTransaction()) {
        Hatch hatch = tr.GetObject(prRes.ObjectId, OpenMode.ForRead) as Hatch;
        if (hatch != null) {
          BlockTableRecord btr = tr.GetObject(hatch.OwnerId, OpenMode.ForWrite) as BlockTableRecord;
          if (btr == null) return;
          Plane plane = hatch.GetPlane();
          int nLoops = hatch.NumberOfLoops;
          for (int i = 0; i < nLoops; i++) {
            HatchLoop loop = hatch.GetLoopAt(i);
            if (loop.IsPolyline) {
              using (Polyline poly = new Polyline()) {
                int iVertex = 0;
                foreach (BulgeVertex bv in loop.Polyline) {
                  poly.AddVertexAt(iVertex++, bv.Vertex, bv.Bulge, 0.0, 0.0);
                }
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
              }
            } else {
              foreach (Curve2d cv in loop.Curves) {
                LineSegment2d line2d = cv as LineSegment2d;
                CircularArc2d arc2d = cv as CircularArc2d;
                EllipticalArc2d ellipse2d = cv as EllipticalArc2d;
                NurbCurve2d spline2d = cv as NurbCurve2d;
                if (line2d != null) {
                  using (Line ent = new Line()) {
                    ent.StartPoint = new Point3d(plane, line2d.StartPoint);
                    ent.EndPoint = new Point3d(plane, line2d.EndPoint);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }
                } else if (arc2d != null) {
                  if (Math.Abs(arc2d.StartAngle - arc2d.EndAngle) < 1e-5) {
                    using (Circle ent = new Circle(new Point3d(plane, arc2d.Center), plane.Normal, arc2d.Radius)) {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  } else {
                    double angle = new Vector3d(plane, arc2d.ReferenceVector).AngleOnPlane(plane);
                    using (Arc ent = new Arc(new Point3d(plane, arc2d.Center), arc2d.Radius, arc2d.StartAngle + angle, arc2d.EndAngle + angle)) {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  }
                } else if (ellipse2d != null) {
                  //-------------------------------------------------------------------------------------------
                  // Bug: Can not assign StartParam and EndParam of Ellipse:
                  // Ellipse ent = new Ellipse(new Point3d(plane, e2d.Center), plane.Normal, 
                  //      new Vector3d(plane,e2d.MajorAxis) * e2d.MajorRadius,
                  //      e2d.MinorRadius / e2d.MajorRadius, e2d.StartAngle, e2d.EndAngle);
                  // ent.StartParam = e2d.StartAngle; 
                  // ent.EndParam = e2d.EndAngle;
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.StartParam' cannot be assigned to -- it is read only
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.EndParam' cannot be assigned to -- it is read only
                  //---------------------------------------------------------------------------------------------
                  // Workaround is using Reflection
                  // 
                  using (Ellipse ent = new Ellipse(new Point3d(plane, ellipse2d.Center), plane.Normal,
                       new Vector3d(plane, ellipse2d.MajorAxis) * ellipse2d.MajorRadius,
                       ellipse2d.MinorRadius / ellipse2d.MajorRadius, ellipse2d.StartAngle, ellipse2d.EndAngle)) {
                    ent.GetType().InvokeMember("StartParam", BindingFlags.SetProperty, null,
                      ent, new object[] { ellipse2d.StartAngle });
                    ent.GetType().InvokeMember("EndParam", BindingFlags.SetProperty, null,
                      ent, new object[] { ellipse2d.EndAngle });
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }

                } else if (spline2d != null) {
                  if (spline2d.HasFitData) {
                    NurbCurve2dFitData n2fd = spline2d.FitData;
                    using (Point3dCollection p3ds = new Point3dCollection()) {
                      foreach (Point2d p in n2fd.FitPoints) p3ds.Add(new Point3d(plane, p));
                      using (Spline ent = new Spline(p3ds, new Vector3d(plane, n2fd.StartTangent), new Vector3d(plane, n2fd.EndTangent),
                        /* n2fd.KnotParam, */  n2fd.Degree, n2fd.FitTolerance.EqualPoint)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                    }
                  } else {
                    NurbCurve2dData n2fd = spline2d.DefinitionData;
                    using (Point3dCollection p3ds = new Point3dCollection()) {
                      DoubleCollection knots = new DoubleCollection(n2fd.Knots.Count);
                      foreach (Point2d p in n2fd.ControlPoints) p3ds.Add(new Point3d(plane, p));
                      foreach (double k in n2fd.Knots) knots.Add(k);
                      double period = 0;
                      using (Spline ent = new Spline(n2fd.Degree, n2fd.Rational,
                               spline2d.IsClosed(), spline2d.IsPeriodic(out period),
                               p3ds, knots, n2fd.Weights, n2fd.Knots.Tolerance, n2fd.Knots.Tolerance)) {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                    }
                  }
                }
              }
            }
          }
        }
        tr.Commit();
      }
    }
  }
}

I hope that this time, everything is fine.

 

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 6 of 9

it works like a charmSmiley Happy

thanks Alexander

René

Message 7 of 9

Anyone ever noticed this (very nice piece of) code doesn't work when hatchboundary is a circle? and at certain arcs in a polyline?

 

 

Message 8 of 9


@stefanveurink68AXD wrote:

Anyone ever noticed this (very nice piece of) code doesn't work when hatchboundary is a circle? and at certain arcs in a polyline?

 

 


Thank you for reporting this bug. Try this code:

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

[assembly: CommandClass(typeof(Rivilis.HatchUtils))]

namespace Rivilis
{
  public class HatchUtils
  {
    [CommandMethod("RHB", CommandFlags.Modal)]
    public void RHB()
    {
      Document doc = Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;
      PromptEntityOptions prOps = new PromptEntityOptions("\nSelect Hatch: ");
      prOps.SetRejectMessage("\nNot a Hatch");
      prOps.AddAllowedClass(typeof(Hatch), false);
      PromptEntityResult prRes = ed.GetEntity(prOps);
      if (prRes.Status != PromptStatus.OK) return;
      using (Transaction tr = doc.TransactionManager.StartTransaction())
      {
        Hatch hatch = tr.GetObject(prRes.ObjectId, OpenMode.ForRead) as Hatch;
        if (hatch != null)
        {
          BlockTableRecord btr = tr.GetObject(hatch.OwnerId, OpenMode.ForWrite) as BlockTableRecord;
          Plane plane = hatch.GetPlane();
          int nLoops = hatch.NumberOfLoops;
          for (int i = 0; i < nLoops; i++)
          {
            HatchLoop loop = hatch.GetLoopAt(i);
            if (loop.IsPolyline)
            {
              using (Polyline poly = new Polyline())
              {
                int iVertex = 0;
                foreach (BulgeVertex bv in loop.Polyline)
                {
                  poly.AddVertexAt(iVertex++, bv.Vertex, bv.Bulge, 0.0, 0.0);
                }
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
              }
            }
            else
            {
              foreach (Curve2d cv in loop.Curves)
              {
                LineSegment2d line2d = cv as LineSegment2d;
                CircularArc2d arc2d = cv as CircularArc2d;
                EllipticalArc2d ellipse2d = cv as EllipticalArc2d;
                NurbCurve2d spline2d = cv as NurbCurve2d;
                if (line2d != null)
                {
                  using (Line ent = new Line())
                  {
                    ent.StartPoint = new Point3d(plane, line2d.StartPoint);
                    ent.EndPoint = new Point3d(plane, line2d.EndPoint);
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }
                }
                else if (arc2d != null)
                {
                  if (arc2d.IsClosed() || Math.Abs(arc2d.EndAngle - arc2d.StartAngle) < 1e-5)
                  {
                    using (Circle ent = new Circle(new Point3d(plane, arc2d.Center), plane.Normal, arc2d.Radius))
                    {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  }
                  else
                  {
                    if (arc2d.IsClockWise) {
                      arc2d = arc2d.GetReverseParameterCurve() as CircularArc2d;
                    }
                    double angle = new Vector3d(plane, arc2d.ReferenceVector).AngleOnPlane(plane);
                    double startAngle = arc2d.StartAngle + angle;
                    double endAngle = arc2d.EndAngle + angle;
                    using (Arc ent = new Arc(new Point3d(plane, arc2d.Center), plane.Normal, arc2d.Radius, startAngle, endAngle))
                    {
                      btr.AppendEntity(ent);
                      tr.AddNewlyCreatedDBObject(ent, true);
                    }
                  }
                }
                else if (ellipse2d != null)
                {
                  //-------------------------------------------------------------------------------------------
                  // Bug: Can not assign StartParam and EndParam of Ellipse:
                  // Ellipse ent = new Ellipse(new Point3d(plane, e2d.Center), plane.Normal, 
                  //      new Vector3d(plane,e2d.MajorAxis) * e2d.MajorRadius,
                  //      e2d.MinorRadius / e2d.MajorRadius, e2d.StartAngle, e2d.EndAngle);
                  // ent.StartParam = e2d.StartAngle; 
                  // ent.EndParam = e2d.EndAngle;
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.StartParam' cannot be assigned to -- it is read only
                  // error CS0200: Property or indexer 'Autodesk.AutoCAD.DatabaseServices.Curve.EndParam' cannot be assigned to -- it is read only
                  //---------------------------------------------------------------------------------------------
                  // Workaround is using Reflection
                  // 
                  using (Ellipse ent = new Ellipse(new Point3d(plane, ellipse2d.Center), plane.Normal,
                       new Vector3d(plane, ellipse2d.MajorAxis) * ellipse2d.MajorRadius,
                       ellipse2d.MinorRadius / ellipse2d.MajorRadius, ellipse2d.StartAngle, ellipse2d.EndAngle))
                  {
                    ent.GetType().InvokeMember("StartParam", BindingFlags.SetProperty, null,
                      ent, new object[] { ellipse2d.StartAngle });
                    ent.GetType().InvokeMember("EndParam", BindingFlags.SetProperty, null,
                      ent, new object[] { ellipse2d.EndAngle });
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                  }

                }
                else if (spline2d != null)
                {
                  if (spline2d.HasFitData)
                  {
                    NurbCurve2dFitData n2fd = spline2d.FitData;
                    using (Point3dCollection p3ds = new Point3dCollection())
                    {
                      foreach (Point2d p in n2fd.FitPoints) p3ds.Add(new Point3d(plane, p));
                      using (Spline ent = new Spline(p3ds, new Vector3d(plane, n2fd.StartTangent), new Vector3d(plane, n2fd.EndTangent),
                        /* n2fd.KnotParam, */  n2fd.Degree, n2fd.FitTolerance.EqualPoint))
                      {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                    }
                  }
                  else
                  {
                    NurbCurve2dData n2fd = spline2d.DefinitionData;
                    using (Point3dCollection p3ds = new Point3dCollection())
                    {
                      DoubleCollection knots = new DoubleCollection(n2fd.Knots.Count);
                      foreach (Point2d p in n2fd.ControlPoints) p3ds.Add(new Point3d(plane, p));
                      foreach (double k in n2fd.Knots) knots.Add(k);
                      double period = 0;
                      using (Spline ent = new Spline(n2fd.Degree, n2fd.Rational,
                               spline2d.IsClosed(), spline2d.IsPeriodic(out period),
                               p3ds, knots, n2fd.Weights, n2fd.Knots.Tolerance, n2fd.Knots.Tolerance))
                      {
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                      }
                    }
                  }
                }
              }
            }
          }
        }
        tr.Commit();
      }
    }
  }
}

 

 

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 9 of 9

yes great seems to work fine now!!

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost