private static void AutoLayersBtr([CanBeNull] BlockTableRecord btr) { if (btr == null) { return; } var idEnts = btr.Cast <ObjectId>().ToList(); var idBlRefs = idEnts.Where(w => w.ObjectClass == General.ClassBlRef).ToList(); idEnts = idEnts.Except(idBlRefs).ToList(); foreach (var idBlRef in idBlRefs) { var blRef = idBlRef.GetObject <BlockReference>(); if (blRef == null) { continue; } AutoLayersBtr(blRef.BlockTableRecord.GetObject <BlockTableRecord>()); } foreach (var autoLayer in AutoLayers) { var autoLayerEnts = autoLayer.GetAutoLayerEnts(idEnts); AutoLayerEntities(autoLayer, autoLayerEnts); idEnts = idEnts.Except(autoLayerEnts).ToList(); } }
/// <summary> /// Closests the point. /// </summary> /// <param name="point3D">The point3 d.</param> /// <param name="collection">The collection.</param> public static void ClosestPoint(Point3d point3D, Point2dCollection collection) { Document doc = Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; Editor ed = doc.Editor; //PromptPointResult ppr = ed.GetPoint("\nSpecify a point: "); //if (ppr.Status != PromptStatus.OK) return; //Point3d pt = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem); Point3d pt = point3D; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead); var closest = btr .Cast <ObjectId>() .Select(id => tr.GetObject(id, OpenMode.ForRead) as Polyline) .Where(ent => ent != null) .Select(pline => new { pLine = pline, Dist = pt.DistanceTo(pline.GetClosestPointTo(pt, false)) }) .Aggregate((l1, l2) => l1.Dist < l2.Dist ? l1 : l2); if (closest != null) { closest.pLine.Highlight(); ed.WriteMessage("\nDistance = {0}", closest.Dist); } tr.Commit(); } }
/// <summary> /// Метод добавляет к вхождению блока атрибуты, определённые в определении блока /// </summary> /// <param name="o">Вхождение блока</param> /// <param name="UseDefaultTexts">Использовать ли значения по умолчанию, установленные атрибутам</param> public static void AppendAttributes(this BlockReference o, bool UseDefaultTexts = true) { Database db = o.Database; if (db == null) { throw new ArgumentNullException("BlockReference didn't added to database"); } ObjectId blockDefinitionId = o.IsDynamicBlock ? o.DynamicBlockTableRecord : o.BlockTableRecord; BlockTableRecord blockDefinition = blockDefinitionId.GetObject <BlockTableRecord>(); if (blockDefinition == null) { throw new System.Exception("BlockTableRecord missed"); } if (blockDefinition.HasAttributeDefinitions) { using (Transaction tr = db.TransactionManager.StartTransaction()) { var attDefinitions = blockDefinition.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => n.GetObject <AttributeDefinition>(OpenMode.ForRead)); foreach (AttributeDefinition attdef in attDefinitions) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, o.BlockTransform); if (UseDefaultTexts) { attref.TextString = attdef.TextString; } o.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); } tr.Commit(); } } }
private void LoopThroughModelSpace() { try { //run 2 long processing loops for (int n = 0; n < 2; n++) { using (var tran = _dwg.TransactionManager.StartTransaction()) { //Get all entities' ID in ModelSpace BlockTableRecord model = (BlockTableRecord) tran.GetObject( SymbolUtilityServices.GetBlockModelSpaceId( _dwg.Database), OpenMode.ForRead); ObjectId[] entIds = model.Cast <ObjectId>().ToArray(); if (ProcessingStarted != null) { string process = n == 0 ? "Searching ModelSpace for AAAA" : "Search ModelSpace for BBBB"; LongProcessStartedEventArgs e = new LongProcessStartedEventArgs( process, entIds.Length, true); ProcessingStarted(this, e); } int count = 0; foreach (var entId in entIds) { count++; if (ProcessingProgressed != null) { string progMsg = string.Format( "{0} out of {1}. {2} remaining...\n" + "Processing entity: {3}", count, entIds.Length, entIds.Length - count, entId.ObjectClass.DxfName); LongProcessingProgressEventArgs e = new LongProcessingProgressEventArgs(progMsg); ProcessingProgressed(this, e); //Since this processing is cancellable, we //test if user clicked the "Stop" button in the //progressing dialog box if (e.Cancel) { break; } } //Do something with the entity Entity ent = (Entity)tran.GetObject( entId, OpenMode.ForRead); long s = 0; for (int i = 0; i < 1000000; i++) { s += i * i; } } ProcessingEnded?.Invoke(this, EventArgs.Empty); tran.Commit(); } } } finally { //Make sure the CloseProgressUIRequested event always fires, so //that the progress dialog box gets closed because of this event CloseProgressUIRequested?.Invoke(this, EventArgs.Empty); } }
public ObjectId DefineRasterImage(Document doc, string url, Point3d basePoint, Vector3d v1, Vector3d v2, string suggestedName, byte transparency) { ObjectId result; try { System.Drawing.Image.FromStream(new WebClient().OpenRead(url)); } catch { result = ObjectId.Null; return(result); } Database database = doc.Database; Editor editor = doc.Editor; ObjectId objectId = ObjectId.Null; ObjectId arg_39_0 = ObjectId.Null; try { using (doc.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, false)) { Autodesk.AutoCAD.ApplicationServices.TransactionManager transactionManager = doc.TransactionManager; doc.TransactionManager.EnableGraphicsFlush(true); using (Transaction transaction = transactionManager.StartTransaction()) { string.IsNullOrEmpty(suggestedName); ObjectId objectId2 = RasterImageDef.GetImageDictionary(database); if (objectId2.IsNull) { objectId2 = RasterImageDef.CreateImageDictionary(database); } RasterImageDef rasterImageDef = new RasterImageDef(); rasterImageDef.SourceFileName = (url); rasterImageDef.Load(); bool arg_A4_0 = rasterImageDef.IsLoaded; DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(objectId2, OpenMode.ForWrite); string text = RasterImageDef.SuggestName(dBDictionary, url); if (!string.IsNullOrEmpty(suggestedName)) { text = suggestedName; int num = 0; while (dBDictionary.Contains(text)) { num++; text = suggestedName + num; } } ObjectId arg_F8_0 = ObjectId.Null; if (dBDictionary.Contains(text)) { //editor.WriteMessage(AfaStrings.ImageAlreadyExits); result = ObjectId.Null; return(result); } dBDictionary.SetAt(text, rasterImageDef); transaction.AddNewlyCreatedDBObject(rasterImageDef, true); dBDictionary.Contains(text); ObjectId layer = GetLayer(database, transaction, ref text); RasterImage rasterImage = new RasterImage(); rasterImage.ImageDefId = (rasterImageDef.ObjectId); rasterImage.SetLayerId(layer, false); byte b = Convert.ToByte(Math.Floor((100.0 - (double)transparency) / 100.0 * 254.0)); Transparency transparency2 = new Transparency(b); rasterImage.Transparency = transparency2; ; rasterImage.Orientation = new CoordinateSystem3d(basePoint, v1, v2); BlockTable blockTable = (BlockTable)transactionManager.GetObject(database.BlockTableId, 0, false); BlockTableRecord blockTableRecord = (BlockTableRecord)transactionManager.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false); int num2 = 0; try { num2 = blockTableRecord.Cast <object>().Count <object>(); } catch { } rasterImage.ColorIndex = (256); objectId = blockTableRecord.AppendEntity(rasterImage); transactionManager.AddNewlyCreatedDBObject(rasterImage, true); rasterImage.AssociateRasterDef(rasterImageDef); RasterImage.EnableReactors(true); rasterImageDef.UpdateEntities(); DrawOrderTable drawOrderTable = (DrawOrderTable)transaction.GetObject(blockTableRecord.DrawOrderTableId, OpenMode.ForWrite); ObjectIdCollection objectIdCollection = new ObjectIdCollection(); objectIdCollection.Add(objectId); drawOrderTable.MoveToBottom(objectIdCollection); try { rasterImageDef.UpdateEntities(); if (num2 == 0) { ZoomExtents(rasterImage.GeometricExtents.MinPoint, rasterImage.GeometricExtents.MaxPoint); editor.WriteMessage(rasterImage.Orientation.Origin.ToString()); } } catch { } transaction.Commit(); } } result = objectId; } catch (System.Exception ex) { result = ObjectId.Null; } catch { //rrorReport.ShowErrorMessage(AfaStrings.UnexpectedErrorInAddingRasterImage); result = ObjectId.Null; } return(result); }
public void Main() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; List <ObjectId> ids = null; LayoutManager layManager = LayoutManager.Current; ObjectId layoutId = layManager.GetLayoutId(layManager.CurrentLayout); //Layout layoutObj = (Layout)tr.GetObject(layoutId, OpenMode.ForRead); Layout layoutObj = layoutId.Open(OpenMode.ForRead) as Layout; PlotSettings plotSettingsObj = new PlotSettings(layoutObj.ModelType); string setName = "Langamer_Plot"; using (var trAddPlotSet = db.TransactionManager.StartTransaction()) { // Adiciona o PlotSetup ao DWG atual ********************************************************************************************** string plotSetDWGName = "Z:\\Lisp\\dwg_plot_setup.dwg"; Database dbPlotSet = new Database(); dbPlotSet.ReadDwgFile(plotSetDWGName, FileOpenMode.OpenForReadAndAllShare, true, ""); using (var trPlotSet = dbPlotSet.TransactionManager.StartTransaction()) { BlockTable btPlotSet = trPlotSet.GetObject(dbPlotSet.BlockTableId, OpenMode.ForWrite) as BlockTable; var btrPlotSet = trPlotSet.GetObject(btPlotSet[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Layout loPlotSet = trPlotSet.GetObject(btrPlotSet.LayoutId, OpenMode.ForWrite) as Layout; PlotSettings psPlotSet = new PlotSettings(loPlotSet.ModelType); psPlotSet.CopyFrom(loPlotSet); psPlotSet.AddToPlotSettingsDictionary(db); trPlotSet.Commit(); trAddPlotSet.Commit(); } } using (var tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DBDictionary plotSettingsDic = (DBDictionary)tr.GetObject(db.PlotSettingsDictionaryId, OpenMode.ForRead); if (!plotSettingsDic.Contains(setName)) { return; } ObjectId plotSettingsId = plotSettingsDic.GetAt(setName); //layout type bool bModel = layoutObj.ModelType; plotSettingsObj = tr.GetObject(plotSettingsId, OpenMode.ForRead) as PlotSettings; if (plotSettingsObj.ModelType != bModel) { return; } object backgroundPlot = Application.GetSystemVariable("BACKGROUNDPLOT"); Application.SetSystemVariable("BACKGROUNDPLOT", 0); // Fim: Adiciona o PlotSetup ao DWG atual **************************************************************************************** // Pega todos os POLYLINE do desenho atual ********************************************************************************************** // Cast the BlockTableRecord into IEnumerable<T> collection IEnumerable <ObjectId> b = btr.Cast <ObjectId>(); // Using LINQ statement to select LWPOLYLINE from ModelSpace ids = (from id1 in b where OpenObject(tr, id1) is BlockReference && OpenObject(tr, id1).Layer == "LANG-GR-PRANCHA 1" select id1).ToList <ObjectId>(); // Fim: Pega todos os POLYLINE do desenho atual ********************************************************************************************** foreach (var id in ids) { //ObjectId id = ids[0]; //Polyline objPl = tr.GetObject(id, OpenMode.ForRead) as Polyline; BlockReference objPrancha = tr.GetObject(id, OpenMode.ForRead) as BlockReference; Extents3d bounds = (Extents3d)objPrancha.Bounds.Value; Point2d ptMin = new Point2d(bounds.MinPoint.X, bounds.MinPoint.Y); Point2d ptMax = new Point2d(bounds.MaxPoint.X, bounds.MaxPoint.Y); Extents2d plotWin = new Extents2d(ptMin, ptMax); GetSheetExtents(tr, objPrancha); try { PlotSettingsValidator psv = PlotSettingsValidator.Current; psv.SetPlotWindowArea(plotSettingsObj, plotWin); psv.SetPlotRotation(plotSettingsObj, PlotRotation.Degrees180); //now plot the setup... PlotInfo plotInfo = new PlotInfo(); plotInfo.Layout = layoutObj.ObjectId; plotInfo.OverrideSettings = plotSettingsObj; PlotInfoValidator piv = new PlotInfoValidator(); piv.Validate(plotInfo); string outName = "C:\\Users\\weiglas.ribeiro.LANGAMER\\Desktop\\" + System.DateTime.Now.Millisecond + ".pdf"; using (var pe = PlotFactory.CreatePublishEngine()) { // Begin plotting a document. pe.BeginPlot(null, null); pe.BeginDocument(plotInfo, doc.Name, null, 1, true, outName); // Begin plotting the page PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, plotInfo, true, null); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); // Finish the sheet pe.EndPage(null); // Finish the document pe.EndDocument(null); //// And finish the plot pe.EndPlot(null); } } catch (Exception er) { } } tr.Commit(); } }
/// <summary> /// Синхронизация вхождений блоков с их определением /// via http://sites.google.com/site/bushmansnetlaboratory/moi-zametki/attsynch /// </summary> /// <param name="btr">Запись таблицы блоков, принятая за определение блока</param> /// <param name="directOnly">Следует ли искать только на верхнем уровне, или же нужно /// анализировать и вложенные вхождения, т.е. следует ли рекурсивно обрабатывать блок в блоке: /// true - только верхний; false - рекурсивно проверять вложенные блоки.</param> /// <param name="removeSuperfluous"> /// Следует ли во вхождениях блока удалять лишние атрибуты (те, которых нет в определении блока).</param> /// <param name="setAttDefValues"> /// Следует ли всем атрибутам, во вхождениях блока, назначить текущим значением значение по умолчанию.</param> public static void AttSync(this BlockTableRecord btr, bool directOnly, bool removeSuperfluous, bool setAttDefValues) { Database db = btr.Database; // using (Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher wdb = new Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher(db)) { using (Transaction t = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead); //Получаем все определения атрибутов из определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)) .Where(n => !n.Constant);//Исключаем константные атрибуты, т.к. для них AttributeReference не создаются. //В цикле перебираем все вхождения искомого определения блока foreach (ObjectId brId in btr.GetBlockReferenceIds(directOnly, false)) { BlockReference br = (BlockReference)t.GetObject(brId, OpenMode.ForWrite); //Проверяем имена на соответствие. В том случае, если вхождение блока "A" вложено в определение блока "B", //то вхождения блока "B" тоже попадут в выборку. Нам нужно их исключить из набора обрабатываемых объектов //- именно поэтому проверяем имена. if (br.Name != btr.Name) { continue; } //Получаем все атрибуты вхождения блока IEnumerable <AttributeReference> attrefs = br.AttributeCollection.Cast <ObjectId>() .Select(n => (AttributeReference)t.GetObject(n, OpenMode.ForWrite)); //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); //Тэги существующих атрибутов во вхождении IEnumerable <string> rtags = attrefs.Select(n => n.Tag); //Если требуется - удаляем те атрибуты, для которых нет определения //в составе определения блока if (removeSuperfluous) { foreach (AttributeReference attref in attrefs.Where(n => rtags .Except(dtags).Contains(n.Tag))) { attref.Erase(true); } } //Свойства существующих атрибутов синхронизируем со свойствами их определений foreach (AttributeReference attref in attrefs.Where(n => dtags .Join(rtags, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs.First(n => n.Tag == attref.Tag); //Метод SetAttributeFromBlock, используемый нами далее в коде, сбрасывает //текущее значение многострочного атрибута. Поэтому запоминаем это значение, //чтобы восстановить его сразу после вызова SetAttributeFromBlock. string value = attref.TextString; attref.SetAttributeFromBlock(ad, br.BlockTransform); //Восстанавливаем значение атрибута attref.TextString = value; if (attref.IsMTextAttribute) { } //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { attref.TextString = ad.TextString; } attref.AdjustAlignment(db); } //Если во вхождении блока отсутствуют нужные атрибуты - создаём их IEnumerable <AttributeDefinition> attdefsNew = attdefs.Where(n => dtags .Except(rtags).Contains(n.Tag)); foreach (AttributeDefinition ad in attdefsNew) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(ad, br.BlockTransform); attref.AdjustAlignment(db); br.AttributeCollection.AppendAttribute(attref); t.AddNewlyCreatedDBObject(attref, true); } } btr.UpdateAnonymousBlocks(); t.Commit(); } //Если это динамический блок if (btr.IsDynamicBlock) { using (Transaction t = db.TransactionManager.StartTransaction()) { foreach (ObjectId id in btr.GetAnonymousBlockIds()) { BlockTableRecord _btr = (BlockTableRecord)t.GetObject(id, OpenMode.ForWrite); //Получаем все определения атрибутов из оригинального определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)); //Получаем все определения атрибутов из определения анонимного блока IEnumerable <AttributeDefinition> attdefs2 = _btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForWrite)); //Определения атрибутов анонимных блоков следует синхронизировать //с определениями атрибутов основного блока //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); IEnumerable <string> dtags2 = attdefs2.Select(n => n.Tag); //1. Удаляем лишние foreach (AttributeDefinition attdef in attdefs2.Where(n => !dtags.Contains(n.Tag))) { attdef.Erase(true); } //2. Синхронизируем существующие foreach (AttributeDefinition attdef in attdefs.Where(n => dtags .Join(dtags2, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs2.First(n => n.Tag == attdef.Tag); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { ad.TextString = attdef.TextString; } ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; ad.AdjustAlignment(db); } //3. Добавляем недостающие foreach (AttributeDefinition attdef in attdefs.Where(n => !dtags2.Contains(n.Tag))) { AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif ad.TextString = attdef.TextString; ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; _btr.AppendEntity(ad); t.AddNewlyCreatedDBObject(ad, true); ad.AdjustAlignment(db); } //Синхронизируем все вхождения данного анонимного определения блока _btr.AttSync(directOnly, removeSuperfluous, setAttDefValues); } //Обновляем геометрию определений анонимных блоков, полученных на основе //этого динамического блока btr.UpdateAnonymousBlocks(); t.Commit(); } } // } }
public static IEnumerable <ObjectId> FilterIntities(this BlockTableRecord btr, Func <ObjectId, bool> filterFunction, bool doValidChecks = true) { return (btr.Cast <ObjectId>() .Where(id => filterFunction(id) && (!doValidChecks || id.CheckValid()))); }