コード例 #1
0
        /// <summary>
        /// Экспорт блока в файл - файл в корне текущего чертежа с именем блока.
        /// Точка вставки блока - 0,0
        /// </summary>
        public void ExportToFile()
        {
            using (var db = new Autodesk.AutoCAD.DatabaseServices.Database(true, true))
            {
                db.CloseInput(true);

                var ids  = new ObjectIdCollection(new[] { IdBlRef });
                var idMS = SymbolUtilityServices.GetBlockModelSpaceId(db);

                using (IdMapping map = new IdMapping())
                {
                    db.WblockCloneObjects(ids, idMS, map, DuplicateRecordCloning.Replace, false);
                    // перенос блока в ноль
                    var idBlRefMap = map[IdBlRef].Value;
                    if (!idBlRefMap.IsNull)
                    {
                        using (var t = db.TransactionManager.StartTransaction())
                        {
                            var blRef = idBlRefMap.GetObject(OpenMode.ForWrite, false, true) as BlockReference;
                            blRef.Position = Point3d.Origin;

                            // Изменение вида
                            if (blRef.Bounds.HasValue)
                            {
                                try
                                {
                                    zoomDb(db, blRef.Bounds.Value);
                                    // Перенос штриховки на задний план
                                    var btrApart = blRef.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;
                                    var orders   = btrApart.DrawOrderTableId.GetObject(OpenMode.ForWrite) as DrawOrderTable;
                                    var idsHatch = new ObjectIdCollection();
                                    foreach (var idEnt in btrApart)
                                    {
                                        if (idEnt.ObjectClass == RXClass.GetClass(typeof(Hatch)))
                                        {
                                            idsHatch.Add(idEnt);
                                        }
                                    }
                                    if (idsHatch.Count > 0)
                                    {
                                        orders.MoveToBottom(idsHatch);
                                    }
                                    // Превью чертежа из блока квартиры
                                    db.ThumbnailBitmap = new Bitmap(btrApart.PreviewIcon, new Size(320, 270));
                                }
                                catch { }
                            }
                            t.Commit();
                        }
                        db.SaveAs(File, DwgVersion.Current);
                    }
                }
                //Inspector.AddError($"Экспортирован блок {Name} в файл {File}", IdBlRef, icon: System.Drawing.SystemIcons.Information);
            }
        }
コード例 #2
0
        public static void PurgeDgnLinetypesExt()
        {
            var doc =
                Application.DocumentManager.MdiActiveDocument;
            var ed = doc.Editor;

            var pofo = new PromptOpenFileOptions("\nSelect file to purge");

            // Use the command-line version if FILEDIA is 0 or
            // CMDACTIVE indicates we're being called from a script
            // or from LISP

            short fd = (short)Application.GetSystemVariable("FILEDIA");
            short ca = (short)Application.GetSystemVariable("CMDACTIVE");

            pofo.PreferCommandLine = (fd == 0 || (ca & 36) > 0);
            pofo.Filter            = "DWG (*.dwg)|*.dwg|All files (*.*)|*.*";

            // Ask the user to select a DWG file to purge

            var pfnr = ed.GetFileNameForOpen(pofo);

            if (pfnr.Status == PromptStatus.OK)
            {
                // Make sure the file exists
                // (it should unless entered via the command-line)

                if (!File.Exists(pfnr.StringResult))
                {
                    ed.WriteMessage(
                        "\nCould not find file: \"{0}\".",
                        pfnr.StringResult
                        );
                    return;
                }

                try
                {
                    // We'll just suffix the selected filename with "-purged"
                    // for the output location. This file will be overwritten
                    // if the command is called multiple times

                    var output =
                        Path.GetDirectoryName(pfnr.StringResult) + "\\" +
                        Path.GetFileNameWithoutExtension(pfnr.StringResult) +
                        "-purged" +
                        Path.GetExtension(pfnr.StringResult);

                    // Assume a post-R12 drawing

                    using (var db = new ACADDB.Database(false, true))
                    {
                        // Read the DWG file into our Database object

                        db.ReadDwgFile(
                            pfnr.StringResult,
                            FileOpenMode.OpenForReadAndReadShare,
                            false,
                            ""
                            );

                        // No graphical changes, so we can keep the preview
                        // bitmap

                        db.RetainOriginalThumbnailBitmap = true;

                        // We'll store the current working database, to reset
                        // after the purge operation

                        var wdb = HostApplicationServices.WorkingDatabase;
                        HostApplicationServices.WorkingDatabase = db;

                        // Purge unused DGN linestyles from the drawing
                        // (returns false if nothing is erased)

                        if (PurgeDgnLinetypesInDb(db, ed))
                        {
                            // Check the version of the drawing to save back to

                            var ver =
                                (db.LastSavedAsVersion == DwgVersion.MC0To0
                                    ? DwgVersion.Current
                                    : db.LastSavedAsVersion
                                );

                            // Now we can save

                            db.SaveAs(output, ver);

                            ed.WriteMessage(
                                "\nSaved purged file to \"{0}\".",
                                output
                                );
                        }

                        // Still need to reset the working database

                        HostApplicationServices.WorkingDatabase = wdb;
                    }
                }
                catch (ACADRT.Exception ex)
                {
                    ed.WriteMessage("\nException: {0}", ex.Message);
                }
            }
        }
コード例 #3
0
        public static void LoadandProcessPolys()
        {
            using (DatabaseCommands commands = new DatabaseCommands())
            {
                var TemplatePath = commands.GetTemplatePath();

                #region Get Dwgs to Process

                var dwgs = commands.LoadandProcessPolys();

                if (dwgs == null)
                {
                    throw new ArgumentNullException(nameof(dwgs));
                }
                IList <DrawingStack> DwDrawingStacks = new List <DrawingStack>();
                foreach (var dwg in dwgs)
                {
                    if (DwDrawingStacks != null)
                    {
                        DwDrawingStacks.Add(dwg);
                    }
                }

                #endregion

                GDwgPath   = commands.GetGlobalDWGPath();
                GCloudPath = commands.GetGlobalPointCloudPath();



                foreach (DrawingStack dwg in DwDrawingStacks)
                {
                    m_PolylineChildren.Clear();
                    var      acDocMgr = ACAD.Application.DocumentManager;
                    Document acNewDoc = null;
                    Document acDoc    = ACAD.Application.DocumentManager.MdiActiveDocument;

                    if (acDocMgr.Count == 1)
                    {
                        acNewDoc = acDocMgr.Add(TemplatePath);
                        using (acDocMgr.MdiActiveDocument.LockDocument())
                        {
                            acDocMgr.MdiActiveDocument = acDoc;
                            acDocMgr.CurrentDocument.CloseAndDiscard();
                            acDocMgr.MdiActiveDocument = acNewDoc;
                        }
                    }

                    using (acDocMgr.MdiActiveDocument.LockDocument())
                    {
                        if (acDoc != null)

                        {
                            ACADDB.Database acDbNewDoc = acNewDoc.Database;

                            //var ed = doc.Editor;

                            string gpath = Convert.ToString(GDwgPath);

                            if (gpath != null)
                            {
                                string path = Path.Combine(gpath, dwg.PolylineDwgName);

                                if (path == null)
                                {
                                    throw new ArgumentNullException(nameof(path));
                                }


                                if (!File.Exists(path))
                                {
                                    DatabaseLogs.FormatLogs("File Not Found", path);
                                    return;
                                }

                                try
                                {
                                    using (ACADDB.Database db = new ACADDB.Database(false, true))
                                    {
                                        // Read the DWG file into our Database object

                                        db.ReadDwgFile(
                                            path,
                                            ACADDB.FileOpenMode.OpenForReadAndReadShare,
                                            false,
                                            ""
                                            );

                                        // No graphical changes, so we can keep the preview
                                        // bitmap

                                        db.RetainOriginalThumbnailBitmap = true;

                                        // We'll store the current working database, to reset
                                        // after the purge operation

                                        var wdb = ACADDB.HostApplicationServices.WorkingDatabase;
                                        ACADDB.HostApplicationServices.WorkingDatabase = db;

                                        // Purge unused DGN linestyles from the drawing
                                        // (returns false if nothing is erased)
                                        collection = Process.GetIdsByTypeTypeValue(
                                            "POLYLINE", "LWPOLYLINE", "POLYLINE2D", "POLYLINE3d");
                                        NumberofPolylines = collection.Count;
                                        Process.CopyPolylinesBetweenDatabases(db, collection);

                                        // Still need to reset the working database
                                        datetime = (DateTime)dwg.DateStamp;
                                        ACADDB.HostApplicationServices.WorkingDatabase = wdb;

                                        string output = SetOutPutFolder(dwg, commands);

                                        // PLineToLayers.ProcessLayers(collection, wdb);
                                        string fileName = System.IO.Path.GetFileNameWithoutExtension(dwg.PolylineDwgName);
                                        outdxf = Path.Combine(output, String.Format("{0}{1}", fileName, ".dxf"));
                                        outdwg = Path.Combine(output, dwg.PolylineDwgName);
                                        collection.Clear();
                                        //Before Simplification Create Breakline Data
                                        OriginalCollection =
                                            RefreshSelectionOfPolylines(collection);

                                        m_PolylineChildren = CreatePolylineChildren(OriginalCollection);
                                    }
                                }
                                catch (Exception e)
                                {
                                    DatabaseLogs.FormatLogs("Exception: {0}", e.Message);
                                }
                            }
                        }
                    }

                    PGA.SimplifyPolylines.Commands.SimplifyPolylines();

                    using (acDocMgr.MdiActiveDocument.LockDocument())
                    {
                        try
                        {
                            Document        acDocument = ACAD.Core.Application.DocumentManager.MdiActiveDocument;
                            ACADDB.Database acDbNewDoc = acDocument.Database;
                            // if (collection != null) collection.Clear();
                            //collection = RefreshSelectionOfPolylines(collection);
                            collection        = OriginalCollection;
                            NumberofPolylines = collection.Count;

                            //Check Polyline Count

                            //Change Layer Names
                            AssignNames.ChangeLayers();

                            // collection.Clear();
                            // get the copied collection of this drawing
                            ///collection = RefreshSelectionOfPolylines(collection);

                            //NumberofPolylines = collection.Count;
                            //Get the Distinct LIDAR Points
                            //var p3d = ProcessLidarFile(
                            //    PlineToPoints(collection), datetime, dwg.Hole.ToString());
                            var lidarFile = RetrieveLidarFile(datetime, dwg.Hole.ToString());

                            //Get the Nearest Neighbor to add to Point Set
                            var neighbors = IncludeIntersectingNeighbor(lidarFile, OriginalCollection);
                            Point3dCollection totalpoints = MergePoint3DCollections(lidarFile, neighbors);
                            var p5d = ProcessLidarFile(
                                PlineToPoints(collection), datetime, dwg.Hole.ToString(), totalpoints);
                            //var p5d = ProcessLidarFileSubtractRegions(
                            //  PlineToPoints(collection), datetime, dwg.Hole.ToString(), totalpoints,collection);


                            //Insert into DB

                            InsertPointCloudToDB(dwg, datetime, p5d, PlineToPoints(collection));

                            //Create all the Distinct surfaces
                            CreateTinForDistinctSurfaces(p5d, collection);

                            acDbNewDoc.SaveAs(outdwg, ACADDB.DwgVersion.Current);
                            acDbNewDoc.DxfOut(outdxf, 16, ACADDB.DwgVersion.Current);
                        }
                        catch (ACADRT.Exception ex)
                        {
                            DatabaseLogs.FormatLogs("Exception: {0}", ex.Message);
                        }
                    }
                }
            }
        }
コード例 #4
0
ファイル: PostAudit.cs プロジェクト: dsb6063/TOUR-2018.V18.0
        private void DeletePoly2D3DObjects(string source, string dest, string drawingName)
        {
            bool eraseOrig = true;

            try
            {
                if (drawingName == null)
                {
                    throw new ArgumentNullException(nameof(drawingName));
                }

                _logger.AddLog(String.Format("Drawing to Open: {0}", source));


                Autodesk.AutoCAD.DatabaseServices.Database oldDb = HostApplicationServices.WorkingDatabase;

                using (Autodesk.AutoCAD.DatabaseServices.Database db =
                           new Autodesk.AutoCAD.DatabaseServices.Database(false, true))
                {
                    db.ReadDwgFile(source, FileOpenMode.OpenForReadAndWriteNoShare, true, null);

                    db.CloseInput(true);

                    HostApplicationServices.WorkingDatabase = db;

                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        // Collect our exploded objects in a single collection
                        var selected = BBC.Common.AutoCAD.AcadUtilities.
                                       GetAllObjectIdsInModel(db, false);

                        DBObjectCollection objs = new DBObjectCollection();

                        // Loop through the selected objects

                        foreach (ObjectId so in selected)
                        {
                            // Open one at a time

                            Entity ent =
                                (Entity)tr.GetObject(
                                    so,
                                    OpenMode.ForRead
                                    );
                            ;

                            if (ent.GetType() == typeof(Polyline3d) ||
                                ent.GetType() == typeof(Polyline2d) ||
                                ent.GetType() == typeof(Acad.Polyline) ||
                                ent.GetType() == typeof(Line))
                            {
                                if (eraseOrig)
                                {
                                    ent.UpgradeOpen();
                                    ent.Erase();
                                }
                            }
                        }
                        tr.Commit();
                    }

                    var output = Path.Combine(_sdir, "S-" + drawingName + ".DWG");
                    var dxfout = output.Replace(".DWG", ".DXF");
                    db.SaveAs(output, DwgVersion.Current);

                    HostApplicationServices.WorkingDatabase = oldDb;

                    db.DxfOut(dxfout, 16, DwgVersion.Current);
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }