protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw) { lock (Entities) { Entities.Clear(); Entities.AddRange(_arrow.Explode().Select(x => { if (x is DBText) { return(_convertToAttribute((DBText)x)); } return(x); })); ObjectId btrId = AcadBlocks.BlockTools.CreateBlockTableRecordEx(_insertPoint, "*U", Entities.Select(x => (Entity)x.Clone()).ToList(), AnnotativeStates.True); ObjectId brId = AcadBlocks.BlockTools.AddBlockRefToModelSpace(btrId, null, _insertPoint, _ucs); Tools.StartTransaction(() => { BlockReference br = brId.GetObjectForWrite <BlockReference>(); br.SetDatabaseDefaults(HostApplicationServices.WorkingDatabase); br.RecordGraphicsModified(true); Entity inMemoryEntity = (Entity)br.Clone(); draw.Geometry.Draw(inMemoryEntity); var btr = br.BlockTableRecord.GetObjectForWrite <BlockTableRecord>(); br.Erase(); btr.EraseBolckTableRecord(); inMemoryEntity.Dispose(); }); } return(true); }
public static List <Entity> CloneAttribute(ObjectId blk_ref_id, ObjectId btr_id) { List <Entity> ents = new List <Entity>(); //return ents; using (Transaction tran = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction()) { BlockReference blk_ref = tran.GetObject(blk_ref_id, OpenMode.ForWrite) as BlockReference; BlockTableRecord btr = tran.GetObject(btr_id, OpenMode.ForRead) as BlockTableRecord; foreach (var obj_id in btr) { AttributeDefinition att_def = obj_id.GetObject(OpenMode.ForRead) as AttributeDefinition; if (null != att_def && !att_def.Constant) { AttributeReference att_ref = new AttributeReference(); att_ref.SetAttributeFromBlock(att_def, blk_ref.BlockTransform); att_ref.Position = att_def.Position.TransformBy(blk_ref.BlockTransform); att_ref.AlignmentPoint = att_def.AlignmentPoint.TransformBy(blk_ref.BlockTransform); blk_ref.AttributeCollection.AppendAttribute(att_ref); tran.AddNewlyCreatedDBObject(att_ref, true); } } blk_ref.RecordGraphicsModified(true); tran.Commit(); } return(ents); }
public void SaveToDatabase() { ObjectId btrId = AcadBlocks.BlockTools.CreateBlockTableRecordEx(_insertPoint, "*U", Entities, AnnotativeStates.True); ObjectId brId = AcadBlocks.BlockTools.AddBlockRefToModelSpace(btrId, null, _insertPoint, _ucs); Tools.StartTransaction(() => { BlockReference br = brId.GetObjectForWrite <BlockReference>(); br.SetDatabaseDefaults(HostApplicationServices.WorkingDatabase); br.RecordGraphicsModified(true); var xrecord = CustomObjects.Helpers.XRecordTools.GetSetExtensionDictionaryEntry(br.Id, "ICmdFlag_WALLARROW_FLAG").GetObjectForRead <Xrecord>(); xrecord.UpgradeOpen(); //Point3d p = _jigPoint.TransformBy(Arrow.GetToLocalTransform(_lowerPointUcs, _ucs)); Point3d p = _insertPoint; ResultBuffer rb = new ResultBuffer( new TypedValue((int)DxfCode.Real, p.X), new TypedValue((int)DxfCode.Real, p.Y), new TypedValue((int)DxfCode.Real, p.Z) ); xrecord.Append(rb); _arrow.SerializeTo(br); }); }
protected override SamplerStatus Sampler(JigPrompts prompts) { JigPromptPointOptions jppo = new JigPromptPointOptions("\nУкажите точку: "); jppo.UseBasePoint = true; jppo.BasePoint = _position; _jigPoint = prompts.AcquirePoint(jppo).Value; if (_jigPoint.IsEqualTo(_jigBasePoint)) { return(SamplerStatus.NoChange); } else { //Matrix3d mat = Matrix3d.Displacement(_jigBasePoint.GetVectorTo(_jigPoint)); //Entity.TransformBy(mat); _transformProcessor(_jigPoint); _br.Position = _jigPoint; _br.RecordGraphicsModified(true); _jigBasePoint = _jigPoint; return(SamplerStatus.OK); } }
public static ObjectId AppendBlockItem(Point3d insertPoint, ObjectId blockTableRecordId, List <string> attrTextValues, Matrix3d toWcsTransform) { ObjectId resBlockId = ObjectId.Null; Tools.StartTransaction(() => { Transaction trans = Tools.GetTopTransaction(); // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(OpenMode.ForWrite); BlockTableRecord btr = blockTableRecordId.GetObjectForRead <BlockTableRecord>(); BlockReference br = new BlockReference(insertPoint, blockTableRecordId); br.SetDatabaseDefaults(); br.TransformBy(toWcsTransform); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } resBlockId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } } br.RecordGraphicsModified(true); }); return(resBlockId); }
private static bool DeleteLevelText(ObjectId fflToEditId) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; // Loop so user can delete multiple levels bool deletingLevels = true; while (deletingLevels) { // Prompt the user to select the level to edit PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to delete (spacebar to finish):"); PromptNestedEntityResult nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt); if (nestedEntRes.Status == PromptStatus.OK) { using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity; if (ent.GetType() == typeof(MText)) { MText levelToDelete = ent as MText; if (levelToDelete.Layer != StyleNames.JPP_APP_Levels_Layer) { acEditor.WriteMessage("\nSelected text is on the wrong layer!"); continue; } levelToDelete.UpgradeOpen(); levelToDelete.Erase(); // Update block graphics BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; fflToEdit.RecordGraphicsModified(true); acTrans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError deleting level!\n"); acTrans.Abort(); return(false); } } } if (nestedEntRes.Status == PromptStatus.Cancel) { deletingLevels = false; } } return(true); }
private static void Redraw(Document doc, BlockTableRecord btr) { Regex regex = new Regex(@"\\[Ff][^;]+;"); // 替换模型里所有文本的TextStyle foreach (ObjectId oid in btr) { if (oid.ObjectClass.DxfName == "TEXT") { DBText text = (DBText)oid.GetObject(OpenMode.ForWrite); if (doc.UserData.ContainsKey(text.TextStyleName) && (bool)doc.UserData[text.TextStyleName]) { text.WidthFactor = text.WidthFactor * WIDTH_SCALE; text.Height = text.Height * HEIGHT_SCALE; } } else if (oid.ObjectClass.DxfName == "MTEXT") { MText text = (MText)oid.GetObject(OpenMode.ForWrite); if (doc.UserData.ContainsKey(text.TextStyleName) && (bool)doc.UserData[text.TextStyleName]) { text.TextHeight = text.TextHeight * HEIGHT_SCALE; text.LineSpacingFactor = text.LineSpacingFactor * HEIGHT_SCALE; // 多行文本中可以嵌入字体,去掉这个信息 text.Contents = regex.Replace(text.Contents, ""); } } else if (oid.ObjectClass.DxfName == "DIMENSION") { Dimension dim = (Dimension)oid.GetObject(OpenMode.ForRead); dim.Draw(); } else if (oid.ObjectClass.DxfName == "INSERT") { Entity entity = (Entity)oid.GetObject(OpenMode.ForRead); if (entity is BlockReference) { BlockReference br = entity as BlockReference; // 处理未命名块(命名块在其他地方处理) if (br.Name.StartsWith("*")) { Redraw(doc, br.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord); } br.RecordGraphicsModified(true); } } } }
public void Update() { Tools.StartTransaction(() => { if (_blockRecordId != ObjectId.Null) { BlockTableRecord btr = _blockRecordId.GetObjectForRead <BlockTableRecord>(false); //btr.UpgradeOpen(); foreach (ObjectId id in btr.GetBlockReferenceIds(true, true)) { BlockReference br = id.GetObjectForWrite <BlockReference>(false); br.RecordGraphicsModified(true); btr.Database.TransactionManager.QueueForGraphicsFlush(); } } }); }
public static void InnerTransform(this BlockReference br, Matrix3d transform) { Tools.StartTransaction(() => { br = br.Id.GetObjectForRead <BlockReference>(); //br = br.GetAnonymClone(br.Position).GetObjectForRead<BlockReference>(); BlockTableRecord btr = br.BlockTableRecord.GetObjectForRead <BlockTableRecord>(); btr.UpgradeOpen(); foreach (ObjectId id in btr) { Entity ent = id.GetObjectForWrite <Entity>(); ent.TransformBy(transform); } br.UpgradeOpen(); br.RecordGraphicsModified(true); br.Database.TransactionManager.QueueForGraphicsFlush(); }); }
private void _setEntitiesToBlock(Point3d insertPointUcs, IEnumerable <Entity> entities, Dictionary <string, string> attrInfo, bool erase) { ObjectId btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", Point3d.Origin, entities, Annotative); ObjectId brId = AcadBlocks.BlockTools.AppendBlockItem(insertPointUcs.TransformBy(Ucs), btrId, attrInfo); Tools.StartTransaction(() => { BlockReference br = brId.GetObjectForRead <BlockReference>(); br.UpgradeOpen(); if (_arrowUpper != null) { _arrowUpper.SaveToEntity(br); } br.RecordGraphicsModified(true); Entities.Add((Entity)br.Clone()); if (erase) { br.Erase(true); } }); }
public static void AppendAttributeTest() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; try { using (doc.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord currSp = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect source attribute to append new attribute below this one >>"); PromptNestedEntityResult nres = ed.GetNestedEntity(pno); if (nres.Status != PromptStatus.OK) { return; } ObjectId id = nres.ObjectId; Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); Point3d pnt = nres.PickedPoint; ObjectId owId = ent.OwnerId; AttributeReference attref = null; if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference)))) { attref = tr.GetObject(id, OpenMode.ForWrite) as AttributeReference; } BlockTableRecord btr = null; BlockReference bref = null; if (owId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference)))) { bref = tr.GetObject(owId, OpenMode.ForWrite) as BlockReference; if (bref.IsDynamicBlock) { btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } else { btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } } Point3d insPt = attref.Position.TransformBy(bref.BlockTransform); btr.UpgradeOpen(); ObjectIdCollection bids = new ObjectIdCollection(); AttributeDefinition def = null; foreach (ObjectId defid in btr) { if (defid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { def = tr.GetObject(defid, OpenMode.ForRead) as AttributeDefinition; if (def.Tag == attref.Tag) { def.UpgradeOpen(); bids.Add(defid); break; } } } IdMapping map = new IdMapping(); db.DeepCloneObjects(bids, btr.ObjectId, map, true); ObjectIdCollection coll = new ObjectIdCollection(); AttributeDefinition attDef = null; foreach (IdPair pair in map) { if (pair.IsPrimary) { Entity oent = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite); if (oent != null) { if (pair.Value.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { attDef = oent as AttributeDefinition; attDef.UpgradeOpen(); attDef.SetPropertiesFrom(def as Entity); // add other properties from source attribute definition to suit here: attDef.Justify = def.Justify; attDef.Position = btr.Origin.Add( new Vector3d(attDef.Position.X, attDef.Position.Y - attDef.Height * 1.25, attDef.Position.Z)).TransformBy(Matrix3d.Identity ); attDef.Tag = "NEW_TAG"; attDef.TextString = "New Prompt"; attDef.TextString = "New Textstring"; coll.Add(oent.ObjectId); } } } } btr.AssumeOwnershipOf(coll); btr.DowngradeOpen(); attDef.Dispose();//optional bref.RecordGraphicsModified(true); tr.TransactionManager.QueueForGraphicsFlush(); doc.TransactionManager.FlushGraphics();//optional ed.UpdateScreen(); tr.Commit(); } } } catch (System.Exception ex) { ed.WriteMessage(ex.Message + "\n" + ex.StackTrace); } finally { AcAp.ShowAlertDialog("Call command \"ATTSYNC\" manually"); } }
public static bool EditFFLValue(ObjectId fflToEditId, double level) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { // Prompt user for new FFL double?newFFL = 0.0; // Declare here to ensure in scope for later BlockTable acBlkTbl = acTrans.GetObject(acCurrDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockReference fflBlock = acTrans.GetObject(fflToEditId, OpenMode.ForRead) as BlockReference; BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[fflBlock.Name], OpenMode.ForWrite) as BlockTableRecord; if (acBlkTblRec == null) { acEditor.WriteMessage("\nError FFL block not found."); return(false); } // Check there is only one instance of this block reference in the drawing if (acBlkTblRec.GetBlockReferenceIds(false, true).Count != 1) { acEditor.WriteMessage("\nError more than one instance of the block reference."); return(false); } // Iterate around the object collection to find the polyline to retrieve the current FFL value newFFL = level; double?fflDiff = 0.0; foreach (ObjectId objId in acBlkTblRec) { // Fetch the object Object fflObj = acTrans.GetObject(objId, OpenMode.ForWrite); double?currFFL = 0.0; if (fflObj.GetType() == typeof(Polyline)) { Polyline acPline = fflObj as Polyline; // Check the outline has an extension dictionary DBDictionary acExtDict = (DBDictionary)acTrans.GetObject(acPline.ExtensionDictionary, OpenMode.ForRead); if (acExtDict == null) { acEditor.WriteMessage("\nError cannot retrieve the extension dictionary of polyline."); return(false); } currFFL = JPPUtils.getFFL(acPline.Id); if (currFFL == null) { acEditor.WriteMessage("\nError retrieving current FFL value."); return(false); } fflDiff = newFFL - currFFL; // Update FFL Xrecord ResultBuffer resBuff = new ResultBuffer(); resBuff.Add(new TypedValue((int)DxfCode.ExtendedDataReal, newFFL)); // Overwrite the Xrecord with new data if (!JPPUtils.addXrecord(objId, "FFL", resBuff)) { acEditor.WriteMessage("\nError updating Xrecord with new FFL value."); return(false); } // Update the levels Xrecords to reflect the new ffl for (int vertexIndex = 0; vertexIndex < acPline.NumberOfVertices; vertexIndex++) { // Access Xrecord for the vertex and update the level value ObjectId vertexXrecId = acExtDict.GetAt("Vertex_" + vertexIndex.ToString()); if (vertexXrecId == null) { acEditor.WriteMessage("\nError cannot retrieve vertex Xrecord"); acTrans.Abort(); return(false); } Xrecord vertexXrec = acTrans.GetObject(vertexXrecId, OpenMode.ForWrite) as Xrecord; TypedValue[] vertexXrecData = vertexXrec.Data.AsArray(); // Get the current level double currLevel = Convert.ToDouble(vertexXrecData[3].Value); ResultBuffer newXrecData = new ResultBuffer(); newXrecData.Add(vertexXrecData[0]); newXrecData.Add(vertexXrecData[1]); newXrecData.Add(vertexXrecData[2]); newXrecData.Add(new TypedValue((int)DxfCode.ExtendedDataReal, currLevel + fflDiff)); // Overwrite the data in the Xrecord with new data vertexXrec.Data = newXrecData; } break; } } // Iterate around the MText objects of the block to update the FFL text and // levels text foreach (ObjectId objId in acBlkTblRec) { // Fetch the object Object fflObj = acTrans.GetObject(objId, OpenMode.ForWrite); if (fflObj.GetType() == typeof(MText)) { MText fflMText = (MText)fflObj; if (fflMText.Text.StartsWith("FFL")) { double dblNewFFL = (double)newFFL; fflMText.Contents = "FFL " + dblNewFFL.ToString("N3"); } else { double currLevel = Convert.ToDouble(fflMText.Contents); double newLevel = currLevel + (double)fflDiff; fflMText.Contents = newLevel.ToString("N3"); } } } // Update the graphics fflBlock.UpgradeOpen(); fflBlock.RecordGraphicsModified(true); acTrans.Commit(); return(true); } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError editing FFL value!\n"); return(false); } } // return true; }
public void SetBlockProperties(BlockProps OneBlock) { //Функция устанавливает свойства одного блока, которые передаются в виде аргумента { //ed.WriteMessage(String.Format("DEBUG: Changing {0} - {1} with E={2} and Uscale={3}",OneBlock.BlockId.ToString(), OneBlock.BlockName, OneBlock.Explodable, OneBlock.UniformScale.ToString())); //Начинаем транзакцию Transaction tx = AcDb.TransactionManager.StartTransaction(); //Открываем таблицу описаний блоков на запись BlockTable blkTbl = tx.GetObject(AcDb.BlockTableId, OpenMode.ForWrite, false, true) as BlockTable; if (blkTbl.Has(OneBlock.BlockId)) //Если { try { //Открываем текущий документ на запись BlockTableRecord bt = (BlockTableRecord)tx.GetObject( AcDb.CurrentSpaceId, OpenMode.ForWrite ); //Пример итерации по таблице определений блоков //https://sites.google.com/site/bushmansnetlaboratory/sendbox/stati/multipleattsync //Как я понимаю, здесь пробегается по всем таблицам записей, //в которых определения блоков не являются анонимными //и не являются листами foreach (BlockTableRecord btr in blkTbl.Cast <ObjectId>().Select(n => (BlockTableRecord)tx.GetObject(n, OpenMode.ForWrite, false)) .Where(n => !n.IsAnonymous && !n.IsLayout)) { if (btr.ObjectId == OneBlock.BlockId) //Если нашли в таблице записей блок с нужным ObjectId { //То назначаем ему атрибуты btr.Name = OneBlock.BlockName; btr.Explodable = OneBlock.Explodable; btr.BlockScaling = OneBlock.UniformScale; ed.WriteMessage(String.Format("Изменен блок {1}", OneBlock.BlockId.ToString(), OneBlock.BlockName, OneBlock.Explodable, OneBlock.UniformScale.ToString())); btr.Dispose(); } } ; //Дальше необходимо "уведомить" все вставки блоков об изменении описания блока - пробегаем по чертежу ObjectIdCollection brefIds = bt.GetBlockReferenceIds(true, true); foreach (ObjectId id in brefIds) { BlockReference bl = tx.GetObject(id, OpenMode.ForWrite) as BlockReference; bl.RecordGraphicsModified(true); } } catch (PlatformDb.Runtime.Exception ex) { //Если что-то сломалось, то в командную строку выводится ошибка ed.WriteMessage("Ошибка применения свойств: " + ex.Message); }; } tx.Commit(); } }
private static bool EditLevelValue(ObjectId fflToEditId) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; // Loop so user can edit multiple levels bool editingLevels = true; while (editingLevels) { // Prompt the user to select the level to edit PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to edit (spacebar to finish):"); PromptNestedEntityResult nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt); if (nestedEntRes.Status == PromptStatus.OK) { using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity; if (ent.GetType() == typeof(MText)) { MText levelToEdit = ent as MText; if (levelToEdit.Layer != StyleNames.JPP_APP_Levels_Layer) { acEditor.WriteMessage("\nSelected text is on the wrong layer!"); } else { // Fetch the Xdata for the MText - needed to update the vertex Xrecord on the outline Int32?vertexIndex = GetXdata(levelToEdit.Id); if (vertexIndex == null) { acEditor.WriteMessage("\nError, unable to retrieve level vertex index!"); } else { // Prompt the user for the new level PromptDoubleResult newLevelValue = acEditor.GetDouble("\nEnter the new level: "); if (newLevelValue.Status == PromptStatus.OK) { double newLevel = newLevelValue.Value; // Call function to update the outline Xrecord of the block definition if (!UpdateOutline(fflToEditId, (Int32)vertexIndex, newLevel)) { acEditor.WriteMessage("\nError, unable to update outline with edited level!"); } // Update level text levelToEdit.UpgradeOpen(); levelToEdit.Contents = newLevel.ToString("N3"); levelToEdit.RecordGraphicsModified(true); // Update block graphics BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; fflToEdit.RecordGraphicsModified(true); } else { acEditor.WriteMessage("\nInvalid level entered!"); } } acTrans.Commit(); } } } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError editing level!\n"); acTrans.Abort(); return(false); } } } if (nestedEntRes.Status == PromptStatus.Cancel) { editingLevels = false; } } return(true); }
public static void testAttributedBlockInsert() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // change block name to your suit PromptEntityOptions pEnOpt = new PromptEntityOptions("\nPick Block Reference:"); pEnOpt.SetRejectMessage("\nObject Not Block Reference"); pEnOpt.AddAllowedClass(typeof(BlockReference), true); PromptEntityResult pEnRes = ed.GetEntity(pEnOpt); ObjectId EntId = pEnRes.ObjectId; //PromptResult pr = ed.GetString("\nType Block Name: "); //string blockName = pr.StringResult; string blockName = null; BlockReference UserBlockref = null; using (Transaction trans = db.TransactionManager.StartTransaction()) { UserBlockref = (BlockReference)trans.GetObject(EntId, OpenMode.ForRead); blockName = UserBlockref.Name; } Matrix3d ucs = ed.CurrentUserCoordinateSystem; //get current UCS matrix try { using (Transaction tr = db.TransactionManager.StartTransaction()) { // to force update drawing screen doc.TransactionManager.EnableGraphicsFlush(true); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); // if the block table doesn't already exists, exit if (!bt.Has(blockName)) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Block " + blockName + " does not exist."); return; } // insert the block in the current space PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: "); if (ppr.Status != PromptStatus.OK) { return; } DBObjectCollection dbobjcoll = ed.TraceBoundary(ppr.Value, false); Double area = 0; try { if (dbobjcoll.Count > 0) { BlockTableRecord blockTableRecmSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); ObjectIdCollection traceObjIds = new ObjectIdCollection(); foreach (DBObject obj in dbobjcoll) { Entity EntTrace = obj as Entity; if (EntTrace != null) { if (EntTrace is Polyline) { Polyline p = (Polyline)EntTrace; if (p.Closed) { area = p.Area; } } if (EntTrace is Line) { Line Ln = (Line)EntTrace; if (Ln.Closed) { area = Ln.Area; } } } } } } catch { throw; } string presisi = "#"; switch (db.Auprec) { case 0: presisi = "#"; break; case 1: presisi = "#0.0"; break; case 2: presisi = "#0.00"; break; case 3: presisi = "#0.000"; break; case 4: presisi = "#0.0000"; break; case 5: presisi = "#0.00000"; break; default: presisi = "#0.00"; break; } valueAreaBoundary = area.ToString(presisi); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); List<string> ListTag = new List<string>(); List<string> ListString = new List<string>(); Point3d pt = ppr.Value; BlockReference bref = new BlockReference(pt, bt[blockName]); Dictionary<string, string> dic = GetAttributDef(bref.BlockTableRecord, tr); foreach (KeyValuePair<string, string> item in dic) { ListTag.Add(item.Key.ToUpper().ToString()); // string[] info = item.Value.Split('|'); } formUserInputAttribut frmInput = new formUserInputAttribut(); IntPtr handle = AcAp.MainWindow.Handle; if (frmInput.ShowDialog(ListTag) == System.Windows.Forms.DialogResult.OK) { ListString.AddRange(frmInput.InputString); } else { return; } bref.Rotation = frmInput.UseRotation ? UserBlockref.Rotation : 0.0; bref.TransformBy(ucs); bref.AddContext(occ.CurrentContext); //add blockreference to current space btr.AppendEntity(bref); tr.AddNewlyCreatedDBObject(bref, true); // set attributes to desired values ApplyAttibutes(db, tr, bref, ListTag, ListString); bref.RecordGraphicsModified(true); // to force updating a block reference tr.TransactionManager.QueueForGraphicsFlush(); tr.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message); } finally { // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Pokey") } }
public static ObjectId AddBlockRefToModelSpace(ObjectId blockTableRecordId, List <string> attrTextValues, Point3d location, Matrix3d matrix, Transaction trans, bool commit) { // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(trans, OpenMode.ForWrite); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(blockTableRecordId, OpenMode.ForRead); BlockReference br = new BlockReference(location, blockTableRecordId); br.TransformBy(matrix); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } //br.RecordGraphicsModified(true); ObjectId brId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { //acAttRef.RecordGraphicsModified(true); acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); //acAttRef.Position = acAtt.Position.TransformBy(br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } //if (acAtt.Annotative == AnnotativeStates.True) //acAttRef.AddContext(occ.CurrentContext); br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } // Change the attribute definition to be displayed as backwards //acAtt.UpgradeOpen(); //acAtt.IsMirroredInX = true; //acAtt.IsMirroredInY = false; } br.RecordGraphicsModified(true); if (commit) { trans.Commit(); } return(brId); }
private static bool MoveLevelText(ObjectId fflToEditId) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; // Loop so user can move multiple levels bool movingLevels = true; while (movingLevels) { // Prompt the user to select the level to move PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to move (spacebar to finish):"); PromptNestedEntityResult nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt); if (nestedEntRes.Status == PromptStatus.OK) { using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity; if (ent.GetType() == typeof(MText)) { MText textToEdit = ent as MText; // All work will be done in the WCS so save the current UCS // to restore later and set the UCS to WCS Matrix3d CurrentUCS = acEditor.CurrentUserCoordinateSystem; acEditor.CurrentUserCoordinateSystem = Matrix3d.Identity; // Fetch the block reference for the outline BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; // Calculate the corner coordinates. Text rotation will either be 0 to 90 degrees or // 270 - 360 degrees. // What happens if text is not in these ranges? // Point3d textLocation = textToEdit.Location.TransformBy(fflToEdit.BlockTransform); Point3d cornerPoint = CalculateCornerPoint(textToEdit, fflToEdit); // Save the current text rotation angle for use later double oldTextAngle = textToEdit.Rotation; // Create a new UCS basesd on the corner point and the text rotation. The new UCS // origin will be at the corner point and the X-axis aligned with the text direction. if (!SwitchUCS(cornerPoint, textToEdit.Rotation)) { acEditor.WriteMessage("\nError, unable to create UCS!"); acTrans.Abort(); // Restore current UCS acEditor.CurrentUserCoordinateSystem = CurrentUCS; return(false); } // Prompt the user for the new position Point3d newLocation = new Point3d(); // Declare here so in scope AttachmentPoint newJustification = new AttachmentPoint(); double newAngle = 0.0; PromptPointResult promptRes; PromptPointOptions promptOpts = new PromptPointOptions("\nClick new text position: "); promptRes = acEditor.GetPoint(promptOpts); if (promptRes.Status != PromptStatus.OK) { acEditor.WriteMessage("\nInvalid level text position picked - please try again."); acTrans.Abort(); // Restore current UCS acEditor.CurrentUserCoordinateSystem = CurrentUCS; continue; } // If the text is justified TC or BC it's on a straight line so move to the other side, swap the // justification and maintain the same rotation if ((textToEdit.Attachment == AttachmentPoint.TopCenter) || (textToEdit.Attachment == AttachmentPoint.BottomCenter)) { newAngle = Constants.Deg_0; if (promptRes.Value.Y > 0) { newLocation = new Point3d(0.0, Constants.TextOffset, 0.0); newJustification = AttachmentPoint.BottomCenter; } else { newLocation = new Point3d(0.0, -Constants.TextOffset, 0.0); newJustification = AttachmentPoint.TopCenter; } } else { // Ask user if text needs to be rotated. PromptKeywordOptions promptKeyOpts = new PromptKeywordOptions("\nRotate text [Yes/No]: ", "Yes No"); promptKeyOpts.Keywords.Default = "No"; PromptResult promptRotRes = acEditor.GetKeywords(promptKeyOpts); if (promptRotRes.Status != PromptStatus.OK) { acEditor.WriteMessage("\nInvalid option - please try again."); acTrans.Abort(); // Restore current UCS acEditor.CurrentUserCoordinateSystem = CurrentUCS; continue; } // Calculate the new location point and text justification if (promptRes.Value.X < 0) { if (promptRes.Value.Y < 0) { newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45), -Constants.TextOffset * Math.Cos(Constants.Deg_45), 0.0); if (promptRotRes.StringResult == "Yes") { if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90)) { newJustification = AttachmentPoint.TopLeft; newAngle = Constants.Deg_270; // The UCS is origin currently lies at the corner point // and the x-axis at the text rotation } else { newJustification = AttachmentPoint.BottomRight; newAngle = Constants.Deg_90; } } else { newJustification = AttachmentPoint.TopRight; newAngle = Constants.Deg_0; } } else { newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45), Constants.TextOffset * Math.Cos(Constants.Deg_45), 0.0); if (promptRotRes.StringResult == "Yes") { if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90)) { newJustification = AttachmentPoint.TopRight; newAngle = Constants.Deg_270; } else { newJustification = AttachmentPoint.BottomLeft; newAngle = Constants.Deg_90; } } else { newJustification = AttachmentPoint.BottomRight; newAngle = Constants.Deg_0; } } } else if (promptRes.Value.X > 0) { if (promptRes.Value.Y < 0) { newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45), -Constants.TextOffset * Math.Sin(Constants.Deg_45), 0.0); if (promptRotRes.StringResult == "Yes") { if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90)) { newJustification = AttachmentPoint.BottomLeft; newAngle = Constants.Deg_270; } else { newJustification = AttachmentPoint.TopRight; newAngle = Constants.Deg_90; } } else { newJustification = AttachmentPoint.TopLeft; newAngle = Constants.Deg_0; } } else { newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45), Constants.TextOffset * Math.Cos(Constants.Deg_45), 0.0); if (promptRotRes.StringResult == "Yes") { if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90)) { newJustification = AttachmentPoint.BottomRight; newAngle = Constants.Deg_270; } else { newJustification = AttachmentPoint.TopLeft; newAngle = Constants.Deg_90; } } else { newJustification = AttachmentPoint.BottomLeft; newAngle = Constants.Deg_0; } } } else { acEditor.WriteMessage("\nInvalid point picked - please try again."); acTrans.Abort(); // Restore current UCS acEditor.CurrentUserCoordinateSystem = CurrentUCS; continue; } } // Translate these points to the WCS ViewportTableRecord acVportTblRec = acTrans.GetObject(acEditor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord; Matrix3d jppMatrix = new Matrix3d(); jppMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, acVportTblRec.Ucs.Origin, acVportTblRec.Ucs.Xaxis, acVportTblRec.Ucs.Yaxis, acVportTblRec.Ucs.Zaxis); Point3d wcsNewLoc = newLocation.TransformBy(jppMatrix); // Transform the new location to coordinates relative to the block reference wcsNewLoc = wcsNewLoc.TransformBy(fflToEdit.BlockTransform.Inverse()); // wcsNewLoc = new Point3d(wcsNewLoc.X - fflToEdit.BlockTransform.Translation.X, // wcsNewLoc.Y - fflToEdit.BlockTransform.Translation.Y, // wcsNewLoc.Z - fflToEdit.BlockTransform.Translation.Z); // Update the text textToEdit.UpgradeOpen(); textToEdit.Attachment = newJustification; textToEdit.Location = wcsNewLoc; textToEdit.Rotation = newAngle; // Update block graphics // BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference; fflToEdit.RecordGraphicsModified(true); acTrans.Commit(); // Restore current UCS acEditor.CurrentUserCoordinateSystem = CurrentUCS; } } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError moving level!\n"); acTrans.Abort(); return(false); } } } if (nestedEntRes.Status == PromptStatus.Cancel) { movingLevels = false; } } return(true); }