private void LoadEmptities(Transaction transaction, BlockTable blockTable) { var blockTableRecord = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; Debug.Assert(blockTableRecord != null, "blockTableRecord != null"); foreach (var objectId in blockTableRecord) { var entity = DwgEntity.CreateInstance(objectId); entity.Initialization(transaction); MoveEntityToLayer(entity); } }
public static void GetPropsToSave(string blName, BlockTable bt, ref List<SaveDynProp> propsToSave) { if (bt.Has(blName)) { var btr = bt[blName].GetObject(OpenMode.ForRead) as BlockTableRecord; var idsBlRef = btr.GetBlockReferenceIds(true, false); IterateIdsBlRef(idsBlRef, blName, ref propsToSave); var idsBtrAnonyms = btr.GetAnonymousBlockIds(); foreach (ObjectId idBtrAnonym in idsBtrAnonyms) { var btrAnonym = idBtrAnonym.GetObject(OpenMode.ForRead) as BlockTableRecord; var idsBlRefAnonym = btrAnonym.GetBlockReferenceIds(true, false); IterateIdsBlRef(idsBlRefAnonym, blName, ref propsToSave); } } }
/** * @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; }
public static BlockReference AddBlockDwgEasy(this Point3d ptInsert, Database db, Transaction tr, BlockTable bt, BlockTableRecord btr, string sourceFileName, string newBlockName, double dAngle) { if (!File.Exists(sourceFileName)) { return(null); } BlockReference bref = null; try { ObjectId objId = new ObjectId(); if (bt.Has(newBlockName) && !bt[newBlockName].IsErased) { objId = bt[newBlockName]; } else { Database databaseFromFile = Getdb(sourceFileName, System.IO.FileShare.Read, true); objId = db.Insert(newBlockName, databaseFromFile, true); databaseFromFile.Dispose(); } bref = new BlockReference(ptInsert, objId); bref.Rotation = dAngle; ObjectId blockobj = btr.AppendEntity(bref); BlockTableRecord empBtr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForWrite) as BlockTableRecord; tr.AddNewlyCreatedDBObject(bref, true); } catch (Exception ex) { if (!File.Exists(sourceFileName)) { throw new Exception("缺少文件:" + sourceFileName); } else { throw new Exception(ex.Message); } } return(bref); }
public void getReference() { Document curDoc = Application.DocumentManager.MdiActiveDocument; Database db = curDoc.Database; Editor ed = curDoc.Editor; try { ed.WriteMessage("\ngetAttr\n"); using (Transaction tr = db.TransactionManager.StartTransaction()) { PostInfo postInfo = new PostInfo(); BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; ObjectId btrecId = bt[BlockTableRecord.ModelSpace]; //ObjectId btrecId = SymbolUtilityServices.GetBlockModelSpaceId(db); BlockTableRecord btrec = tr.GetObject(btrecId, OpenMode.ForRead) as BlockTableRecord; RXClass refClass = RXClass.GetClass(typeof(BlockReference)); foreach (ObjectId id in btrec) { //ed.WriteMessage("\n" + id.ObjectClass.Name+"--"+id.ObjectClass.AppName + "\n"); if (id.ObjectClass == refClass) { //getAttributeDefInfo(id, ed); BlockReference bref = tr.GetObject(id, OpenMode.ForRead) as BlockReference; ed.WriteMessage("\nblock name:" + bref.Name + "\n"); postInfo.writeBlockName(bref.Name); foreach (ObjectId attrId in bref.AttributeCollection) { AttributeReference attrRef = tr.GetObject(attrId, OpenMode.ForRead) as AttributeReference; ed.WriteMessage("\ntag:" + attrRef.Tag + "--value:" + attrRef.TextString + "\n"); postInfo.writeAttrRef(attrRef.Tag, attrRef.TextString); } } } postInfo.endWrite(); tr.Commit(); } } catch (System.Exception ex) { ed.WriteMessage(ex.Message + ex.StackTrace); } }
private void polacz_Click(object sender, EventArgs e) { Document document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; DB_AC.Database db = document.Database; Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; document.LockDocument(); try { SQL_CLIENT.SqlDataAdapter adapter = new SQL_CLIENT.SqlDataAdapter("Select * from CIRCLE", @"Data Source =" + data_src.Text + "; Initial Catalog =" + tabela.Text + "; User ID =" + user.Text + ";Password ="******"; Integrated Security = true"); System.Data.DataTable tb = new System.Data.DataTable(); adapter.Fill(tb); dane.DataSource = tb; Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Liczba odczytanych okręgów: " + tb.Rows.Count); using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable blockTb = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord record = trans.GetObject(blockTb[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; for (int i = 0; i < tb.Rows.Count; i++) { Circle circle = new Circle(); circle.Radius = Convert.ToDouble(tb.Rows[i]["radius"]); Point3d cCenter = new Point3d(Convert.ToDouble(tb.Rows[i]["centerX"]), Convert.ToDouble(tb.Rows[i]["centerY"]), Convert.ToDouble(tb.Rows[i]["centerZ"])); circle.Center = cCenter; record.AppendEntity(circle); trans.AddNewlyCreatedDBObject(circle, true); } trans.Commit(); } } catch (System.Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Błąd odczytu: " + ex.Message); } this.Close(); }
public void DrawLine1() { Database db = AcadApp.Application.DocumentManager.MdiActiveDocument.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable blk_tbl = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; if (null == blk_tbl) { return; } BlockTableRecord model_space = tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; if (null == model_space) { return; } DoSomething(model_space); //error here Line line = new Line(); //bad coding habit /* * calculate something here to findout the start point of the line */ line.StartPoint = new AcadGeo.Point3d(0.0, 0.0, 0.0); /* * Calculate something here to findout the end point of the line */ line.EndPoint = new AcadGeo.Point3d(10.0, 0.0, 0.0); model_space.UpgradeOpen(); model_space.AppendEntity(line); tr.AddNewlyCreatedDBObject(line, true); tr.Commit(); } }
public DBObjectCollection GetBlockTableRecordSpaceCollection(Document acDoc, Transaction acTrans) { Database acCurDb = acDoc.Database; BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); DBObjectCollection acBlkTblRecSpcColl = new DBObjectCollection(); foreach (ObjectId acObj in acBlkTbl) { DBObject acDbObj = acTrans.GetObject(acObj, OpenMode.ForRead); if (acDbObj is BlockTableRecord) { BlockTableRecord acBlkTblRec = (BlockTableRecord)acDbObj; if (acBlkTblRec.IsLayout) { acBlkTblRecSpcColl.Add(acBlkTblRec); } } } return(acBlkTblRecSpcColl); }
public static void PrintNote(Database db, ObjectId recderID, Point3d InsertPoint) { using (Transaction tr = db.TransactionManager.StartTransaction()) { TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable; BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord recorder = tr.GetObject(recderID, OpenMode.ForWrite) as BlockTableRecord; MText theNote = new MText(); theNote.Contents = "Some text in the default colour...\\P" + "{\\C1;Something red}\\P" + "{\\C2;Something yellow}\\P" + "{\\C3;And} {\\C4;something} " + "{\\C5;multi-}{\\C6;coloured}\\P"; theNote.Location = InsertPoint; recorder.AppendEntity(theNote); tr.AddNewlyCreatedDBObject(theNote, true); tr.Commit(); } return; }
public static void addVerticalRotatedDimension(Database db, Point3d pt1, Point3d pt2, double distance, ObjectId dimid) { using (Transaction trans = db.TransactionManager.StartOpenCloseTransaction()) { BlockTable blockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord space = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; RotatedDimension dimRotated = new RotatedDimension(); dimRotated.Rotation = Math.PI / 2; dimRotated.XLine1Point = pt1; dimRotated.XLine2Point = pt2; dimRotated.DimLinePoint = new Point3d((pt1.X + pt2.X) / 2, (pt1.Y + pt2.Y) / 2, (pt1.Z + pt2.Z) / 2).TransformBy(Matrix3d.Displacement(Vector3d.XAxis * distance)); dimRotated.Layer = "Dim_Layer"; dimRotated.DimensionStyle = dimid; space.AppendEntity(dimRotated); trans.AddNewlyCreatedDBObject(dimRotated, true); trans.Commit(); } }
public static ObjectId GetLayoutId(Database db, string name) { ObjectId layoutId = new ObjectId(); BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); if (btr.IsLayout) { Layout layout = (Layout)btr.LayoutId.GetObject(OpenMode.ForRead); if (layout.LayoutName.CompareTo(name) == 0) { layoutId = btr.LayoutId; break; } } } return(layoutId); }
public static ObjectId ToBlockDefinition(this IEnumerable <Entity> ents, string blockName, Database db = null) { db = (db ?? Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database); ObjectId id = ObjectId.Null; BlockTableRecord blkDef = new BlockTableRecord(); blkDef.Name = blockName; foreach (Entity ent in ents) { blkDef.AppendEntity(ent); } using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = blkTbl.Add(blkDef); trans.AddNewlyCreatedDBObject(blkDef, true); trans.Commit(); } return(id); }
public static ObjectId InsertBlockRefByDWGFile(Document doc, Transaction transaction, string dwgPath, Point3d point, Matrix3d?mtx, string blockName = "") { ObjectId objectId2 = ObjectId.Null; blockName = (string.IsNullOrEmpty(blockName) ? Guid.NewGuid().ToString("N") : Regex.Replace(blockName, "[\\u005c\\u003a]", "X")); BlockTableRecord block = GetBlock(doc, transaction, blockName, dwgPath); BlockTable bt = (BlockTable)transaction.GetObject(doc.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)transaction.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); using (BlockReference bref = new BlockReference(point, block.ObjectId)) { if (mtx.HasValue) { bref.TransformBy(mtx.Value); } objectId2 = btr.AppendEntity(bref); transaction.AddNewlyCreatedDBObject(bref, true); return(objectId2); } }
public void cmdMyFirst() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database db = acDoc.Database; Transaction trans = db.TransactionManager.StartTransaction(); // acDoc.SendStringToExecute("circle 2,2,0 4 ", true, false, true); para enviar a linea de comandos 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(10, 10, 0); Point3d pnt2 = new Point3d(20, 20, 0); Line lineObj = new Line(pnt1, pnt2); msBlkRec.AppendEntity(lineObj); trans.AddNewlyCreatedDBObject(lineObj, true); trans.Commit(); }
private static IEnumerable <IGrouping <int, ObjectId> > getGroupedAparts(BlockTable bt, out int count) { count = 0; List <Tuple <int, ObjectId> > btrAparts = new List <Tuple <int, ObjectId> >(); foreach (var idBtr in bt) { var btr = idBtr.GetObject(OpenMode.ForRead) as BlockTableRecord; if (Revit.Apartment.IsBlockNameApartment(btr.Name)) { int group = getGroup(btr.Name); btrAparts.Add(new Tuple <int, ObjectId>(group, btr.Id)); count++; } } // группировка var groups = btrAparts.GroupBy(g => g.Item1, s => s.Item2); return(groups); }
private ObjectId AppendEntity(Entity ent) { ObjectId entId; ent.Visible = true; Database db = HostApplicationServices.WorkingDatabase; 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); ((Polyline)ent).ConstantWidth = HeatSourceLayoutApp.globalProperty.BuildingOutlineWidth; entId = btr.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); trans.Commit(); } return(entId); }
public void AddEntityToModelSpaceFunc() { Database db = HostApplicationServices.WorkingDatabase; DBText text = new DBText(); text.Position = new Point3d(); text.TextString = "fck13"; ObjectId objectId; using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)transaction.GetObject(db.BlockTableId, OpenMode.ForWrite); BlockTableRecord btr = (BlockTableRecord)transaction.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); objectId = btr.AppendEntity(text); transaction.AddNewlyCreatedDBObject(text, true); transaction.Commit(); } }
public void CreateEmployee() { Database db = HostApplicationServices.WorkingDatabase; Transaction trans = db.TransactionManager.StartTransaction(); try { BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite)); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //Create the block reference...use the return from CreateEmployeeDefinition directly! BlockReference br = new BlockReference(new Point3d(10, 10, 0), CreateEmployeeDefinition()); btr.AppendEntity(br); //Add the reference to ModelSpace trans.AddNewlyCreatedDBObject(br, true); //Let the transaction know about it trans.Commit(); } finally { trans.Dispose(); } }
getXRefMSpace(string name) { BlockTableRecord MS = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { BlockReference BR = getXRefBlockReference(name); BlockTable BT = (BlockTable)BR.Database.BlockTableId.GetObject(OpenMode.ForRead); MS = (BlockTableRecord)BT[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForRead); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " xRef.cs: line: 1102"); } return(MS); }
/// <summary> /// 改变图形图层 /// </summary> /// <param name="c1Id">图形的ObjectId</param> /// <param name="layerName">图层名称</param> /// <returns>图形的ObjectId</returns> 图形已经添加图形数据库 public static ObjectId ChangeEntityLayer(this ObjectId c1Id, string layerName) { // 图形数据库 Database db = HostApplicationServices.WorkingDatabase; // 开启事务处理 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); // 获取图形对象 Entity ent1 = (Entity)c1Id.GetObject(OpenMode.ForWrite); // 设置颜色 ent1.Layer = layerName; trans.Commit(); } return(c1Id); }
/// <summary> /// Gets the handles of all visible document objects that can be converted to Speckle /// </summary> /// <param name="doc"></param> /// <param name="converter"></param> /// <returns></returns> public static List <string> ConvertibleObjects(this Document doc, ISpeckleConverter converter) { var objs = new List <string>(); using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { BlockTable blckTbl = tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId id in blckTblRcrd) { DBObject dbObj = tr.GetObject(id, OpenMode.ForRead); if (converter.CanConvertToSpeckle(dbObj) && dbObj.Visible()) { objs.Add(dbObj.Handle.ToString()); } } tr.Commit(); } return(objs); }
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(10, 10, 0); Point3d pnt2 = new Point3d(20, 20, 0); Line lineObj = new Line(pnt1, pnt2); msBlkRec.AppendEntity(lineObj); trans.AddNewlyCreatedDBObject(lineObj, true); trans.Commit(); }
public void DrawLine() { // Get the current document and database, and start a transaction Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; // 'using' a Transaction with the Transaction Manager using (Transaction ACDrawLine = acCurDb.TransactionManager.StartTransaction()) { BlockTable blockTable = ACDrawLine.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRecord = ACDrawLine.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d Point1 = new Point3d(0, 0, 0); Point3d Point2 = new Point3d(100, 200, 0); Line LineBetween = new Line(Point1, Point2); blockTableRecord.AppendEntity(LineBetween); ACDrawLine.AddNewlyCreatedDBObject(LineBetween, true); ACDrawLine.Commit(); } }
public static ObjectId AlignDim(Point3d line_pt1, Point3d line_pt2, Point3d dim_pt, string text, ObjectId dimstyleid) { Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument; Database database = mdiActiveDocument.Database; ObjectId result; using (mdiActiveDocument.LockDocument()) { using (Transaction transaction = database.TransactionManager.StartTransaction()) { BlockTable blockTable = transaction.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRecord = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; AlignedDimension alignedDimension = new AlignedDimension(line_pt1, line_pt2, dim_pt, text, dimstyleid); result = blockTableRecord.AppendEntity(alignedDimension); transaction.AddNewlyCreatedDBObject(alignedDimension, true); transaction.Commit(); } } return(result); }
public void FillParentNodes(TreeView tv) { doc = AcadApp.DocumentManager.MdiActiveDocument; db = doc.Database; ed = doc.Editor; using (Transaction trx = db.TransactionManager.StartTransaction()) { BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; foreach (ObjectId objId in bt) { BlockTableRecord btr = (BlockTableRecord)objId.GetObject(OpenMode.ForRead); if (btr.HasAttributeDefinitions) { tv.Nodes.Add(btr.Name); } } } }
public static double DrawLine(Point3d pt1, Point3d pt2, string layerName, short colour = 255) { Document doc = Application.DocumentManager.MdiActiveDocument; Database currentDB = doc.Database; CreateLayer(layerName, colour); using (Transaction tr = currentDB.TransactionManager.StartTransaction()) { BlockTable blckTable = tr.GetObject(currentDB.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRec = tr.GetObject(blckTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Line line = new Line(); line.StartPoint = pt1; line.EndPoint = pt2; line.Layer = layerName; blockTableRec.AppendEntity(line); tr.AddNewlyCreatedDBObject(line, true); tr.Commit(); return(line.Length); } }
public ObjectId AddBlockTableRecord(BlockTableRecord btr, Database db) { ObjectId id = new ObjectId(); try { using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message); } return(id); }
public void SaveGrid() { Database db = Application.DocumentManager.MdiActiveDocument.Database; Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; foreach (Entity obj in this.GridObjCollection) { btr.AppendEntity(obj); trans.AddNewlyCreatedDBObject(obj, true); } trans.Commit(); } }
public ObjectId CreateBlockWithAttributes() { Database db = HostApplicationServices.WorkingDatabase; ObjectId blockId = ObjectId.Null; BlockTableRecord record = new BlockTableRecord(); record.Name = "RMNUM"; using (Transaction trans = db.TransactionManager.StartTransaction()) { Point3dCollection points = new Point3dCollection(); points.Add(new Point3d(-18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, 6.0, 0.0)); points.Add(new Point3d(-18.0, 6.0, 0.0)); Polyline2d pline = new Polyline2d(Poly2dType.SimplePoly, points, 0.0, true, 0.0, 0.0, null); record.AppendEntity(pline); AttributeDefinition attdef = new AttributeDefinition(); attdef.Position = new Point3d(0.0, 0.0, 0.0); attdef.Height = 8.0; //设置文字高度 attdef.Rotation = 0.0; //设置文字旋转角度 attdef.HorizontalMode = TextHorizontalMode.TextMid; //设置水平对齐方式 attdef.VerticalMode = TextVerticalMode.TextVerticalMid; //设置垂直对齐方式 attdef.Prompt = "Room Number:"; //设置属性提示 attdef.TextString = "0000"; //设置属性的缺省值 attdef.Tag = "NUMBER"; //设置属性标签 attdef.Invisible = false; //设置不可见选项为假 attdef.Verifiable = false; //设置验证方式为假 attdef.Preset = false; //设置预置方式为假 attdef.Constant = false; //设置常数方式为假 record.Origin = points[3]; record.AppendEntity(attdef); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if (!bt.Has("RMNUM")) //判断是否存在名为"RMNUM"的块 { blockId = bt.Add(record); //在块表中加入"RMNUM"块 trans.AddNewlyCreatedDBObject(record, true); trans.Commit(); } } return(blockId); }
public void ChangeBlock(string blockName, string roomNumber) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); //打开块表中名为blockName的块表记录 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[blockName], OpenMode.ForRead); //获取所有名为blockName的块参照 ObjectIdCollection blcokRefIds = btr.GetBlockReferenceIds(true, true); //循环遍历块参照 foreach (ObjectId blockRefId in blcokRefIds) { //打开当前块参照 BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead); //获取当前块参照的属性集合 AttributeCollection blockRefAtts = blockRef.AttributeCollection; //循环遍历属性集合 foreach (ObjectId attId in blockRefAtts) { //获取当前属性参照对象 AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead); //只改变NUMBER属性值为"0000"的属性值为roomNumber switch (attRef.Tag) { case "NUMBER": if (attRef.TextString == "0000") { attRef.UpgradeOpen(); //切换属性参照对象为可写状态 attRef.TextString = roomNumber; } break; } } } trans.Commit(); } }
getNestedEntityCoordinates2(Handle h, string nameFile) { List <Point3d> pnts3d = new List <Point3d>(); try { using (BaseObjs._acadDoc.LockDocument()) { using (Transaction tr = BaseObjs.startTransactionDb()) { Database db = getXRefDatabase(nameFile); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForRead); foreach (ObjectId id in ms) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); if (ent.Handle == h) { if (ent is Line) { Line line = (Line)ent; pnts3d.Add(line.StartPoint); pnts3d.Add(line.EndPoint); break; } else if (ent is Polyline || ent is Polyline3d) { pnts3d = Conv.polyX_listPnts3d(id); } } } tr.Commit(); } } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " xRef2.cs: line: 198"); } return(pnts3d); }
public void PrintoutEmployee() { //Declare the tool//s we//ll use throughout... Database db = HostApplicationServices.WorkingDatabase; Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; try { using (Transaction trans = db.TransactionManager.StartTransaction()) //Start the transaction. { //First, get at the BlockTable, and the ModelSpace BlockTableRecord BlockTable bt = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); //Now, we need to be able to print to the commandline. Here is an object which will help us: //Now, here is the fun part. This is where we iterate through ModelSpace: foreach (ObjectId id in btr) { Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false); //Use it to open the current object! if (ent.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.BlockReference")) //We use .NET//s RTTI to establish type. { ArrayList saEmployeeList = new ArrayList(); // We use ArrayList which can have dynamic size in C# ListEmployee(id, saEmployeeList); //String sEmployeeData; if (saEmployeeList.Count == 4) { ed.WriteMessage("Employee Name: {0}", saEmployeeList[0]); ed.WriteMessage("Employee Salary: {0}", saEmployeeList[1]); ed.WriteMessage("Employee Division: {0}", saEmployeeList[2]); ed.WriteMessage("Division Manager: {0}", saEmployeeList[3]); } } } trans.Commit(); } } catch { ed.WriteMessage("Error Printing Out Employees"); } }
public void CurveBoolean() { // 提示用户选择所要计算距离的两条直线 ObjectIdCollection polyIds = new ObjectIdCollection(); if (PromptSelectEnts("\n请选择要处理的复合线:", "LWPOLYLINE", ref polyIds)) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; if (polyIds.Count != 1) { ed.WriteMessage("\n必须选择一条多段线进行操作."); return; } var plineId = DrawWallMethod(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { if (plineId.Equals(ObjectId.Null)) { return; } polyIds.Add(plineId); // 获得两条曲线的交点 Polyline poly1 = (Polyline)trans.GetObject(polyIds[0], OpenMode.ForRead); Polyline poly2 = (Polyline)trans.GetObject(polyIds[1], OpenMode.ForRead); Point3dCollection intPoints = new Point3dCollection(); poly1.IntersectWith(poly2, Intersect.OnBothOperands, intPoints, 0, 0); if (intPoints.Count < 2) { ed.WriteMessage("\n曲线交点少于2个, 无法进行计算."); } // 根据交点和参数值获得交点之间的曲线 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); GetCurveBetweenIntPoints(trans, btr, poly1, poly2, intPoints); trans.Commit(); } } }
/** * @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 IEnumerable<IGrouping<int, ObjectId>> getGroupedAparts(BlockTable bt, out int count) { count = 0; List<Tuple<int, ObjectId>> btrAparts = new List<Tuple<int, ObjectId>>(); foreach (var idBtr in bt) { var btr = idBtr.GetObject(OpenMode.ForRead) as BlockTableRecord; if (Revit.Apartment.IsBlockNameApartment(btr.Name)) { int group = getGroup(btr.Name); btrAparts.Add(new Tuple<int, ObjectId>(group, btr.Id)); count++; } } // группировка var groups = btrAparts.GroupBy(g => g.Item1, s=>s.Item2); return groups; }
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 ObjectId getBtr(string name, BlockTable bt) { if (bt.Has(name)) { return bt[name]; } else { doc.Editor.WriteMessage("Не найден блок оформления {0}", name); return ObjectId.Null; } }
// // Vérification de la non-utilisation du nom des blocks // private string checkName(BoxCollection boxArray, BlockTable bt, int x, Editor ed) { string blkName = ""; do try { blkName = boxArray.ArrayBox[x].BlckName + _id.ToString(CultureInfo.InvariantCulture); while (bt.Has(blkName)) { _id++; blkName = boxArray.ArrayBox[x].BlckName + _id.ToString(CultureInfo.InvariantCulture); } } catch { ed.WriteMessage("\nInvalid block name."); } while (blkName == ""); return blkName; }
private ObjectId getIdBtrEnd(BlockTable bt) { ObjectId idBtrEnd; if (bt.Has(BlNameEnd)) { // отредактировать существующий блок торца - удалтить все старые объекты idBtrEnd = bt[BlNameEnd]; eraseEntInBlock(idBtrEnd); IsExistsBlockEnd = true; } else { using (var btr = new BlockTableRecord()) { btr.Name = BlNameEnd; bt.UpgradeOpen(); idBtrEnd = bt.Add(btr); bt.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true); } } return idBtrEnd; }
/** * @brief Metodo que descompone una enitdad AUTOCAD en sub-entidades cuando es posible. Replica el comportamiento del comando * DESCOMPONER / EXPLODE de AutoCAD. Las unidades básicas que devuelve son puntos y lineas. Descompone recursivamente * las entidades hasta dejarlas representadas como puntos, lineas y arcos. * * @param ent Entidad que debe ser descompuesta * @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. * * @return Devuelve una colección de entidades bajo la clase DBObjectCollection. **/ private static DBObjectCollection ObtenerPuntosyLineas(Entity ent, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec, Transaction t) { DBObjectCollection retorno = new DBObjectCollection(); DBObjectCollection procesar = new DBObjectCollection(); ent.Explode(procesar); while (procesar.Count != 0) { Entity obj = (Entity) procesar[0]; acBlkTblRec.AppendEntity(obj); t.AddNewlyCreatedDBObject(obj, true); dwgf.objetosArtificiales.Add(obj.ObjectId); if (obj.ObjectId.ObjectClass.DxfName == "POINT" || obj.ObjectId.ObjectClass.DxfName == "LINE") { if (retorno.Contains(obj) == false) { retorno.Add(obj); } } if (obj.ObjectId.ObjectClass.DxfName == "ARC") { // Completar con el proceso para los arcos. if (retorno.Contains(obj) == false) { retorno.Add(obj); } } if (obj.ObjectId.ObjectClass.DxfName == "LWPOLYLINE") { DBObjectCollection aux = new DBObjectCollection(); obj.Explode(aux); foreach (DBObject aux2 in aux) { procesar.Add(aux2); } } procesar.Remove(obj); } return retorno; }