public void CreateContour(BlockTableRecord btr) { if (panelBtr.ExtentsByTile.Diagonal() < endOffset) { return; } // из всех плиток отделить торцевые плитки???? // дерево границ плиток TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>(); panelBtr.Tiles.ForEach(t => { try { var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0); TreeTiles.Add(r, t); } catch { } }); // Первый угол панели - левый нижний var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower); var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop); var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop); var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower); Extents3d extNoEnd = new Extents3d(pt1, pt2); extNoEnd.AddPoint(pt3); extNoEnd.AddPoint(pt4); panelBtr.ExtentsNoEnd = extNoEnd; Point3dCollection pts = new Point3dCollection(); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); pts.Add(pt4); using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true)) { poly.LayerId = panelBtr.CPS.IdLayerContour; btr.AppendEntity(poly); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true); } }
public void Create(BlockTableRecord btrPanel, Transaction t) { Polyline plContour = new Polyline(); plContour.LayerId = panelBase.Service.Env.IdLayerContourPanel; // Определение подрезок и пустот defineUndercuts(); // Outsides - части сторон панели без плитки - заходит под торец другой угловой панели addOutsides(btrPanel, t); definePtsLeftSide(); definePtsTopSide(); definePtsRightSide(); definePtsBotSide(); int i = 0; ptsLeftSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0)); ptsTopSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0)); ptsRightSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0)); ptsBotSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0)); plContour.Closed = true; btrPanel.AppendEntity(plContour); t.AddNewlyCreatedDBObject(plContour, true); }
/// <summary> /// </summary> /// <param name="acBlkTableRec"></param> /// <param name="blockName"></param> /// <param name="insertPt"></param> /// <param name="acCurDb"></param> /// <returns></returns> public static BlockReference InsertBlock(this BlockTableRecord acBlkTableRec, string blockName, Point3d insertPt, Database acCurDb) { BlockReference acBlkRef = null; using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read var acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; if (acBlkTbl != null && acBlkTbl.Has(blockName)) { var blkRecId = acBlkTbl[blockName]; // Insert the block into the current space if (blkRecId != ObjectId.Null) { acBlkRef = new BlockReference(insertPt, blkRecId); acBlkTableRec?.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); acBlkRef.AppendAttributes(blkRecId, acTrans); } acTrans.Commit(); } } return(acBlkRef); }
//-------------------------------------------------------------- // ����:����һ���鶨�壨����¼�� // ���ߣ� // ���ڣ�2007-7-20 // ˵���� // //---------------------------------------------------------------- public ObjectId CreateBlkDef() { //���庯���ķ���ֵObjectId ObjectId blkObjId = new ObjectId(); Database db = HostApplicationServices.WorkingDatabase; // ʹ�� "using"�ؼ���ָ������ı߽� using (Transaction trans = db.TransactionManager.StartTransaction()) { //��ȡ��� BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); //ͨ������myBlkName�жϿ�����Ƿ��������¼ if ((bt.Has("myBlkName"))) { blkObjId = bt["myBlkName"];//����Ѿ����ڣ�ͨ��������ȡ���Ӧ��ObjectId } else { //����һ��Բ Point3d center = new Point3d(10, 10, 0); Circle circle = new Circle(center, Vector3d.ZAxis, 2); circle.ColorIndex = 1; //�����ı�Text: MText text = new MText(); text.Contents = " "; text.Location = center; text.ColorIndex = 2; //�����µĿ���¼ myBlkName BlockTableRecord newBtr = new BlockTableRecord(); newBtr.Name = "myBlkName"; newBtr.Origin = center; //�������¼����� blkObjId = bt.Add(newBtr); // ���ؿ��Ӧ��ObjectId trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database! //�����´�����ʵ�嵽����¼ newBtr.AppendEntity(circle); newBtr.AppendEntity(text); // ֪ͨ�����´����˶��� trans.AddNewlyCreatedDBObject(circle, true); trans.AddNewlyCreatedDBObject(text, true); } trans.Commit(); //�ύ���� } return blkObjId; }
public void Create(Point2d ptCell, BlockTableRecord cs, Transaction t) { var cellWidth = ColorBookHelper.CellWidth; var cellHeight = ColorBookHelper.CellHeight; var margin = ColorBookHelper.Margin; var marginHalf = margin * 0.5; Point3d ptText = new Point3d(ptCell.X + cellWidth * 0.5, ptCell.Y - ColorBookHelper.TextHeight-margin, 0); Polyline pl = new Polyline(4); pl.AddVertexAt(0, new Point2d(ptCell.X+margin, ptText.Y- marginHalf), 0, 0, 0); pl.AddVertexAt(1, new Point2d(ptCell.X+cellWidth- margin, ptText.Y- marginHalf), 0, 0, 0); pl.AddVertexAt(2, new Point2d(ptCell.X + cellWidth-margin, ptCell.Y-cellHeight+margin), 0, 0, 0); pl.AddVertexAt(3, new Point2d(ptCell.X+margin, ptCell.Y - cellHeight+margin), 0, 0, 0); pl.Closed = true; pl.SetDatabaseDefaults(); pl.Color = Color; cs.AppendEntity(pl); t.AddNewlyCreatedDBObject(pl, true); Hatch h = new Hatch(); h.SetDatabaseDefaults(); h.SetHatchPattern(HatchPatternType.PreDefined, "Solid"); h.Annotative = AnnotativeStates.False; cs.AppendEntity(h); t.AddNewlyCreatedDBObject(h, true); h.Associative = true; h.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection(new[] { pl.Id })); h.Color = Color; h.EvaluateHatch(true); DBText text = new DBText(); text.SetDatabaseDefaults(); text.HorizontalMode = TextHorizontalMode.TextCenter; text.Annotative = AnnotativeStates.False; text.Height = ColorBookHelper.TextHeight; text.AlignmentPoint = ptText; text.AdjustAlignment(cs.Database); text.TextStyleId = ColorBookHelper.IdTextStylePik; text.TextString = Name; cs.AppendEntity(text); t.AddNewlyCreatedDBObject(text, true); }
public void Create(BlockTableRecord btr, Transaction t) { var table = GetTable(); table.Position = ptPlan; table.TransformBy(Matrix3d.Scaling(100, table.Position)); btr.AppendEntity(table); t.AddNewlyCreatedDBObject(table, true); }
public static ObjectId AppendEntityToDatabase(Entity ent) { Document doc = AcAp.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Transaction trans = doc.TransactionManager.StartTransaction(); using (trans) { BlockTable blockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRecord = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite); blockTableRecord.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); trans.Commit(); doc.Editor.WriteMessage("\nAdd success"); } return(ent.ObjectId); }
public void netDimAngular() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peo = new PromptEntityOptions("\nSelect an Arc: "); peo.SetRejectMessage("\nMust be an Arc..."); peo.AddAllowedClass(typeof(Arc), true); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } using (Transaction Tx = db.TransactionManager.StartTransaction()) { Arc arc = Tx.GetObject(per.ObjectId, OpenMode.ForRead) as Arc; BlockTable bt = Tx.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = Tx.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; string dimStyle = "Standard"; DimStyleTable dimStyleTable = Tx.GetObject(db.DimStyleTableId, OpenMode.ForRead) as DimStyleTable; if (dimStyleTable.Has(dimStyle)) { Point3d point3 = arc.StartPoint.Add(arc.EndPoint.GetAsVector()).MultiplyBy(0.5); ObjectId dimStyleId = dimStyleTable[dimStyle]; Point3AngularDimension dim = new Point3AngularDimension(arc.Center, arc.StartPoint, arc.EndPoint, point3, "", dimStyleId); btr.AppendEntity(dim); Tx.AddNewlyCreatedDBObject(dim, true); Tx.Commit(); } } }
public ObjectId CreateEllipse(Point3d centerPoint, Transaction trans, BlockTableRecord btr, ObjectId layerId) { var ellipse = new Ellipse( centerPoint, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, Math.PI * 2); ellipse.LayerId = layerId; var id = btr.AppendEntity(ellipse); trans.AddNewlyCreatedDBObject(ellipse, true); return(id); }
public ObjectId CreateText(Point3d centerPoint, Transaction trans, BlockTableRecord btr, ObjectId layerId) { var text = new DBText(); text.Height = 0.7; text.TextString = "xu.shuai"; text.HorizontalMode = TextHorizontalMode.TextCenter; text.VerticalMode = TextVerticalMode.TextVerticalMid; text.Position = centerPoint; text.AlignmentPoint = centerPoint; text.LayerId = layerId; var id = btr.AppendEntity(text); trans.AddNewlyCreatedDBObject(text, true); return(id); }
private ObjectId GetOrCreateBlock(Database db, string blockName, ObjectId textLayerId, ObjectId lineLayerId, ObjectId textStyleId) { ObjectId id = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable table = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); if (table.Has(blockName)) { id = table[blockName]; } else { BlockTableRecord blockDef = new BlockTableRecord(); blockDef.Name = blockName; table.UpgradeOpen(); id = table.Add(blockDef); tr.AddNewlyCreatedDBObject(blockDef, true); double crossSize = 1; double spacing = 0.5; double th = 1; Point3d pt = new Point3d(0, 0, 0); Line line1 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(crossSize, 0, 0), pt + new Vector3d(crossSize, 0, 0), lineLayerId); Line line2 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(0, crossSize, 0), pt + new Vector3d(0, crossSize, 0), lineLayerId); AttributeDefinition text1 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(crossSize + spacing, 0, 0), "Y", "Y", "0 000 000", th, 0, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId); text1.LockPositionInBlock = true; AttributeDefinition text2 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(0, crossSize + spacing, 0), "X", "X", "0 000 000", th, Math.PI / 2, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId); text2.LockPositionInBlock = true; foreach (Entity ent in new Entity[] { line1, line2, text1, text2 }) { blockDef.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } } tr.Commit(); } return(id); }
public void CreateCircle(Point3d center, int colorIndex) { Database workingDatabase = HostApplicationServices.WorkingDatabase; using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, 0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[(BlockTableRecord.ModelSpace)], OpenMode.ForWrite); Circle circle = new Circle(center, Vector3d.ZAxis, 10.0); circle.ColorIndex = (colorIndex); this.CreateLayer("结构注意"); circle.Layer = ("结构注意"); blockTableRecord.AppendEntity(circle); transaction.AddNewlyCreatedDBObject(circle, true); transaction.Commit(); } }
/// <summary> /// 将实体添加到模型空间 /// </summary> /// <param name="db">数据库对象</param> /// <param name="ent">要添加的实体</param> /// <returns>返回添加到模型空间中的实体ObjectId</returns> public static ObjectId AddToModelSpace(this Database db, Entity ent) { ObjectId entId;//用于返回添加到模型空间中的实体ObjectId //定义一个指向当前数据库的事务处理,以添加直线 using (Transaction trans = db.TransactionManager.StartTransaction()) { //以读方式打开块表 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); //以写方式打开模型空间块表记录. BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); entId = btr.AppendEntity(ent); //将图形对象的信息添加到块表记录中 trans.AddNewlyCreatedDBObject(ent, true); //把对象添加到事务处理中 trans.Commit(); //提交事务处理 } return(entId); //返回实体的ObjectId }
//////////////////////////// //// MATERIALS //////////////////////////// private void DisplayPropsMaterial() { Database db = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager tm = db.TransactionManager; Transaction trans = db.TransactionManager.StartTransaction(); try { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Get all the Display Properties and the Display components works with AecDbMaterialDef in ZAxis view\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); DisplayRepresentationManager drm = new DisplayRepresentationManager(db); Viewport vport = new Viewport(); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false); btr.AppendEntity(vport); trans.AddNewlyCreatedDBObject(vport, true); ObjectId viewportId = vport.ObjectId; Vector3d viewDirection = Vector3d.ZAxis; ObjectId setId = drm.DisplayRepresentationSet(viewportId, viewDirection); DisplaySet ds = trans.GetObject(setId, OpenMode.ForWrite) as DisplaySet; DisplayRepresentationIdCollection repIds = ds.DisplayRepresentationIds; DisplayRepresentation dr = null; foreach (ObjectId repId in repIds) { dr = trans.GetObject(repId, OpenMode.ForRead) as DisplayRepresentation; if (dr.WorksWith.Name == "AecDbMaterialDef") { ObjectId dpId = dr.DefaultDisplayPropertiesId; DisplayProperties dp = trans.GetObject(dpId, OpenMode.ForWrite) as DisplayProperties; ListDisplayProperties(dp); } } } catch (System.Exception e) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message + "\n"); trans.Abort(); } finally { trans.Dispose(); } return; }
/// <summary> /// Добавляем примитивы в БД чертежа /// </summary> /// <param name="wEntlist"> список примитивов </param> public void DrawEntity(List <Entity> wEntlist) { AppServ.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); BlockTableRecord acBlkTblRec = (BlockTableRecord)acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite); foreach (Entity ent in wEntlist) { acBlkTblRec.AppendEntity(ent); acTrans.AddNewlyCreatedDBObject(ent, true); } acTrans.Commit(); } }
public static ObjectId GetAnonymCopy(ObjectId brId, Transaction trans, bool commit) { BlockReference baseBr = (BlockReference)brId.GetObject(OpenMode.ForRead, true, true); BlockTableRecord baseBtr = (BlockTableRecord)baseBr.BlockTableRecord.GetObject(OpenMode.ForRead, false, true); var bt = (BlockTable)trans.GetObject(Tools.GetAcadDatabase().BlockTableId, OpenMode.ForRead); Matrix3d mat = Matrix3d.Identity; mat = mat.PreMultiplyBy(baseBr.BlockTransform); mat = mat.PreMultiplyBy(Matrix3d.Displacement(baseBtr.Origin - baseBr.Position)); BlockTableRecord btr = new BlockTableRecord() { Name = "*U" }; btr.Annotative = baseBtr.Annotative; btr.Origin = baseBtr.Origin; // Add the new block to the block table bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); foreach (ObjectId id in baseBtr) { Entity ent = id.GetObject(OpenMode.ForRead, false, true) as Entity; if (ent != null) { ent = ent.GetTransformedCopy(mat); btr.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); } } // Commit the transaction if (commit) { trans.Commit(); } return(btr.Id); }
public void cmdMyFirst() { Database db = HostApplicationServices.WorkingDatabase; Transaction trans = db.TransactionManager.StartTransaction(); BlockTable blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord msBlkRec = trans.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d pnt1 = new Point3d(0, 0, 0); Point3d pnt2 = new Point3d(10, 10, 0); Line lineObj = new Line(pnt1, pnt2); msBlkRec.AppendEntity(lineObj); trans.AddNewlyCreatedDBObject(lineObj, true); trans.Commit(); }
public void makeCircle() { Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10); CircleJig jigCir = new CircleJig(circle); for (int i = 0; i < 2; ++i) { jigCir.CurrentInput = i; Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptResult prompt = ed.Drag(jigCir); if (prompt.Status == PromptStatus.Cancel || prompt.Status == PromptStatus.Error) { return; } } Database dwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; using (Transaction trans = dwg.TransactionManager.StartTransaction()) { try { // use the transaction to open these objects. // the transaction will automatically dispose these objects when done // so we don't have to worry about manually disposing them. BlockTable blk = trans.GetObject(dwg.BlockTableId, OpenMode.ForWrite) as BlockTable; if (blk == null) { return; } BlockTableRecord blkRecord = trans.GetObject(blk[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; blkRecord.AppendEntity(circle); trans.AddNewlyCreatedDBObject(circle, true); trans.Commit(); } catch (System.Exception) { trans.Abort(); throw; } } }
public void CreateContour(BlockTableRecord btr) { if (panelBtr.ExtentsByTile.Diagonal() < endOffset) { return; } // из всех плиток отделить торцевые плитки???? // дерево границ плиток TreeTiles = new RTree <Tuple <ObjectId, Extents3d> >(); panelBtr.Tiles.ForEach(t => { try { var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0); TreeTiles.Add(r, t); } catch { } }); // Первый угол панели - левый нижний var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower); var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop); var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop); var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower); Extents3d extNoEnd = new Extents3d(pt1, pt2); extNoEnd.AddPoint(pt3); extNoEnd.AddPoint(pt4); panelBtr.ExtentsNoEnd = extNoEnd; Point3dCollection pts = new Point3dCollection(); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); pts.Add(pt4); using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true)) { poly.LayerId = panelBtr.CPS.IdLayerContour; btr.AppendEntity(poly); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true); } }
/// <summary> /// Метод создаёт Viewport на заданном Layout, в размер листа /// </summary> /// <param name="layout">Layout, на котором создаётся viewport</param> /// <param name="borders">Границы выделенной области в модели</param> void CreateViewport(Layout layout, DrawingBorders borders, Transaction tr) { int vpCount = layout.GetViewports().Count; if (vpCount == 0) { throw new System.Exception(String.Format("Layout {0} не инициализирован", layout.LayoutName)); } Viewport vp; if (vpCount == 1) { BlockTableRecord lbtr = (BlockTableRecord)tr.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite); vp = new Viewport(); vp.SetDatabaseDefaults(); lbtr.AppendEntity(vp); tr.AddNewlyCreatedDBObject(vp, true); vp.On = true; } else { ObjectId vpId = layout.GetViewports()[vpCount - 1]; if (vpId.IsNull) { throw new System.Exception("Не удалось получить вьюпорт!"); } vp = (Viewport)tr.GetObject(vpId, OpenMode.ForWrite); if (vp == null) { throw new System.Exception("Не удалось получить вьюпорт!"); } } // Высоту и ширину вьюпорта выставляем в размер выделенной области vp.Height = borders.Height / borders.ScaleFactor; vp.Width = borders.Width / borders.ScaleFactor; vp.CenterPoint = new Point3d(vp.Width / 2 + layout.PlotOrigin.X, vp.Height / 2 + layout.PlotOrigin.Y, 0); vp.ViewTarget = new Point3d(0, 0, 0); vp.ViewHeight = borders.Height; vp.ViewCenter = new Point2d(borders.Center.X, borders.Center.Y); vp.Locked = LayoutsFromModel.Configuration.AppConfig.Instance.LockViewPorts; }
public static void CreateTest() { using (Document.LockDocument()) { using (var trans = TransactionManager.StartTransaction()) { BlockTable blockTable = trans.GetObject(Database.BlockTableId, OpenMode.ForRead, false) as BlockTable; BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false) as BlockTableRecord; List <Curve> curves; if (false) { var arc = new Arc(new Point3d(2391.1289, 1383.962, 0), 563.3755, 12 * Math.PI / 180, 159 * Math.PI / 180); curves = new List <Curve> { new Line(arc.EndPoint, new Point3d(2017, 1047, 0)), new Line(new Point3d(2017, 1047, 0), new Point3d(2627, 1009, 0)), new Line(arc.StartPoint, new Point3d(2627, 1009, 0)), arc }; } else { Polyline acPoly = new Polyline(); acPoly.AddVertexAt(0, new Point2d(2000, 1500), -0.5, 0, 0); acPoly.AddVertexAt(1, new Point2d(3000, 1500), 0, 0, 0); acPoly.AddVertexAt(2, new Point2d(2800, 700), 0, 0, 0); acPoly.AddVertexAt(3, new Point2d(2300, 700), 0, 0, 0); acPoly.Closed = true; curves = new List <Curve> { acPoly, new Line(new Point3d(-20, 40, 0), new Point3d(0, 0, 0)) }; } foreach (Curve curve in curves) { blockTableRecord.AppendEntity(curve); trans.AddNewlyCreatedDBObject(curve, true); } trans.Commit(); Editor.UpdateScreen(); } } }
private static Entity Draw3dPline(Point[] points, bool closePart) { Document document = AfaDocData.ActiveDocData.Document; Database database = document.Database; var transactionManager = document.TransactionManager; Polyline3d polyline3d = new Polyline3d(); using (document.LockDocument()) { using (Transaction transaction = transactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, 0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[(BlockTableRecord.ModelSpace)], (OpenMode)1); polyline3d.ColorIndex = (256); blockTableRecord.AppendEntity(polyline3d); transaction.AddNewlyCreatedDBObject(polyline3d, true); int num = 0; if (points != null && points.Length > 0) { for (int i = 0; i < points.Length; i++) { Point point = points[i]; PointN pointN = (PointN)point; PolylineVertex3d polylineVertex3d = new PolylineVertex3d(new Point3d(pointN.X, pointN.Y, pointN.Z)); polyline3d.AppendVertex(polylineVertex3d); num++; } } if (num == 0) { return(null); } if (closePart) { polyline3d.Closed = (true); } polyline3d.ColorIndex = (256); document.TransactionManager.QueueForGraphicsFlush(); document.TransactionManager.FlushGraphics(); document.Editor.UpdateScreen(); transaction.Commit(); } } return(polyline3d); }
jigSplineLeader(Point3d pnt3dFirst, double txtSize, string nameLayer, short color) { ObjectId idLDR = ObjectId.Null; Editor ed = BaseObjs._editor; JigSplineLeader jig = new JigSplineLeader(pnt3dFirst, txtSize, nameLayer, color); bool bSuccess = true, bComplete = false; int pntCount = 0; while (bSuccess && !bComplete) { _mIsJigStarted = false; PromptResult dragres = ed.Drag(jig); bSuccess = (dragres.Status == PromptStatus.OK); if (bSuccess) { jig.addVertex(); pntCount++; } bComplete = (dragres.Status == PromptStatus.None || pntCount == 3); } if (bComplete) { try{ using (Transaction tr = BaseObjs.startTransactionDb()){ BlockTableRecord ms = Blocks.getBlockTableRecordMS(); Leader ldr = (Leader)jig.getEntity(); ms.AppendEntity(ldr); tr.AddNewlyCreatedDBObject(ldr, true); tr.Commit(); idLDR = ldr.ObjectId; } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " BB_Jig.cs: line: 155"); } } return(idLDR); }
public void LXC() { DocumentCollection dm = Application.DocumentManager; Editor ed = dm.MdiActiveDocument.Editor; Database db = dm.MdiActiveDocument.Database; //该图库地址后期应修改未变量 string xckPath = Tools.GetCurrentPath() + @"\BaseDwgs\铝型材标准块库.dwg"; ed.WriteMessage(xckPath); //根据编号生成需要的块名 PromptStringOptions pso = new PromptStringOptions("\n百福工具箱——插入铝型材\n请输入型材编号") { AllowSpaces = false }; PromptResult xcbhpr = ed.GetString(pso); string xcbh = "LC" + xcbhpr.StringResult; //输入块参照插入的点 PromptPointResult ppr = ed.GetPoint("\n请选择插入点"); Point3d pt = ppr.Value; //从外部DWG文件中插入图块 //BlockTools.ImportBlocksFromDWG(xckPath, db); db.ImportBlocksFromDWG(xckPath, xcbh); using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; if (bt.Has(xcbh)) { using (BlockReference brf = new BlockReference(pt, bt[xcbh])) { btr.AppendEntity(brf); trans.AddNewlyCreatedDBObject(brf, true); } } else { ed.WriteMessage("\n未在图库中找到图块" + xcbh); } trans.Commit(); } }
// write the AC entity into the AC database public static void Add(Entity entity) { // get database reference Database db = Application.DocumentManager.MdiActiveDocument.Database; using (Transaction acTrans = db.TransactionManager.StartTransaction()) { Log.Append("> Start Transaction..."); try { // create a block table record BlockTableRecord acBTR = (BlockTableRecord)acTrans.GetObject( db.CurrentSpaceId, // space id (f.e. model space) OpenMode.ForWrite); // put entity into block table record acBTR.AppendEntity(entity); // put it into the transaction // |true add, false delete acTrans.AddNewlyCreatedDBObject(entity, true); // write data into the database completing the transaction acTrans.Commit(); Log.Append("> Transaction successfull!"); } // handle autocad exception catch (Autodesk.AutoCAD.Runtime.Exception ex) { acTrans.Abort(); Log.Append("*** error in transaction!"); Log.Append(ex.ToString()); } // clearing finally { GC.Collect(); // clear the memory } Log.Append("> completed!"); } }
public static Polyline smethod_2(Point3dCollection point3dCollection_2) { Database workingDatabase = HostApplicationServices.WorkingDatabase; Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument; Polyline result; using (Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, 0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(workingDatabase.CurrentSpaceId, 1); Polyline polyline = new Polyline(); int num = 0; try { foreach (object obj in point3dCollection_2) { Point3d point3d2; Point3d point3d = (obj != null) ? ((Point3d)obj) : point3d2; Polyline polyline2 = polyline; int num2 = num; Point2d point2d; point2d..ctor(point3d.X, point3d.Y); polyline2.AddVertexAt(num2, point2d, 0.0, 0.0, 0.0); Math.Max(Interlocked.Increment(ref num), checked (num - 1)); } } finally { IEnumerator enumerator; if (enumerator is IDisposable) { (enumerator as IDisposable).Dispose(); } } polyline.Closed = true; blockTableRecord.AppendEntity(polyline); transaction.AddNewlyCreatedDBObject(polyline, true); transaction.Commit(); result = polyline; } } return(result); }
public static ObjectIdCollection ToSpace(this IEnumerable <Entity> ents, Database db = null, string space = null) { db = (db ?? Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database); ObjectIdCollection ids = new ObjectIdCollection(); using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord mdlSpc = trans.GetObject(blkTbl[space ?? BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; foreach (Entity ent in ents) { ids.Add(mdlSpc.AppendEntity(ent)); trans.AddNewlyCreatedDBObject(ent, true); } trans.Commit(); } return(ids); }
public ObjectId addShape(Entity shape) { Document doc = Application.DocumentManager.MdiActiveDocument; using (doc.LockDocument()) using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ObjectId id; using (shape) { id = btr.AppendEntity(shape); tr.AddNewlyCreatedDBObject(shape, true); } tr.Commit(); //doc.Editor.UpdateScreen(); return(id); } }
/// <summary>点击响应事件,创建一个圆 /// /// </summary> /// <param name="o"></param> /// <param name="e"></param> private void MyMenuItem_OnClick(object o, EventArgs e) { using (DocumentLock doclock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { //创建一个红色的圆 Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Circle cir = new Circle(new Point3d(10, 10, 0), Vector3d.ZAxis, 100); cir.ColorIndex = 1; btr.AppendEntity(cir); trans.AddNewlyCreatedDBObject(cir, true); trans.Commit(); } } }
public static List <ObjectId> AppendEntity <T>(IEnumerable <T> entities) where T : Entity { List <ObjectId> res = new List <ObjectId>(); Tools.StartTransaction(() => { Transaction trans = HostApplicationServices.WorkingDatabase.TransactionManager.TopTransaction; BlockTableRecord btr = GetAcadBlockTableRecordCurrentSpace(trans, HostApplicationServices.WorkingDatabase, OpenMode.ForWrite); foreach (var ent in entities) { res.Add(btr.AppendEntity(ent)); trans.AddNewlyCreatedDBObject(ent, true); } }); return(res); }
public static IEnumerable <ObjectId> AddToModelSpace(this IEnumerable <Entity> ents) { List <ObjectId> list = new List <ObjectId>(ents.Count()); using (Transaction trans = db.TransactionManager.StartTransaction()) { //③ 以读方式打开图形数据库的块表 : 默认有 模型空间、布局1、布局2 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); //④以写方式打开模型空间块表记录.打开一个存储实体的块表记录(通常绘图都在模型空间进行),所有模型空间的实体都存储在块表的“模型空间”记录中 BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //⑤将图形对象的信息添加到块表记录中,并返回对象的ID号. ents.ForEach(ent => { list.Add(btr.AppendEntity(ent)); trans.AddNewlyCreatedDBObject(ent, true); //把对象添加到事务处理中. }); trans.Commit(); //提交事务处理 } return(list); }
/// <summary> /// 将一个实体加入到指定的DataBase的模型空间中 /// </summary> /// <param name="entity">实体对象</param> /// <param name="db">数据库</param> /// <returns></returns> public static ObjectId AddToModelSpace(Entity entity) { ObjectId entityId; Database db = Application.DocumentManager.MdiActiveDocument.Database; using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; entityId = btr.AppendEntity(entity); trans.AddNewlyCreatedDBObject(entity, true); trans.Commit(); } } return(entityId); }
public Polyline3d CreatePolye(Point3dCollection points) { Database workingDatabase = HostApplicationServices.WorkingDatabase; Polyline3d polyline3d = new Polyline3d(0, points, true); using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, 0); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite); polyline3d.ColorIndex = (1); this.CreateLayer("删除"); polyline3d.Layer = ("删除"); blockTableRecord.AppendEntity(polyline3d); transaction.AddNewlyCreatedDBObject(polyline3d, true); transaction.Commit(); } return(polyline3d); }
/// <summary>Создание лучей</summary> private void CreateRays(XElement root, Transaction tr, BlockTableRecord btr) { foreach (XElement rayXElement in root.Elements("Ray")) { XElement originXElement = rayXElement.Element("Origin"); Point3d originPoint = originXElement.GetAsPoint(); XElement directionXElement = rayXElement.Element("Direction"); Vector3d direction = directionXElement.GetAsPoint().GetAsVector(); using (Ray ray = new Ray()) { ray.BasePoint = originPoint; ray.UnitDir = direction; btr.AppendEntity(ray); tr.AddNewlyCreatedDBObject(ray, true); } } }
void CreateLine(BlockTableRecord acBlkTblRec, Transaction acTrans, Point3d Point1, Point3d Point2, Color color) { try { // Create a line that starts at Point1 and ends at Point2 Line acLine = new Line(Point1, Point2); acLine.Color = color; acLine.SetDatabaseDefaults(); // Add the new object to the block table record and the transaction acBlkTblRec.AppendEntity(acLine); acTrans.AddNewlyCreatedDBObject(acLine, true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/** * @brief Metodo que descompone una curva en un conjunto de segmentos de línea que aproximan o recubren la curva original. * * @param cur Entidad curva que debe ser linealizada. * @param numSeg Número de líneas en las que tiene que ser partida la curva. * @param acBlkTbl Tabla de bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param acBlkTblRec Tabla de registros de los bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param t Transaccion abierta para manipular la tabla de bloques de AutoCAD. * @param LayerId Parámetro del tipo ObjectId que identifica la capa a la que tendrán que asociarse las nuevas líneas generadas por el proceso * de descomposición de la curva. * @param dwfg Parámetro del tipo dwgFile donde se almacenaran las nuevas líneas creadas a partir del proceso de descomposición de la curva. * * @return Devuelve una colección de entidades tipo linea bajo la clase DBObjectCollection. **/ public static DBObjectCollection curvaAlineas(Curve cur, int numSeg, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec,Transaction t, ObjectId LayerId, dwgFile dwfg) { DBObjectCollection ret = new DBObjectCollection(); // Collect points along our curve Point3dCollection pts = new Point3dCollection(); // Split the curve's parameter space into // equal parts double startParam = cur.StartParam; double segLen = (cur.EndParam - startParam) / numSeg; // Loop along it, getting points each time for (int i = 0; i < numSeg + 1; i++) { Point3d pt = cur.GetPointAtParameter(startParam + segLen * i); pts.Add(pt); } if (pts != null && pts.Count > 0) { if (pts.Count == 1) { // Retornamos un punto. } else if (pts.Count >= 2) { // Retornamos una secuencia de lineas for (int i = 0; i < pts.Count - 1; i++) { Line ln = new Line(); ln.StartPoint = pts[i]; ln.EndPoint = pts[i + 1]; ln.LayerId = LayerId; acBlkTblRec.AppendEntity(ln); t.AddNewlyCreatedDBObject(ln, true); dwfg.objetosArtificiales.Add(ln.ObjectId); ret.Add(ln); } } } return ret; }
/// <summary> /// Создание ассоциативной штриховки по полилинии /// Полилиния должна быть в базе чертежа /// </summary> public static Hatch CreateAssociativeHatch(Curve loop, BlockTableRecord cs, Transaction t, string pattern = "SOLID", string layer = null, LineWeight lw = LineWeight.LineWeight015) { var h = new Hatch(); h.SetDatabaseDefaults(); if (layer != null) { Layers.LayerExt.CheckLayerState(layer); h.Layer = layer; } h.LineWeight = lw; h.Linetype = SymbolUtilityServices.LinetypeContinuousName; h.SetHatchPattern(HatchPatternType.PreDefined, pattern); cs.AppendEntity(h); t.AddNewlyCreatedDBObject(h, true); h.Associative = true; h.HatchStyle = HatchStyle.Normal; // добавление контура полилинии в гштриховку var ids = new ObjectIdCollection(); ids.Add(loop.Id); try { h.AppendLoop(HatchLoopTypes.Default, ids); } catch (Exception ex) { Logger.Log.Error(ex, $"CreateAssociativeHatch"); h.Erase(); return null; } h.EvaluateHatch(true); var orders = cs.DrawOrderTableId.GetObject(OpenMode.ForWrite) as DrawOrderTable; orders.MoveToBottom(new ObjectIdCollection(new[] { h.Id })); return h; }
/// <summary> /// Generates and adds a series of <see cref="Hatch"/> objects to the supplied <see cref="BlockTableRecord"/> /// </summary> /// <returns>The selected color as a<see cref="Autodesk.AutoCAD.Colors.Color"/></returns> private static void CreateHatchesForConcentricCircles(BlockTableRecord blockTableRecord, ObjectIdCollection objectIdCollection, Transaction transaction) { var rand = new Random(); var previousPattern = string.Empty; for (var i = 0; i < objectIdCollection.Count - 1; i++) { var r = Convert.ToByte((i + 1)*rand.Next(0, 25)); var g = Convert.ToByte((i + 1)*rand.Next(0, 25)); var b = Convert.ToByte((i + 1)*rand.Next(0, 25)); using (var hatch = new Hatch()) { blockTableRecord.AppendEntity(hatch); transaction.AddNewlyCreatedDBObject(hatch, true); var pattern = GetRandomHatchPatternName(); //ensure pattern isn't repeated by from previous hatch // in production quality code I would move this behavior to avoid violating SRP/SoC while (pattern.Equals(previousPattern, StringComparison.InvariantCultureIgnoreCase)) { pattern = GetRandomHatchPatternName(); } previousPattern = pattern; hatch.SetHatchPattern(HatchPatternType.PreDefined, pattern); hatch.Color = Color.FromRgb(r, g, b); // Associative must be set after the hatch object is appended to the block table record and before AppendLoop hatch.Associative = true; // Take the current circle and the next to create a HatchLoop hatch.AppendLoop(HatchLoopTypes.Outermost, new ObjectIdCollection {objectIdCollection[i]}); hatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection {objectIdCollection[i + 1]}); hatch.EvaluateHatch(true); } } }
private void addOutsides(BlockTableRecord btrPanel, Transaction t) { if (panelBase.Panel.outsides?.outside?.Count()>0) { foreach (var outside in panelBase.Panel.outsides.outside) { Polyline plOut = new Polyline(); Point2d pt;// =new Point2d(outside.posi.X, outside.posi.Y); double width = Math.Abs(outside.width)+70; // Если это левое примыкание Outside if (Math.Abs(outside.posi.X)<10) { pt = new Point2d(outside.posi.X, outside.posi.Y); panelBase.XMinContour = width; panelBase.XStartTile = width+11; //panelBase.XMinPanel = pt.X; panelBase.IsOutsideLeft = true; } else { pt = new Point2d(outside.posi.X-70, outside.posi.Y); panelBase.XMaxContour += -70; panelBase.XMaxPanel = pt.X + width; panelBase.IsOutsideRight = true; } plOut.AddVertexAt(0, pt, 0, 0, 0); pt = new Point2d(pt.X+ width, pt.Y); plOut.AddVertexAt(1, pt, 0, 0, 0); pt = new Point2d(pt.X, pt.Y+outside.height); plOut.AddVertexAt(2, pt, 0, 0, 0); pt = new Point2d(pt.X- width, pt.Y); plOut.AddVertexAt(3, pt, 0, 0, 0); plOut.Closed = true; plOut.Layer = "0"; btrPanel.AppendEntity(plOut); t.AddNewlyCreatedDBObject(plOut, true); } } }
private void addTile(BlockTableRecord btrPanel, Transaction t, Point3d pt) { if (Service.Env.IdBtrTile.IsNull) { return; } BlockReference blRefTile = new BlockReference(pt, Service.Env.IdBtrTile); blRefTile.Layer = "0"; blRefTile.ColorIndex = 256; // ByLayer btrPanel.AppendEntity(blRefTile); t.AddNewlyCreatedDBObject(blRefTile, true); }
public void DrawConcentricCirclesAndHatchesCommand() { var document = Application.DocumentManager.MdiActiveDocument; if (document == null) return; using (document.LockDocument()) { using (var database = HostApplicationServices.WorkingDatabase) { using (var transactionManager = database.TransactionManager) { using (var transaction = transactionManager.StartTransaction()) { // Get the concentric circle objects var circles = GetConcentricCircles(GetNumberOfCirclesToDraw(), database); document.Editor.WriteMessage("Creating concentric circles"); // Get a writable version of the blocktable via the transaction based on the database's BlockTableId using (var blockTable = (BlockTable) transaction.GetObject(database.BlockTableId, OpenMode.ForWrite)) { // Create a new BlockTableRecord for the circles var blockTableRecordCircles = new BlockTableRecord { Name = "Concentric Circles" }; // Check for name conflict and abort (due to limited challenge time) if (blockTable.Has(blockTableRecordCircles.Name)) { document.Editor.WriteMessage("A block table record for the circles with this name already exists... aborting."); transaction.Abort(); return; } // Add the circle BlockTableRecord to the BlockTable and Transaction blockTable.Add(blockTableRecordCircles); transaction.AddNewlyCreatedDBObject(blockTableRecordCircles, true); var circleObjectIds = new ObjectIdCollection(); // Add each circle to the circle BlockTableRecord and transaction foreach (var circle in circles) { blockTableRecordCircles.AppendEntity(circle); transaction.AddNewlyCreatedDBObject(circle, true); circleObjectIds.Add(circle.ObjectId); //add to id collection for later reference } // Create a new BlockTableRecord for the hatches var blockTableRecordHatches = new BlockTableRecord { Name = "Hatch Block" }; // Check for name conflict and abort (due to limited challenge time) if (blockTable.Has(blockTableRecordHatches.Name)) { document.Editor.WriteMessage("A block table record for the hatches with this name already exists... aborting."); transaction.Abort(); return; } // Add the htach BlockTableRecord to the BlockTable and Transaction blockTable.Add(blockTableRecordHatches); transaction.AddNewlyCreatedDBObject(blockTableRecordHatches, true); // Generate all the hatches based on the circles created earlier CreateHatchesForConcentricCircles(blockTableRecordHatches, circleObjectIds, transaction); // Get the modelspace for appending the blockreferences we'll create later var modelSpace = (BlockTableRecord) transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite); // Create BlockReferences for the hatches and circles BlockTableRecords var blockReferenceHatches = new BlockReference(Center, blockTableRecordHatches.Id); var blockReferenceCircles = new BlockReference(Center, blockTableRecordCircles.Id); modelSpace.AppendEntity(blockReferenceHatches); modelSpace.AppendEntity(blockReferenceCircles); transaction.AddNewlyCreatedDBObject(blockReferenceHatches, true); transaction.AddNewlyCreatedDBObject(blockReferenceCircles, true); transaction.Commit(); } } } } } }
public void CreateNewHatch(BlockTableRecord btr) { var h = new Hatch(); h.Annotative = AnnotativeStates.False; h.Layer = Layer; h.Color = Color; h.LineWeight = Lineweight; h.SetHatchPattern(PatternType, PatternName); h.PatternAngle = PatternAngle; h.PatternScale = PatternScale; h.SetHatchPattern(PatternType, PatternName); Id = btr.AppendEntity(h); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(h, true); if (IdsAssociate != null && IdsAssociate.Count > 0) { h.Associative = true; h.AppendLoop(HatchLoopTypes.Default, IdsAssociate); h.EvaluateHatch(false); } }
private void addWindows(BlockTableRecord btrPanel, Transaction t) { // все окна и балеоны в панели var windows = Panel.windows?.window?.Select(w => new { posi = w.posi, width = w.width, height = w.height }); var balconys = Panel.balconys?.balcony?.Select(b => new { posi = b.posi, width = b.width, height = b.height }); var apertures = balconys==null? windows: windows?.Union(balconys)?? balconys; if (apertures != null) { foreach (var item in apertures) { // контур окон Polyline plWindow = new Polyline(); plWindow.LayerId = Service.Env.IdLayerContourPanel; Point2d ptMinWindow = new Point2d(item.posi.X, item.posi.Y); plWindow.AddVertexAt(0, ptMinWindow, 0, 0, 0); plWindow.AddVertexAt(0, new Point2d(ptMinWindow.X, ptMinWindow.Y + item.height), 0, 0, 0); Point2d ptMaxWindow = new Point2d(ptMinWindow.X + item.width, ptMinWindow.Y + item.height); plWindow.AddVertexAt(0, ptMaxWindow, 0, 0, 0); plWindow.AddVertexAt(0, new Point2d(ptMinWindow.X + item.width, ptMinWindow.Y), 0, 0, 0); plWindow.Closed = true; btrPanel.AppendEntity(plWindow); t.AddNewlyCreatedDBObject(plWindow, true); // добавление точек для верхнего образмеривания. PtsForTopDim.Add(ptMinWindow.X); PtsForTopDim.Add(ptMaxWindow.X); Openings.Add(new Extents3d(ptMinWindow.Convert3d(), ptMaxWindow.Convert3d())); // Вставка окон if (WindowsBaseCenters.Count > 0) { var xCenter = item.posi.X + item.width * 0.5; var winMarkMin = WindowsBaseCenters.Where(w => Math.Abs(w.Key.X - xCenter) < 600); if (winMarkMin.Count() > 0) { var winMark = winMarkMin.MinBy(g => (g.Key.X - xCenter)); if (string.IsNullOrWhiteSpace(winMark.Value)) { continue; } // Точка вставки блока окна Point3d ptWin = new Point3d(item.posi.X, item.posi.Y, 0); // Вставка блока окна if (!Service.Env.IdBtrWindow.IsNull) { BlockReference blRefWin = new BlockReference(ptWin, Service.Env.IdBtrWindow); blRefWin.LayerId = Service.Env.IdLayerWindow; btrPanel.AppendEntity(blRefWin); t.AddNewlyCreatedDBObject(blRefWin, true); var resSetDyn = BlockWindow.SetDynBlWinMark(blRefWin, winMark.Value); if (!resSetDyn) { // Добавление текста марки окна DBText dbTextWin = new DBText(); dbTextWin.Position = ptWin; dbTextWin.LayerId = Service.Env.IdLayerWindow; dbTextWin.TextString = winMark.Value; dbTextWin.Height = 180; btrPanel.AppendEntity(dbTextWin); t.AddNewlyCreatedDBObject(dbTextWin, true); } } #if Test // Test else { // Добавление текста марки окна DBText dbTextWin = new DBText(); dbTextWin.Position = ptWin; dbTextWin.LayerId = Service.Env.IdLayerWindow; dbTextWin.TextString = winMark.Value; dbTextWin.Height = 180; btrPanel.AppendEntity(dbTextWin); t.AddNewlyCreatedDBObject(dbTextWin, true); } #endif } } // Сортировка окон слева-направо Openings.Sort((w1, w2) => w1.MinPoint.X.CompareTo(w2.MinPoint.X)); } } }
private ObjectId replaceText(ObjectId idBdText, BlockTableRecord btr) { using (var text = idBdText.GetObject(OpenMode.ForWrite, false, true) as DBText) { using (var copyText = text.Clone() as DBText) { text.Erase(); return btr.AppendEntity(copyText); } } }
/** * @brief Metodo que contiene toda la lógica para procesar cada tipo de entidad. En función del tipo de entidad crea las estructuras * en memoria necesarias y almacena toda la información en la clase dwgFile para que posteriormente sea explotada. * **/ private static void ProcesarObjetos(ObjectId acObjId, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec, Transaction t, ObjectId parentId) { Entity ent = (Entity)t.GetObject(acObjId, OpenMode.ForRead); switch (acObjId.ObjectClass.DxfName) { case "POINT": DBPoint porigen = (DBPoint)ent; dwgPunto punto = new dwgPunto(); punto.objId = acObjId; punto.capaId = ent.LayerId; punto.parentId = parentId; punto.coordenadas = porigen.Position; punto.colorPunto = porigen.Color; punto.color_R = porigen.Color.Red; punto.color_G = porigen.Color.Green; punto.color_B = porigen.Color.Blue; if (dwgf.dwgPuntos.ContainsKey(punto.objId) == false) { dwgf.dwgPuntos.Add(punto.objId, punto); } log("Procesado punto: " + punto.objId.ToString(),true,true); break; case "LINE": Line lorigen = (Line)ent; dwgLinea linea = new dwgLinea(); linea.objId = acObjId; linea.capaId = ent.LayerId; linea.parentId = parentId; linea.colorLinea = lorigen.Color; linea.color_R = lorigen.Color.Red; linea.color_G = lorigen.Color.Green; linea.color_B = lorigen.Color.Blue; linea.LineWeight = (Double)lorigen.LineWeight; if (linea.LineWeight == -1) { log("Ancho de la linea igual al ancho de la capa: " + linea.objId.ToString(), true, true); // Reemplazar por el ancho de la capa. linea.LineWeight = dlwdefault; dwgCapa c; dwgf.dwgCapas.TryGetValue(linea.capaId,out c); if (c != null) { linea.LineWeight = c.default_gruesoLinea; } } else if ((linea.LineWeight == -2) || (linea.LineWeight == -3)) { // -2: Reemplazar por el ancho del bloque. Esto habra que implementarlo cuando se de soporte a bloques. // -3: ancho por defecto del autocad. Comando LWDEFAULT log("Ancho de la linea igual al del bloque o al ancho por defecto: " + linea.objId.ToString(), true, true); linea.LineWeight = dlwdefault; } DBPoint p_origen_0 = new DBPoint(lorigen.StartPoint); DBPoint p_final_0 = new DBPoint(lorigen.EndPoint); acBlkTblRec.AppendEntity(p_origen_0); acBlkTblRec.AppendEntity(p_final_0); t.AddNewlyCreatedDBObject(p_origen_0, true); t.AddNewlyCreatedDBObject(p_final_0, true); dwgPunto p_origen_1 = new dwgPunto(); p_origen_1.objId = p_origen_0.ObjectId; p_origen_1.coordenadas = p_origen_0.Position; p_origen_1.capaId = linea.capaId; linea.p_origen = p_origen_1; dwgPunto p_final_1 = new dwgPunto(); p_final_1.objId = p_final_0.ObjectId; p_final_1.coordenadas = p_final_0.Position; p_final_1.capaId = linea.capaId; linea.p_final = p_final_1; if (dwgf.dwgPuntos.ContainsKey(p_origen_1.objId) == false) { dwgf.dwgPuntos.Add(p_origen_1.objId, p_origen_1); } if (dwgf.dwgPuntos.ContainsKey(p_final_1.objId) == false) { dwgf.dwgPuntos.Add(p_final_1.objId, p_final_1); } if (dwgf.dwgLineas.ContainsKey(linea.objId) == false) { dwgf.dwgLineas.Add(linea.objId, linea); } log("Procesada linea: " + linea.objId.ToString(), true, true); break; case "LWPOLYLINE": dwgPolylinea poli = new dwgPolylinea(); poli.objId = acObjId; poli.capaId = ent.LayerId; poli.parentId = parentId; // Descomponemos en subcomponentes. DBObjectCollection entitySet = new DBObjectCollection(); log("Descomponemos polylinea en lineas y puntos: " + poli.objId.ToString(), true, true); entitySet = dwgDecoder.ObtenerPuntosyLineas(ent, acBlkTbl, acBlkTblRec, t); // Procesamos cada uno de los subcomponentes. // Solo pueden ser: lineas y arcos. Una polylinea no puede formarse con nada mas. foreach (Entity ent2 in entitySet) { switch (ent2.ObjectId.ObjectClass.DxfName) { case "LINE": log("Obtenida linea: " + poli.objId.ToString() + ":" + ent2.ObjectId.ToString(),true, true); poli.lineas.Add(ent2.ObjectId); break; case "ARC": log("Obtenido arco: " + poli.objId.ToString() + ":" + ent2.ObjectId.ToString(), true, true); poli.arcos.Add(ent2.ObjectId); break; default: log("Al descomponer polylinea, objeto no reconocido:" + ent2.ObjectId.ObjectClass.DxfName, true, true); break; } log("Procesamos la nueva entidad obtenida - " + ent2.ObjectId.ObjectClass.DxfName + ":" + ent2.ObjectId, true, true); dwgDecoder.ProcesarObjetos(ent2.ObjectId, acBlkTbl, acBlkTblRec, t, poli.objId); } if ((entitySet.Count > 0) && (dwgf.dwgPolylineas.ContainsKey(poli.objId) == false)) { dwgf.dwgPolylineas.Add(poli.objId, poli); } log("Procesada polilinea: " + poli.objId.ToString(),true, true); break; case "ARC": Arc ar = (Arc) ent; dwgArco arco = new dwgArco(); arco.objId = acObjId; arco.capaId = ent.LayerId; arco.parentId = parentId; arco.radio = ar.Radius; arco.angulo_inicio = ar.StartAngle; arco.angulo_final = ar.EndAngle; DBPoint p_centro = new DBPoint(ar.Center); acBlkTblRec.AppendEntity(p_centro); t.AddNewlyCreatedDBObject(p_centro, true); dwgPunto p_centro_1 = new dwgPunto(); p_centro_1.objId = p_centro.ObjectId; p_centro_1.coordenadas = p_centro.Position; p_centro_1.capaId = arco.capaId; if (dwgf.dwgPuntos.ContainsKey(p_centro_1.objId) == false) { dwgf.dwgPuntos.Add(p_centro_1.objId, p_centro_1); } arco.punto_centro = p_centro_1.objId; // Descomponemos en subcomponentes. log("Descomponemos arco en lineas: " + arco.objId.ToString(), true, true); DBObjectCollection entitySet2 = new DBObjectCollection(); entitySet2 = herramientasCurvas.curvaAlineas((Curve)ent, 5, acBlkTbl, acBlkTblRec, t,arco.capaId, dwgf); // Procesamos cada uno de los subcomponentes. // Solo pueden ser: lineas. Eso lo garantiza la funcion curvaAlineas foreach (Entity ent2 in entitySet2) { log("Nueva entidad - " + ent2.ObjectId.ObjectClass.DxfName + ":" + ent2.ObjectId, true, true); arco.lineas.Add(ent2.ObjectId); dwgDecoder.ProcesarObjetos(ent2.ObjectId, acBlkTbl, acBlkTblRec, t, arco.objId); } if (dwgf.dwgArcos.ContainsKey(arco.objId) == false) { dwgf.dwgArcos.Add(arco.objId, arco); } log("Procesado arco: " + arco.objId.ToString(),true, true); break; default: log("Elemento no reconocido para procesar. No procesado. " + acObjId.ObjectClass.ClassVersion.ToString(),true,true); break; } return; }
private static DBText addText(BlockTableRecord btr, Transaction t, Point3d pt, string value, double height, TextHorizontalMode horMode = TextHorizontalMode.TextCenter) { // Подпись развертки - номер вида DBText text = new DBText(); text.SetDatabaseDefaults(); text.Height = height; text.TextStyleId = IdTextStylePik; text.TextString = value; if (horMode == TextHorizontalMode.TextLeft) { text.Position = pt; } else { text.HorizontalMode = horMode; text.AlignmentPoint = pt; text.AdjustAlignment(btr.Database); } btr.AppendEntity(text); t.AddNewlyCreatedDBObject(text, true); return text; }
private static ObjectId GetBlRefTemplate(double length, double height, ObjectId idBtr, BlockTableRecord btrOwner, Transaction t) { ObjectId res = ObjectId.Null; using (BlockReference blRefTemplate = new BlockReference(Point3d.Origin, idBtr)) { blRefTemplate.ColorIndex = 256; blRefTemplate.Linetype = SymbolUtilityServices.LinetypeByLayerName; blRefTemplate.LineWeight = LineWeight.ByLayer; btrOwner.AppendEntity(blRefTemplate); t.AddNewlyCreatedDBObject(blRefTemplate, true); foreach (DynamicBlockReferenceProperty prop in blRefTemplate.DynamicBlockReferencePropertyCollection) { if (prop.PropertyName.Equals(Settings.Default.BlockColorAreaDynPropLength, StringComparison.OrdinalIgnoreCase)) { prop.Value = length; } else if (prop.PropertyName.Equals(Settings.Default.BlockColorAreaDynPropHeight, StringComparison.OrdinalIgnoreCase)) { prop.Value = height; } } res = blRefTemplate.Id; } return res; }
private void InsertPanel(Transaction t, BlockTable bt, BlockTableRecord ms, Point3d pt, string name) { var blRef = new BlockReference(pt, bt[name]); ms.AppendEntity(blRef); t.AddNewlyCreatedDBObject(blRef, true); }
private void GetDocument2(BoxCollection boxArray) { for (int y = 0; y <= _rLevels; y++) { for (int x = 0; x < _rRacks; x++) { try { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the block table from the drawing var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); string blkName = checkName(boxArray, bt, x, ed); // Create our new block table record... var btr = new BlockTableRecord { Name = blkName }; // ... and set its properties // Add the new block to the block table using (Application.DocumentManager.MdiActiveDocument.LockDocument()) { bt.UpgradeOpen(); Application.UpdateScreen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); // Add some lines to the block to form a square // (the entities belong directly to the block) DBObjectCollection ents = RacksOfLines(_rHeight, _rDeep); foreach (Entity ent in ents) { btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } // Add a block reference to the model space var ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); var br = new BlockReference(new Point3d(0, x * _rDistance, y * _rHeight), btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); // Commit the transaction tr.Commit(); // Report what we've done ed.WriteMessage("\nCreated block named \"{0}\" containing {1} entities.", blkName, ents.Count); } } } catch (Exception e) { MessageBox.Show("There is a problem in block creation, here is the error : " + e); } } } }
public void TestDynBlSec() { string testFile = @"c:\temp\test\АКР\Base\Tests\TestDynBlSec.dwg"; using (var db = new Database(false, true)) { db.ReadDwgFile(testFile, FileOpenMode.OpenForReadAndAllShare, false, ""); db.CloseInput(true); using (AcadLib.WorkingDatabaseSwitcher dbSwitcher = new AcadLib.WorkingDatabaseSwitcher(db)) { ObjectId idBtrPanel; ObjectId idBtrMs; using (var t = db.TransactionManager.StartTransaction()) { BlockTableRecord ms; BlockTableRecord btrPanel; ObjectId idBtrSec; BlockTableRecord btrDim; using (var bt = db.BlockTableId.GetObject(OpenMode.ForWrite) as BlockTable) { ms = bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord; idBtrMs = ms.Id; idBtrSec = bt["Test"]; btrPanel = new BlockTableRecord(); btrPanel.Name = "Panel"; idBtrPanel = bt.Add(btrPanel); t.AddNewlyCreatedDBObject(btrPanel, true); btrDim = new BlockTableRecord(); btrDim.Name = "Dim"; bt.Add(btrDim); t.AddNewlyCreatedDBObject(btrDim, true); } BlockReference blRefDim = new BlockReference(Point3d.Origin, btrDim.Id); btrPanel.AppendEntity(blRefDim); t.AddNewlyCreatedDBObject(blRefDim, true); BlockReference blRef = new BlockReference(Point3d.Origin, idBtrSec); btrDim.AppendEntity(blRef); t.AddNewlyCreatedDBObject(blRef, true); setDynParam(blRef); t.Commit(); } using (var t = db.TransactionManager.StartTransaction()) { var ms = idBtrMs.GetObject(OpenMode.ForWrite) as BlockTableRecord; BlockReference blRefPanel = new BlockReference(Point3d.Origin, idBtrPanel); ms.AppendEntity(blRefPanel); t.AddNewlyCreatedDBObject(blRefPanel, true); t.Commit(); } } string saveFile = @"c:\temp\test\АКР\Base\Tests\TestDynBlSec-TestSaved.dwg"; db.SaveAs(saveFile, DwgVersion.Current); } }
//This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock", //creating it if necessary. The block contains three entities - circle, text //and ellipse. public ObjectId CreateEmployeeDefinition() { ObjectId newBtrId = new ObjectId(); //The return value for this function Database db = HostApplicationServices.WorkingDatabase; //save some space // The "using" keyword used below automatically calls "Dispose" // on the "trans" object. using (Transaction trans = db.TransactionManager.StartTransaction()) { //Now, drill into the database and obtain a reference to the BlockTable BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if ((bt.Has("EmployeeBlock"))) { newBtrId = bt["EmployeeBlock"]; } else { Point3d center = new Point3d(10, 10, 0); // convenient declaration... // Declare and define the entities we want to add: //Circle: Circle circle = new Circle(center, Vector3d.ZAxis, 2); //Text: MText text = new MText(); text.Contents = "Earnest Shackleton"; text.Location = center; //Ellipse: Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, 0); //Next, create a layer with the helper function, and assign //the layer to our entities. ObjectId empId = CreateLayer(); text.LayerId = empId; circle.LayerId = empId; ellipse.LayerId = empId; //Set the color for each entity irrespective of the layer's color. text.ColorIndex = 2; circle.ColorIndex = 1; ellipse.ColorIndex = 3; //Create a new block definition called EmployeeBlock BlockTableRecord newBtr = new BlockTableRecord(); newBtr.Name = "EmployeeBlock"; newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database! newBtr.AppendEntity(circle); //Append our entities... newBtr.AppendEntity(text); newBtr.AppendEntity(ellipse); trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities. trans.AddNewlyCreatedDBObject(text, true); trans.AddNewlyCreatedDBObject(ellipse, true); } trans.Commit(); //All done, no errors? Go ahead and commit! } return newBtrId; }
public static TypedValue ProxyExplodeToBlock(ResultBuffer rbArgs) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; TypedValue res = new TypedValue((int)LispDataType.Text,""); if (rbArgs.AsArray().Length == 2) { TypedValue entity = rbArgs.AsArray()[0]; TypedValue blkPrefix = rbArgs.AsArray()[1]; if ((entity.TypeCode == (int)LispDataType.ObjectId) && (blkPrefix.TypeCode == (int)LispDataType.Text)) { using (Transaction tr = doc.TransactionManager.StartTransaction()) { try { ObjectId id = (ObjectId)entity.Value; DBObjectCollection objs = new DBObjectCollection(); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); Entity entx = (Entity)tr.GetObject(id, OpenMode.ForWrite); entx.Explode(objs); string blkName = blkPrefix.Value.ToString() + entx.Handle.ToString(); if (bt.Has(blkName) == false) { BlockTableRecord btr = new BlockTableRecord(); btr.Name = blkName; bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); foreach (DBObject obj in objs) { Entity ent = (Entity)obj; btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } } res = new TypedValue((int)LispDataType.Text, blkName); tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { tr.Abort(); ed.WriteMessage(ex.Message); } } } } return res; }
private static Extents3d createChangePlan(List<ChangePanel> chPanels, Point3d ptPlan, ObjectId idBtrFloor, BlockTableRecord btr,Transaction t) { // Вставить блок монтажки var blRefFloor = new BlockReference(ptPlan, idBtrFloor); btr.AppendEntity(blRefFloor); t.AddNewlyCreatedDBObject(blRefFloor, true); // Обвести облачком каждую панель с изменившейся покраской foreach (var chPanel in chPanels) { // Границы монт. панели на монт. плане в координатах Модели. var extMP = chPanel.ExtMountPanel; extMP.TransformBy(blRefFloor.BlockTransform); Point3d ptCloudMin; Point3d ptCloudMax; Point3d ptText; if (chPanel.IsHorizontal) { ptCloudMin = new Point3d(extMP.MinPoint.X + 150, extMP.MinPoint.Y - 150, 0); ptCloudMax = new Point3d(extMP.MaxPoint.X - 150, extMP.MaxPoint.Y + 150, 0); ptText = new Point3d(ptCloudMin.X, ptCloudMin.Y - 100, 0); } else { ptCloudMin = new Point3d(extMP.MinPoint.X - 150, extMP.MinPoint.Y + 150, 0); ptCloudMax = new Point3d(extMP.MaxPoint.X + 150, extMP.MaxPoint.Y - 150, 0); ptText = new Point3d(ptCloudMax.X+100, ptCloudMin.Y+(ptCloudMax.Y-ptCloudMin.Y)*0.5, 0); } var extCloud = new Extents3d(ptCloudMin, ptCloudMax); // Полилиния облака изменения var pl = extCloud.GetPolyline(); var plCloud = getCloudPolyline(pl); plCloud.SetDatabaseDefaults(); plCloud.Color = ColorChange; btr.AppendEntity(plCloud); t.AddNewlyCreatedDBObject(plCloud, true); // Текст изменения MText text = new MText(); text.SetDatabaseDefaults(); text.Color = ColorChange; text.TextHeight = 250; text.Contents = $"Старая марка покраски: {chPanel.PaintOld}, \n\rНовая марка покраски: {chPanel.PaintNew} " + $"\n\rПанель: {chPanel.MarkSb}"; text.Location = ptText; btr.AppendEntity(text); t.AddNewlyCreatedDBObject(text, true); chPanel.PanelMount.SetPaintingToAttr(chPanel.PanelAKR.MarkAr); } // Разбить //blRefFloor.ExplodeToOwnerSpace(); return blRefFloor.GeometricExtents; }
public bool TryInsertBlockRecord(string blockName, DBObjectCollection geometricEntities, List<AttributeDefinition> attCollection) { Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (!bt.Has(blockName)) { BlockTableRecord btr = new BlockTableRecord(); btr.Name = blockName; bt.UpgradeOpen(); bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); foreach (Entity ent in geometricEntities) { btr.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); } foreach (AttributeDefinition atd in attCollection) { btr.AppendEntity(atd); trans.AddNewlyCreatedDBObject(atd, true); } trans.Commit(); return true; } else { return false; } } }
private void сreateHatch(Extents3d extText, BlockTableRecord btr) { if (extText.Diagonal() < 100) { return; } // Отступ контура штриховки от границ текста Extents3d ext = new Extents3d(new Point3d(extText.MinPoint.X - 10, extText.MinPoint.Y - 10, 0), new Point3d(extText.MaxPoint.X + 10, extText.MaxPoint.Y + 10, 0)); var h = new Hatch(); h.SetDatabaseDefaults(btr.Database); if (!panelBtr.CaptionLayerId.IsNull) h.LayerId = panelBtr.CaptionLayerId; h.LineWeight = LineWeight.LineWeight015; h.Linetype = SymbolUtilityServices.LinetypeContinuousName; h.Color = Color.FromRgb(250, 250, 250); h.Transparency = new Transparency(80); h.SetHatchPattern(HatchPatternType.PreDefined, "ANGLE"); h.PatternScale = 25.0; btr.AppendEntity(h); var t = btr.Database.TransactionManager.TopTransaction; t.AddNewlyCreatedDBObject(h, true); h.Associative = true; h.HatchStyle = HatchStyle.Normal; // Полилиния по контуру текста Polyline pl = new Polyline(); pl.SetDatabaseDefaults(btr.Database); pl.LineWeight = LineWeight.LineWeight015; pl.Linetype = SymbolUtilityServices.LinetypeContinuousName; pl.ColorIndex = 256; // ПоСлою if (!panelBtr.CaptionLayerId.IsNull) pl.LayerId = panelBtr.CaptionLayerId; pl.AddVertexAt(0, ext.MinPoint.Convert2d(), 0, 0, 0); pl.AddVertexAt(0, new Point2d(ext.MaxPoint.X, ext.MinPoint.Y), 0, 0, 0); pl.AddVertexAt(0, ext.MaxPoint.Convert2d(), 0, 0, 0); pl.AddVertexAt(0, new Point2d(ext.MinPoint.X, ext.MaxPoint.Y), 0, 0, 0); pl.Closed = true; ObjectId idPl = btr.AppendEntity(pl); t.AddNewlyCreatedDBObject(pl, true); // добавление контура полилинии в гштриховку var ids = new ObjectIdCollection(); ids.Add(idPl); h.AppendLoop(HatchLoopTypes.Default, ids); h.EvaluateHatch(true); // Замена текстов - чтобы они стали поверх штриховки. panelBtr.IdCaptionMarkSb = replaceText(panelBtr.IdCaptionMarkSb, btr); panelBtr.IdCaptionPaint = replaceText(panelBtr.IdCaptionPaint, btr); }
private void addCheek(BlockTableRecord btrPanel, Transaction t) { if (IsCheekLeft || IsCheekRight) { int yStep = Settings.Default.TileHeight + Settings.Default.TileSeam; double xTile = 0; List<Point2d> ptsPlContourCheek = new List<Point2d>(); // Торец слева if (IsCheekLeft) { xTile = -(600 + Settings.Default.TileLenght); // Добавление точек контура в список Point2d pt = new Point2d(xTile, 0); ptsPlContourCheek.Add(pt); PtsForBotDimCheek.Add(pt.X); pt = new Point2d(pt.X + 277, 0); PtsForBotDimCheek.Add(pt.X); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X + 12, 0); PtsForBotDimCheek.Add(pt.X); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X, Height); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X-30, pt.Y); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X-20, pt.Y+20); ptsPlContourCheek.Add(pt); pt = new Point2d(xTile, pt.Y); ptsPlContourCheek.Add(pt); } // Торец справа else if (IsCheekRight) { xTile = Length + 600; // Добавление точек контура в список Point2d pt = new Point2d(xTile, 0); ptsPlContourCheek.Add(pt); PtsForBotDimCheek.Add(pt.X); pt = new Point2d(pt.X + 12, 0); PtsForBotDimCheek.Add(pt.X); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X + 277, 0); PtsForBotDimCheek.Add(pt.X); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X, Height+20); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X - 240, pt.Y); ptsPlContourCheek.Add(pt); pt = new Point2d(pt.X - 20, pt.Y - 20); ptsPlContourCheek.Add(pt); pt = new Point2d(xTile, pt.Y); ptsPlContourCheek.Add(pt); } // Заполнение торца плиткой for (int y = 0; y < Height; y += yStep) { Point3d pt = new Point3d(xTile, y, 0); addTile(btrPanel, t, pt); } // Полилиния контура торца Polyline plCheekContour = new Polyline(); plCheekContour.LayerId = Service.Env.IdLayerContourPanel; int i = 0; ptsPlContourCheek.ForEach(p => plCheekContour.AddVertexAt(i++, p, 0, 0, 0)); plCheekContour.Closed = true; btrPanel.AppendEntity(plCheekContour); t.AddNewlyCreatedDBObject(plCheekContour, true); } }
// This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock", // creating it if necessary. The block contains three entities - circle, text // and ellipse. private ObjectId CreateEmployeeDefinition() { ObjectId newBtrId = new ObjectId(); //The return value for this function Database db = HostApplicationServices.WorkingDatabase; //save some space using (Transaction trans = db.TransactionManager.StartTransaction()) //begin the transaction { // Now, access the database and obtain a reference to the BlockTable BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if ((bt.Has("EmployeeBlock"))) { newBtrId = bt["EmployeeBlock"]; } else { Point3d center = new Point3d(0, 0, 0); // Declare and define the entities we want to add: // Circle: Circle circle = new Circle(center, Vector3d.ZAxis, 2); // Attribute Definition AttributeDefinition text = new AttributeDefinition(center, "NoName", "Name:", "Enter Name", db.Textstyle); text.ColorIndex = 2; // Ellipse: Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, 0); // Next, create a layer with the helper function, and assign the layer to our entities. ObjectId empId = CreateLayer(); text.LayerId = empId; circle.LayerId = empId; ellipse.LayerId = empId; // Set the color for each entity irrespective of the layer's color. text.ColorIndex = 2; circle.ColorIndex = 1; ellipse.ColorIndex = 3; // Create a new block definition called EmployeeBlock BlockTableRecord newBtr = new BlockTableRecord(); newBtr.Name = "EmployeeBlock"; newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database! newBtr.AppendEntity(circle); //Append our entities... newBtr.AppendEntity(text); newBtr.AppendEntity(ellipse); trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities. trans.AddNewlyCreatedDBObject(text, true); trans.AddNewlyCreatedDBObject(ellipse, true); } trans.Commit(); //All done, no errors? Go ahead and commit! } return newBtrId; }
private void createImages(jsonAttribute eachatt, Transaction tr, ObjectId lyid) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor; //produce the bitmap of the signature from base64 string string imgPath = "temp.png"; try { //remove the header of the base64 var base64str = eachatt.imgbase64.Replace("data:image/png;base64,", ""); byte[] arr = Convert.FromBase64String(base64str); using (MemoryStream ms = new MemoryStream(arr)) { System.Drawing.Image streamImage = System.Drawing.Image.FromStream(ms); streamImage.Save(imgPath, ImageFormat.Png); } } catch (System.Exception ex) { ed.WriteMessage("\nBase64StringToImage failed :" + ex.Message); return; } try { //get block table and model space Database db = HostApplicationServices.WorkingDatabase; BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord msBtr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //get the position of this attribute string[] split = eachatt.position.Split(new Char[] { ',' }); double posX = Convert.ToDouble(split[0]); double posY = Convert.ToDouble(split[1]); double posZ = Convert.ToDouble(split[2]); //get the range of this attribute double fieldheight = Convert.ToDouble(eachatt.height); double fieldwidth = Convert.ToDouble(eachatt.width_ratio) * fieldheight; double field_center_x = posX + fieldwidth / 2; double field_center_y = posY + fieldheight / 2; //read the signature image System.Drawing.Bitmap operateimage = new System.Drawing.Bitmap(imgPath); System.Drawing.Color c; double maxX = 0, minX = operateimage.Width; double maxY = 0, minY = operateimage.Height; ed.WriteMessage("\nbegin create block def for image"); ObjectId blkRecId = ObjectId.Null; using (BlockTableRecord signatureBlkDef = new BlockTableRecord()) { System.Guid guid = System.Guid.NewGuid(); //block definition name signatureBlkDef.Name = "sigblk" + guid.ToString(); ArrayList ptArr = new ArrayList(); //each pixel color for (int y = 0; y < operateimage.Height; y++) for (int x = 0; x < operateimage.Width; x++) { c = operateimage.GetPixel(x, y); if (c.R == 0 && c.G == 0 && c.B == 0 && c.A == 255) { Autodesk.AutoCAD.Geometry.Point3d pt = new Autodesk.AutoCAD.Geometry.Point3d(x, operateimage.Height - y, 0); minY = y < minY ? y : minY; maxY = y > maxY ? y : maxY; minX = x < minX ? x : minX; maxX = x > maxX ? x : maxX; var sol = new Solid( new Point3d(pt.X, pt.Y, 0), new Point3d(pt.X + 1, pt.Y, 0), new Point3d(pt.X, pt.Y + 1, 0), new Point3d(pt.X + 1, pt.Y + 1, 0) ); //set the solid to the specific layer sol.LayerId = lyid; signatureBlkDef.AppendEntity(sol); } } ed.WriteMessage("\ncreate and add block def"); signatureBlkDef.Origin = new Point3d((maxX + minX) / 2, operateimage.Height - (maxY + minY) / 2, 0); bt.Add(signatureBlkDef); tr.AddNewlyCreatedDBObject(signatureBlkDef, true); //set the block definition to the specific layer blkRecId = signatureBlkDef.Id; ed.WriteMessage("\nend creating block def"); } operateimage.Dispose(); //scale the signature to fit the field along X, Y double blkscaleY = fieldheight / (maxY - minY) * 2; double blkscaleX = (maxX - minX) / (maxY - minY) * blkscaleY; ed.WriteMessage("\nto begin create block ref"); using (BlockReference acBlkRef = new BlockReference(new Point3d(field_center_x, field_center_y, 0), blkRecId)) { acBlkRef.ScaleFactors = new Scale3d(blkscaleY, blkscaleY, 1); acBlkRef.LayerId = lyid; msBtr.AppendEntity(acBlkRef); tr.AddNewlyCreatedDBObject(acBlkRef, true); } ed.WriteMessage("\nend of creating block ref"); } catch (Autodesk.AutoCAD.Runtime.Exception ex){ ed.WriteMessage("\nfailed to produce the image: " + ex.ToString()); } }
public static void DrawVolumesTableInBlock(decimal[] decVolumesArray/*, Point3d tablePosition */) { if (decVolumesArray == null) { AcVolShowForm(); return; } string tableLayerName = "acVlm_Таблицы объемов"; CreateLayer(tableLayerName, true, false); string tableAttributeLayerName = "acVlm_Invisible Layers"; CreateLayer(tableAttributeLayerName, false, true); Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ. //Editor acDocEd = acDoc.Editor; // Editor текущего документа. Database acDocDb = acDoc.Database; // Database текущего документа. using (acDoc.LockDocument()) // блокировка документа { // начинаем транзакцию using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) { //*** // ШАГ 0 - запрос ПК поперечника и его распознание //*** double doublePk = ParcePk(SelectPk("Укажите ПК поперечного профиля:")); if (doublePk < 0) { MessageBox.Show("Пикет не распознан или выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } //*** //ШАГ 1 - создаем таблицу и заполняем ее //*** Table objTable = new Table(); int tableColNumber = 3; int tableRowNumber = _form.listBoxLayers.Items.Count + 1;// количество слоев +1 строка на заголовок таблицы objTable.SetSize(tableRowNumber, tableColNumber); Point3d tablePosition = GetUserPoint("Укажите точку вставки таблицы:"); if (tablePosition == new Point3d(2147483647, 2147483647, 2147483647)) { acTrans.Abort(); AcVolShowForm(); return; } objTable.Position = tablePosition; //создаем массив значений для таблицы включая заголовки. string[,] strTableArray = new string[tableRowNumber, tableColNumber]; //Записываем в массив заголовки strTableArray[0, 0] = "Наименование"; strTableArray[0, 1] = "Ед.Изм."; strTableArray[0, 2] = "Значение"; //Записываем в массив Имя объема, Ед.Изм и значение объема и так для каждого объема из лист бокса for (int rowNumber = 1; rowNumber < tableRowNumber; rowNumber++) { strTableArray[rowNumber, 0] = (string)_form.listBoxLayers.Items[rowNumber - 1]; strTableArray[rowNumber, 1] = (string)_form.listBoxLayersUnits.Items[rowNumber - 1]; strTableArray[rowNumber, 2] = Convert.ToString(Math.Round(decVolumesArray[rowNumber - 1], 2), CultureInfo.InvariantCulture); } // Заполняем таблицу значениями из массива String[,] strTableArray for (int rowNumber = 0; rowNumber < tableRowNumber; rowNumber++) { for (int colNumber = 0; colNumber < tableColNumber; colNumber++) { objTable.Cells[rowNumber, colNumber].TextHeight = 2.5; switch (colNumber) { case 0: objTable.Columns[colNumber].Width = 60; break; case 1: objTable.Columns[colNumber].Width = 15; break; case 2: objTable.Columns[colNumber].Width = 20; break; } objTable.Rows[rowNumber].Height = 8; if (colNumber == 0 & rowNumber > 0) { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleLeft; } else { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleCenter; } objTable.Cells[rowNumber, colNumber].SetValue(strTableArray[rowNumber, colNumber], ParseOption.ParseOptionNone); } } // задаем слой таблице objTable.Layer = tableLayerName; //*** // если ПК распознан, то создаем блок, помещаем таблицу в блок и присваиваем атрибут "ПК" //*** if (doublePk >= 0) { string pk = Convert.ToString(doublePk, CultureInfo.InvariantCulture); // имя создаваемого блока string objTableBlockName = "acVlm_" + Convert.ToString((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, CultureInfo.InvariantCulture); // открываем таблицу блоков на чтение BlockTable blockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead); // вначале проверяем, нет ли в таблице блока с таким именем // если есть - выводим сообщение об ошибке и заканчиваем выполнение команды if (blockTable.Has(objTableBlockName)) { MessageBox.Show("A block with the name \"" + objTableBlockName + "\" already exists.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // создаем новое определение блока, задаем ему имя BlockTableRecord objBtr = new BlockTableRecord { Name = objTableBlockName }; blockTable.UpgradeOpen(); //переоткрываем blockTable на запись. // добавляем созданное определение блока в таблицу блоков и в транзакцию, // запоминаем ID созданного определения блока (оно пригодится чуть позже) ObjectId objBtrId = blockTable.Add(objBtr); acTrans.AddNewlyCreatedDBObject(objBtr, true); //добавляем таблицу в блок и в транзацию objBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); // создаем определение аттрибута AttributeDefinition objAttribute = new AttributeDefinition { Position = new Point3d(0, 0, 0), Tag = "ПК", Layer = tableAttributeLayerName }; // добавляем атрибут в блок и в транзакцию objBtr.AppendEntity(objAttribute); acTrans.AddNewlyCreatedDBObject(objAttribute, true); //*** // добавляем вхождение созданного блока на чертеж //*** var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; // создаем новое вхождение блока, используя ранее сохраненный ID определения блока BlockReference objBlockReference = new BlockReference(Point3d.Origin, objBtrId) { Layer = tableLayerName }; // добавляем созданное вхождение блока на пространство чертежа и в транзакцию if (acBtr != null) acBtr.AppendEntity(objBlockReference); acTrans.AddNewlyCreatedDBObject(objBlockReference, true); // задаем значение аттрибута AttributeReference objAttributeReference = new AttributeReference(); objAttributeReference.SetAttributeFromBlock(objAttribute, objBlockReference.BlockTransform); objAttributeReference.TextString = pk; objAttributeReference.Layer = tableAttributeLayerName; objBlockReference.AttributeCollection.AppendAttribute(objAttributeReference); acTrans.AddNewlyCreatedDBObject(objAttributeReference, true); } //*** // если ПК _НЕ_распознан, то помещаем таблицу на чертеж без создания блока с выводом предупреждения //*** else { var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; if (acBtr != null) acBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); } // фиксируем транзакцию acTrans.Commit(); AcVolShowForm(); } } }
public ObjectId CreateContour2(BlockTableRecord btr) { if (panelBtr.ExtentsByTile.Diagonal() < endOffset) { return ObjectId.Null; } // из всех плиток отделить торцевые плитки???? // дерево границ плиток TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>(); foreach (var item in panelBtr.Tiles) { try { var r = new Rectangle(Math.Round(item.Item2.MinPoint.X, 1), Math.Round(item.Item2.MinPoint.Y, 1), Math.Round(item.Item2.MaxPoint.X, 1), Math.Round(item.Item2.MaxPoint.Y, 1), 0, 0); TreeTiles.Add(r, item); } catch { } } // Отфильтровать плитки - панели от торцевых. using (var colPlTiles = new DisposableSet<Polyline>()) { //List<Polyline> colPlTile = new List<Polyline>(); foreach (var item in panelBtr.Tiles) { // Проверить наличие плиток справа и слева - если есть плитка с одной из сторон то это плитка панели а не торца // Проверка наличия плиток слева от этой double yCenter = ((Math.Round(item.Item2.MaxPoint.Y, 1) - Math.Round(item.Item2.MinPoint.Y, 1)) * 0.5); var ptCenterLeft = new Point(Math.Round(item.Item2.MinPoint.X, 1), yCenter, 0); var finds = TreeTiles.Nearest(ptCenterLeft, distTileMinInPanel); if (!finds.Skip(1).Any()) { // Нет плиток слева, проверка плиток справа var ptCenterRight = new Point(Math.Round(item.Item2.MaxPoint.X, 1), yCenter, 0); finds = TreeTiles.Nearest(ptCenterRight, distTileMinInPanel); if (!finds.Skip(1).Any()) { // Нет плиток справа // Проверка - торцевые плитки могут быть только у граней панели if ((item.Item2.MinPoint.X - panelBtr.ExtentsByTile.MinPoint.X) < distTileMinInPanel || panelBtr.ExtentsByTile.MaxPoint.X - item.Item2.MaxPoint.X < distTileMinInPanel || item.Item2.MinPoint.Y - panelBtr.ExtentsByTile.MinPoint.Y < distTileMinInPanel || panelBtr.ExtentsByTile.MaxPoint.Y - item.Item2.MaxPoint.Y < distTileMinInPanel) { continue; } } } // Плитка панели, а не торца Polyline pl = item.Item2.GetPolyline(); colPlTiles.Add(pl); } using (var regUnion = BrepExtensions.Union(colPlTiles, null)) { var plUnion = regUnion.GetPolylines().FirstOrDefault(f => f.Value == BrepLoopType.LoopExterior); //var pl3d = colPlTiles.GetExteriorContour(); if (plUnion.Key != null) { if (panelBtr.CPS != null) { plUnion.Key.LayerId = panelBtr.CPS.IdLayerContour; } btr.AppendEntity(plUnion.Key); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(plUnion.Key, true); panelBtr.ExtentsNoEnd = plUnion.Key.GeometricExtents; return plUnion.Key.Id; } } } return ObjectId.Null; }