/// <summary>
 /// преобразование панеелей
 /// </summary>
 public void ConvertBtr()
 {
     ProgressMeter progress = new ProgressMeter();
     progress.SetLimit(PanelsBtrExport.Count);
     progress.Start("Преобразование блоков панелей в экспортированном файле");
     // Преобразования определений блоков панелей
     foreach (var panelBtr in PanelsBtrExport)
     {
         progress.MeterProgress();
         if (HostApplicationServices.Current.UserBreak())
             throw new System.Exception("Отменено пользователем.");
         try
         {
             panelBtr.ConvertBtr();
             if (!string.IsNullOrEmpty(panelBtr.ErrMsg))
             {
                 Inspector.AddError(panelBtr.ErrMsg, panelBtr.Panels.First().Extents, panelBtr.Panels.First().IdBlRefAkr,
                    icon: System.Drawing.SystemIcons.Error);
             }
         }
         catch (System.Exception ex)
         {
             Inspector.AddError($"Ошибка конвертации блока панели - {ex.Message}", icon: System.Drawing.SystemIcons.Error);
             //Logger.Log.Error(ex, "Ошибка конвертиации экспортрированного блока панели");
         }
     }
     progress.Stop();
 }
Пример #2
0
        public static void CreateFacades(List<FacadeMounting> facades)
        {
            // Создание фасадов по монтажным планам
            if (facades.Count == 0) return;

            // Определение высот этажей по загруженным блокам панелей
            DefineStoreyHeight(facades);

            Database db = HostApplicationServices.WorkingDatabase;
            checkLayers(db);
            using (var t = db.TransactionManager.StartTransaction())
            {
                var ms = SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForWrite) as BlockTableRecord;
                //double yFirstFloor = getFirstFloorY(facades); // Y для первых этажей всех фасадов

                ProgressMeter progress = new ProgressMeter();

                progress.SetLimit(facades.SelectMany(f => f.Panels).Count());
                progress.Start("Создание фасадов");

                foreach (var facade in facades)
                {
                    //double yFloor = yFirstFloor;
                    foreach (var panelSb in facade.Panels)
                    {
                        double yFloor = panelSb.Y;
                        // Подпись номера этажа
                        captionFloor(facade.XMin, yFloor, panelSb.Floor, ms, t);
                        if (panelSb.PanelAkr != null || panelSb.PanelBase != null)
                        {
                            Point3d ptPanelAkr = new Point3d(panelSb.ExtTransToModel.MinPoint.X, yFloor, 0);
                            //testGeom(panelSb, facade, floor, yFloor, t, ms);
                            ObjectId idBtrPanelAkr;
                            if (panelSb.PanelBase != null)
                            {
                                if (panelSb.PanelBase.IdBtrPanel.IsNull) continue;
                                idBtrPanelAkr = panelSb.PanelBase.IdBtrPanel;
                            }
                            else
                            {
                                idBtrPanelAkr = panelSb.PanelAkr.IdBtrPanelAkrInFacade;
                            }

                            var blRefPanelAkr = new BlockReference(ptPanelAkr, idBtrPanelAkr);
                            blRefPanelAkr.Layer = panelSb.Floor.Storey.Layer;
                            ms.AppendEntity(blRefPanelAkr);
                            t.AddNewlyCreatedDBObject(blRefPanelAkr, true);
                            //blRefPanelAkr.RecordGraphicsModified(true);
                            //blRefPanelAkr.Draw();
                        }
                        progress.MeterProgress();
                    }
                }
                t.Commit();
                progress.Stop();
            }
        }
Пример #3
0
        public void CloseAndDelete(List<PanelAKR> panelsToDelete)
        {
            string file = dbLib.Filename;
            try
            {
                dbLib.Dispose();
            }
            catch { }
            File.Delete(file);

            // Удаление блоков
            if (panelsToDelete != null && panelsToDelete.Count > 0)
            {
                // Сделать копию библиотеки
                PanelLibrarySaveService.BackUpLibPanelsFile();

                using (ProgressMeter progress = new ProgressMeter())
                {
                    progress.SetLimit(panelsToDelete.Count);
                    progress.Start($"Удаление {panelsToDelete.Count} панелей из библиотеки...");

                    using (var db = new Database(false, true))
                    {
                        db.ReadDwgFile(PanelLibrarySaveService.LibPanelsFilePath, FileShare.None, true, "");
                        db.CloseInput(true);

                        using (var t = db.TransactionManager.StartTransaction())
                        {
                            var bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;

                            foreach (var item in panelsToDelete)
                            {
                                if (bt.Has(item.BlName))
                                {
                                    var idPanelAkr = bt[item.BlName];
                                    var dbo = idPanelAkr.GetObject(OpenMode.ForWrite);
                                    try
                                    {
                                        dbo.Erase();
                                        progress.MeterProgress();
                                    }
                                    catch { };
                                }
                            }
                            t.Commit();
                        }
                        db.SaveAs(PanelLibrarySaveService.LibPanelsFilePath, DwgVersion.Current);
                    }
                    Logger.Log.Error ($"Удалены панели АКР из библиотеки - {panelsToDelete.Count}шт.: {string.Join(", ",panelsToDelete)}");
                    progress.Stop();
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Получение списка квартир в базе
        /// </summary>
        public static List<Apartment> GetAll()
        {
            // Преобразование квартир в базе в объекты Apartment
            List<Apartment> apartments = new List<Apartment>();
            using (var entities = BaseApartments.ConnectEntities())
            {
                entities.F_R_Flats.Load();

                using (var progress = new ProgressMeter())
                {
                    progress.SetLimit(entities.F_R_Flats.Local.Count);
                    progress.Start("Считывание квартир из базы...");

                    var flatsLastRev = entities.F_R_Flats.Local.GroupBy(g => g.WORKNAME).Select(f => f.MaxBy(r => r.REVISION)).ToList();
                    foreach (var flatEnt in flatsLastRev)
                    {
                        progress.MeterProgress();

                        Apartment apart = new Apartment(flatEnt);
                        apartments.Add(apart);

                        //Все модули в квартире
                        var fmsLastModRev = flatEnt.F_nn_FlatModules.GroupBy(fm => fm.F_R_Modules.NAME_MODULE)
                                             .Select(m => m.MaxBy(r => r.F_R_Modules.REVISION)).ToList();

                        foreach (var fmEnt in fmsLastModRev)
                        {
                            Module module = new Module(fmEnt, apart);

                            // Елементы в модуле
                            var emsEnt = fmEnt.F_R_Modules.F_nn_Elements_Modules.ToList();
                            foreach (var emEnt in emsEnt)
                            {
                                // Создание элемента из элемента базы базы
                                Element elem = ElementFactory.CreateElementDB(module, emEnt);
                            }
                            // Для дверей определение элемента стены
                            var doors = module.Elements.OfType<DoorElement>();
                            foreach (var door in doors)
                            {
                                door.SearchHostWallDB(fmEnt.F_R_Modules);
                            }
                        }
                    }
                    progress.Stop();
                }
            }
            return apartments;
        }
Пример #5
0
        // Открытие и печать всех файлов в папке
        public void PlotDir(string dir)
        {
            var dirInfo = new DirectoryInfo(dir);
             var filesDwg = dirInfo.GetFiles("*.dwg", SearchOption.TopDirectoryOnly);
             Database dbOrig = HostApplicationServices.WorkingDatabase;

             if (!Application.DocumentManager.DocumentActivationEnabled)
            Application.DocumentManager.DocumentActivationEnabled = true;

             ProgressMeter progressMeter = new ProgressMeter();
             progressMeter.SetLimit(filesDwg.Count());
             progressMeter.Start("Печать всех файлов в папке " + dir);

             int i = 0;
             foreach (var fileDwg in filesDwg)
             {
            if (_isCancelPublish || HostApplicationServices.Current.UserBreak())
               break;

            Document docOpen;
            progressMeter.MeterProgress();
            if (!isAlreadyOpenDoc(fileDwg.FullName, out docOpen))
            {
               docOpen = Application.DocumentManager.Open(fileDwg.FullName);
            }
            Application.DocumentManager.MdiActiveDocument = docOpen;
            HostApplicationServices.WorkingDatabase = docOpen.Database;
            try
            {
               using (var lockDoc = docOpen.LockDocument())
               {
                  //MultiSheetPlot(Path.GetDirectoryName(docOpen.Name));
                  MultiSheetPlot(string.Format("Печать {0} из {1} файлов в папке {2}", i++, filesDwg.Length, dirInfo.Name));
               }
            }
            catch (System.Exception ex)
            {
               Logger.Log.Error(ex, "MultiSheetPlot()");
            }
            finally
            {
               docOpen.CloseAndDiscard();
               HostApplicationServices.WorkingDatabase = dbOrig;
            }
             }
             progressMeter.Stop();
        }
Пример #6
0
        public void WriteXYZ(ObjectId[] pointIDs)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(pointIDs.Length);
            progressMeter.Start("Writing XYZ");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), Conversions.GetUCS());
                int    num  = 0;
                int    num2 = 0;
                string a    = this.method_6();
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    using (StreamWriter streamWriter = new StreamWriter(IO.string_5))
                    {
                        streamWriter.WriteLine(string.Concat(new object[]
                        {
                            "C ",
                            IO.string_5,
                            " generated ",
                            DateTime.Now
                        }));
                        if (a == ",")
                        {
                            streamWriter.WriteLine("C Format: x, y, z,");
                        }
                        if (a == ";")
                        {
                            streamWriter.WriteLine("C Format: x; y; z;");
                        }
                        if (a == " ")
                        {
                            streamWriter.WriteLine("C Format: x  y  z");
                        }
                        for (int i = 0; i < pointIDs.Length; i++)
                        {
                            DBPoint dBPoint = (DBPoint)transaction.GetObject(pointIDs[i], (OpenMode)0, true);
                            ngeometry.VectorGeometry.Point point = new ngeometry.VectorGeometry.Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                            coordinateTransformator.Transform(point);
                            string text = this.method_5(point, ref num);
                            streamWriter.WriteLine(text.TrimEnd(new char[0]));
                            progressMeter.MeterProgress();
                            messageFilter.CheckMessageFilter((long)i, 10000);
                            num2++;
                        }
                        streamWriter.Flush();
                    }
                }
                progressMeter.Stop();
                if (num > 0)
                {
                    editor.WriteMessage(string.Concat(new object[]
                    {
                        Environment.NewLine,
                        num,
                        " conversion errors occurred writing ",
                        IO.string_5,
                        ". Increase the column width and/or decrease the number of decimal digits."
                    }));
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Concat(new object[]
                    {
                        num,
                        " conversion errors occurred writing ",
                        IO.string_5,
                        ".\nIncrease the column width and/or decrease the number of decimal digits."
                    }));
                }
                FileInfo fileInfo = new FileInfo(IO.string_5);
                editor.WriteMessage(Environment.NewLine + "Output file name            : " + fileInfo.FullName);
                editor.WriteMessage(Environment.NewLine + "Number of points written    : " + num2.ToString());
                editor.WriteMessage(Environment.NewLine + "Coordinate conversion errors: " + num.ToString());
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #7
0
        private void method_3(ObjectId[] objectId_0)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Writing 3df");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), Conversions.GetUCS());
                int    num  = 0;
                int    num2 = 0;
                string text = this.method_6();
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    using (StreamWriter streamWriter = new StreamWriter(IO.string_2))
                    {
                        streamWriter.WriteLine(string.Concat(new object[]
                        {
                            "C ",
                            IO.string_2,
                            " generated ",
                            DateTime.Now
                        }));
                        if (text == ",")
                        {
                            streamWriter.WriteLine("C Format: Layer name, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4");
                        }
                        if (text == ";")
                        {
                            streamWriter.WriteLine("C Format: Layer name; x1; y1; z1; x2; y2; z2; x3; y3; z3; x4; y4; z4");
                        }
                        if (text == " ")
                        {
                            streamWriter.WriteLine("C Format: Layer name  x1  y1  z1  x2  y2  z2  x3  y3  z3  x4  y4  z4");
                        }
                        for (int i = 0; i < objectId_0.Length; i++)
                        {
                            Autodesk.AutoCAD.DatabaseServices.Face face = (Autodesk.AutoCAD.DatabaseServices.Face)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            Point3d vertexAt  = face.GetVertexAt(0);
                            Point3d vertexAt2 = face.GetVertexAt(1);
                            Point3d vertexAt3 = face.GetVertexAt(2);
                            Point3d vertexAt4 = face.GetVertexAt(3);
                            ngeometry.VectorGeometry.Point point  = new ngeometry.VectorGeometry.Point(vertexAt.X, vertexAt.Y, vertexAt.Z);
                            ngeometry.VectorGeometry.Point point2 = new ngeometry.VectorGeometry.Point(vertexAt2.X, vertexAt2.Y, vertexAt2.Z);
                            ngeometry.VectorGeometry.Point point3 = new ngeometry.VectorGeometry.Point(vertexAt3.X, vertexAt3.Y, vertexAt3.Z);
                            ngeometry.VectorGeometry.Point point4 = new ngeometry.VectorGeometry.Point(vertexAt4.X, vertexAt4.Y, vertexAt4.Z);
                            coordinateTransformator.Transform(point);
                            coordinateTransformator.Transform(point2);
                            coordinateTransformator.Transform(point3);
                            coordinateTransformator.Transform(point4);
                            string text2 = face.Layer.PadLeft(IO.int_0) + text;
                            text2 += this.method_5(point, ref num);
                            text2 += this.method_5(point2, ref num);
                            text2 += this.method_5(point3, ref num);
                            text2 += this.method_5(point4, ref num);
                            streamWriter.WriteLine(text2.TrimEnd(new char[0]));
                            progressMeter.MeterProgress();
                            messageFilter.CheckMessageFilter((long)i, 10000);
                            num2++;
                        }
                        streamWriter.Flush();
                    }
                }
                progressMeter.Stop();
                if (num > 0)
                {
                    editor.WriteMessage(string.Concat(new object[]
                    {
                        Environment.NewLine,
                        num,
                        " conversion errors occurred writing ",
                        IO.string_2,
                        ". Increase the column width and/or decrease the number of decimal digits."
                    }));
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Concat(new object[]
                    {
                        num,
                        " conversion errors occurred writing ",
                        IO.string_2,
                        ".\nIncrease the column width and/or decrease the number of decimal digits."
                    }));
                }
                FileInfo fileInfo = new FileInfo(IO.string_2);
                editor.WriteMessage(Environment.NewLine + "Output file name            : " + fileInfo.FullName);
                editor.WriteMessage(Environment.NewLine + "Number of faces written     : " + num2.ToString());
                editor.WriteMessage(Environment.NewLine + "Coordinate conversion errors: " + num.ToString());
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #8
0
        private void method_1(ObjectId[] objectId_0)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            EntityList    entityList      = new EntityList();
            int           num             = 0;
            int           num2            = 0;
            int           num3            = 0;
            int           num4            = 0;
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Serializing XML entities");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), Conversions.GetUCS());
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    LayerTable arg_83_0 = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0);
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        messageFilter.CheckMessageFilter((long)i, 10000);
                        progressMeter.MeterProgress();
                        Entity entity = (Entity)transaction.GetObject(objectId_0[i], (OpenMode)0);
                        string name   = ((LayerTableRecord)transaction.GetObject(entity.LayerId, (OpenMode)0)).Name;
                        Autodesk.AutoCAD.DatabaseServices.Face face = entity as Autodesk.AutoCAD.DatabaseServices.Face;
                        if (face != null)
                        {
                            Point3d vertexAt  = face.GetVertexAt(0);
                            Point3d vertexAt2 = face.GetVertexAt(1);
                            Point3d vertexAt3 = face.GetVertexAt(2);
                            Point3d vertexAt4 = face.GetVertexAt(3);
                            global::TerrainComputeC.XML.Vertex v     = new global::TerrainComputeC.XML.Vertex(vertexAt.X, vertexAt.Y, vertexAt.Z);
                            global::TerrainComputeC.XML.Vertex v2    = new global::TerrainComputeC.XML.Vertex(vertexAt2.X, vertexAt2.Y, vertexAt2.Z);
                            global::TerrainComputeC.XML.Vertex v3    = new global::TerrainComputeC.XML.Vertex(vertexAt3.X, vertexAt3.Y, vertexAt3.Z);
                            global::TerrainComputeC.XML.Vertex v4    = new global::TerrainComputeC.XML.Vertex(vertexAt4.X, vertexAt4.Y, vertexAt4.Z);
                            global::TerrainComputeC.XML.Face   face2 = new global::TerrainComputeC.XML.Face(v, v2, v3, v4);
                            face2.SetProperties(name, face.Color.ColorIndex);
                            entityList.Faces.Add(face2);
                            coordinateTransformator.Transform(face2);
                            num4++;
                        }
                        else
                        {
                            DBPoint dBPoint = entity as DBPoint;
                            if (dBPoint != null)
                            {
                                global::TerrainComputeC.XML.Point point = new global::TerrainComputeC.XML.Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                                point.SetProperties(name, dBPoint.Color.ColorIndex);
                                entityList.Points.Add(point);
                                coordinateTransformator.Transform(point);
                                num++;
                            }
                            else
                            {
                                Autodesk.AutoCAD.DatabaseServices.Line line = entity as Autodesk.AutoCAD.DatabaseServices.Line;
                                if (line != null)
                                {
                                    Point3d startPoint = line.StartPoint;
                                    Point3d endPoint   = line.EndPoint;
                                    global::TerrainComputeC.XML.Vertex startVertex = new global::TerrainComputeC.XML.Vertex(startPoint.X, startPoint.Y, startPoint.Z);
                                    global::TerrainComputeC.XML.Vertex endVertex   = new global::TerrainComputeC.XML.Vertex(endPoint.X, endPoint.Y, endPoint.Z);
                                    global::TerrainComputeC.XML.Line   line2       = new global::TerrainComputeC.XML.Line(startVertex, endVertex);
                                    line2.SetProperties(name, line.Color.ColorIndex);
                                    entityList.Lines.Add(line2);
                                    coordinateTransformator.Transform(line2);
                                    num2++;
                                }
                                else
                                {
                                    Polyline   polyline   = entity as Polyline;
                                    Polyline2d polyline2d = entity as Polyline2d;
                                    Polyline3d polyline3d = entity as Polyline3d;
                                    if (polyline != null || polyline2d != null || polyline3d != null)
                                    {
                                        short colorIndex = 256;
                                        if (polyline != null)
                                        {
                                            colorIndex = polyline.Color.ColorIndex;
                                        }
                                        if (polyline2d != null)
                                        {
                                            colorIndex = polyline2d.Color.ColorIndex;
                                        }
                                        if (polyline3d != null)
                                        {
                                            colorIndex = polyline3d.Color.ColorIndex;
                                        }
                                        PointSet pointSet = PointGeneration.SubdividePolyline(entity, transaction, 0.0);
                                        List <global::TerrainComputeC.XML.Vertex> list = new List <global::TerrainComputeC.XML.Vertex>();
                                        for (int j = 0; j < pointSet.Count; j++)
                                        {
                                            list.Add(new global::TerrainComputeC.XML.Vertex(pointSet[j].X, pointSet[j].Y, pointSet[j].Z));
                                        }
                                        PolyLine polyLine = new PolyLine(list);
                                        polyLine.SetProperties(name, colorIndex);
                                        entityList.Polylines.Add(polyLine);
                                        coordinateTransformator.Transform(polyLine);
                                        num3++;
                                    }
                                }
                            }
                        }
                    }
                }
                progressMeter.Stop();
                editor.WriteMessage("\nXML entity list created:");
                editor.WriteMessage("\nNumber of points        : " + entityList.Points.Count);
                editor.WriteMessage("\nNumber of lines         : " + entityList.Lines.Count);
                editor.WriteMessage("\nNumber of polylines     : " + entityList.Polylines.Count);
                editor.WriteMessage("\nNumber of faces         : " + entityList.Faces.Count);
                editor.WriteMessage("\nTotal number of entities: " + entityList.Count);
                editor.WriteMessage("\nWriting xml file " + IO.string_0 + "...");
                Serializer.Serialize(IO.string_0, entityList);
                editor.WriteMessage("OK\n");
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #9
0
        /// <summary>
        /// Gets a list of all unique values of the attribute field.
        /// </summary>
        /// <param name="fieldName">Name of the field that gets checked.</param>
        /// <param name="source">Attribute source that contains the field.</param>
        /// <param name="progressHandler">The progress handler.</param>
        /// <returns>A list with the unique values.</returns>
        private List <Break> GetUniqueValues(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler)
        {
            ArrayList lst;
            bool      hugeCountOk = false;

            if (_cachedUniqueValues.ContainsKey(fieldName))
            {
                lst = _cachedUniqueValues[fieldName];
            }
            else
            {
                lst = new ArrayList();
                AttributePager ap = new AttributePager(source, 5000);
                ProgressMeter  pm = new ProgressMeter(progressHandler, "Discovering Unique Values", source.NumRows());
                for (int row = 0; row < source.NumRows(); row++)
                {
                    object val = ap.Row(row)[fieldName] ?? "[NULL]";
                    if (val.ToString() == string.Empty)
                    {
                        val = "[NULL]";
                    }
                    if (lst.Contains(val))
                    {
                        continue;
                    }

                    lst.Add(val);
                    if (lst.Count > 1000 && !hugeCountOk)
                    {
                        CancelEventArgs args = new CancelEventArgs(true);
                        TooManyCategories?.Invoke(this, args);
                        if (args.Cancel)
                        {
                            break;
                        }

                        hugeCountOk = true;
                    }

                    pm.CurrentValue = row;
                    if (progressHandler.Cancel)
                    {
                        break;
                    }
                }

                lst.Sort();
                if (lst.Count < EditorSettings.MaxSampleCount)
                {
                    _cachedUniqueValues[fieldName] = lst;
                }
            }

            List <Break> result = new List <Break>();

            if (lst != null)
            {
                foreach (object item in lst)
                {
                    result.Add(new Break(item.ToString()));
                }
            }

            return(result);
        }
Пример #10
0
        private PointSet method_1(ObjectId[] objectId_0, double double_1)
        {
            if (objectId_0 == null)
            {
                return(null);
            }
            Editor        arg_14_0        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            PointSet      pointSet        = new PointSet();
            PointSet      pointSet2       = new PointSet();
            ProgressMeter progressMeter   = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Computing points on entities");
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        if (i % 10000 == 0)
                        {
                            System.Windows.Forms.Application.DoEvents();
                        }
                        Entity entity = (Entity)objectId_0[i].GetObject((OpenMode)0);
                        string text   = entity.ToString();
                        if (text.ToUpper().Contains("POLYLINE"))
                        {
                            text = "PLINE";
                        }
                        string key;
                        switch (key = text)
                        {
                        case "Autodesk.AutoCAD.DatabaseServices.Line":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Line dbl = (Autodesk.AutoCAD.DatabaseServices.Line)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = PointGeneration.SubdivideLine(dbl, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.DBText":
                        {
                            DBText dbtext_ = (DBText)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_2(dbtext_);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Circle":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Circle circle_ = (Autodesk.AutoCAD.DatabaseServices.Circle)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_3(circle_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Ellipse":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Ellipse ellipse_ = (Autodesk.AutoCAD.DatabaseServices.Ellipse)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_4(ellipse_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Arc":
                        {
                            Autodesk.AutoCAD.DatabaseServices.Arc arc_ = (Autodesk.AutoCAD.DatabaseServices.Arc)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_5(arc_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Spline":
                        {
                            Spline spline_ = (Spline)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_6(spline_, double_1);
                            break;
                        }

                        case "Autodesk.AutoCAD.DatabaseServices.Face":
                        {
                            Face face_ = (Face)transaction.GetObject(objectId_0[i], (OpenMode)0, true);
                            pointSet2 = this.method_7(face_);
                            break;
                        }

                        case "PLINE":
                        {
                            DBObject @object = transaction.GetObject(objectId_0[i], (OpenMode)0);
                            pointSet2 = PointGeneration.SubdividePolyline(@object, transaction, double_1);
                            break;
                        }
                        }
                        if (pointSet2 != null)
                        {
                            pointSet.Add(pointSet2);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
            progressMeter.Stop();
            if (pointSet.Count == 0)
            {
                return(null);
            }
            pointSet.RemoveMultiplePoints3d();
            return(pointSet);
        }
Пример #11
0
        private void BuildPaths(MapArgs e, IEnumerable <int> indices, out List <GraphicsPath> paths)
        {
            paths = new List <GraphicsPath>();
            Extent             drawExtents = e.GeographicExtents;
            Rectangle          clipRect    = e.ProjToPixel(e.GeographicExtents);
            SoutherlandHodgman shClip      = new SoutherlandHodgman(clipRect);

            List <GraphicsPath> graphPaths = new List <GraphicsPath>();
            Dictionary <FastDrawnState, GraphicsPath> borders = new Dictionary <FastDrawnState, GraphicsPath>();

            for (int selectState = 0; selectState < 2; selectState++)
            {
                foreach (IPolygonCategory category in Symbology.Categories)
                {
                    FastDrawnState state = new FastDrawnState(selectState == 1, category);

                    GraphicsPath border = new GraphicsPath();
                    borders.Add(state, border);
                    graphPaths.Add(border);
                }
            }

            paths.AddRange(graphPaths);

            List <ShapeRange> shapes = DataSet.ShapeIndices;

            double[] vertices = DataSet.Vertex;

            if (ProgressReportingEnabled)
            {
                ProgressMeter = new ProgressMeter(ProgressHandler, "Building Paths", indices.Count());
            }

            if (!DrawnStatesNeeded)
            {
                FastDrawnState state = new FastDrawnState(false, Symbology.Categories[0]);

                foreach (int shp in indices)
                {
                    if (ProgressReportingEnabled)
                    {
                        ProgressMeter.Next();
                    }
                    ShapeRange shape = shapes[shp];
                    if (!shape.Extent.Intersects(e.GeographicExtents))
                    {
                        return;
                    }
                    if (shp >= shapes.Count)
                    {
                        return;
                    }
                    if (!borders.ContainsKey(state))
                    {
                        return;
                    }

                    BuildPolygon(vertices, shapes[shp], borders[state], e, drawExtents.Contains(shape.Extent) ? null : shClip);
                }
            }
            else
            {
                FastDrawnState[] states = DrawnStates;
                foreach (GraphicsPath borderPath in borders.Values)
                {
                    if (borderPath != null)
                    {
                        borderPath.FillMode = FillMode.Winding;
                    }
                }

                foreach (int shp in indices)
                {
                    if (ProgressReportingEnabled)
                    {
                        ProgressMeter.Next();
                    }
                    if (shp >= shapes.Count)
                    {
                        return;
                    }
                    if (shp >= states.Length)
                    {
                        AssignFastDrawnStates();
                        states = DrawnStates;
                    }
                    if (states[shp].Visible == false)
                    {
                        continue;
                    }
                    ShapeRange shape = shapes[shp];
                    if (!shape.Extent.Intersects(e.GeographicExtents))
                    {
                        continue;
                    }
                    if (drawExtents.Contains(shape.Extent))
                    {
                        FastDrawnState state = states[shp];
                        if (!borders.ContainsKey(state))
                        {
                            continue;
                        }
                        BuildPolygon(vertices, shapes[shp], borders[state], e, null);
                    }
                    else
                    {
                        FastDrawnState state = states[shp];
                        if (!borders.ContainsKey(state))
                        {
                            continue;
                        }
                        BuildPolygon(vertices, shapes[shp], borders[state], e, shClip);
                    }
                }
            }
            if (ProgressReportingEnabled)
            {
                ProgressMeter.Reset();
            }
        }
Пример #12
0
        public static List<PanelAKR> GetAkrPanelLib(Database dbLib, bool defineFullPaneldata)
        {
            List<PanelAKR> panelsAkrLIb = new List<PanelAKR>();
            using (var bt = dbLib.BlockTableId.Open(OpenMode.ForRead) as BlockTable)
            {
                using (ProgressMeter progress = new ProgressMeter())
                {
                    List<Tuple<ObjectId, string>> idBtrPanels = new List<Tuple<ObjectId, string>>();

                    foreach (ObjectId idBtr in bt)
                    {
                        using (var btr = idBtr.Open(OpenMode.ForRead) as BlockTableRecord)
                        {
                            if (MarkSb.IsBlockNamePanel(btr.Name))
                            {
                                idBtrPanels.Add(new Tuple<ObjectId, string>(idBtr, btr.Name));
                            }
                        }
                    }

                    progress.SetLimit(idBtrPanels.Count);
                    progress.Start("Считывание панелей из библиотеки...");

                    foreach (var idBtr in idBtrPanels)
                    {
                        if (HostApplicationServices.Current.UserBreak())
                        {
                            throw new System.Exception(AcadLib.General.CanceledByUser);
                        }

                        PanelAKR panelAkr = new PanelAKR(idBtr.Item1, idBtr.Item2);
                        if (defineFullPaneldata)
                        {
                            panelAkr.DefineGeom(idBtr.Item1);
                        }
                        panelsAkrLIb.Add(panelAkr);

                        progress.MeterProgress();
                    }
                    progress.Stop();
                }
            }
            return panelsAkrLIb;
        }
Пример #13
0
        private List <Edge> method_0(ObjectId[] objectId_0, ObjectId[] objectId_1, CoordinateSystem coordinateSystem_0, bool bool_0)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            int         num        = 0;
            int         num2       = 0;
            int         num3       = 0;
            IdEdgeList  idEdgeList = new IdEdgeList();
            List <Edge> list       = new List <Edge>();
            int         num4       = DBManager.SetEpsilon();
            int         num5       = (int)Convert.ToInt16(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("LUPREC").ToString());

            num4 = Math.Min(num5 + 2, num4);
            double num6 = Math.Max(Math.Pow(10.0, (double)(-(double)num4)), Global.AbsoluteEpsilon);
            CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), coordinateSystem_0);
            CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
            List <Triangle>         list2 = Conversions.ToCeometricAcDbTriangleList(objectId_1);

            using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
            {
                BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                ObjectId         layerId          = DBManager.CurrentLayerId();
                DBManager.CurrentLayerName();
                List <IdEdge> list3 = new List <IdEdge>();
                double        num7  = -1.7976931348623157E+308;
                for (int i = 0; i < objectId_0.Length; i++)
                {
                    Autodesk.AutoCAD.DatabaseServices.Line line = (Autodesk.AutoCAD.DatabaseServices.Line)transaction.GetObject(objectId_0[i], (OpenMode)1, true);
                    IdEdge idEdge = new IdEdge(line);
                    if (LineProjection.string_0 == "Y" & !idEdge.Line.IsErased)
                    {
                        idEdge.Line.Erase();
                    }
                    coordinateTransformator.Transform(idEdge.Edge);
                    double num8  = idEdge.Edge.StartPoint.X - idEdge.Edge.EndPoint.X;
                    double num9  = idEdge.Edge.StartPoint.Y - idEdge.Edge.EndPoint.Y;
                    double num10 = Math.Sqrt(num8 * num8 + num9 * num9);
                    if (Math.Abs(num8) > num7)
                    {
                        num7 = Math.Abs(num8);
                    }
                    if (num10 < Global.AbsoluteEpsilon)
                    {
                        num2++;
                    }
                    else
                    {
                        idEdge.SetMinMaxXY();
                        list3.Add(idEdge);
                    }
                }
                list3.Sort(new CompareMin());
                progressMeter.SetLimit(objectId_1.Length);
                if ((double)objectId_1.Length > 10000.0)
                {
                    progressMeter.Start("Projecting lines...");
                }
                try
                {
                    for (int j = 0; j < list2.Count; j++)
                    {
                        progressMeter.MeterProgress();
                        messageFilter.CheckMessageFilter((long)j, 1000);
                        Triangle triangle = list2[j];
                        coordinateTransformator.Transform(triangle);
                        if (Math.Abs(triangle.NormalVector.Z) < Global.AbsoluteEpsilon)
                        {
                            num++;
                        }
                        else
                        {
                            double minimumX = triangle.MinimumX;
                            double maximumX = triangle.MaximumX;
                            double minimumY = triangle.MinimumY;
                            double maximumY = triangle.MaximumY;
                            IdEdge item     = new IdEdge(new Edge(new Point(maximumX, minimumY, 0.0), new Point(maximumX + 1.0, minimumY, 0.0)));
                            int    num11    = list3.BinarySearch(item, new CompareMin());
                            if (num11 < 0)
                            {
                                num11 = ~num11;
                            }
                            IdEdge item2 = new IdEdge(new Edge(new Point(minimumX - num7, maximumY, 0.0), new Point(minimumX - num7 + 1.0, maximumY, 0.0)));
                            int    num12 = list3.BinarySearch(item2, new CompareMin());
                            if (num12 < 0)
                            {
                                num12 = ~num12;
                            }
                            try
                            {
                                for (int k = num12; k < num11; k++)
                                {
                                    IdEdge idEdge2 = list3[k];
                                    if (idEdge2.MinX <= maximumX && idEdge2.MinY <= maximumY && idEdge2.MaxX >= minimumX && idEdge2.MaxY >= minimumY)
                                    {
                                        Edge   edge  = idEdge2.Edge;
                                        double num13 = Predicate.InTriangle2dArbitraryExact(triangle.Vertex1, triangle.Vertex2, triangle.Vertex3, edge.StartPoint);
                                        double num14 = Predicate.InTriangle2dArbitraryExact(triangle.Vertex1, triangle.Vertex2, triangle.Vertex3, edge.EndPoint);
                                        Edge   edge2 = new Edge();
                                        if (!double.IsNaN(num14) && !double.IsNaN(num13))
                                        {
                                            if (num14 == 1.0 && num13 == 1.0)
                                            {
                                                edge2 = edge;
                                            }
                                            else if (num13 == 1.0 && num14 == 0.0)
                                            {
                                                edge2 = edge;
                                            }
                                            else if (num13 == 0.0 && num14 == 1.0)
                                            {
                                                edge2 = edge;
                                            }
                                            else if (num13 == 0.0 && num14 == 0.0)
                                            {
                                                edge2 = edge;
                                            }
                                            else if (num13 == -1.0 && num14 == 1.0)
                                            {
                                                edge2 = this.method_1(edge, triangle, edge.EndPoint);
                                            }
                                            else if (num13 == 1.0 && num14 == -1.0)
                                            {
                                                edge2 = this.method_1(edge, triangle, edge.StartPoint);
                                            }
                                            else if (num13 == 0.0 && num14 == -1.0)
                                            {
                                                edge2 = this.method_2(edge, triangle, edge.StartPoint);
                                            }
                                            else if (num13 == -1.0 && num14 == 0.0)
                                            {
                                                edge2 = this.method_2(edge, triangle, edge.EndPoint);
                                            }
                                            else if (num13 == -1.0 && num14 == -1.0)
                                            {
                                                edge2 = this.method_3(edge, triangle);
                                            }
                                            if (!(edge2 == null))
                                            {
                                                Edge edge3 = edge2.DeepCopy();
                                                edge3.StartPoint.Z = PointProjection.smethod_0(triangle, edge3.StartPoint);
                                                edge3.EndPoint.Z   = PointProjection.smethod_0(triangle, edge3.EndPoint);
                                                if (edge3.Length >= num6)
                                                {
                                                    Edge edge4 = edge3.DeepCopy();
                                                    edge4.SwapSort();
                                                    edge4.StartPoint.X = (double)((float)edge4.StartPoint.X);
                                                    edge4.StartPoint.Y = (double)((float)edge4.StartPoint.Y);
                                                    edge4.StartPoint.Z = (double)((float)edge4.StartPoint.Z);
                                                    edge4.EndPoint.X   = (double)((float)edge4.EndPoint.X);
                                                    edge4.EndPoint.Y   = (double)((float)edge4.EndPoint.Y);
                                                    edge4.EndPoint.Z   = (double)((float)edge4.EndPoint.Z);
                                                    if (!idEdgeList.ContainsKey(edge4))
                                                    {
                                                        idEdgeList.Add(edge4, null);
                                                        inverseTransformation.Transform(edge3);
                                                        list.Add(edge3);
                                                        if (bool_0)
                                                        {
                                                            Point3d point3d = new Point3d(edge3.StartPoint.X, edge3.StartPoint.Y, edge3.StartPoint.Z);
                                                            //point3d..ctor(edge3.StartPoint.X, edge3.StartPoint.Y, edge3.StartPoint.Z);
                                                            Point3d point3d2 = new Point3d(edge3.EndPoint.X, edge3.EndPoint.Y, edge3.EndPoint.Z);
                                                            //point3d2..ctor(edge3.EndPoint.X, edge3.EndPoint.Y, edge3.EndPoint.Z);
                                                            Autodesk.AutoCAD.DatabaseServices.Line line2 = new Autodesk.AutoCAD.DatabaseServices.Line(point3d, point3d2);
                                                            if (LineProjection.string_1 == "C")
                                                            {
                                                                LayerTableRecord layerTableRecord = (LayerTableRecord)transaction.GetObject(triangle.AcDbFace.LayerId, (OpenMode)0);
                                                                Color            color            = triangle.AcDbFace.Color;
                                                                if (color.IsByLayer)
                                                                {
                                                                    color = layerTableRecord.Color;
                                                                }
                                                                line2.SetPropertiesFrom(triangle.AcDbFace);
                                                                line2.LayerId = (layerId);
                                                                line2.Color   = (color);
                                                            }
                                                            else if (LineProjection.string_1 == "F")
                                                            {
                                                                line2.SetPropertiesFrom(triangle.AcDbFace);
                                                            }
                                                            else if (LineProjection.string_1 == "L")
                                                            {
                                                                line2.SetPropertiesFrom(idEdge2.Line);
                                                            }
                                                            blockTableRecord.AppendEntity(line2);
                                                            transaction.AddNewlyCreatedDBObject(line2, true);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (System.Exception ex)
                            {
                                editor.WriteMessage("\n" + ex.Message);
                                num3++;
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    progressMeter.Stop();
                    throw;
                }
                transaction.Commit();
            }
            progressMeter.Stop();
            if (bool_0)
            {
                editor.WriteMessage("\nNumber of lines projected             : " + idEdgeList.Count);
                editor.WriteMessage("\nNumber of failed faces                : " + num3);
                editor.WriteMessage("\nFaces parallel to projection direction: " + num);
                editor.WriteMessage("\nLines parallel to projection direction: " + num2);
            }
            return(list);
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private IImageData OpenFile(string fileName)
        {
            Dataset dataset;

            try
            {
                dataset = Gdal.Open(fileName, Access.GA_Update);
            }
            catch
            {
                try
                {
                    dataset = Gdal.Open(fileName, Access.GA_ReadOnly);
                }
                catch (Exception ex)
                {
                    throw new GdalException(ex.ToString());
                }
            }

            Band        red      = dataset.GetRasterBand(1);
            ColorInterp bandType = red.GetRasterColorInterpretation();

            if (bandType != ColorInterp.GCI_PaletteIndex &&
                bandType != ColorInterp.GCI_GrayIndex &&
                bandType != ColorInterp.GCI_RedBand &&
                bandType != ColorInterp.GCI_AlphaBand)
            {
                // This is an image, not a raster, so return null.
                dataset.Dispose();
                dataset = null;
                return(null);
            }

            GdalImage result = new GdalImage(fileName);

            if (result.Width > 8000 || result.Height > 8000)
            {
                // Firstly, if there are pyramids inside of the GDAL file itself, we can just work with this directly,
                // without creating our own pyramid image.

                // For now, we can't get fast, low-res versions without some kind of pyramiding happening.
                // since that can take a while for huge images, I'd rather do this once, and create a kind of
                // standardized file-based pyramid system.  Maybe in future pyramid tiffs could be used instead?
                string pyrFile = Path.ChangeExtension(fileName, ".mwi");
                if (File.Exists(pyrFile))
                {
                    if (File.Exists(Path.ChangeExtension(pyrFile, ".mwh")))
                    {
                        return(new PyramidImage(fileName));
                    }
                    File.Delete(pyrFile);
                }

                GdalImageSource gs          = new GdalImageSource(fileName);
                PyramidImage    py          = new PyramidImage(pyrFile, gs.Bounds);
                int             width       = gs.Bounds.NumColumns;
                int             blockHeight = 64000000 / width;
                if (blockHeight > gs.Bounds.NumRows)
                {
                    blockHeight = gs.Bounds.NumRows;
                }
                int           numBlocks = (int)Math.Ceiling(gs.Bounds.NumRows / (double)blockHeight);
                ProgressMeter pm        = new ProgressMeter(ProgressHandler, "Copying Data To Pyramids", numBlocks * 2);
                //ProgressHandler.Progress("pyramid", 0, "Copying Data To Pyramids: 0% Complete");
                Application.DoEvents();
                for (int j = 0; j < numBlocks; j++)
                {
                    int h = blockHeight;
                    if (j == numBlocks - 1)
                    {
                        h = gs.Bounds.NumRows - j * blockHeight;
                    }
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    byte[] vals = gs.ReadWindow(j * blockHeight, 0, h, width, 0);
                    Debug.WriteLine("Reading Value time: " + sw.ElapsedMilliseconds);
                    pm.CurrentValue = j * 2 + 1;
                    sw.Reset();
                    sw.Start();
                    py.WriteWindow(vals, j * blockHeight, 0, h, width, 0);
                    sw.Stop();
                    Debug.WriteLine("Writing Pyramid time: " + sw.ElapsedMilliseconds);
                    pm.CurrentValue = (j + 1) * 2;
                }
                gs.Dispose();
                pm.Reset();
                py.ProgressHandler = ProgressHandler;
                py.CreatePyramids();
                py.WriteHeader(pyrFile);
                return(py);
            }
            result.Open();
            return(result);
        }
Пример #15
0
        public static void DeleteOldAkrPanels(List<FacadeMounting> facades)
        {
            // удаление старых АКР-Панелей фасадов
            Database db = HostApplicationServices.WorkingDatabase;
            // список всех акр панелей в модели
            List<ObjectId> idsBlRefPanelAkr = Panel.GetPanelsBlRefInModel(db);

            ProgressMeter progressMeter = new ProgressMeter();
            progressMeter.SetLimit(idsBlRefPanelAkr.Count);
            progressMeter.Start("Удаление старых фасадов");

            foreach (var idBlRefPanelAkr in idsBlRefPanelAkr)
            {
                using (var blRefPanelAkr = idBlRefPanelAkr.Open(OpenMode.ForRead, false, true) as BlockReference)
                {
                    var extentsAkr = blRefPanelAkr.GeometricExtents;
                    var ptCenterPanelAkr = extentsAkr.Center();
                    // если панель входит в границы любого фасада, то удаляем ее
                    //FacadeMounting facade = facades.Find(f => f.XMin < ptCenterPanelAkr.X && f.XMax > ptCenterPanelAkr.X);
                    //if (facade != null)
                    //{
                        blRefPanelAkr.UpgradeOpen();
                        blRefPanelAkr.Erase();
                    //}
                    progressMeter.MeterProgress();
                }
            }
            progressMeter.Stop();
        }
Пример #16
0
        internal void genContour2(ObjectId[] objectId_0, CoordinateSystem coordinateSystem_0)
        {
            Editor        editor        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ProgressMeter progressMeter = new ProgressMeter();
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            CoordinateSystem coordinateSystem = CoordinateSystem.Global();

            try
            {
                if (objectId_0 == null)
                {
                    throw new ArgumentException("No faces selected.");
                }
                string   layerName       = UserCmd.contourLNPrefix + cmd.mydb.Resolution;
                string   assistLayerName = "contour_assist_" + cmd.mydb.Resolution;
                ObjectId layerId         = LayerUtil.CreateLayer(layerName, 127, true, false);
                ObjectId assistLayerId   = LayerUtil.CreateLayer(assistLayerName, 127, true, false);
                int      num             = DBManager.SetEpsilon();
                int      num2            = (int)Convert.ToInt16(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("LUPREC").ToString());
                num = Math.Min(num2 + 2, num);
                List <Triangle> list = Conversions.ToCeometricCADDataTriangleList(objectId_0);
                if (coordinateSystem_0 != coordinateSystem)
                {
                    Triangle.TransformCoordinates(list, coordinateSystem, coordinateSystem_0);
                }
                else
                {
                    coordinateSystem_0 = null;
                }
                int limit = (int)(Math.Abs(ContourLineComputation.endElevation - ContourLineComputation.startElevation) / ContourLineComputation.spacing);
                progressMeter.SetLimit(limit);
                progressMeter.Start("Computing contours");
                int    num3      = 0;
                int    num4      = 0;
                int    num5      = 0;
                int    num6      = 0;
                int    num7      = 0;
                double maxZ      = cmd.mydb.TEDicList[cmd.mydb.Resolution].maxMaxZ;
                double elevation = ContourLineComputation.startElevation;
                Plane  plane     = new Plane(new ngeometry.VectorGeometry.Point(0.0, 0.0, elevation), new Vector3d(0.0, 0.0, 1.0));
                cmd.mydb.assistContourDics[cmd.mydb.Resolution] = new AssistContourDic();
                while (elevation <= ContourLineComputation.endElevation)
                {
                    if (elevation >= maxZ)
                    {
                        break;
                    }
                    progressMeter.MeterProgress();
                    messageFilter.CheckMessageFilter();
                    List <Edge> interEdgeList = this.getInterSection2(list, plane, num3, ref num5, ref num4);
                    if (interEdgeList.Count <= 0)
                    {
                        editor.WriteMessage("\nNo contours at elevation : " + elevation.ToString());
                    }
                    else
                    {
                        Autodesk.AutoCAD.Geometry.Plane    plane1  = new Autodesk.AutoCAD.Geometry.Plane(new Autodesk.AutoCAD.Geometry.Point3d(0, 0, 0), new Autodesk.AutoCAD.Geometry.Vector3d(0, 0, 1));
                        Autodesk.AutoCAD.Geometry.Matrix3d prjMat1 = Autodesk.AutoCAD.Geometry.Matrix3d.Projection(plane1, plane1.Normal);
                        TransformUtil.Transform(interEdgeList, prjMat1);
                        List <Polyline3d> pline3ds = new List <Polyline3d>();
                        List <PLine>      pllist   = DBManager.WritePlinesInDataBase2(interEdgeList, coordinateSystem_0, num, false, layerId, Color.White, pline3ds);
                        cmd.contColorize.addContour(pline3ds, elevation);
                        num6 += pllist.Count;

                        double assistElevation = elevation + spacing / 2;
                        if (assistElevation >= maxZ)
                        {
                            assistElevation = elevation + (maxZ - elevation) / 2;
                        }
                        genAssistContour(list, plane, coordinateSystem_0, assistLayerId, assistElevation, num, num3);
                        num7 += interEdgeList.Count;
                    }

                    elevation    += ContourLineComputation.spacing;
                    plane.Point.Z = elevation;
                    num3++;
                }
                editor.WriteMessage("\nFailed intersections     : " + num5);
                editor.WriteMessage("\nDegenerate intersections : " + num4);
                editor.WriteMessage("\nTotal number of segments : " + num7);
                editor.WriteMessage("\nTotal number of polylines: " + num6);
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #17
0
        internal void genContour(ObjectId[] objectId_0, CoordinateSystem coordinateSystem_0)
        {
            Editor        editor        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ProgressMeter progressMeter = new ProgressMeter();
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            CoordinateSystem coordinateSystem = CoordinateSystem.Global();

            try
            {
                if (objectId_0 == null)
                {
                    throw new ArgumentException("No faces selected.");
                }
                int num  = DBManager.SetEpsilon();
                int num2 = (int)Convert.ToInt16(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("LUPREC").ToString());
                num = Math.Min(num2 + 2, num);
                List <Triangle> list = Conversions.ToCeometricCADDataTriangleList(objectId_0);
                if (coordinateSystem_0 != coordinateSystem)
                {
                    Triangle.TransformCoordinates(list, coordinateSystem, coordinateSystem_0);
                }
                else
                {
                    coordinateSystem_0 = null;
                }
                int limit = (int)(Math.Abs(ContourLineComputation.endElevation - ContourLineComputation.startElevation) / ContourLineComputation.spacing);
                progressMeter.SetLimit(limit);
                progressMeter.Start("Computing contours");
                int    num3  = 0;
                int    num4  = 0;
                int    num5  = 0;
                int    num6  = 0;
                int    num7  = 0;
                double num8  = ContourLineComputation.startElevation;
                Plane  plane = new Plane(new ngeometry.VectorGeometry.Point(0.0, 0.0, ContourLineComputation.startElevation), new Vector3d(0.0, 0.0, 1.0));
                while (num8 <= ContourLineComputation.endElevation)
                {
                    progressMeter.MeterProgress();
                    messageFilter.CheckMessageFilter();
                    List <Edge> interEdgeList = this.getInterSection(list, plane, num3, ref num5, ref num4);
                    num6 += DBManager.WritePlinesInDataBase(interEdgeList, coordinateSystem_0, num, false);
                    if (interEdgeList.Count == 0)
                    {
                        editor.WriteMessage("\nNo contours at elevation : " + num8.ToString());
                    }
                    num7         += interEdgeList.Count;
                    plane.Point.Z = num8;
                    num8         += ContourLineComputation.spacing;
                    num3++;
                }
                editor.WriteMessage("\nFailed intersections     : " + num5);
                editor.WriteMessage("\nDegenerate intersections : " + num4);
                editor.WriteMessage("\nTotal number of segments : " + num7);
                editor.WriteMessage("\nTotal number of polylines: " + num6);
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #18
0
        public void Reconstruct(ObjectId[] objectId_0)
        {
            Database            workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor              editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            List <Edge>         list            = Conversions.ToCeometricAcDbEdgeList(objectId_0);
            List <List <Edge> > list2           = new List <List <Edge> >();

            if (CMD_ReconstructSurface.string_0 == "L")
            {
                list2 = this.method_0(list);
            }
            else
            {
                list2.Add(list);
            }
            ProgressMeter progressMeter = new ProgressMeter();

            try
            {
                for (int i = 0; i < list2.Count; i++)
                {
                    List <Edge>           list3 = list2[i];
                    SurfaceReconstruction surfaceReconstruction = new SurfaceReconstruction(list3);
                    surfaceReconstruction.ReconstructSurface(progressMeter, CMD_ReconstructSurface.int_0);
                    List <SurfaceReconstruction.Tri>  tris  = surfaceReconstruction.Tris;
                    List <SurfaceReconstruction.Quad> quads = surfaceReconstruction.Quads;
                    using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                    {
                        BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                        BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                        string           str = "0";
                        if (CMD_ReconstructSurface.string_1 == "A" || CMD_ReconstructSurface.string_1 == "T")
                        {
                            for (int j = 0; j < tris.Count; j++)
                            {
                                Face acadFace = surfaceReconstruction.GetAcadFace(tris[j]);
                                if (CMD_ReconstructSurface.string_0 == "L")
                                {
                                    acadFace.SetPropertiesFrom(list3[0].AcDbLine);
                                }
                                blockTableRecord.AppendEntity(acadFace);
                                transaction.AddNewlyCreatedDBObject(acadFace, true);
                            }
                        }
                        if (CMD_ReconstructSurface.string_1 == "A" || CMD_ReconstructSurface.string_1 == "Q")
                        {
                            for (int k = 0; k < quads.Count; k++)
                            {
                                Face acadFace2 = surfaceReconstruction.GetAcadFace(quads[k]);
                                if (CMD_ReconstructSurface.string_0 == "L")
                                {
                                    acadFace2.SetPropertiesFrom(list3[0].AcDbLine);
                                }
                                blockTableRecord.AppendEntity(acadFace2);
                                transaction.AddNewlyCreatedDBObject(acadFace2, true);
                            }
                        }
                        if (tris.Count > 0)
                        {
                            str = DBManager.GetLayerName(list3[0].AcDbLine.LayerId);
                        }
                        if (quads.Count > 0)
                        {
                            str = DBManager.GetLayerName(list3[0].AcDbLine.LayerId);
                        }
                        if (CMD_ReconstructSurface.string_0 == "C")
                        {
                            str = DBManager.CurrentLayerName();
                        }
                        transaction.Commit();
                        editor.WriteMessage("\n");
                        editor.WriteMessage("\nLayer                             : " + str);
                        editor.WriteMessage("\nNumber of edges                   : " + list3.Count);
                        editor.WriteMessage("\nNumber of triangular faces created: " + tris.Count);
                        editor.WriteMessage("\nNumber of quad faces created      : " + quads.Count);
                    }
                }
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #19
0
        private static void placementColors(BlockTableRecord cs, ColorBook colorBookNcs, Point3d ptStart)
        {
            Transaction t = db.TransactionManager.TopTransaction;

            double widthLayout = Options.Instance.Width;
            double heightLayout = Options.Instance.Height;

            double widthCells = widthLayout - widthLayout * 0.1;
            double heightCells = heightLayout - heightLayout * 0.1;

            int columns = Options.Instance.Columns;
            int rows = Options.Instance.Rows;

            // Определение длины и высоты для каждой ячейки цвета
            CellWidth = widthCells / columns;
            CellHeight = heightCells / rows;

            Margin = CellWidth * 0.1;
            TextHeight = Convert.ToInt32(CellWidth * 0.09);

            Point3d ptLayout = ptStart;

            var progress = new ProgressMeter();
            progress.SetLimit(colorBookNcs.Colors.Count);
            progress.Start("Расстановка цветов...");

            // Кол листов
            double cellsCount = columns * rows;
            int layCount = Convert.ToInt32(Math.Ceiling(colorBookNcs.Colors.Count / cellsCount));

            int index = 0;
            for (int l = 1; l < layCount+1; l++)
            {
                // создание рамки листа
                addLayout(ptLayout, l, widthLayout, heightLayout, cs, t);
                Point2d ptCellFirst = new Point2d(ptLayout.X + (widthLayout - widthCells) * 0.5,
                    ptLayout.Y - (heightLayout - heightCells) * 0.5);

                // Заполнение ячейками цветов
                for (int r = 0; r < rows; r++)
                {
                    bool isBreak = false;
                    for (int c = 0; c < columns; c++)
                    {
                        index++;
                        if (index == colorBookNcs.Colors.Count)
                        {
                            isBreak = true;
                            break;
                        }
                        ColorItem colorItem = colorBookNcs.Colors[index];
                        Point2d ptCell = new Point2d(ptCellFirst.X + c * CellWidth, ptCellFirst.Y - r * CellHeight);
                        colorItem.Create(ptCell, cs, t);
                        progress.MeterProgress();
                    }
                    if (isBreak)
                    {
                        break;
                    }
                }
                ptLayout = new Point3d(ptLayout.X, ptLayout.Y + heightLayout, 0);
            }
            progress.Stop();
        }
Пример #20
0
        private IImageData OpenFile(string fileName)
        {
            var  dataset = Helpers.Open(fileName);
            bool hasOverviews;

            using (var red = dataset.GetRasterBand(1))
            {
                ColorInterp bandType = red.GetRasterColorInterpretation();
                if (bandType != ColorInterp.GCI_PaletteIndex && bandType != ColorInterp.GCI_GrayIndex && bandType != ColorInterp.GCI_RedBand && bandType != ColorInterp.GCI_AlphaBand)
                {
                    // This is an image, not a raster, so return null.
                    dataset.Dispose();
                    return(null);
                }

                hasOverviews = red.GetOverviewCount() > 0;
            }

            GdalImage result = new GdalImage(fileName);

            // Firstly, if there are pyramids inside of the GDAL file itself, we can just work with this directly,
            // without creating our own pyramid image.
            if ((result.Width > 8000 || result.Height > 8000) && !hasOverviews)
            {
                // For now, we can't get fast, low-res versions without some kind of pyramiding happening.
                // since that can take a while for huge images, I'd rather do this once, and create a kind of
                // standardized file-based pyramid system.  Maybe in future pyramid tiffs could be used instead?
                string pyrFile = Path.ChangeExtension(fileName, ".mwi");
                if (pyrFile != null && File.Exists(pyrFile))
                {
                    if (File.Exists(Path.ChangeExtension(pyrFile, ".mwh")))
                    {
                        return(new PyramidImage(fileName));
                    }

                    File.Delete(pyrFile);
                }

                GdalImageSource gs          = new GdalImageSource(fileName);
                PyramidImage    py          = new PyramidImage(pyrFile, gs.Bounds);
                int             width       = gs.Bounds.NumColumns;
                int             blockHeight = 64000000 / width;
                if (blockHeight > gs.Bounds.NumRows)
                {
                    blockHeight = gs.Bounds.NumRows;
                }
                int           numBlocks = (int)Math.Ceiling(gs.Bounds.NumRows / (double)blockHeight);
                ProgressMeter pm        = new ProgressMeter(ProgressHandler, "Copying Data To Pyramids", numBlocks * 2);

                Application.DoEvents();
                for (int j = 0; j < numBlocks; j++)
                {
                    int h = blockHeight;
                    if (j == numBlocks - 1)
                    {
                        h = gs.Bounds.NumRows - (j * blockHeight);
                    }

                    byte[] vals = gs.ReadWindow(j * blockHeight, 0, h, width, 0);

                    pm.CurrentValue = (j * 2) + 1;
                    py.WriteWindow(vals, j * blockHeight, 0, h, width, 0);
                    pm.CurrentValue = (j + 1) * 2;
                }

                gs.Dispose();
                pm.Reset();
                py.ProgressHandler = ProgressHandler;
                py.CreatePyramids();
                py.WriteHeader(pyrFile);
                result.Dispose();

                return(py);
            }

            result.Open();
            return(result);
        }
        private static void copyFlats(string[] fileFlats, Document docFlats)
        {
            using (var progress = new ProgressMeter())
            {
                progress.SetLimit(fileFlats.Length);
                progress.Start("Копирование квартир из файлов подложек...");

                foreach (var fileFlat in fileFlats)
                {
                    progress.MeterProgress();
                    // Копирование блока квартиры из файла подложки
                    try
                    {
                        copyFlat(fileFlat, docFlats.Database.BlockTableId);
                    }
                    catch (System.Exception ex)
                    {
                        Inspector.AddError($"Ошибка копирования квартиры из файла {fileFlat} - {ex.ToString()}.",
                            System.Drawing.SystemIcons.Error);
                    }
                }
                progress.Stop();
            }
        }
 /// <summary>
 /// Constructs a new <see cref="NtpNetworkTimeClient"/>
 /// </summary>
 /// <param name="serverName">The name or IP address of the NTP server</param>
 /// <param name="port">The UDP port number for the NTP server</param>
 public NtpNetworkTimeClient(string serverName, int port)
     : base(serverName, port)
 {
     progress = new ProgressMeter(this, 0, 4, 0, "");
 }
Пример #23
0
        public static void PolyTrimExtend() // mod 20130228
        {
            double epsilon = Interaction.GetValue("\nEpsilon", _polyTrimExtendEpsilon);

            if (double.IsNaN(epsilon))
            {
                return;
            }
            _polyTrimExtendEpsilon = epsilon;

            var visibleLayers = DbHelper
                                .GetAllLayerIds()
                                .QOpenForRead <LayerTableRecord>()
                                .Where(x => !x.IsHidden && !x.IsFrozen && !x.IsOff)
                                .Select(x => x.Name)
                                .ToList();

            var ids = Interaction
                      .GetSelection("\nSelect polyline", "LWPOLYLINE")
                      .QWhere(x => visibleLayers.Contains(x.Layer) && x.Visible)
                      .ToArray(); // newly 20130729

            var pm = new ProgressMeter();

            pm.Start("Processing...");
            pm.SetLimit(ids.Length);
            ids.QOpenForWrite <Polyline>(list =>
            {
                foreach (var poly in list)
                {
                    int[] indices = { 0, poly.NumberOfVertices - 1 };
                    foreach (int index in indices)
                    {
                        var end = poly.GetPoint3dAt(index);
                        foreach (var poly1 in list)
                        {
                            if (poly1 != poly)
                            {
                                var closest  = poly1.GetClosestPointTo(end, false);
                                double dist  = closest.DistanceTo(end);
                                double dist1 = poly1.StartPoint.DistanceTo(end);
                                double dist2 = poly1.EndPoint.DistanceTo(end);

                                double distance = poly1.GetDistToPoint(end);
                                if (poly1.GetDistToPoint(end) > 0)
                                {
                                    if (dist1 <= dist2 && dist1 <= dist && dist1 < epsilon)
                                    {
                                        poly.SetPointAt(index, new Point2d(poly1.StartPoint.X, poly1.StartPoint.Y));
                                    }
                                    else if (dist2 <= dist1 && dist2 <= dist && dist2 < epsilon)
                                    {
                                        poly.SetPointAt(index, new Point2d(poly1.EndPoint.X, poly1.EndPoint.Y));
                                    }
                                    else if (dist <= dist1 && dist <= dist2 && dist < epsilon)
                                    {
                                        poly.SetPointAt(index, new Point2d(closest.X, closest.Y));
                                    }
                                }
                            }
                        }
                    }
                    pm.MeterProgress();
                }
            });
            pm.Stop();
        }
Пример #24
0
        // Создание определений блоков панелей марки АР
        private void CreatePanelsMarkAR()
        {
            ProgressMeter progressMeter = new ProgressMeter();
            progressMeter.Start("Создание определений блоков панелей марки АР ");
            progressMeter.SetLimit(_marksSB.Count);
            progressMeter.Start();

            foreach (var markSB in _marksSB)
            {
                progressMeter.MeterProgress();
                if (HostApplicationServices.Current.UserBreak())
                    throw new System.Exception("Отменено пользователем.");

                foreach (var markAR in markSB.MarksAR)
                {
                    markAR.CreateBlock();
                }
            }
            progressMeter.Stop();
        }
Пример #25
0
        /// <summary>
        /// Создание панелей
        /// Не нужна транзакция!!!
        /// </summary>      
        public void CreateBtrPanels(List<FacadeMounting> facadesMounting, List<FloorArchitect> floorsAr)
        {
            var panelsBaseGroup = matchingPlans(facadesMounting, floorsAr).Values.GroupBy(p => p.Panel.mark);

             ProgressMeter progressMeter = new ProgressMeter();
             progressMeter.SetLimit(panelsBaseGroup.Sum(g=>g.Count()));
             progressMeter.Start("Создание блоков панелей");

             foreach (var itemGroupPanelByMark in panelsBaseGroup)
             {
            if (HostApplicationServices.Current.UserBreak())
            {
               throw new System.Exception("Отменено пользователем.");
            }

            // Нумерация индексов окон
            if (itemGroupPanelByMark.Count() > 1)
            {
               // Панели отличающиеся сочетанием окон - пронумеровать индекс окна
               int index = 1;
               itemGroupPanelByMark.ForEach(p => p.WindowsIndex = index++);
            }

            //using (var t = Db.TransactionManager.StartTransaction())
            //{
            foreach (var panelBase in itemGroupPanelByMark)
            {
               try
               {
                  panelBase.CreateBlock();
                  progressMeter.MeterProgress();
               }
               catch (System.Exception ex)
               {
                  Inspector.AddError($"Не создана панель {panelBase.Panel.mark}. Ошибка - {ex.Message}",icon: System.Drawing.SystemIcons.Error);
               }
            }
            //   t.Commit();
            //}
             }
             progressMeter.Stop();
        }
Пример #26
0
        // Замена вхождений блоков панелей Марки СБ на панели Марки АР
        private void ReplaceBlocksMarkSbOnMarkAr()
        {
            ProgressMeter progressMeter = new ProgressMeter();
            progressMeter.SetLimit(_marksSB.Count);
            progressMeter.Start("Замена вхождений блоков панелей Марки СБ на панели Марки АР ");

            using (var t = _db.TransactionManager.StartTransaction())
            {
                var ms = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(_db), OpenMode.ForWrite) as BlockTableRecord;
                foreach (var markSb in _marksSB)
                {
                    if (HostApplicationServices.Current.UserBreak())
                        throw new System.Exception("Отменено пользователем.");

                    markSb.ReplaceBlocksSbOnAr(t, ms);
                    progressMeter.MeterProgress();
                }
                t.Commit();
            }
            progressMeter.Stop();
        }
Пример #27
0
        /// <summary>
        /// Clips a raster with a polygon feature
        /// </summary>
        /// <param name="polygon">The clipping polygon feature</param>
        /// <param name="input">The input raster object</param>
        /// <param name="outputFileName">the output raster file name</param>
        /// <param name="cancelProgressHandler">Progress handler for reporting progress status and cancelling the operation</param>
        /// <remarks>We assume there is only one part in the polygon.
        /// Traverses the raster with a vertical scan line from left to right, bottom to top</remarks>
        /// <returns></returns>
        public static IRaster ClipRasterWithPolygon(IFeature polygon, IRaster input, string outputFileName,
                                                    ICancelProgressHandler cancelProgressHandler = null)
        {
            //if the polygon is completely outside the raster
            if (!input.ContainsFeature(polygon))
            {
                return(input);
            }

            if (cancelProgressHandler != null)
            {
                cancelProgressHandler.Progress(null, 16, "Retrieving the borders.");
            }

            List <Border> borders = GetBorders(polygon);

            if (cancelProgressHandler != null)
            {
                cancelProgressHandler.Progress(null, 33, "Copying raster.");
            }

            //create output raster
            IRaster output = Raster.CreateRaster(outputFileName, input.DriverCode, input.NumColumns, input.NumRows, 1,
                                                 input.DataType, new[] { string.Empty });

            output.Bounds      = input.Bounds.Copy();
            output.NoDataValue = input.NoDataValue;
            if (input.CanReproject)
            {
                output.Projection = input.Projection;
            }

            // set all initial values of Output to NoData
            for (int i = 0; i < output.NumRows; i++)
            {
                for (int j = 0; j < output.NumColumns; j++)
                {
                    output.Value[i, j] = output.NoDataValue;
                }
            }

            double xStart      = GetXStart(polygon, output);
            int    columnStart = GetStartColumn(polygon, output); //get the index of first column
            double xCurrent    = xStart;

            ProgressMeter pm = new ProgressMeter(cancelProgressHandler, "Clipping Raster", output.NumColumns);

            pm.StepPercent = 5;
            pm.StartValue  = 33;

            int col = 0;

            for (int columnCurrent = columnStart; columnCurrent < output.NumColumns; columnCurrent++)
            {
                xCurrent = xStart + col * output.CellWidth;

                var intersections = GetYIntersections(borders, xCurrent);
                intersections.Sort();
                ParseIntersections(intersections, xCurrent, columnCurrent, output, input);

                // update progess meter
                pm.CurrentValue = xCurrent;

                //update counter
                col++;

                // cancel if requested
                if (cancelProgressHandler != null && cancelProgressHandler.Cancel)
                {
                    return(null);
                }
            }

            output.Save();

            return(output);
        }
Пример #28
0
        internal PointSet method_0(ObjectId[] objectId_0, double double_0)
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            if (objectId_0.Length > 1)
            {
                progressMeter.Start("Generating points...");
            }
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            int      num      = 0;
            PointSet pointSet = new PointSet();
            PointSet result;

            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    List <Entity> list = new List <Entity>();
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        list.Add((Entity)transaction.GetObject(objectId_0[i], (OpenMode)0));
                    }
                    Mesh2dControl mesh2dControl = new Mesh2dControl();
                    mesh2dControl.MaxNodeSpacing = (double_0);
                    mesh2dControl.ElementShape   = (0);
                    for (int j = 0; j < objectId_0.Length; j++)
                    {
                        Brep         brep         = new Brep(list[j]);
                        Mesh2dFilter mesh2dFilter = new Mesh2dFilter();
                        mesh2dFilter.Insert(brep, mesh2dControl);
                        Mesh2d mesh2d = new Mesh2d(mesh2dFilter);
                        using (Mesh2dElement2dEnumerator enumerator = mesh2d.Element2ds.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                Element2d current = enumerator.Current;
                                messageFilter.CheckMessageFilter((long)num, 100);
                                num++;
                                using (Element2dNodeEnumerator enumerator2 = current.Nodes.GetEnumerator())
                                {
                                    while (enumerator2.MoveNext())
                                    {
                                        Node current2 = enumerator2.Current;
                                        pointSet.Add(new Point(current2.Point.X, current2.Point.Y, current2.Point.Z));
                                        current2.Dispose();
                                    }
                                }
                                current.Dispose();
                            }
                        }
                        progressMeter.MeterProgress();
                    }
                    pointSet.RemoveMultiplePoints3d();
                }
                progressMeter.Stop();
                result = pointSet;
            }
            catch
            {
                progressMeter.Stop();
                throw;
            }
            return(result);
        }
Пример #29
0
        /// <summary>
        /// Gets the values from a file based data source rather than an in memory object.
        /// </summary>
        /// <param name="source">Source to get the values from.</param>
        /// <param name="progressHandler">The progress handler.</param>
        public void GetValues(IAttributeSource source, ICancelProgressHandler progressHandler)
        {
            int pageSize = 100000;

            Values = new List <double>();
            string normField = EditorSettings.NormField;
            string fieldName = EditorSettings.FieldName;

            if (source.NumRows() < EditorSettings.MaxSampleCount)
            {
                int numPages = (int)Math.Ceiling((double)source.NumRows() / pageSize);
                for (int ipage = 0; ipage < numPages; ipage++)
                {
                    int       numRows = (ipage == numPages - 1) ? source.NumRows() % pageSize : pageSize;
                    DataTable table   = source.GetAttributes(ipage * pageSize, numRows);
                    if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression))
                    {
                        DataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")");
                        foreach (DataRow row in rows)
                        {
                            double val;
                            if (!double.TryParse(row[fieldName].ToString(), out val))
                            {
                                continue;
                            }
                            if (double.IsNaN(val))
                            {
                                continue;
                            }

                            if (normField != null)
                            {
                                double norm;
                                if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val))
                                {
                                    continue;
                                }

                                Values.Add(val / norm);
                                continue;
                            }

                            Values.Add(val);
                        }
                    }
                    else
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            double val;
                            if (!double.TryParse(row[fieldName].ToString(), out val))
                            {
                                continue;
                            }
                            if (double.IsNaN(val))
                            {
                                continue;
                            }

                            if (normField != null)
                            {
                                double norm;
                                if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val))
                                {
                                    continue;
                                }

                                Values.Add(val / norm);
                                continue;
                            }

                            Values.Add(val);
                        }
                    }
                }
            }
            else
            {
                Dictionary <int, double> randomValues = new Dictionary <int, double>();
                pageSize = 10000;
                int count = EditorSettings.MaxSampleCount;

                // Specified seed is required for consistently recreating the break values
                Random         rnd          = new Random(9999);
                AttributePager ap           = new AttributePager(source, pageSize);
                int            countPerPage = count / ap.NumPages();
                ProgressMeter  pm           = new ProgressMeter(progressHandler, "Sampling " + count + " random values", count);
                for (int iPage = 0; iPage < ap.NumPages(); iPage++)
                {
                    for (int i = 0; i < countPerPage; i++)
                    {
                        double val;
                        double norm = 1;
                        int    index;
                        bool   failed = false;
                        do
                        {
                            index = rnd.Next(ap.StartIndex, ap.StartIndex + pageSize);
                            DataRow dr = ap.Row(index);
                            if (!double.TryParse(dr[fieldName].ToString(), out val))
                            {
                                failed = true;
                            }
                            if (normField == null)
                            {
                                continue;
                            }

                            if (!double.TryParse(dr[normField].ToString(), out norm))
                            {
                                failed = true;
                            }
                        }while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed);

                        if (normField != null)
                        {
                            Values.Add(val / norm);
                        }
                        else
                        {
                            Values.Add(val);
                        }

                        randomValues.Add(index, val);
                        pm.CurrentValue = i + (iPage * countPerPage);
                    }

                    if (progressHandler != null && progressHandler.Cancel)
                    {
                        break;
                    }
                }
            }

            Values.Sort();
            Statistics.Calculate(Values);
        }
Пример #30
0
        public static void CreateContours2(List <Apartment> apartments)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (var t = db.TransactionManager.StartTransaction())
            {
                db.RegApp(Commands.RegAppApartBase);

                ProgressMeter progress = new ProgressMeter();
                progress.SetLimit(apartments.Count);
                progress.Start("Построение контуров квартир...");

                foreach (var apart in apartments)
                {
                    progress.MeterProgress();
                    try
                    {
                        List <Polyline>   colPl = new List <Polyline>();
                        Point3dCollection pts   = new Point3dCollection();
                        foreach (var module in apart.Modules)
                        {
                            var blRefModule = module.IdBlRef.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                            foreach (var wall in module.Elements.OfType <WallElement>())
                            {
                                var pl = wall.Contour?.Clone() as Polyline;
                                if (pl == null)
                                {
                                    pl = wall.ExtentsClean.GetPolyline();
                                }
                                pl.TransformBy(blRefModule.BlockTransform);
                                colPl.Add(pl);
                            }
                        }

                        var plContour = colPl.GetExteriorContour();

                        var btrApart   = apart.IdBtr.GetObject(OpenMode.ForWrite) as BlockTableRecord;
                        var blRefApart = apart.IdBlRef.GetObject(OpenMode.ForRead, false, true) as BlockReference;

                        var layerApartInfo = new AcadLib.Layers.LayerInfo(blRefApart.Layer);
                        AcadLib.Layers.LayerExt.CheckLayerState(layerApartInfo);

                        plContour.SetXData(Commands.RegAppApartBase, 1);
                        plContour.SetDatabaseDefaults();
                        plContour.LayerId = blRefApart.LayerId;

                        ClearOldContour(btrApart);

                        btrApart.AppendEntity(plContour);
                        t.AddNewlyCreatedDBObject(plContour, true);

                        Hatch h = new Hatch();
                        h.SetXData(Commands.RegAppApartBase, 1);
                        h.SetDatabaseDefaults();
                        h.LayerId = blRefApart.LayerId;
                        h.SetHatchPattern(HatchPatternType.PreDefined, "Solid");

                        btrApart.AppendEntity(h);
                        t.AddNewlyCreatedDBObject(h, true);

                        h.Associative = true;
                        var idsH = new ObjectIdCollection(new[] { plContour.Id });
                        h.AppendLoop(HatchLoopTypes.Default, idsH);
                        h.EvaluateHatch(true);

                        var btrDrawOrder = btrApart.DrawOrderTableId.GetObject(OpenMode.ForWrite) as DrawOrderTable;
                        btrDrawOrder.MoveToBottom(new ObjectIdCollection(new[] { h.Id }));

                        btrApart.SetBlRefsRecordGraphicsModified();
                    }
                    catch (System.Exception ex)
                    {
                        Inspector.AddError($"Ошибка при построении контура или штриховки в квартире {apart.Name} - {ex.Message}",
                                           apart.IdBlRef, System.Drawing.SystemIcons.Error);
                    }
                }
                progress.Stop();
                t.Commit();
            }
        }
Пример #31
0
        private void method_2()
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            string        value           = IO.AutoDetermineDelimiter(IO.string_3, true);
            char          c             = Convert.ToChar(value);
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            int num = 0;

            using (StreamReader streamReader = new StreamReader(IO.string_3))
            {
                while (streamReader.Peek() >= 0)
                {
                    streamReader.ReadLine();
                    num++;
                }
            }
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(num);
            progressMeter.Start("Reading 3df file");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(Conversions.GetUCS(), CoordinateSystem.Global());
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    LayerTable       lt                = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0);
                    BlockTable       arg_D1_0          = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)0);
                    ObjectId         blockModelSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(workingDatabase);
                    BlockTableRecord blockTableRecord  = (BlockTableRecord)transaction.GetObject(blockModelSpaceId, (OpenMode)1);
                    int num2 = 1;
                    int num3 = 0;
                    using (StreamReader streamReader2 = new StreamReader(IO.string_3))
                    {
                        while (streamReader2.Peek() >= 0)
                        {
                            string text = streamReader2.ReadLine();
                            if (!text.StartsWith("C", true, null) && !(text == ""))
                            {
                                try
                                {
                                    string[] array = text.Split(new char[]
                                    {
                                        c
                                    }, StringSplitOptions.RemoveEmptyEntries);
                                    string text2 = array[0].Trim();
                                    if (!DBManager.ValidateName(text2))
                                    {
                                        throw new System.Exception(string.Concat(new object[]
                                        {
                                            "Invalid layer name in line ",
                                            num2,
                                            ":\n",
                                            text
                                        }));
                                    }
                                    if (text2 == "")
                                    {
                                        text2 = "0";
                                    }
                                    double num4  = Convert.ToDouble(array[1]);
                                    double num5  = Convert.ToDouble(array[2]);
                                    double num6  = Convert.ToDouble(array[3]);
                                    double num7  = Convert.ToDouble(array[4]);
                                    double num8  = Convert.ToDouble(array[5]);
                                    double num9  = Convert.ToDouble(array[6]);
                                    double num10 = Convert.ToDouble(array[7]);
                                    double num11 = Convert.ToDouble(array[8]);
                                    double num12 = Convert.ToDouble(array[9]);
                                    double num13 = Convert.ToDouble(array[10]);
                                    double num14 = Convert.ToDouble(array[11]);
                                    double num15 = Convert.ToDouble(array[12]);
                                    coordinateTransformator.Transform(ref num4, ref num5, ref num6);
                                    coordinateTransformator.Transform(ref num7, ref num8, ref num9);
                                    coordinateTransformator.Transform(ref num10, ref num11, ref num12);
                                    coordinateTransformator.Transform(ref num13, ref num14, ref num15);
                                    Point3d point3d = new Point3d(num4, num5, num6);
                                    //point3d..ctor(num4, num5, num6);
                                    Point3d point3d2 = new Point3d(num7, num8, num9);
                                    //point3d2..ctor(num7, num8, num9);
                                    Point3d point3d3 = new Point3d(num10, num11, num12);
                                    //point3d3..ctor(num10, num11, num12);
                                    Point3d point3d4 = new Point3d(num13, num14, num15);
                                    //point3d4..ctor(num13, num14, num15);
                                    Entity entity = new Autodesk.AutoCAD.DatabaseServices.Face(point3d, point3d2, point3d3, point3d4, true, true, true, true);
                                    entity.LayerId    = (DBManager.GetLayerId(text2, 7, lt));
                                    entity.ColorIndex = (256);
                                    blockTableRecord.AppendEntity(entity);
                                    transaction.AddNewlyCreatedDBObject(entity, true);
                                    num3++;
                                }
                                catch (System.Exception ex)
                                {
                                    if (text.Trim() == "")
                                    {
                                        text = "Empty line!";
                                    }
                                    throw new FormatException(string.Concat(new string[]
                                    {
                                        "Invalid format in line ",
                                        num2.ToString(),
                                        ":",
                                        Environment.NewLine,
                                        text,
                                        Environment.NewLine
                                    }));
                                }
                            }
                            num2++;
                            progressMeter.MeterProgress();
                            messageFilter.CheckMessageFilter((long)num2, 1000);
                        }
                    }
                    transaction.Commit();
                    progressMeter.Stop();
                    editor.WriteMessage(string.Concat(new object[]
                    {
                        Environment.NewLine,
                        num3,
                        " faces read.",
                        Environment.NewLine
                    }));
                }
                DBManager.ZoomExtents();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #32
0
        /// <summary>
        /// Поиск квартир в чертеже.
        /// </summary>
        public static List <Apartment> GetApartments(Autodesk.AutoCAD.DatabaseServices.Database db)
        {
            List <Apartment> apartments = new List <Apartment>();

            // Импользование базы для проверки категории элементов и их параметров
            using (var entities = BaseApartments.ConnectEntities())
            {
                entities.F_nn_Category_Parameters.Load();
                BaseCategoryParameters = entities.F_nn_Category_Parameters.Local.GroupBy(cp => cp.F_S_Categories).Select(p =>
                                                                                                                         new KeyValuePair <string, List <F_S_Parameters> >(p.Key.NAME_RUS_CATEGORY, p.Select(i => i.F_S_Parameters).ToList())).ToList();
            }

            using (var t = db.TransactionManager.StartTransaction())
            {
                ProgressMeter progress = new ProgressMeter();
                progress.Start("Считывание квартир с чертежа...");

                var ms = SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId idEnt in ms)
                {
                    progress.MeterProgress();

                    var blRefApart = idEnt.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                    if (blRefApart != null)
                    {
                        string blName = blRefApart.GetEffectiveName();
                        if (IsBlockNameApartment(blName))
                        {
                            // Не добавлять одну и ту же квартиру в список
                            if (!apartments.Exists(a => a.Name.Equals(blName, StringComparison.OrdinalIgnoreCase)))
                            {
                                // Проверка масштабирования блока
                                if (!blRefApart.CheckNaturalBlockTransform())
                                {
                                    Inspector.AddError($"Блок квартиры масштабирован '{blName}' - {blRefApart.ScaleFactors.ToString()}.",
                                                       blRefApart, icon: SystemIcons.Error);
                                }

                                try
                                {
                                    var apartment = new Apartment(blRefApart, blName);
                                    apartments.Add(apartment);
                                }
                                catch (System.Exception ex)
                                {
                                    Inspector.AddError($"Ошибка считывания блока квартиры '{blName}' - {ex.Message}.",
                                                       blRefApart, icon: SystemIcons.Error);
                                }
                            }
                        }
                        else
                        {
                            Inspector.AddError($"Отфильтрован блок квартиры '{blName}', имя не соответствует " +
                                               $"'{Options.Instance.BlockApartmentNameMatch}",
                                               blRefApart, icon: System.Drawing.SystemIcons.Information);
                        }
                    }
                }
                progress.Stop();
                t.Commit();
            }
            apartments.Sort((a1, a2) => a1.Name.CompareTo(a2.Name));
            return(apartments);
        }
Пример #33
0
        private void method_4()
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            string        value           = IO.AutoDetermineDelimiter(IO.string_4, false);
            char          c             = Convert.ToChar(value);
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            int num = 0;

            using (StreamReader streamReader = new StreamReader(IO.string_4))
            {
                while (streamReader.Peek() >= 0)
                {
                    streamReader.ReadLine();
                    num++;
                }
            }
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(num);
            progressMeter.Start("Reading XYZ");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(Conversions.GetUCS(), CoordinateSystem.Global());
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    ObjectId         layerId           = DBManager.CurrentLayerId();
                    BlockTable       arg_C3_0          = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)0);
                    ObjectId         blockModelSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(workingDatabase);
                    BlockTableRecord blockTableRecord  = (BlockTableRecord)transaction.GetObject(blockModelSpaceId, (OpenMode)1);
                    int num2 = 1;
                    int num3 = 0;
                    using (StreamReader streamReader2 = new StreamReader(IO.string_4))
                    {
                        while (streamReader2.Peek() >= 0)
                        {
                            string text = streamReader2.ReadLine().Trim();
                            if (!text.StartsWith("C", true, null))
                            {
                                try
                                {
                                    string[] array = text.Split(new char[]
                                    {
                                        c
                                    }, StringSplitOptions.RemoveEmptyEntries);
                                    double num4 = Convert.ToDouble(array[0]);
                                    double num5 = Convert.ToDouble(array[1]);
                                    double num6 = 0.0;
                                    if (array.Length > 2)
                                    {
                                        num6 = Convert.ToDouble(array[2]);
                                    }
                                    coordinateTransformator.Transform(ref num4, ref num5, ref num6);
                                    Entity entity = new DBPoint(new Point3d(num4, num5, num6));
                                    entity.LayerId    = (layerId);
                                    entity.ColorIndex = (256);
                                    blockTableRecord.AppendEntity(entity);
                                    transaction.AddNewlyCreatedDBObject(entity, true);
                                    num3++;
                                }
                                catch (System.Exception ex)
                                {
                                    if (text.Trim() == "")
                                    {
                                        text = "Empty line!";
                                    }
                                    throw new FormatException(string.Concat(new string[]
                                    {
                                        "Invalid point data format in line ",
                                        num2.ToString(),
                                        ":",
                                        Environment.NewLine,
                                        text,
                                        Environment.NewLine
                                    }));
                                }
                            }
                            num2++;
                            progressMeter.MeterProgress();
                            messageFilter.CheckMessageFilter((long)num2, 1000);
                        }
                    }
                    transaction.Commit();
                    progressMeter.Stop();
                    editor.WriteMessage(string.Concat(new object[]
                    {
                        Environment.NewLine,
                        num3,
                        " points read",
                        Environment.NewLine
                    }));
                }
                DBManager.ZoomExtents();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #34
0
        /// <summary>
        /// Creates a new raster with the specified cell size.  If the cell size
        /// is zero, this will default to the shorter of the width or height
        /// divided by 256.  If the cell size produces a raster that is greater
        /// than 8, 000 pixels in either dimension, it will be re-sized to
        /// create an 8, 000 length or width raster.
        /// </summary>
        /// <param name="fs">The featureset to convert to a raster.</param>
        /// <param name="extent">Force the raster to this specified extent.</param>
        /// <param name="cellSize">The double extent of the cell.</param>
        /// <param name="fieldName">The integer field index of the file.</param>
        /// <param name="outputFileName">The fileName of the raster to create.</param>
        /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
        /// for a format that is not discernable from the file extension.  An empty string
        ///  is usually perfectly acceptable here.</param>
        /// <param name="options">For GDAL rasters, they can be created with optional parameters
        ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Generates a raster from the vectors.</returns>
        public static IRaster ToRaster(IFeatureSet fs, Extent extent, double cellSize, string fieldName, string outputFileName, string driverCode, string[] options, IProgressHandler progressHandler)
        {
            Extent env = extent;

            if (cellSize == 0)
            {
                if (env.Width < env.Height)
                {
                    cellSize = env.Width / 256;
                }
                else
                {
                    cellSize = env.Height / 256;
                }
            }

            int w = (int)Math.Ceiling(env.Width / cellSize);

            if (w > 8000)
            {
                w        = 8000;
                cellSize = env.Width / 8000;
            }

            int h = (int)Math.Ceiling(env.Height / cellSize);

            if (h > 8000)
            {
                h = 8000;
            }

            Bitmap   bmp = new Bitmap(w, h);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Transparent);
            g.SmoothingMode     = SmoothingMode.None;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            Hashtable colorTable;
            MapArgs   args = new MapArgs(new Rectangle(0, 0, w, h), env, g);

            switch (fs.FeatureType)
            {
            case FeatureType.Polygon:
            {
                MapPolygonLayer mpl = new MapPolygonLayer(fs);
                PolygonScheme   ps  = new PolygonScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }

            break;

            case FeatureType.Line:
            {
                MapLineLayer mpl = new MapLineLayer(fs);
                LineScheme   ps  = new LineScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }

            break;

            default:
            {
                MapPointLayer mpl = new MapPointLayer(fs);
                PointScheme   ps  = new PointScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }

            break;
            }

            Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType;

            // We will try to convert to double if it is a string
            if (tp == typeof(string))
            {
                tp = typeof(double);
            }

            InRamImageData image = new InRamImageData(bmp, env);
            ProgressMeter  pm    = new ProgressMeter(progressHandler, "Converting To Raster Cells", h);

            var output = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options);

            output.Bounds = new RasterBounds(h, w, env);

            double noDataValue = output.NoDataValue;

            if (fieldName != "FID")
            {
                // We can't use this method to calculate Max on a non-existent FID field.
                double dtMax = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", string.Empty));
                double dtMin = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", string.Empty));

                if (dtMin <= noDataValue && dtMax >= noDataValue)
                {
                    if (dtMax != GetFieldValue(tp, "MaxValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                    else if (dtMin != GetFieldValue(tp, "MinValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                }
            }

            List <RcIndex> locations   = new List <RcIndex>();
            List <string>  failureList = new List <string>();

            for (int row = 0; row < h; row++)
            {
                for (int col = 0; col < w; col++)
                {
                    Color c = image.GetColor(row, col);
                    if (c.A == 0)
                    {
                        output.Value[row, col] = output.NoDataValue;
                    }
                    else
                    {
                        if (colorTable.ContainsKey(c) == false)
                        {
                            if (c.A < 125)
                            {
                                output.Value[row, col] = output.NoDataValue;
                                continue;
                            }

                            // Use a color matching distance to pick the closest member
                            object val = GetCellValue(w, h, row, col, image, c, colorTable, locations);

                            output.Value[row, col] = GetDouble(val, failureList);
                        }
                        else
                        {
                            output.Value[row, col] = GetDouble(colorTable[c], failureList);
                        }
                    }
                }

                pm.CurrentValue = row;
            }

            const int MaxIterations = 5;
            int       iteration     = 0;

            while (locations.Count > 0)
            {
                List <RcIndex> newLocations = new List <RcIndex>();
                foreach (RcIndex location in locations)
                {
                    object val = GetCellValue(w, h, location.Row, location.Column, image, image.GetColor(location.Row, location.Column), colorTable, newLocations);
                    output.Value[location.Row, location.Column] = GetDouble(val, failureList);
                }

                locations = newLocations;
                iteration++;
                if (iteration > MaxIterations)
                {
                    break;
                }
            }

            pm.Reset();
            return(output);
        }
Пример #35
0
        private void ReadRgb()
        {
            if (_dataset.RasterCount < 3)
            {
                throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }

            _green = _dataset.GetRasterBand(2);
            _blue  = _dataset.GetRasterBand(3);

            int           tw  = TileCollection.TileWidth;
            int           th  = TileCollection.TileHeight;
            int           ntt = TileCollection.NumTilesTall();
            int           ntw = TileCollection.NumTilesWide();
            ProgressMeter pm  = new ProgressMeter(ProgressHandler, "Reading Tiles ", ntt * ntw);

            for (int row = 0; row < ntt; row++)
            {
                for (int col = 0; col < ntw; col++)
                {
                    int            width  = TileCollection.GetTileWidth(col);
                    int            height = TileCollection.GetTileHeight(row);
                    InRamImageData id     = new InRamImageData(width, height);

                    Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);

                    byte[] red = new byte[width * height];
                    byte[] g   = new byte[width * height];
                    byte[] b   = new byte[width * height];

                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0);
                    _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0);

                    BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);
                    byte[]    vals   = new byte[width * height * 4];
                    int       stride = Stride;
                    const int Bpp    = 4;
                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            vals[(r * stride) + (c * Bpp)]     = b[(r * width) + c];
                            vals[(r * stride) + (c * Bpp) + 1] = g[(r * width) + c];
                            vals[(r * stride) + (c * Bpp) + 2] = red[(r * width) + c];
                            vals[(r * stride) + (c * Bpp) + 3] = 255;
                        }
                    }

                    id.Values = vals;
                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                    pm.CurrentValue = (row * ntw) + col;
                }
            }

            pm.Reset();
            SetTileBounds(Bounds.AffineCoefficients);
        }
Пример #36
0
        public static ObjectId[] GetDublicates2d(List <IdPoint> points, double epsilon)
        {
            List <ObjectId> list  = new List <ObjectId>();
            List <IdPoint>  list2 = new List <IdPoint>();

            new List <IdPoint>();
            IComparer <IdPoint> comparer = new Class2();

            new Class3();
            new Class4();
            double num = epsilon * epsilon;

            for (int i = 0; i < points.Count; i++)
            {
                list2.Add(points[i]);
            }
            points.Sort(comparer);
            points.Reverse();
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(points.Count / 10);
            try
            {
                progressMeter.Start("Eliminating points");
                list2.Sort(comparer);
                for (int j = 0; j < points.Count; j++)
                {
                    if (j % 10 == 0)
                    {
                        progressMeter.MeterProgress();
                    }
                    IdPoint idPoint = points[j];
                    if (!idPoint.IsErased)
                    {
                        Point   point  = new Point(idPoint.Point.X - epsilon, -1.7976931348623157E+308, -1.7976931348623157E+308);
                        Point   point2 = new Point(idPoint.Point.X + epsilon, 1.7976931348623157E+308, 1.7976931348623157E+308);
                        IdPoint item   = new IdPoint(point, ObjectId.Null);
                        IdPoint item2  = new IdPoint(point2, ObjectId.Null);
                        int     num2   = list2.BinarySearch(item, comparer);
                        int     num3   = list2.BinarySearch(item2, comparer);
                        if (num2 < 0)
                        {
                            num2 = Math.Abs(num2) - 2;
                        }
                        if (num2 < 0)
                        {
                            num2 = 0;
                        }
                        if (num2 >= points.Count)
                        {
                            num2 = points.Count - 1;
                        }
                        if (num3 < 0)
                        {
                            num3 = Math.Abs(num3) - 1;
                        }
                        if (num3 < 0)
                        {
                            num3 = 0;
                        }
                        if (num3 >= points.Count)
                        {
                            num3 = points.Count - 1;
                        }
                        for (int k = num2; k <= num3; k++)
                        {
                            if (!list2[k].IsErased && list2[k] != idPoint && IdPoint.smethod_0(idPoint.Point, list2[k].Point) < num)
                            {
                                list2[k].IsErased = true;
                            }
                        }
                    }
                }
                for (int l = 0; l < points.Count; l++)
                {
                    if (points[l].IsErased)
                    {
                        list.Add(points[l].ID);
                    }
                }
            }
            catch
            {
                progressMeter.Stop();
                throw;
            }
            progressMeter.Stop();
            return(list.ToArray());
        }
        private static void placementAparts(Database db)
        {
            using (var t = db.TransactionManager.StartTransaction())
            {
                ObjectId idTextStylePik = db.GetTextStylePIK();

                var bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;
                var ms = bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord;
                int countAparts;
                var btrApartGroups = getGroupedAparts(bt, out countAparts);
                Point3d pt = Point3d.Origin;
                Point3d ptCenterPlace;

                using (var progress = new ProgressMeter())
                {
                    progress.SetLimit(countAparts);
                    progress.Start("Расстановка квартир...");

                    foreach (var btrApartGroup in btrApartGroups)
                    {
                        progress.MeterProgress();

                        foreach (var idBtrApart in btrApartGroup)
                        {
                            var curPlaceWidth = placeWidth;

                            var blRefApart = new BlockReference(pt, idBtrApart);
                            blRefApart.SetDatabaseDefaults(db);
                            var extApart = blRefApart.GeometricExtents;
                            var lenApart = extApart.MaxPoint.X - extApart.MinPoint.X;
                            if (lenApart > placeWidth)
                            {
                                curPlaceWidth = lenApart + 1000;
                            }

                            ptCenterPlace = new Point3d(pt.X + curPlaceWidth*0.5, pt.Y - placeHeight*0.5, 0);

                            var ptBlCenter = extApart.Center();
                            // Перемещение блока в центр прямоугольной области
                            Matrix3d displace = Matrix3d.Displacement(ptCenterPlace - ptBlCenter);
                            blRefApart.TransformBy(displace);
                            ms.AppendEntity(blRefApart);
                            t.AddNewlyCreatedDBObject(blRefApart, true);

                            // Подпись квартиры
                            DBText text = new DBText();
                            text.SetDatabaseDefaults();
                            text.TextStyleId = idTextStylePik;
                            text.Height = 900;
                            text.TextString = getApartName(blRefApart.Name);
                            text.Position = new Point3d (pt.X+300, pt.Y+300,0);
                            ms.AppendEntity(text);
                            t.AddNewlyCreatedDBObject(text, true);

                            // Прямоугольник расположения квартиры
                            Polyline pl = new Polyline(4);
                            pl.AddVertexAt(0, pt.Convert2d(), 0, 0, 0);
                            pl.AddVertexAt(1, new Point2d (pt.X+ curPlaceWidth, pt.Y), 0, 0, 0);
                            pl.AddVertexAt(2, new Point2d(pt.X + curPlaceWidth, pt.Y-placeHeight), 0, 0, 0);
                            pl.AddVertexAt(3, new Point2d(pt.X, pt.Y - placeHeight), 0, 0, 0);
                            pl.Closed = true;
                            pl.SetDatabaseDefaults();
                            ms.AppendEntity(pl);
                            t.AddNewlyCreatedDBObject(pl, true);

                            pt = new Point3d(pt.X + curPlaceWidth, pt.Y, 0);
                        }
                        pt = new Point3d(0, pt.Y - placeHeight - 8000, 0);
                    }
                    progress.Stop();
                }
                t.Commit();
            }
        }
Пример #38
0
        // Содержание тома (Общие данные. Ведомость комплекта чертежей.)
        public void Contents()
        {
            // Создание файла содержания и титульных листов
             string fileContent = Path.Combine(_album.AlbumDir, "00_Содержание" + _album.StartOptions.Abbr + ".dwg");
             File.Copy(_sheetsSet.SheetTemplateFileContent, fileContent);

             // Кол листов содержания = Суммарное кол лисчтов панелей / на кол строк в таблице на одном листе
             // Но на первом листе содержания первые 5 строк заняты (обложка, тит, общие данные, наруж стен панели, том1).
             //_dbFacade = HostApplicationServices.WorkingDatabase;
             using (_dbContent = new Database(false, true))
             {
            _dbContent.ReadDwgFile(fileContent, FileShare.ReadWrite, false, "");
            _dbContent.CloseInput(true);

            using (new AcadLib.WorkingDatabaseSwitcher(_dbContent))
            {
               // Замена блока рамки из чертежа фасада, если он есть
               _album.AlbumInfo?.Frame?.ChangeBlockFrame(_dbContent, false);
               _album?.AlbumInfo?.CoverTitle?.ChangeCoverAndTitle(_dbContent);

               using (var t = _dbContent.TransactionManager.StartTransaction())
               {
                  int curContentLayoutNum = _countSheetsBeforContent+1;
                  Table tableContent;
                  BlockReference blRefStamp;
                  CopyContentSheet(t, curContentLayoutNum, out tableContent, out blRefStamp);
                  // Определение кол-ва марок АР
                  int countMarkArs = CalcMarksArNumber(_sheetsMarkSB);
                  // Определение кол-ва листов содержания (только для панелей без учета лтстов обложек и тп.)
                  _countContentSheets = CalcSheetsContentNumber(tableContent.Rows.Count, countMarkArs) + _album.StartOptions.NumberAddSheetContent;
                  // Заполнение штампа на первом листе содержания
                  FillingStampContent(blRefStamp, curContentLayoutNum- _countSheetsBeforContent, t);
                  // текущая строка для записи листа
                  int row = _firstRowInTableForSheets;

                  // На первом листе содержания заполняем строки для Обложки, Тит, Общ дан, НСП, Том1.
                  tableContent.Cells[row, 2].TextString = 1.ToString();
                  tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter;
                  tableContent.Cells[row++, 1].TextString = "Обложка";

                  tableContent.Cells[row, 2].TextString = 2.ToString();
                  tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter;
                  tableContent.Cells[row++, 1].TextString = "Титульный лист";

                  tableContent.Cells[row, 1].TextString = "Общие данные. Ведомость комплекта чертежей";
                  tableContent.Cells[row, 2].TextString = _countContentSheets > 1 ? "3-" + (3 + _countContentSheets - 1).ToString() : "3";
                  tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter;
                  row++;
                  tableContent.Cells[row++, 1].TextString = "Наружные стеновые панели";
                  tableContent.Cells[row++, 1].TextString = "ТОМ";

                  int curSheetArNum;
                  if (_album.StartOptions.NumberFirstSheet == 0)
                  {
                     curSheetArNum = _countContentSheets + _countSheetsBeforContent;// номер для первого листа Марки АР
                  }
                  else
                  {
                     curSheetArNum = _album.StartOptions.NumberFirstSheet - 1;
                  }

                  ProgressMeter progressMeter = new ProgressMeter();
                  progressMeter.SetLimit(_sheetsMarkSB.Count);
                  progressMeter.Start("Создание содержания ");

                  foreach (var sheetMarkSB in _sheetsMarkSB)
                  {
                     progressMeter.MeterProgress();
                     foreach (var sheetMarkAR in sheetMarkSB.SheetsMarkAR)
                     {
                        tableContent.Cells[row, 1].TextString = sheetMarkAR.MarkArFullName + ". Раскладка плитки на фасаде";
                        sheetMarkAR.SheetNumber = ++curSheetArNum;
                        tableContent.Cells[row, 2].TextString = curSheetArNum.ToString();
                        tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter;
                        row++;
                        CheckEndOfTable(t, ref curContentLayoutNum, ref tableContent, ref blRefStamp, ref row);

                        tableContent.Cells[row, 1].TextString = sheetMarkAR.MarkArFullName + ". Раскладка плитки в форме";
                        tableContent.Cells[row, 2].TextString = curSheetArNum.ToString() + ".1";
                        sheetMarkAR.SheetNumberInForm = curSheetArNum.ToString() + ".1";
                        tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter;
                        row++;
                        CheckEndOfTable(t, ref curContentLayoutNum, ref tableContent, ref blRefStamp, ref row);
                     }
                  }
                  progressMeter.Stop();

                  //Удаление пустых строк в таблице содержания
                  if (tableContent.Rows.Count > row + 1)
                  {
                     tableContent.DeleteRows(row, tableContent.Rows.Count - row);
                  }

                  // Удаление последнего листа содержания (пустой копии)
                  HostApplicationServices.WorkingDatabase = _dbContent;
                  LayoutManager lm = LayoutManager.Current;
                  //lm.CurrentLayout = getLayoutContentName(_countSheetsBeforContent + 1);
                  //string layoutNameToDel = (_countSheetsBeforContent + (++_countContentSheets)).ToString("00") + "_" + Settings.Default.SheetTemplateLayoutNameForContent;
                  lm.DeleteLayout(Settings.Default.SheetTemplateLayoutNameForContent);

                  t.Commit();
               }
               //HostApplicationServices.WorkingDatabase = _dbFacade;
            }
            _dbContent.SaveAs(fileContent, DwgVersion.Current);
             }
        }
        private void placementSpots(List<Spot> spots)
        {
            using (var lockdoc = _doc.LockDocument())
            {
                using (var t = _db.TransactionManager.StartTransaction())
                {
                    var bt = t.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    var cs = t.GetObject(_db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    _idMS = cs.Id;
                    var btrColorArea = t.GetObject(bt[Settings.Default.BlockColorAreaName], OpenMode.ForRead) as BlockTableRecord;
                    var blRefColorAreaTemplate = new BlockReference(Point3d.Origin, btrColorArea.Id);
                    cs.AppendEntity(blRefColorAreaTemplate);
                    t.AddNewlyCreatedDBObject(blRefColorAreaTemplate, true);
                    _idBlRefColorAreaTemplate = blRefColorAreaTemplate.Id;
                    SetDynParamColorAreaBlock(blRefColorAreaTemplate, _colorAreaSize);
                    using (_idColCopy = new ObjectIdCollection())
                    {
                        _idColCopy.Add(_idBlRefColorAreaTemplate);
                        ProgressMeter progressMeter = new ProgressMeter();
                        progressMeter.SetLimit(spots.Count);
                        progressMeter.Start("Вставка блоков зон покраски...");

                        _countInsertBlocksSpot = 0;
                        foreach (var spot in spots)
                        {
                            progressMeter.MeterProgress();
                            if (HostApplicationServices.Current.UserBreak())
                                break;
                            if (spot != null)
                            {
                                insertSpot(spot, spot.Index / _ysize, spot.Index % _ysize, t);
                            }
                        }
                        progressMeter.Stop();
                    }
                    Logger.Log.Debug("Вставлено блоков {0}", _countInsertBlocksSpot);

                    blRefColorAreaTemplate.Erase(true);
                    t.Commit();
                }
            }
        }
Пример #40
0
        public static void Compute2dHull(ObjectId[] idArray, CoordinateSystem actualCS)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter value           = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(value);
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    progressMeter.SetLimit(idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        progressMeter.Start("Computing 2d hull...");
                    }
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), actualCS);
                    CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        coordinateTransformator.Transform(point);
                        pointSet.Add(point);
                    }
                    ConvexHull2d convexHull2d = new ConvexHull2d();
                    convexHull2d.InitialPoints = pointSet;
                    convexHull2d.ComputeHull();
                    PointSet vertices = convexHull2d.Vertices;
                    double   z        = vertices[0].Z;
                    for (int j = 0; j < vertices.Count; j++)
                    {
                        vertices[j].Z = z;
                    }
                    double areaXY = convexHull2d.AreaXY;
                    for (int k = 0; k < vertices.Count; k++)
                    {
                        inverseTransformation.Transform(vertices[k]);
                    }
                    Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(vertices.ToList());
                    Polyline3d        polyline3d        = new Polyline3d(0, point3dCollection, true);
                    polyline3d.LayerId = (layerId);
                    blockTableRecord.AppendEntity(polyline3d);
                    transaction.AddNewlyCreatedDBObject(polyline3d, true);
                    editor.WriteMessage("\n2d convex hull properties:");
                    editor.WriteMessage("\nNumber of vertices on hull : " + convexHull2d.Vertices.Count);
                    editor.WriteMessage("\nHull perimeter length      : " + convexHull2d.PerimeterLength.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nEnclosed area in hull plane: " + areaXY.ToString(DBManager.GetFormatFromLUPREC()));
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #41
0
        private void ReadRgb()
        {
            if (_dataset.RasterCount < 3)
            {
                throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _green = _dataset.GetRasterBand(2);
            _blue = _dataset.GetRasterBand(3);

            int tw = TileCollection.TileWidth;
            int th = TileCollection.TileHeight;
            int ntt = TileCollection.NumTilesTall();
            int ntw = TileCollection.NumTilesWide();
            ProgressMeter pm = new ProgressMeter(ProgressHandler, "Reading Tiles ", ntt * ntw);
            for (int row = 0; row < ntt; row++)
            {
                for (int col = 0; col < ntw; col++)
                {
                    int width = TileCollection.GetTileWidth(col);
                    int height = TileCollection.GetTileHeight(row);
                    InRamImageData id = new InRamImageData(width, height);

                    Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);

                    byte[] red = new byte[width * height];
                    byte[] g = new byte[width * height];
                    byte[] b = new byte[width * height];

                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0);
                    _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0);

                    BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                                       PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);
                    byte[] vals = new byte[width * height * 4];
                    int stride = Stride;
                    const int bpp = 4;
                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            vals[r * stride + c * bpp] = b[r * width + c];
                            vals[r * stride + c * bpp + 1] = g[r * width + c];
                            vals[r * stride + c * bpp + 2] = red[r * width + c];
                            vals[r * stride + c * bpp + 3] = 255;
                        }
                    }
                    id.Values = vals;
                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                    pm.CurrentValue = row * ntw + col;
                }
            }
            pm.Reset();
            SetTileBounds(Bounds.AffineCoefficients);
        }
Пример #42
0
        // Создание альбома панелей
        public void CreateAlbum()
        {
            //Создание файлов марок СБ и листов марок АР в них.
            // Проверка наличия файла шаблона листов
            _sheetTemplateFileMarkSB = Path.Combine(Commands.CurDllDir, Settings.Default.TemplateSheetMarkSBFileName);
            _sheetTemplateFileContent = Path.Combine(Commands.CurDllDir, Settings.Default.TemplateSheetContentFileName);
            if (!File.Exists(_sheetTemplateFileMarkSB))
                throw new System.Exception("\nНе найден файл шаблона для листов панелей - " + _sheetTemplateFileMarkSB);
            if (!File.Exists(_sheetTemplateFileContent))
                throw new System.Exception("\nНе найден файл шаблона для содержания альбома - " + _sheetTemplateFileContent);

            // Обработка панелей. получение списка Марок СБ SheetMarkSB (без создания папок, файлов и листов автокада)
            _sheetsMarkSB = ProcessingSheets(Album.MarksSB);
            if (_sheetsMarkSB.Count == 0)
            {
                throw new System.Exception("Не определены панели марок АР");
            }

            // Создаение папки для альбома панелей
            CreateAlbumFolder();

            //Поиск блока рамки на текущем чертеже фасада
            Album.AlbumInfo = new AlbumInfo();
            Album.AlbumInfo.Search();

            // Титульные листы и обложеи в одном файле "Содержание".
            // Создание титульных листов
            // Листы содержания
            SheetsContent content = new SheetsContent(this);
            content.Contents();

            ProgressMeter progressMeter = new ProgressMeter();
            progressMeter.SetLimit(_sheetsMarkSB.Count);
            progressMeter.Start("Создание файлов панелей марок СБ с листами марок АР...");
            int countMarkSB = 1;
            foreach (var sheetMarkSB in _sheetsMarkSB)
            {
                if (HostApplicationServices.Current.UserBreak())
                    throw new System.Exception("Отменено пользователем.");
                progressMeter.MeterProgress();

                sheetMarkSB.CreateSheetMarkSB(this, countMarkSB++);
            }
            progressMeter.Stop();
        }
Пример #43
0
        public static void EraseDublicates2d(ObjectId[] pointIDs, double epsilon, string keepMultiple, ref int numberOfPointsErased)
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            IComparer <IdPoint> comparer = new Class2();
            double num = epsilon * epsilon;

            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    CoordinateSystem        ceometricUcs            = Conversions.GetCeometricUcs();
                    CoordinateSystem        actualCS                = CoordinateSystem.Global();
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(actualCS, ceometricUcs);
                    List <IdPoint>          list = new List <IdPoint>();
                    for (int i = 0; i < pointIDs.Length; i++)
                    {
                        DBPoint dbPoint = (DBPoint)transaction.GetObject(pointIDs[i], (OpenMode)1, true);
                        IdPoint idPoint = new IdPoint(dbPoint);
                        coordinateTransformator.Transform(idPoint.Point);
                        list.Add(idPoint);
                    }
                    list.Sort(comparer);
                    List <IdPoint> list2 = new List <IdPoint>();
                    for (int j = 0; j < list.Count; j++)
                    {
                        list2.Add(list[j]);
                    }
                    if (keepMultiple == "H")
                    {
                        list.Reverse();
                    }
                    progressMeter.SetLimit(list.Count);
                    if ((double)list.Count > 10000.0)
                    {
                        progressMeter.Start("Eliminating points");
                    }
                    for (int k = 0; k < list.Count; k++)
                    {
                        progressMeter.MeterProgress();
                        messageFilter.CheckMessageFilter((long)k, 1000);
                        IdPoint idPoint2 = list[k];
                        if (!idPoint2.IsErased)
                        {
                            Point   point  = new Point(idPoint2.Point.X - epsilon, -1.7976931348623157E+308, -1.7976931348623157E+308);
                            Point   point2 = new Point(idPoint2.Point.X + epsilon, 1.7976931348623157E+308, 1.7976931348623157E+308);
                            IdPoint item   = new IdPoint(point, ObjectId.Null);
                            IdPoint item2  = new IdPoint(point2, ObjectId.Null);
                            int     num2   = list2.BinarySearch(item, comparer);
                            int     num3   = list2.BinarySearch(item2, comparer);
                            if (num2 < 0)
                            {
                                num2 = Math.Abs(num2) - 2;
                            }
                            if (num2 < 0)
                            {
                                num2 = 0;
                            }
                            if (num2 >= list.Count)
                            {
                                num2 = list.Count - 1;
                            }
                            if (num3 < 0)
                            {
                                num3 = Math.Abs(num3) - 1;
                            }
                            if (num3 < 0)
                            {
                                num3 = 0;
                            }
                            if (num3 >= list.Count)
                            {
                                num3 = list.Count - 1;
                            }
                            for (int l = num2; l <= num3; l++)
                            {
                                if (!list2[l].IsErased && list2[l] != idPoint2 && IdPoint.smethod_0(idPoint2.Point, list2[l].Point) < num)
                                {
                                    list2[l].IsErased = true;
                                    list2[l].DBPoint.Erase();
                                    numberOfPointsErased++;
                                }
                            }
                        }
                    }
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #44
0
        public static void ComputeMinEnclosingCircle(ObjectId[] idArray, CoordinateSystem actualCS)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter value           = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(value);
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    progressMeter.SetLimit(idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        progressMeter.Start("Computing min. enclosing circle...");
                    }
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), actualCS);
                    CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        coordinateTransformator.Transform(point);
                        pointSet.Add(point);
                    }
                    ConvexHull2d convexHull2d = new ConvexHull2d();
                    convexHull2d.InitialPoints = pointSet;
                    convexHull2d.ComputeHull();
                    PointSet vertices = convexHull2d.Vertices;
                    double   z        = vertices[0].Z;
                    for (int j = 0; j < vertices.Count; j++)
                    {
                        vertices[j].Z = z;
                    }
                    SmallestEnclosingCircle         smallestEnclosingCircle = new SmallestEnclosingCircle(vertices);
                    ngeometry.VectorGeometry.Circle circle = smallestEnclosingCircle.ComputeCircle();
                    Point center = circle.Center;
                    Point point2 = circle.NormalVector.ToPoint();
                    inverseTransformation.Transform(center);
                    inverseTransformation.Transform(point2);
                    Autodesk.AutoCAD.DatabaseServices.Circle circle2 = new Autodesk.AutoCAD.DatabaseServices.Circle(new Autodesk.AutoCAD.Geometry.Point3d(center.X, center.Y, center.Z), new Autodesk.AutoCAD.Geometry.Vector3d(point2.X, point2.Y, point2.Z), circle.Radius);
                    circle2.LayerId = (layerId);
                    blockTableRecord.AppendEntity(circle2);
                    transaction.AddNewlyCreatedDBObject(circle2, true);
                    editor.WriteMessage("\nMinimum enclosing circle properties:");
                    editor.WriteMessage("\n------------------------------------");
                    editor.WriteMessage("\nRadius          : " + circle.Radius.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nArea            : " + circle.Area.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nPerimeter length: " + circle.Circumference.ToString(DBManager.GetFormatFromLUPREC()));
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
        public void DefinePanels(List<Facade> facades)
        {
            // определение экспортируемых панелей - в файле АКР
            Dictionary<ObjectId, PanelBtrExport> dictPanelsBtrExport = new Dictionary<ObjectId, PanelBtrExport>();

            //RTreeLib.RTree<Facade> treeFacades = new RTreeLib.RTree<Facade>();
            //facades.ForEach(f =>
            //               {
            //                  try
            //                  {
            //                     treeFacades.Add(ColorArea.GetRectangleRTree(f.Extents), f);
            //                  }
            //                  catch { }
            //               });

            ProgressMeter progress = new ProgressMeter();
            progress.SetLimit(Service.SelectPanels.IdsBlRefPanelAr.Count);
            progress.Start("Определение панелей в файле АКР");

            foreach (var idBlRefPanel in Service.SelectPanels.IdsBlRefPanelAr)
            {
                progress.MeterProgress();
                if (HostApplicationServices.Current.UserBreak())
                    throw new System.Exception("Отменено пользователем.");
                using (var blRef = idBlRefPanel.Open(OpenMode.ForRead, false, true) as BlockReference)
                {
                    // панель определения блока
                    PanelBtrExport panelBtrExport;
                    if (!dictPanelsBtrExport.TryGetValue(blRef.BlockTableRecord, out panelBtrExport))
                    {
                        panelBtrExport = new PanelBtrExport(blRef.BlockTableRecord, this);
                        dictPanelsBtrExport.Add(blRef.BlockTableRecord, panelBtrExport);
                    }
                    panelBtrExport.Def();

                    // панель вхождения блока
                    PanelBlRefExport panelBlRefExport = new PanelBlRefExport(blRef, panelBtrExport);
                    panelBtrExport.Panels.Add(panelBlRefExport);

                    //// определение фасада панели
                    //panelBlRefExport.Facade = defFacadeForPanel(treeFacades, blRef, panelBtrExport, panelBlRefExport);
                }
            }
            PanelsBtrExport = dictPanelsBtrExport.Values.ToList();
            progress.Stop();
        }
Пример #46
0
        /// <summary>
        /// Creates a bitmap based on the specified RasterSymbolizer
        /// </summary>
        /// <param name="bitmap"> the bitmap to paint to</param>
        /// <param name="progressHandler">The progress handler</param>
        public void PaintShadingToBitmap(Bitmap bitmap, IProgressHandler progressHandler)
        {
            BitmapData bmpData;

            if (_hillshade == null)
            {
                return;
            }

            // Create a new Bitmap and use LockBits combined with Marshal.Copy to get an array of bytes to work with.
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            try
            {
                bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            }
            catch (ArgumentException ex)
            {
                if (ex.ParamName == "format")
                {
                    throw new BitmapFormatException();
                }

                throw;
            }

            int numBytes = bmpData.Stride * bmpData.Height;

            byte[] rgbData = new byte[numBytes];
            Marshal.Copy(bmpData.Scan0, rgbData, 0, numBytes);

            float[][] hillshade = _hillshade;

            ProgressMeter pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingHillshade, bitmap.Height);

            if (bitmap.Width * bitmap.Height < 100000)
            {
                pm.StepPercent = 50;
            }
            if (bitmap.Width * bitmap.Height < 500000)
            {
                pm.StepPercent = 10;
            }
            if (bitmap.Width * bitmap.Height < 1000000)
            {
                pm.StepPercent = 5;
            }
            for (int row = 0; row < bitmap.Height; row++)
            {
                for (int col = 0; col < bitmap.Width; col++)
                {
                    int  offset = (row * bmpData.Stride) + (col * 4);
                    byte b      = rgbData[offset];
                    byte g      = rgbData[offset + 1];
                    byte r      = rgbData[offset + 2];

                    // rgbData[offset + 3] = a; don't worry about alpha
                    int red   = Convert.ToInt32(r * hillshade[row][col]);
                    int green = Convert.ToInt32(g * hillshade[row][col]);
                    int blue  = Convert.ToInt32(b * hillshade[row][col]);
                    if (red > 255)
                    {
                        red = 255;
                    }
                    if (green > 255)
                    {
                        green = 255;
                    }
                    if (blue > 255)
                    {
                        blue = 255;
                    }
                    if (red < 0)
                    {
                        red = 0;
                    }
                    if (green < 0)
                    {
                        green = 0;
                    }
                    if (blue < 0)
                    {
                        blue = 0;
                    }
                    b = (byte)blue;
                    r = (byte)red;
                    g = (byte)green;

                    rgbData[offset]     = b;
                    rgbData[offset + 1] = g;
                    rgbData[offset + 2] = r;
                }

                pm.CurrentValue = row;
            }

            pm.Reset();

            // Copy the values back into the bitmap
            Marshal.Copy(rgbData, 0, bmpData.Scan0, numBytes);
            bitmap.UnlockBits(bmpData);
        }
Пример #47
0
        private void RedefBlockInFiles(Editor ed, Database db, List<RedefineBlock> blocksRedefine,
                                        List<RedefineBlock> renameBlocks, List<FileInfo> filesDwg)
        {
            int countFilesRedefined = 0;
            int countFilesWithoutBlock = 0;
            int countFilesError = 0;

            // Прогресс бар
            ProgressMeter pBar = new ProgressMeter();
            pBar.Start("Переопределение блоков в файлах... нажмите Esc для отмены");
            pBar.SetLimit(filesDwg.Count);

            // Переименование блоков в этом файле
            var errs = RenameBlocks(db, renameBlocks);
            if (errs.Count != 0)
                Inspector.Errors.AddRange(errs);

            Dictionary<string, Document> dictDocs = new Dictionary<string, Document>(StringComparer.OrdinalIgnoreCase);
            foreach (Document doc in Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager)
            {
                dictDocs.Add(doc.Name, doc);
            }

            foreach (var file in filesDwg)
            {
                // Переопределение блока в файле
                try
                {
                    Document doc;
                    if (dictDocs.TryGetValue(file.FullName, out doc))
                    {
                        using (doc.LockDocument())
                        {
                            RedefineBlockInFile(doc, blocksRedefine, renameBlocks, file, ref countFilesRedefined, ref countFilesWithoutBlock);
                            Inspector.AddError($"Обработан открытый документ '{doc.Name}'", System.Drawing.SystemIcons.Hand);
                        }
                    }
                    else
                    {
                        RedefineBlockInFile(ed, db, blocksRedefine, renameBlocks, file, ref countFilesRedefined, ref countFilesWithoutBlock);
                    }
                }
                catch (System.Exception ex)
                {
                    Inspector.AddError($"Ошибка при переопределении блока в файле {file.Name} - {ex.Message}", System.Drawing.SystemIcons.Error);
                    ed.WriteMessage("\nОшибка при переопределении блока в файле " + file.Name);
                    ed.WriteMessage("\nТекст ошибки " + ex.Message);
                }
                pBar.MeterProgress();
            }

            pBar.Stop();

            ed.WriteMessage("\nПереопределен блок в " + countFilesRedefined + " файле.");
            if (countFilesWithoutBlock != 0)
                ed.WriteMessage("\nНет блока в " + countFilesWithoutBlock + " файле.");
            if (countFilesError != 0)
                ed.WriteMessage("\nОшибка при переопределении блока в " + countFilesError + " файле.");
            ed.WriteMessage("\nГотово");
        }
Пример #48
0
        private void BuildPaths(MapArgs e, IEnumerable <int> indices, out Dictionary <FastDrawnState, GraphicsPath> paths, bool selected)
        {
            paths = new Dictionary <FastDrawnState, GraphicsPath>();

            var indiceList = indices as IList <int> ?? indices.ToList();

            FastDrawnState[] states = DrawnStatesNeeded ? DrawnStates : new FastDrawnState[0];
            if (DrawnStatesNeeded && indiceList.Max() >= states.Length)
            {
                AssignFastDrawnStates();
                states = DrawnStates;
            }

            if (selected && (!DrawnStatesNeeded || !DrawnStates.Any(_ => _.Selected)))
            {
                return;
            }

            if (ProgressReportingEnabled)
            {
                ProgressMeter = new ProgressMeter(ProgressHandler, "Building Paths", indiceList.Count);
            }

            FastDrawnState     state       = new FastDrawnState(selected, Symbology.Categories[0]);
            Extent             drawExtents = e.GeographicExtents;
            Rectangle          clipRect    = e.ProjToPixel(e.GeographicExtents);
            SoutherlandHodgman shClip      = new SoutherlandHodgman(clipRect);

            List <ShapeRange> shapes = DataSet.ShapeIndices;

            double[] vertices = DataSet.Vertex;

            foreach (int shp in indiceList)
            {
                if (ProgressReportingEnabled)
                {
                    ProgressMeter.Next();
                }
                if (shp >= shapes.Count)
                {
                    return;
                }
                ShapeRange shape = shapes[shp];
                if (!shape.Extent.Intersects(e.GeographicExtents))
                {
                    continue;
                }

                if (DrawnStatesNeeded)
                {
                    if (!states[shp].Visible || (selected && !states[shp].Selected))
                    {
                        continue;
                    }

                    state = new FastDrawnState(selected, states[shp].Category);
                }

                if (!paths.ContainsKey(state))
                {
                    paths.Add(state, new GraphicsPath(FillMode.Winding));
                }

                BuildPolygon(vertices, shapes[shp], paths[state], e, drawExtents.Contains(shape.Extent) ? null : shClip);
            }

            if (ProgressReportingEnabled)
            {
                ProgressMeter.Reset();
            }
        }
Пример #49
0
        /// <summary>
        /// Экспорт квартир в базу.
        /// </summary>      
        public static void Export(List<Apartment> apartments)
        {
            //TestInfoApartmentstoDb(apartments);
            if (apartments.Count == 0)
            {
                return;
            }

            using (entities = ConnectEntities())
            {
                //entities.Configuration.AutoDetectChangesEnabled = false;
                //entities.Configuration.ValidateOnSaveEnabled = false;

                // Загрузка последних квартир
                var flatsBD = entities.F_R_Flats.GroupBy(g => g.WORKNAME).
                            Select(s => s.OrderByDescending(o => o.REVISION).First()).ToList();
                // Загрузка последних модулей
                var modulesBD = entities.F_R_Modules.GroupBy(g=>g.NAME_MODULE).
                              Select(s=>s.OrderByDescending(o=>o.REVISION).First());
                entities.F_nn_FlatModules.Load();
                entities.F_nn_ElementParam_Value.Load();
                entities.F_nn_Elements_Modules.Load();
                entities.F_S_Elements.Load();
                entities.F_S_FamilyInfos.Load();
                entities.F_S_Categories.Load();
                entities.F_nn_Category_Parameters.Load();

                try
                {
                    // Элементы дверей и их стены - для обновления параметрв idWall
                    doorsAndHostWall = new List<Tuple<F_nn_Elements_Modules, List<F_nn_Elements_Modules>>>();

                    // Модули - новые или с изменениями
                    var modules = apartments.SelectMany(a => a.Modules)
                                            .Where(m => !m.BaseStatus.HasFlag(EnumBaseStatus.Error) &&
                                                     (
                                                        m.BaseStatus.HasFlag(EnumBaseStatus.Changed) ||
                                                        m.BaseStatus.HasFlag(EnumBaseStatus.New)
                                                     )
                                                  )
                                            .GroupBy(g => g.Name).Select(g => g.First());

                    using (var progress = new ProgressMeter())
                    {
                        progress.SetLimit(modules.Count());
                        progress.Start("Запись модулей в базу...");

                        foreach (var module in modules)
                        {
                            progress.MeterProgress();
                            // поиск модуля
                            var moduleEnt = defineModuleEnt(module, modulesBD);
                        }
                        progress.Stop();
                    }

                    using (var progress = new ProgressMeter())
                    {
                        progress.SetLimit(modules.Count());
                        progress.Start("Запись квартир в базу...");

                        // Определение квартир и привязка модулей
                        foreach (Apartment apart in apartments)
                        {
                            progress.MeterProgress();
                            // Определение квартиры
                            var flatEnt = defineFlatEnt(apart);
                        }
                        progress.Stop();
                    }

                    // Сохранение изменений
                    entities.SaveChanges();

                    // обновление параметра стен для дверей
                    if (doorsAndHostWall.Count > 0)
                    {
                        foreach (var doorAndHostWall in doorsAndHostWall)
                        {
                            F_nn_Elements_Modules doorEmEnt = doorAndHostWall.Item1;
                            string hostWallsValue = string.Join(";", doorAndHostWall.Item2.Select(w => w.ID_ELEMENT_IN_MODULE.ToString()));
                            // Запись id стены в параметр
                            // Поиск параметра IdWall для заполнения
                            var paramHostWall = doorEmEnt.F_S_Elements.F_nn_ElementParam_Value.Single(p =>
                                  p.F_nn_Category_Parameters.F_S_Parameters.NAME_PARAMETER
                                     .Equals(Options.Instance.DoorHostWallParameter, StringComparison.OrdinalIgnoreCase));
                            paramHostWall.PARAMETER_VALUE = hostWallsValue;// wallEmEnt.ID_ELEMENT_IN_MODULE.ToString();
                        }
                    }
                    entities.SaveChanges();
                }
                catch (System.Exception ex)
                {
                    Inspector.AddError(ex.Message, icon: System.Drawing.SystemIcons.Error);
                }
            }
            return;
        }
Пример #50
0
        private void method_0(ObjectId[] objectId_0, ref ProgressMeter progressMeter_0, CoordinateSystem coordinateSystem_0)
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            List <Region> list            = new List <Region>();
            double        epsilon         = Convert.ToDouble(CMD_Silhouette.string_1);

            DBManager.SetEpsilon();
            List <Triangle> list2 = Conversions.ToCeometricAcDbTriangleList(objectId_0);

            if (!Conversions.IsWCS(coordinateSystem_0))
            {
                Triangle.TransformCoordinates(list2, CoordinateSystem.Global(), coordinateSystem_0);
            }
            list2.Sort(new Triangle.CompareMinX());
            int    num  = 0;
            double num2 = -1.7976931348623157E+308;
            double num3 = -1.7976931348623157E+308;
            double num4 = 1.7976931348623157E+308;
            double num5 = 1.7976931348623157E+308;

            for (int i = list2.Count - 1; i >= 0; i--)
            {
                if (list2[i].NormalVector.IsOrthogonalTo(new ngeometry.VectorGeometry.Vector3d(0.0, 0.0, 1.0)))
                {
                    list2.RemoveAt(i);
                    num++;
                }
                else
                {
                    Global.SuspendEpsilon(0.0, 0.0);
                    list2[i].Vertex1.Z = 0.0;
                    list2[i].Vertex2.Z = 0.0;
                    list2[i].Vertex3.Z = 0.0;
                    Global.ResumeEpsilon();
                    double minimumX = list2[i].MinimumX;
                    if (minimumX < num4)
                    {
                        num4 = minimumX;
                    }
                    double maximumX = list2[i].MaximumX;
                    if (maximumX > num2)
                    {
                        num2 = maximumX;
                    }
                    double minimumY = list2[i].MinimumY;
                    if (minimumY < num5)
                    {
                        num5 = minimumY;
                    }
                    double maximumY = list2[i].MaximumY;
                    if (maximumY > num3)
                    {
                        num3 = maximumY;
                    }
                }
            }
            ngeometry.VectorGeometry.Vector3d vector3d = new ngeometry.VectorGeometry.Vector3d(0.5 * (num4 + num2), 0.5 * (num5 + num3), 0.0);
            double num6 = 0.5 * Math.Max(Math.Abs(num2 - num4), Math.Abs(num3 - num5));
            double num7 = Math.Ceiling(100000.0 / num6);

            for (int j = 0; j < list2.Count; j++)
            {
                list2[j] = list2[j].Move(-1.0 * vector3d);
            }
            SubDMeshHandler subDMeshHandler = new SubDMeshHandler(list2);

            subDMeshHandler.BuildDataStructure(false);
            int k = 2147483647;

            while (k > 0)
            {
                this.messageFilter_0.CheckMessageFilter();
                k    = subDMeshHandler.Heal(epsilon);
                num += k;
            }
            editor.WriteMessage("\nDegenerate projections healed: " + num);
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d  = Autodesk.AutoCAD.Geometry.Matrix3d.Scaling(num7, new Point3d(0.0, 0.0, 0.0));
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d2 = Autodesk.AutoCAD.Geometry.Matrix3d.Scaling(1.0 / num7, new Point3d(0.0, 0.0, 0.0));
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d3 = Autodesk.AutoCAD.Geometry.Matrix3d.Displacement(new Autodesk.AutoCAD.Geometry.Vector3d(vector3d.X, vector3d.Y, 0.0));
            progressMeter_0 = new ProgressMeter();
            progressMeter_0.SetLimit(subDMeshHandler.FaceVertexIndex1.Count);
            progressMeter_0.Start("Generating projections");
            int num8 = 0;

            for (int l = 0; l < subDMeshHandler.FaceVertexIndex1.Count; l++)
            {
                try
                {
                    progressMeter_0.MeterProgress();
                    this.messageFilter_0.CheckMessageFilter((long)l, 1000);
                }
                catch (System.Exception ex)
                {
                    for (int m = 0; m < list.Count; m++)
                    {
                        list[m].Dispose();
                    }
                    progressMeter_0.Stop();
                    throw;
                }
                Region region = this.method_2(subDMeshHandler, l);
                if (region == null)
                {
                    num8++;
                }
                else
                {
                    region.TransformBy(matrix3d);
                    list.Add(region);
                }
            }
            editor.WriteMessage("\nNumber of failed projections: " + num8.ToString());
            progressMeter_0.Stop();
            progressMeter_0 = new ProgressMeter();
            int limit = (int)Math.Ceiling(Math.Log((double)list.Count) / Math.Log(2.0));

            progressMeter_0.SetLimit(limit);
            progressMeter_0.Start("Computing silhouette");
            if (list.Count > 1)
            {
                this.method_1(ref list, ref progressMeter_0);
            }
            list[0].TransformBy(matrix3d2);
            list[0].TransformBy(matrix3d3);
            CoordinateTransformator coordinateTransformator = new CoordinateTransformator(coordinateSystem_0, CoordinateSystem.Global());

            if (!coordinateTransformator.bool_0)
            {
                list[0].TransformBy(coordinateTransformator.ToAcadTransformation());
            }
            using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
            {
                BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                blockTableRecord.AppendEntity(list[0]);
                transaction.AddNewlyCreatedDBObject(list[0], true);
                transaction.Commit();
            }
            progressMeter_0.Stop();
        }
Пример #51
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private IImageData OpenFile(string fileName)
        {
            Dataset dataset;
            try
            {
                dataset = Gdal.Open(fileName, Access.GA_Update);
            }
            catch
            {
                try
                {
                    dataset = Gdal.Open(fileName, Access.GA_ReadOnly);
                }
                catch (Exception ex)
                {
                    throw new GdalException(ex.ToString());
                }
            }

            Band red = dataset.GetRasterBand(1);
            ColorInterp bandType = red.GetRasterColorInterpretation();
            if (bandType != ColorInterp.GCI_PaletteIndex &&
                bandType != ColorInterp.GCI_GrayIndex &&
                bandType != ColorInterp.GCI_RedBand &&
                bandType != ColorInterp.GCI_AlphaBand)
            {
                // This is an image, not a raster, so return null.
                dataset.Dispose();
                dataset = null;
                return null;
            }

            GdalImage result = new GdalImage(fileName);
            if (result.Width > 8000 || result.Height > 8000)
            {
                // Firstly, if there are pyramids inside of the GDAL file itself, we can just work with this directly,
                // without creating our own pyramid image.

                // For now, we can't get fast, low-res versions without some kind of pyramiding happening.
                // since that can take a while for huge images, I'd rather do this once, and create a kind of
                // standardized file-based pyramid system.  Maybe in future pyramid tiffs could be used instead?
                string pyrFile = Path.ChangeExtension(fileName, ".mwi");
                if (File.Exists(pyrFile))
                {
                    if (File.Exists(Path.ChangeExtension(pyrFile, ".mwh")))
                    {
                        return new PyramidImage(fileName);
                    }
                    File.Delete(pyrFile);
                }

                GdalImageSource gs = new GdalImageSource(fileName);
                PyramidImage py = new PyramidImage(pyrFile, gs.Bounds);
                int width = gs.Bounds.NumColumns;
                int blockHeight = 64000000 / width;
                if (blockHeight > gs.Bounds.NumRows) blockHeight = gs.Bounds.NumRows;
                int numBlocks = (int)Math.Ceiling(gs.Bounds.NumRows / (double)blockHeight);
                ProgressMeter pm = new ProgressMeter(ProgressHandler, "Copying Data To Pyramids", numBlocks * 2);
                //ProgressHandler.Progress("pyramid", 0, "Copying Data To Pyramids: 0% Complete");
                Application.DoEvents();
                for (int j = 0; j < numBlocks; j++)
                {
                    int h = blockHeight;
                    if (j == numBlocks - 1)
                    {
                        h = gs.Bounds.NumRows - j * blockHeight;
                    }
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    byte[] vals = gs.ReadWindow(j * blockHeight, 0, h, width, 0);
                    Debug.WriteLine("Reading Value time: " + sw.ElapsedMilliseconds);
                    pm.CurrentValue = j * 2 + 1;
                    sw.Reset();
                    sw.Start();
                    py.WriteWindow(vals, j * blockHeight, 0, h, width, 0);
                    sw.Stop();
                    Debug.WriteLine("Writing Pyramid time: " + sw.ElapsedMilliseconds);
                    pm.CurrentValue = (j + 1) * 2;
                }
                gs.Dispose();
                pm.Reset();
                py.ProgressHandler = ProgressHandler;
                py.CreatePyramids();
                py.WriteHeader(pyrFile);
                return py;
            }
            result.Open();
            return result;
        }
Пример #52
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="raster">The input altitude raster.</param>
        /// <param name="inZFactor">The double precision multiplicative scaling factor for elevation values.</param>
        /// <param name="slopeInPercent">A boolean parameter that clarifies the nature of the slope values.  If this is true, the values represent percent slope.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>The output slope raster, or null if the process was unsuccessful.</returns>
        public static IRaster GetSlope(IRaster raster, double inZFactor, bool slopeInPercent,
                                       ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (raster == null)
            {
                return(null);
            }
            int noOfCol = raster.NumColumns;
            int noOfRow = raster.NumRows;

            //Create the new raster with the appropriate dimensions
            var result = Raster.CreateRaster("SlopeRaster.bgd", string.Empty, noOfCol, noOfRow, 1, typeof(double),
                                             new[] { string.Empty });

            result.NoDataValue = raster.NoDataValue;
            result.Bounds      = raster.Bounds;
            result.Projection  = raster.Projection;

            ProgressMeter progMeter = null;

            try
            {
                if (cancelProgressHandler != null)
                {
                    progMeter = new ProgressMeter(cancelProgressHandler, "Calculating Slope", result.NumRows);
                }

                // Cache cell size for faster access
                var cellWidth  = raster.CellWidth;
                var cellHeight = raster.CellHeight;
                for (int i = 0; i < result.NumRows; i++)
                {
                    if (cancelProgressHandler != null)
                    {
                        progMeter.Next();
                        if ((i % 100) == 0)
                        {
                            progMeter.SendProgress();

                            // HACK: DoEvents messes up the normal flow of your application.
                            Application.DoEvents();
                        }
                    }
                    for (int j = 0; j < result.NumColumns; j++)
                    {
                        if (i > 0 && i < result.NumRows - 1 && j > 0 && j < result.NumColumns - 1)
                        {
                            double z1 = raster.Value[i - 1, j - 1];
                            double z2 = raster.Value[i - 1, j];
                            double z3 = raster.Value[i - 1, j + 1];
                            double z4 = raster.Value[i, j - 1];
                            double z5 = raster.Value[i, j + 1];
                            double z6 = raster.Value[i + 1, j - 1];
                            double z7 = raster.Value[i + 1, j];
                            double z8 = raster.Value[i + 1, j + 1];

                            //3rd Order Finite Difference slope algorithm
                            double dZdX = inZFactor * ((z3 - z1) + (2 * (z5 - z4)) + (z8 - z6)) / (8 * cellWidth);
                            double dZdY = inZFactor * ((z1 - z6) + (2 * (z2 - z7)) + (z3 - z8)) / (8 * cellHeight);

                            double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI);

                            //change to radius and in percentage
                            if (slopeInPercent)
                            {
                                slope = (Math.Tan(slope * Math.PI / 180)) * 100;
                            }

                            result.Value[i, j] = slope;

                            if (cancelProgressHandler != null && cancelProgressHandler.Cancel)
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            result.Value[i, j] = result.NoDataValue;
                        }

                        if (cancelProgressHandler != null && cancelProgressHandler.Cancel)
                        {
                            return(null);
                        }
                    }
                }

                if (result.IsFullyWindowed())
                {
                    result.Save();
                    return(result);
                }
                return(null);
            }
            finally
            {
                if (progMeter != null)
                {
                    progMeter.Reset();
                    Application.DoEvents();
                }
            }
        }