예제 #1
0
        public List <Db.ObjectId> GetPipeIdByName(string[] pipeNames)
        {
            Ed.Editor         ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Civ.CivilDocument civDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;
            var pipeIds = new List <Db.ObjectId>();

            // Iterate through each pipe network
            using (Db.Transaction ts = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction()) {
                try {
                    foreach (Db.ObjectId networkId in civDoc.GetPipeNetworkIds())
                    {
                        CivDb.Network oNetwork = ts.GetObject(networkId, Db.OpenMode.ForWrite) as CivDb.Network;
                        foreach (Db.ObjectId pipeId in oNetwork.GetPipeIds())
                        {
                            CivDb.Pipe oPipe = ts.GetObject(pipeId, Db.OpenMode.ForRead) as CivDb.Pipe;
                            foreach (string name in pipeNames)
                            {
                                if (oPipe.Name == name)
                                {
                                    pipeIds.Add(oPipe.Id);
                                }
                            }
                        }
                    }
                    return(pipeIds);
                } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                    ed.WriteMessage("StructurePipesData: " + ex.Message);
                    return(null);
                }
            }
        }
예제 #2
0
        private static void SetDrawOrderInBlock(App.Document dwg, Db.ObjectId blkId)
        {
            using (Db.Transaction tran =
                       dwg.TransactionManager.StartTransaction())
            {
                Db.BlockReference bref = (Db.BlockReference)tran.GetObject(
                    blkId, Db.OpenMode.ForRead);

                Db.BlockTableRecord bdef = (Db.BlockTableRecord)tran.GetObject(
                    bref.BlockTableRecord, Db.OpenMode.ForWrite);

                Db.DrawOrderTable doTbl = (Db.DrawOrderTable)tran.GetObject(
                    bdef.DrawOrderTableId, Db.OpenMode.ForWrite);

                Db.ObjectIdCollection col = new Db.ObjectIdCollection();
                foreach (Db.ObjectId id in bdef)
                {
                    if (id.ObjectClass == Rtm.RXObject.GetClass(typeof(Db.Wipeout)))
                    {
                        col.Add(id);
                    }
                }

                if (col.Count > 0)
                {
                    doTbl.MoveToBottom(col);
                }


                tran.Commit();
            }
        }
예제 #3
0
        private static void AddText(Gem.Point2d pnt, string layer, string str)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.MText acMText = new Db.MText();
                acMText.SetDatabaseDefaults();
                acMText.Location = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acMText.Contents = str;
                acMText.Height   = SettingsParser.getInstance()._Scale.Coord;
                acMText.Color    = Autodesk.AutoCAD.Colors.
                                   Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByLayer, 256);
                acMText.Layer = layer;
                acMText.SetDatabaseDefaults();
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acMText);
                acTrans.AddNewlyCreatedDBObject(acMText, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
예제 #4
0
 public void DeleteAllObjects()
 {
     using (DocumentLock doclock = Document.LockDocument())
     {
         using (AcDb.Transaction trans = TransactionManager.StartTransaction())
         {
             foreach (var obj in (ObjectList.FindAll(p => p.ToolpathCurve != null || p.ProcessActions != null)))
             {
                 if (obj.ToolpathCurve != null)
                 {
                     trans.GetObject(obj.ToolpathCurve.ObjectId, AcDb.OpenMode.ForWrite);
                     obj.ToolpathCurve.Erase();
                 }
                 else
                 {
                     obj.ProcessActions.ForEach(p =>
                     {
                         trans.GetObject(p.Toolpath.ObjectId, AcDb.OpenMode.ForWrite);
                         p.Toolpath.Erase();
                     });
                 }
             }
             trans.Commit();
             Editor.UpdateScreen();
         }
     }
     ObjectList.Clear();
 }
예제 #5
0
        } //WriteResourceToFile

        internal static Db.ObjectId GetIDbyName <T>(Db.Database db, string strName)
        {
            Db.ObjectId RecId = Db.ObjectId.Null;
            using (Db.Transaction tr1 = db.TransactionManager.StartTransaction())
            {
                if (typeof(T) == typeof(Db.MLeaderStyle))
                {
                    Db.DBDictionary mlstyles = (Db.DBDictionary)tr1.GetObject(
                        db.MLeaderStyleDictionaryId,
                        Db.OpenMode.ForRead);

                    RecId = (mlstyles.Contains(strName)) ? mlstyles.GetAt(strName) : Db.ObjectId.Null;
                }
                else if (typeof(T) == typeof(Db.LayerTableRecord))
                {
                    Db.LayerTable layerTable;
                    layerTable = (Db.LayerTable)tr1.GetObject(db.LayerTableId,
                                                              Db.OpenMode.ForRead);

                    RecId = (layerTable.Has(strName)) ? layerTable[strName] : Db.ObjectId.Null;
                }
                tr1.Commit();
            }
            // Все еще можно получить Db.ObjectId.Null для передачи.
            return(RecId);
        }
예제 #6
0
        private static void AddCircle(Gem.Point2d pnt, string layer)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.Circle acCircle = new Db.Circle();
                acCircle.SetDatabaseDefaults();
                acCircle.Center = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acCircle.Radius = SettingsParser.getInstance()._Scale.Circle;
                acCircle.Layer  = layer;
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acCircle);
                acTrans.AddNewlyCreatedDBObject(acCircle, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
예제 #7
0
 public void DeleteObject(ProcessObject obj)
 {
     // TODO удалить обработчики
     //obj.ProcessCurve.Modified -= ProcessCurveModifiedEventHandler;
     //obj.ProcessCurve.Erased -= ProcessCurveErasedEventHandler;
     if (obj.ToolpathCurve != null || obj.ProcessActions != null)
     {
         using (DocumentLock doclock = Document.LockDocument())
         {
             using (AcDb.Transaction trans = TransactionManager.StartTransaction())
             {
                 if (obj.ToolpathCurve != null)
                 {
                     trans.GetObject(obj.ToolpathCurve.ObjectId, AcDb.OpenMode.ForWrite);
                     obj.ToolpathCurve.Erase();
                 }
                 else
                 {
                     obj.ProcessActions.ForEach(p =>
                     {
                         trans.GetObject(p.Toolpath.ObjectId, AcDb.OpenMode.ForWrite);
                         p.Toolpath.Erase();
                     });
                 }
                 trans.Commit();
                 Editor.UpdateScreen();
             }
         }
     }
     RemoveConnect(obj, VertexType.Start);
     RemoveConnect(obj, VertexType.End);
     ObjectList.Remove(obj);
     ObjectForm.RefreshList();
 }
        public override List <string> GetObjectsInView()
        {
            var objs = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.BlockTable       blckTbl     = tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead) as AcadDb.BlockTable;
                AcadDb.BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[AcadDb.BlockTableRecord.ModelSpace], AcadDb.OpenMode.ForRead) as AcadDb.BlockTableRecord;
                foreach (AcadDb.ObjectId id in blckTblRcrd)
                {
                    var dbObj = tr.GetObject(id, AcadDb.OpenMode.ForRead);
                    if (dbObj is AcadDb.BlockReference)
                    {
                        var blckRef = (AcadDb.BlockReference)dbObj; // skip block references for now
                    }
                    else
                    {
                        objs.Add(dbObj.Handle.ToString());
                    }
                }
                // TODO: this returns all the doc objects. Need to check for visibility later.
                tr.Commit();
            }
            return(objs);
        }
예제 #9
0
        public int processObjectId(DB.Transaction tr, DB.ObjectId objId, FindReplacer findReplacer)
        {
            int replaced = 0;
            var ent      = tr.GetObject(objId, DB.OpenMode.ForWrite, false);

            if (ent is DB.Table)
            {
                var tbl = ent as DB.Table;
                if (tbl.NumRows > 0 && tbl.NumColumns > 0)
                {
                    for (var r = 0; r < tbl.NumRows; r++)
                    {
                        for (var c = 0; c < tbl.NumColumns; c++)
                        {
                            var text = tbl.GetTextString(r, c, 0, DB.FormatOption.FormatOptionNone);
                            var textWithoutFormat = tbl.GetTextString(r, c, 0, DB.FormatOption.IgnoreMtextFormat);
                            if (findReplacer.ContainsIn(text, textWithoutFormat))
                            {
                                tbl.SetTextString(r, c, text.Replace(findReplacer.Find, findReplacer.Replace));
                                replaced++;
                            }
                        }
                    }
                }
            }
            else if (ent is DB.MText)
            {
                var mtext             = ent as DB.MText;
                var text              = mtext.Contents;
                var textWithoutFormat = mtext.Text;
                if (findReplacer.ContainsIn(text, textWithoutFormat))
                {
                    mtext.Contents = text.Replace(findReplacer.Find, findReplacer.Replace);
                    replaced++;
                }
            }
            else if (ent is DB.DBText)
            {
                var dbtext = ent as DB.DBText;
                var text   = dbtext.TextString;
                if (findReplacer.ContainsIn(text, text))
                {
                    dbtext.TextString = text.Replace(findReplacer.Find, findReplacer.Replace);
                    replaced++;
                }
            }
            else if (ent is DB.BlockReference)
            {
                var br   = ent as DB.BlockReference;
                var brId = br.IsDynamicBlock ? br.DynamicBlockTableRecord : br.BlockTableRecord;
                var btr  = (DB.BlockTableRecord)tr.GetObject(brId, DB.OpenMode.ForRead, false);
                foreach (DB.ObjectId objId2 in btr)
                {
                    processObjectId(tr, objId2, findReplacer);
                }
            }

            return(replaced);
        }
예제 #10
0
        static public void SpaceOnAttributeName()
        {
            // Получение текущего документа и базы данных
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            Ed.Editor    acEd    = acDoc.Editor;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.TypedValue[] acTypValAr = new Db.TypedValue[1];
                acTypValAr.SetValue(new Db.TypedValue((int)Db.DxfCode.Start, "INSERT"), 0);
                Ed.SelectionFilter acSelFtr = new Ed.SelectionFilter(acTypValAr);

                Ed.PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(acSelFtr);
                if (acSSPrompt.Status == Ed.PromptStatus.OK)
                {
                    Ed.SelectionSet acSSet = acSSPrompt.Value;
                    foreach (Ed.SelectedObject acSSObj in acSSet)
                    {
                        if (acSSObj != null)
                        {
                            if (acSSObj.ObjectId.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.BlockReference))))
                            {
                                Db.BlockReference acEnt = acTrans.GetObject(acSSObj.ObjectId,
                                                                            Db.OpenMode.ForRead) as Db.BlockReference;

                                Db.BlockTableRecord blr = acTrans.GetObject(acEnt.BlockTableRecord,
                                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                if (acEnt.IsDynamicBlock)
                                {
                                    blr = acTrans.GetObject(acEnt.DynamicBlockTableRecord,
                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                }

                                if (blr.HasAttributeDefinitions)
                                {
                                    foreach (Db.ObjectId id in blr)
                                    {
                                        if (id.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.AttributeDefinition))))
                                        {
                                            Db.AttributeDefinition acAttrRef = acTrans.GetObject(id,
                                                                                                 Db.OpenMode.ForWrite) as Db.AttributeDefinition;

                                            if (acAttrRef != null)
                                            {
                                                acAttrRef.Tag = acAttrRef.Tag.Replace('_', ' ');
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                acTrans.Commit();
            }
        }
예제 #11
0
        void StreamCollectClipBodiesSample()
        {
            Database db     = GetDatabase();
            Editor   editor = GetEditor();

            editor.WriteMessage("* StreamCollectClipBodies *\n");
            editor.WriteMessage("StreamCollectClipBodies clips all geometry pushed in against the supplied body.\n");
            editor.WriteMessage("Pick some objects in the current drawing and then pick an mass element to define the clipping boundary. The collected graphics will be highlighted in the current view.\n");

            ObjectIdCollection ids = PickObjectSet("Please pick the objects to be clipped");

            if (ids.Count == 0)
            {
                editor.WriteMessage("No object is picked\n");
                return;
            }

            ObjectId massElemId = PickObject(typeof(MassElement), true, "Please pick a mass element to define the clipping boundary");

            if (massElemId.IsNull)
            {
                editor.WriteMessage("A mass element is needed to define the clipping boundary.\n");
                return;
            }

            StreamCollectClipBodies stream = new StreamCollectClipBodies(db);
            // You may tell the stream to retain bodies instead of turning bodies into shells.
            // stream.SetRetainBodies(true);
            // But now we use the default setting, which uses shell as output.
            TransactionManager tm = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                MassElement     masselem = trans.GetObject(massElemId, OpenMode.ForRead) as MassElement;
                AecModeler.Body body     = masselem.Body.Transform(masselem.Ecs);
                stream.SetBodyClipVolume(body);

                stream.PushDisplayParameters(DictionaryDisplayConfiguration.GetStandardDisplayConfiguration(db), trans);

                foreach (ObjectId id in ids)
                {
                    Entity entity = trans.GetObject(id, OpenMode.ForRead) as Entity;
                    stream.Stream(entity);
                }

                stream.PopDisplayParameters();
                trans.Commit();
            }

            GraphicsStorage[] gsCollection = stream.GetCollectedGraphics();
            foreach (GraphicsStorage gs in gsCollection)
            {
                HighlightGraphics(gs);
            }
        }
예제 #12
0
        /// <summary>
        /// This is Extension Method for the <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// class. It gets the localized name of the Model tab.
        /// </summary>
        /// <param name="mng">Target <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// instance.</param>
        /// <returns>Returns the name of current space.</returns>
        public static String GetModelTabLocalizedName(this Db.LayoutManager mng)
        {
            Db.Database db = cad.DocumentManager.MdiActiveDocument.Database;
            String      modelTabLocalizedName = String.Empty;

            using (Db.Transaction tr = db.TransactionManager.StartTransaction())
            {
                Db.BlockTable       bt  = tr.GetObject(db.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord btr = tr.GetObject(bt[Db.BlockTableRecord.ModelSpace], Db.OpenMode.ForRead)
                                          as Db.BlockTableRecord;
                modelTabLocalizedName = (tr.GetObject(btr.LayoutId, Db.OpenMode.ForRead) as Db.Layout).LayoutName;
            }
            return(modelTabLocalizedName);
        }
예제 #13
0
        /// <summary>
        /// 清理指定图层
        /// </summary>
        /// <param name="strLayer">图层名</param>
        /// <param name="isErase">是否删除图层</param>
        public static void ClearLayer(string strLayer, bool isErase)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager transactionManager = db.TransactionManager;
            using (Autodesk.AutoCAD.DatabaseServices.Transaction trans = transactionManager.StartTransaction())
            {
                BlockTable blkTab = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId blkRecId in blkTab)
                {
                    BlockTableRecord btr = trans.GetObject(blkRecId, OpenMode.ForRead) as BlockTableRecord;
                    foreach (ObjectId id in btr)
                    {
                        Entity ent = trans.GetObject(id, OpenMode.ForRead) as Entity;
                        if (ent.Layer == strLayer)
                        {
                            LayerTableRecord entLayer = trans.GetObject(ent.LayerId, OpenMode.ForRead) as LayerTableRecord;
                            if (!(entLayer.IsFrozen || entLayer.IsLocked))
                            {
                                ent.UpgradeOpen();
                                ent.Erase(true);
                            }
                        }
                    }
                }
                trans.Commit();
            }
            if (!isErase)
            {
                return;
            }
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable laTab = trans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                if (laTab != null)
                {
                    if (laTab.Has(strLayer))
                    {
                        ObjectId         layerTabRecId = laTab[strLayer];
                        LayerTableRecord layerTabRec   = trans.GetObject(layerTabRecId, OpenMode.ForWrite) as LayerTableRecord;
                        if (layerTabRec != null)
                        {
                            layerTabRec.Erase();
                        }
                    }
                }
                trans.Commit();
            }
        }
예제 #14
0
        TestImageAngle()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            PromptEntityOptions prOpts = new PromptEntityOptions("\nSelect an Image");

            prOpts.SetRejectMessage("\nSelected entity must by of type RasterImage");
            prOpts.AddAllowedClass(typeof(RasterImage), false);

            PromptEntityResult prRes = ed.GetEntity(prOpts);

            if (prRes.Status == PromptStatus.OK)
            {
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = prRes.ObjectId.Database.TransactionManager;
                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    RasterImage imgObj = (RasterImage)tr.GetObject(prRes.ObjectId, OpenMode.ForRead);

                    CoordinateSystem3d entEcs = imgObj.Orientation;

                    Vector3d arbXAxis  = Utils.Db.GetEcsXAxis(entEcs.Zaxis);  // get AutoCAD's arbitrary X-Axis
                    double   rotAngle1 = arbXAxis.GetAngleTo(entEcs.Xaxis, entEcs.Zaxis);
                    ed.WriteMessage(string.Format("\nECS rotation angle: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle1, AngularUnitFormat.Current, -1)));

                    Plane  ucsPlane  = Utils.Db.GetUcsPlane(prRes.ObjectId.Database);
                    double rotAngle2 = entEcs.Xaxis.AngleOnPlane(ucsPlane);
                    ed.WriteMessage(string.Format("\nRotation angle relative to UCS: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle2, AngularUnitFormat.Current, -1)));

                    tr.Commit();
                }
            }
        }
        private bool GetOrMakeLayer(string layerName, AcadDb.Transaction tr, out string cleanName)
        {
            cleanName = Utils.RemoveInvalidChars(layerName);
            try
            {
                AcadDb.LayerTable lyrTbl = tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead) as AcadDb.LayerTable;
                if (lyrTbl.Has(cleanName))
                {
                    return(true);
                }
                else
                {
                    lyrTbl.UpgradeOpen();
                    var _layer = new AcadDb.LayerTableRecord();

                    // Assign the layer properties
                    _layer.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByColor, 7); // white
                    _layer.Name  = cleanName;

                    // Append the new layer to the layer table and the transaction
                    lyrTbl.Add(_layer);
                    tr.AddNewlyCreatedDBObject(_layer, true);
                }
            }
            catch { return(false); }
            return(true);
        }
예제 #16
0
        static public void GetEnt()
        {
            AcEd.Editor  ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptResult rs = ed.GetString("\nВведите метку примитива (в hex-представлении): ");

            if (rs.Status != PromptStatus.OK)
            {
                return;
            }
            System.Int64  l  = System.Int64.Parse(rs.StringResult, System.Globalization.NumberStyles.HexNumber);
            AcDb.Handle   h  = new AcDb.Handle(l);
            AcDb.Database db = AcDb.HostApplicationServices.WorkingDatabase;
            AcDb.ObjectId id = db.GetObjectId(false, h, 0);
            if (!id.IsValid)
            {
                ed.WriteMessage("\nОшибочная метка примитива {0}", h);
                return;
            }
            using (AcAp.DocumentLock doclock = ed.Document.LockDocument())
            {
                using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    AcDb.Entity ent = tr.GetObject(id, AcDb.OpenMode.ForRead) as AcDb.Entity;
                    if (ent != null)
                    {
                        ed.WriteMessage("\nEntity Class: {0}", AcRx.RXClass.GetClass(ent.GetType()).Name);
                        // Ну и так далее - делаешь с примитивом то, что тебе нужно...
                    }
                    else
                    {
                        ed.WriteMessage("\nЭто не примитив!");
                    }
                }
            }
        }
예제 #17
0
        ProcessObject(AcDb.Transaction trHelp, AcDb.ObjectId lookForObjId, AcDb.ObjectId curObjId)
        {
            AcDb.DBObject tmpObj = trHelp.GetObject(curObjId, AcDb.OpenMode.ForRead);
            if (tmpObj != null)
            {
                m_count++;
                ReferenceFiler filer = new ReferenceFiler();
                tmpObj.DwgOut(filer);                          // find out who this object owns

                RecordReferences(lookForObjId, tmpObj, filer); // record references for this object

                // now recursively visit all the objects this one owns
                for (int i = 0; i < filer.m_hardOwnershipIds.Count; i++)
                {
                    ProcessObject(trHelp, lookForObjId, filer.m_hardOwnershipIds[i]);
                }

                for (int i = 0; i < filer.m_softOwnershipIds.Count; i++)
                {
                    ProcessObject(trHelp, lookForObjId, filer.m_softOwnershipIds[i]);
                }
            }
            else
            {
                m_skipped++;
            }
        }
예제 #18
0
        Extents()
        {
            m_db = Utils.Db.GetCurDwg();

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager;

            while (true)
            {
                PromptEntityResult prEntRes = ed.GetEntity("\nSelect entity to show extents");
                if (prEntRes.Status != PromptStatus.OK)
                {
                    break;
                }

                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    AcDb.Entity ent = (AcDb.Entity)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead);

                    Extents3d ext      = ent.GeometricExtents;
                    Point3d   centerPt = Utils.Ge.Midpoint(ext.MinPoint, ext.MaxPoint);

                    Utils.AcadUi.PrintToCmdLine(string.Format("\nEXTMIN:    {0}", Utils.AcadUi.PtToStr(ext.MinPoint)));
                    Utils.AcadUi.PrintToCmdLine(string.Format("\nEXTMAX:    {0}", Utils.AcadUi.PtToStr(ext.MaxPoint)));
                    Utils.AcadUi.PrintToCmdLine(string.Format("\nCENTER PT: {0}", Utils.AcadUi.PtToStr(centerPt)));

                    tr.Commit();

                    MakeExtentsBlock(ext);
                }
            }
        }
예제 #19
0
파일: SymTbl.cs 프로젝트: 15831944/EM
        GetSymbolTableRecId(System.Type classType, string symName, Database db)
        {
            ObjectId tblId = GetSymbolTableId(classType, db);
            ObjectId recId = new ObjectId();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            try
            {
                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction())
                {
                    SymbolTable tbl = (SymbolTable)tr.GetObject(tblId, OpenMode.ForRead);
                    if (tbl.Has(symName))   // TBD: should indexer return ObjectId.null instead of throwing exception
                    {
                        recId = tbl[symName];
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " SymTbl.cs: line: 276");
            }

            return(recId);
        }
예제 #20
0
파일: Db.cs 프로젝트: 15831944/EM
        idObjToTypeAndHandleStr(ObjectId objId)
        {
            string str = "";

            if (objId.IsNull)
            {
                str = "(null)";
            }
            else
            {
                // open up even if erased
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = objId.Database.TransactionManager;
                try
                {
                    using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction())
                    {
                        DBObject tmpObj = tr.GetObject(objId, OpenMode.ForRead, true);
                        str = idObjToTypeAndHandleStr(tmpObj);
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    BaseObjs.writeDebug(ex.Message + " Db.cs: line: 388");
                }
            }

            return(str);
        }
예제 #21
0
        public static ACADDB.Region AddRegion(ACADDB.ObjectId acadObjectId)
        {
            ACADDB.Region returnvalue = null;
            // Get the current document and database
            Document acDoc = Application.DocumentManager.MdiActiveDocument;

            ACADDB.Database acCurDb = acDoc.Database;

            // Start a transaction
            using (ACADDB.Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Block table for read
                ACADDB.BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             ACADDB.OpenMode.ForRead) as ACADDB.BlockTable;

                // Open the Block table record Model space for write
                ACADDB.BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[ACADDB.BlockTableRecord.ModelSpace],
                                                ACADDB.OpenMode.ForWrite) as ACADDB.BlockTableRecord;

                ACADDB.Polyline polyline = acTrans.GetObject(acadObjectId,
                                                             ACADDB.OpenMode.ForRead) as ACADDB.Polyline;
                if (polyline != null)

                {
                    ACADDB.DBObjectCollection acDBObjColl = new ACADDB.DBObjectCollection();
                    acDBObjColl.Add((ACADDB.DBObject)polyline.AcadObject);

                    // Calculate the regions based on each closed loop
                    ACADDB.DBObjectCollection myRegionColl = new ACADDB.DBObjectCollection();
                    myRegionColl = ACADDB.Region.CreateFromCurves(acDBObjColl);
                    ACADDB.Region acRegion = myRegionColl[0] as ACADDB.Region;
                    returnvalue = acRegion;
                    // Add the new object to the block table record and the transaction
                    acBlkTblRec.AppendEntity(acRegion);
                    acTrans.AddNewlyCreatedDBObject(acRegion, true);

                    // Dispose
                }

                // Save the new object to the database
                acTrans.Commit();
            }
            return(returnvalue);
        }
예제 #22
0
        public static void StatisticsModel123_Steel4(BeamData beam, AcadDB.BlockReference blk_ref)
        {
            AcadDB.Database db = AcadApp.DocumentManager.MdiActiveDocument.Database;
            using (AcadDB.Transaction trans = db.TransactionManager.StartTransaction())
            {
                AcadDB.AttributeCollection atts = blk_ref.AttributeCollection;
                foreach (AcadDB.ObjectId att in atts)
                {
                    AcadDB.AttributeReference att_ref = trans.GetObject(att, AcadDB.OpenMode.ForWrite) as AcadDB.AttributeReference;
                    if (null == att_ref)
                    {
                        continue;
                    }

                    if (ATT_SH == att_ref.Tag)
                    {
                        att_ref.TextString = "4";
                    }
                    if (ATT_DK == att_ref.Tag)
                    {
                        att_ref.TextString = beam.dau_goi_data.first_layer_diameter.ToString();
                    }
                    if (ATT_DAI == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.Length - 2 * Beam.cover).ToString();
                    }
                    if (ATT_L2 == att_ref.Tag)
                    {
                        att_ref.TextString = "2000";
                    }
                    if (ATT_L1 == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.Height - 2 * Beam.cover).ToString();
                    }
                    if (ATT_SL1 == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.dau_goi_data.number_steel_first_layer).ToString();
                    }
                    if (ATT_SLA == att_ref.Tag)
                    {
                        att_ref.TextString = (beam.dau_goi_data.number_steel_first_layer).ToString();
                    }
                    if (ATT_DT == att_ref.Tag)
                    {
                        double total_len = beam.dau_goi_data.number_steel_first_layer * (beam.Length - 2 * Beam.cover);
                        total_len         /= 1000.0;
                        att_ref.TextString = (total_len).ToString();
                    }
                    if (ATT_TL == att_ref.Tag)
                    {
                        att_ref.TextString = "...";
                    }
                }

                trans.Commit();
            }
        }
예제 #23
0
        GetLineOrTwoPoints(out Point3d pt1, out Point3d pt2)
        {
            m_db = Utils.Db.GetCurDwg();

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            pt1 = pt2 = Utils.Ge.kOrigin;    // initialize to make compiler happy

            PromptPointOptions prOpts = new PromptPointOptions("\nFirst extension line origin or RETURN to select");

            prOpts.AllowNone = true;

            PromptPointResult prPt1Res = ed.GetPoint(prOpts);

            // user wants to select a line to specify both points
            if (prPt1Res.Status == PromptStatus.None)
            {
                PromptEntityOptions prEntOpts = new PromptEntityOptions("\nSelect a LINE");
                prEntOpts.SetRejectMessage("\nSelected entity must be of type Line");
                prEntOpts.AddAllowedClass(typeof(Line), false);

                PromptEntityResult prEntRes = ed.GetEntity(prEntOpts);
                if (prEntRes.Status != PromptStatus.OK)
                {
                    return(prEntRes.Status);
                }

                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = m_db.TransactionManager;

                using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) {
                    Line line = (Line)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead);

                    pt1 = Utils.Db.WcsToUcs(line.StartPoint);
                    pt2 = Utils.Db.WcsToUcs(line.EndPoint);
                    tr.Commit();

                    return(PromptStatus.OK);
                }
            }
            else if (prPt1Res.Status == PromptStatus.OK)
            {
                PromptPointOptions prPt2Opts = new PromptPointOptions("\nSecond extension line origin");
                prPt2Opts.UseBasePoint = true;
                prPt2Opts.BasePoint    = prPt1Res.Value;
                PromptPointResult prPt2Res = ed.GetPoint(prPt2Opts);
                if (prPt2Res.Status != PromptStatus.OK)
                {
                    return(PromptStatus.Cancel);
                }

                pt1 = prPt1Res.Value;
                pt2 = prPt2Res.Value;
                return(prPt1Res.Status);
            }

            return(prPt1Res.Status);
        }
예제 #24
0
        private static void AddMLeader(Gem.Point2d pnt, Gem.Vector3d otstup,
                                       double scale, string layer,
                                       string mleaderStyleName, string str)
        {
            SettingsParser settings = SettingsParser.getInstance();

            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;
                Db.MLeader acML = new Db.MLeader();
                acML.SetDatabaseDefaults();
                acML.Layer        = layer;
                acML.MLeaderStyle = CheckLocalRepository.GetIDbyName <Db.MLeaderStyle>(acCurDb, mleaderStyleName);
                acML.ContentType  = Db.ContentType.MTextContent;
                Db.MText mText = new Db.MText();
                mText.SetDatabaseDefaults();
                mText.Contents           = str;
                mText.TextHeight         = scale;
                mText.BackgroundFill     = settings.MTextMask;
                mText.UseBackgroundColor = settings.MTextMask;


                if (settings.MTextMask)
                {
                    mText.BackgroundScaleFactor = settings.MTextMaskKoefficient;
                }

                mText.Location = (new Gem.Point3d(pnt.X, pnt.Y, 0) + otstup);
                acML.MText     = mText;
                int idx = acML.AddLeaderLine(new Gem.Point3d(pnt.X, pnt.Y, 0));

                acML.Scale = 1;


                acBlkTblRec.AppendEntity(acML);
                acTrans.AddNewlyCreatedDBObject(acML, true);
                acTrans.Commit();
            }
        }
예제 #25
0
        private static List <AcadGeo.Point3d> ParseLine(AcadDB.ObjectId id, List <AcadDB.ObjectId> ids)
        {
            List <AcadGeo.Point3d> pnts = new List <AcadGeo.Point3d>();

            using (AcadDB.Transaction tr = AcadFuncs.GetActiveDB().TransactionManager.StartTransaction())
            {
                AcadDB.Entity ent = tr.GetObject(id, AcadDB.OpenMode.ForRead) as AcadDB.Entity;
                if (!(ent is AcadDB.Line))
                {
                    return(pnts);
                }

                AcadDB.Line line = ent as AcadDB.Line;
                pnts.Add(line.StartPoint);
                pnts.Add(line.EndPoint);

                foreach (var tmp_id in ids)
                {
                    if (id == tmp_id)
                    {
                        continue;
                    }

                    AcadDB.Entity             tmp_ent          = tr.GetObject(tmp_id, AcadDB.OpenMode.ForRead) as AcadDB.Entity;
                    AcadGeo.Point3dCollection intersected_pnts = new AcadGeo.Point3dCollection();
                    line.IntersectWith(tmp_ent, AcadDB.Intersect.OnBothOperands, intersected_pnts, (IntPtr)0, (IntPtr)0);

                    for (int i = 0; i < intersected_pnts.Count; i++)
                    {
                        if (intersected_pnts[i].IsEqualTo(line.StartPoint) || intersected_pnts[i].IsEqualTo(line.EndPoint))
                        {
                            continue;
                        }

                        pnts.Add(intersected_pnts[i]);
                    }
                }
            }

            pnts.Sort((x, y) => x.DistanceTo(pnts.First()).CompareTo(y.DistanceTo(pnts.First())));
            pnts = pnts.Distinct().ToList();
            return(pnts);
        }
예제 #26
0
        /// <summary>
        /// This is Extension Method for the <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// class. It gets the name of the current space in the current Database.
        /// </summary>
        /// <param name="mng">Target <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// instance.</param>
        /// <returns>Returns the name of current space.</returns>
        public static String GetCurrentSpaceName(this Db.LayoutManager mng)
        {
            SpaceEnum space = GetCurrentSpaceEnum(mng);

            Db.Database db = cad.DocumentManager.MdiActiveDocument.Database;
            String      modelSpaceLocalizedName = String.Empty;

            using (Db.Transaction tr = db.TransactionManager.StartTransaction())
            {
                Db.BlockTable       bt  = tr.GetObject(db.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord btr = tr.GetObject(bt[Db.BlockTableRecord.ModelSpace], Db.OpenMode.ForRead)
                                          as Db.BlockTableRecord;
                modelSpaceLocalizedName = (tr.GetObject(btr.LayoutId, Db.OpenMode.ForRead) as Db.Layout).LayoutName;
            }
            String result = space == SpaceEnum.Viewport ?
                            "Model" as String : mng.CurrentLayout;

            return(result);
        }
        private void DeleteLayersWithPrefix(string prefix, AcadDb.Transaction tr)
        {
            // Open the Layer table for read
            var lyrTbl = (AcadDb.LayerTable)tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead);

            foreach (AcadDb.ObjectId layerId in lyrTbl)
            {
                AcadDb.LayerTableRecord layer = (AcadDb.LayerTableRecord)tr.GetObject(layerId, AcadDb.OpenMode.ForRead);
                string layerName = layer.Name;
                if (layerName.StartsWith(prefix))
                {
                    layer.UpgradeOpen();

                    // cannot delete current layer: swap current layer to default layer "0" if current layer is to be deleted
                    if (Doc.Database.Clayer == layerId)
                    {
                        var defaultLayerID = lyrTbl["0"];
                        Doc.Database.Clayer = defaultLayerID;
                    }
                    layer.IsLocked = false;

                    // delete all objects on this layer
                    // TODO: this is ugly! is there a better way to delete layer objs instead of looping through each one?
                    var bt = (AcadDb.BlockTable)tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead);
                    foreach (var btId in bt)
                    {
                        var block = (AcadDb.BlockTableRecord)tr.GetObject(btId, AcadDb.OpenMode.ForRead);
                        foreach (var entId in block)
                        {
                            var ent = (AcadDb.Entity)tr.GetObject(entId, AcadDb.OpenMode.ForRead);
                            if (ent.Layer == layerName)
                            {
                                ent.UpgradeOpen();
                                ent.Erase();
                            }
                        }
                    }

                    layer.Erase();
                }
            }
        }
예제 #28
0
        public override List <string> GetObjectsInView() // TODO: this returns all visible doc objects. handle views later.
        {
            var objs = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.BlockTable       blckTbl     = tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead) as AcadDb.BlockTable;
                AcadDb.BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[AcadDb.BlockTableRecord.ModelSpace], AcadDb.OpenMode.ForRead) as AcadDb.BlockTableRecord;
                foreach (AcadDb.ObjectId id in blckTblRcrd)
                {
                    var dbObj = tr.GetObject(id, AcadDb.OpenMode.ForRead);
                    if (dbObj.Visible())
                    {
                        objs.Add(dbObj.Handle.ToString());
                    }
                }
                tr.Commit();
            }
            return(objs);
        }
        public override List <ISelectionFilter> GetSelectionFilters()
        {
            var layers = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.LayerTable lyrTbl = tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead) as AcadDb.LayerTable;
                foreach (AcadDb.ObjectId objId in lyrTbl)
                {
                    AcadDb.LayerTableRecord lyrTblRec = tr.GetObject(objId, AcadDb.OpenMode.ForRead) as AcadDb.LayerTableRecord;
                    layers.Add(lyrTblRec.Name);
                }
                tr.Commit();
            }
            return(new List <ISelectionFilter>()
            {
                new ListSelectionFilter {
                    Name = "Layers", Icon = "Filter", Description = "Selects objects based on their layers.", Values = layers
                }
            });
        }
예제 #30
0
        //public  void GetLengedPoints(T model)
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    ObjectIdCollection ids = new ObjectIdCollection();

        //    PromptSelectionResult ProSset = null;
        //    TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, MethodCommand.LegendLayer)};
        //    SelectionFilter sfilter = new SelectionFilter(filList);
        //    LayoutManager layoutMgr = LayoutManager.Current;

        //   string ss= layoutMgr.CurrentLayout;
        //    ProSset = doc.Editor.SelectAll(sfilter);
        ////  List<ObjectId> idss=  GetEntitiesInModelSpace();
        //    Database db = doc.Database;
        //    if (ProSset.Status == PromptStatus.OK)
        //    {
        //        using (Transaction tran = db.TransactionManager.StartTransaction())
        //        {
        //            SelectionSet sst = ProSset.Value;

        //            ObjectId[] oids = sst.GetObjectIds();
        //            model.LegendList = new Dictionary<int, List<System.Drawing.PointF>>();
        //            int ad = 0;
        //            List<string> aa = new List<string>();
        //            LayerModel lm = new LayerModel();
        //            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
        //            foreach (ObjectId layerId in lt)
        //            {
        //                LayerTableRecord ltr = (LayerTableRecord)tran.GetObject(layerId, OpenMode.ForRead);
        //                if (ltr.Name == MethodCommand.LegendLayer)
        //                {
        //                    lm.Color =  System.Drawing.ColorTranslator.ToHtml(ltr.Color.ColorValue);
        //                }
        //            }
        //            for (int i = 0; i < oids.Length; i++)
        //            {
        //              //  if (idss.Contains(oids[i]))
        //              //  {
        //                    DBObject ob = tran.GetObject(oids[i], OpenMode.ForRead);
        //                if (!aa.Contains((ob as Polyline).BlockName)) { aa.Add((ob as Polyline).BlockName); }
        //                    if (ob is Polyline&&(ob as Polyline).BlockName.ToLower()== "*model_space")
        //                    {
        //                        lengedList.Add(ob as Polyline);
        //                        model.LegendList.Add(ad,PolylineMethod.GetPolyLineInfoPt(ob as Polyline));
        //                        ad++;
        //                    }
        //               // }


        //            }
        //            model.allLines = new List<LayerModel>();

        //            model.allLines.Add(lm);
        //        }
        //    }


        //}

        public List <Autodesk.AutoCAD.DatabaseServices.ObjectId> GetEntitiesInModelSpace()
        {
            List <Autodesk.AutoCAD.DatabaseServices.ObjectId> objects = new List <Autodesk.AutoCAD.DatabaseServices.ObjectId>();

            using (Autodesk.AutoCAD.DatabaseServices.Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
            {
                Autodesk.AutoCAD.DatabaseServices.BlockTable blockTable =
                    (Autodesk.AutoCAD.DatabaseServices.BlockTable)transaction.GetObject(
                        Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.WorkingDatabase.BlockTableId,
                        Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                Autodesk.AutoCAD.DatabaseServices.BlockTableRecord blockTableRecord =
                    (Autodesk.AutoCAD.DatabaseServices.BlockTableRecord)transaction.GetObject(
                        blockTable[Autodesk.AutoCAD.DatabaseServices.BlockTableRecord.ModelSpace],
                        Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                foreach (Autodesk.AutoCAD.DatabaseServices.ObjectId objId in blockTableRecord)
                {
                    objects.Add(objId);
                }
                transaction.Commit();
            }
            return(objects);
        }