using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using AcBr = Autodesk.AutoCAD.BoundaryRepresentation;
[assembly: CommandClass(typeof(Rivilis.PolyUnion))]
namespace Rivilis
{
public class PolyUnion
{
[CommandMethod("PolyUnion2")]
public void PolyUnionHandler2()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null) return;
Editor ed = doc.Editor;
Database db = doc.Database;
SelectionFilter sf = new SelectionFilter(new TypedValue[]
{
new TypedValue((int) DxfCode.Start,"POLYLINE,LWPOLYLINE")
}
);
PromptSelectionResult psr = ed.GetSelection(sf);
if (psr.Status == PromptStatus.OK && psr.Value.Count > 0)
{
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
BlockTableRecord curBtr =
tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
DBObjectCollection dbcol = new DBObjectCollection();
foreach (ObjectId id in psr.Value.GetObjectIds())
{
Curve curve = tr.GetObject(id, OpenMode.ForRead) as Curve;
if (curve != null) dbcol.Add(curve);
}
DBObjectCollection dbRegions = null;
try { dbRegions = Region.CreateFromCurves(dbcol); } catch { }
int nRegs = 0;
if (dbRegions != null && (nRegs = dbRegions.Count) > 0)
{
for (int i = 0; i < nRegs; i++)
{
if (dbRegions[i] == null) continue;
Region reg1 = dbRegions[i] as Region;
for (int j = i+1; j < nRegs; j++)
{
if (dbRegions[j] == null) continue;
Region reg2 = dbRegions[j] as Region;
try {
reg1.BooleanOperation(BooleanOperationType.BoolUnite, reg2);
dbRegions[j].Dispose();
dbRegions[j] = null;
} catch { }
}
if (!reg1.IsNull)
{
// Преобразуем области (Region) в набор замкнутых полилиний
// Для этой цели используем BREP .NET API
using (AcBr.Brep brep = new AcBr.Brep(reg1))
{
foreach (AcBr.Face face in brep.Faces)
{
foreach (AcBr.BoundaryLoop loop in face.Loops)
{
int iVert = 0;
Polyline pl = new Polyline();
foreach (AcBr.Vertex p in loop.Vertices) {
pl.AddVertexAt(iVert++, new Point2d(p.Point.X, p.Point.Y), 0, 0,0);
}
pl.Closed = true;
curBtr.AppendEntity(pl);
tr.AddNewlyCreatedDBObject(pl, true);
}
}
}
reg1.Dispose();
}
}
}
// Удаляем исходные полилинии
foreach (DBObject obj in dbcol)
{
DBObject objwr = tr.GetObject(obj.Id, OpenMode.ForWrite);
objwr.Erase();
}
tr.Commit();
}
}
}
}
}