Example #1
0
        private static void AddText(Gem.Point2d pnt, string layer, string str)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

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

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

                Db.MText acMText = new Db.MText();
                acMText.SetDatabaseDefaults();
                acMText.Location = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acMText.Contents = str;
                acMText.Height   = SettingsParser.getInstance()._Scale.Coord;
                acMText.Color    = Autodesk.AutoCAD.Colors.
                                   Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByLayer, 256);
                acMText.Layer = layer;
                acMText.SetDatabaseDefaults();
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acMText);
                acTrans.AddNewlyCreatedDBObject(acMText, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Example #2
0
        private static void AddCircle(Gem.Point2d pnt, string layer)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

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

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

                Db.Circle acCircle = new Db.Circle();
                acCircle.SetDatabaseDefaults();
                acCircle.Center = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acCircle.Radius = SettingsParser.getInstance()._Scale.Circle;
                acCircle.Layer  = layer;
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acCircle);
                acTrans.AddNewlyCreatedDBObject(acCircle, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Example #3
0
        // This method helps to get correct "boundary box" for the regions which
        // created through the splines. Written by Alexander Rivilis.
        public static void GetVisualBoundary(this Db.Region region, double delta,
                                             ref Gm.Point2d minPoint, ref Gm.Point2d maxPoint)
        {
            using (Gm.BoundBlock3d boundBlk = new Gm.BoundBlock3d())
            {
                using (Br.Brep brep = new Br.Brep(region))
                {
                    foreach (Br.Edge edge in brep.Edges)
                    {
                        using (Gm.Curve3d curve = edge.Curve)
                        {
                            Gm.ExternalCurve3d curve3d = curve as Gm.ExternalCurve3d;

                            if (curve3d != null && curve3d.IsNurbCurve)
                            {
                                using (Gm.NurbCurve3d nurbCurve = curve3d.NativeCurve
                                                                  as Gm.NurbCurve3d)
                                {
                                    Gm.Interval interval = nurbCurve.GetInterval();
                                    for (double par = interval.LowerBound; par <=
                                         interval.UpperBound; par += (delta * 2.0))
                                    {
                                        Gm.Point3d p = nurbCurve.EvaluatePoint(par);
                                        if (!boundBlk.IsBox)
                                        {
                                            boundBlk.Set(p, p);
                                        }
                                        else
                                        {
                                            boundBlk.Extend(p);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (!boundBlk.IsBox)
                                {
                                    boundBlk.Set(edge.BoundBlock.GetMinimumPoint(),
                                                 edge.BoundBlock.GetMaximumPoint());
                                }
                                else
                                {
                                    boundBlk.Extend(edge.BoundBlock.GetMinimumPoint());
                                    boundBlk.Extend(edge.BoundBlock.GetMaximumPoint());
                                }
                            }
                        }
                    }
                }
                boundBlk.Swell(delta);

                minPoint = new Gm.Point2d(boundBlk.GetMinimumPoint().X,
                                          boundBlk.GetMinimumPoint().Y);
                maxPoint = new Gm.Point2d(boundBlk.GetMaximumPoint().X,
                                          boundBlk.GetMaximumPoint().Y);
            }
        }
Example #4
0
        public bool IsEqualTo(Gem.Point2d a, double tolerance)
        {
            double[] dP        = { X - a.X, Y - a.Y };
            double   length_dP = Math.Sqrt(dP[0] * dP[0] + dP[1] * dP[1]);

            if (length_dP < tolerance)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #5
0
        private static void AddMLeader(Gem.Point2d pnt, Gem.Vector3d otstup,
                                       double scale, string layer,
                                       string mleaderStyleName, string str)
        {
            SettingsParser settings = SettingsParser.getInstance();

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


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

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

                acML.Scale = 1;


                acBlkTblRec.AppendEntity(acML);
                acTrans.AddNewlyCreatedDBObject(acML, true);
                acTrans.Commit();
            }
        }
Example #6
0
 //Точка вывода текста с данными линии
 public Gem.Point2d textPoint()
 {
     Gem.Point2d p;
     if (Vertixs.Count < 3)
     {
         Gem.Vector2d dP = new Gem.Point2d(Vertixs[1].X, Vertixs[1].Y) - new Gem.Point2d(Vertixs[0].X, Vertixs[0].Y);
         Gem.Vector2d l  = (dP.Length / 2) * (dP / dP.Length);
         p = new Gem.Point2d(Vertixs[0].X, Vertixs[0].Y) + l;
     }
     else
     {
         Gem.Vector2d dP = new Gem.Point2d(Vertixs[1].X, Vertixs[1].Y) - new Gem.Point2d(Vertixs[0].X, Vertixs[0].Y);
         Gem.Vector2d l  = (dP.Length / 2) * (dP / dP.Length);
         Gem.Point2d  P1 = new Gem.Point2d(Vertixs[0].X, Vertixs[0].Y) + l;
         dP = new Gem.Point2d(Vertixs[2].X, Vertixs[2].Y) - P1;
         l  = (dP.Length / 2) * (dP / dP.Length);
         p  = P1 + l;
     }
     return(p);
 }
Example #7
0
 public Point2D ConvertAcadPoint2dToPoint2D(Autodesk.AutoCAD.Geometry.Point2d Acadpoint, int number)
 {
     return(new Point2D(Acadpoint.X, Acadpoint.Y, number));
 }
Example #8
0
 /// <summary>
 /// Return distance between two points
 /// </summary>
 /// <param name="point2d1">1st point</param>
 /// <param name="point2d2">2nd point</param>
 /// <returns>return distance</returns>
 internal static double Distance(Autodesk.AutoCAD.Geometry.Point2d point2d1, Autodesk.AutoCAD.Geometry.Point2d point2d2)
 {
     return(Math.Sqrt((point2d1.X - point2d2.X) * (point2d1.X - point2d2.X) + (point2d1.Y - point2d2.Y) * (point2d1.Y - point2d2.Y)));
 }
Example #9
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotRegion(Db.ObjectId regionId, String pcsFileName,
                                      String mediaName, String outputFileName)
        {
            if (regionId.IsNull)
            {
                throw new ArgumentException("regionId.IsNull == true");
            }
            if (!regionId.IsValid)
            {
                throw new ArgumentException("regionId.IsValid == false");
            }

            if (regionId.ObjectClass.Name != "AcDbRegion")
            {
                throw new ArgumentException("regionId.ObjectClass.Name != AcDbRegion");
            }

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }

            Db.Database previewDb = Hs.WorkingDatabase;
            Db.Database db        = null;
            Ap.Document doc       = cad.DocumentManager.MdiActiveDocument;
            if (doc == null || doc.IsDisposed)
            {
                return;
            }

            Ed.Editor ed = doc.Editor;
            try
            {
                if (regionId.Database != null && !regionId.Database.IsDisposed)
                {
                    Hs.WorkingDatabase = regionId.Database;
                    db = regionId.Database;
                }
                else
                {
                    db = doc.Database;
                }

                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Region region = tr.GetObject(regionId,
                                                        Db.OpenMode.ForRead) as Db.Region;

                        Db.Extents3d        extends = region.GeometricExtents;
                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo pi = new Pt.PlotInfo())
                        {
                            pi.Layout = model.LayoutId;

                            using (Db.PlotSettings ps = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                ps.CopyFrom(layout);

                                Db.PlotSettingsValidator psv = Db.PlotSettingsValidator
                                                               .Current;

                                Gm.Point2d bottomLeft = Gm.Point2d.Origin;
                                Gm.Point2d topRight   = Gm.Point2d.Origin;

                                region.GetVisualBoundary(0.1, ref bottomLeft,
                                                         ref topRight);

                                Gm.Point3d bottomLeft_3d = new Gm.Point3d(bottomLeft.X,
                                                                          bottomLeft.Y, 0);
                                Gm.Point3d topRight_3d = new Gm.Point3d(topRight.X, topRight.Y,
                                                                        0);

                                Db.ResultBuffer rbFrom = new Db.ResultBuffer(new Db.TypedValue(
                                                                                 5003, 1));
                                Db.ResultBuffer rbTo = new Db.ResultBuffer(new Db.TypedValue(
                                                                               5003, 2));

                                double[] firres = new double[] { 0, 0, 0 };
                                double[] secres = new double[] { 0, 0, 0 };

                                acedTrans(bottomLeft_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, firres);
                                acedTrans(topRight_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, secres);

                                Db.Extents2d extents = new Db.Extents2d(
                                    firres[0],
                                    firres[1],
                                    secres[0],
                                    secres[1]
                                    );

                                psv.SetZoomToPaperOnUpdate(ps, true);

                                psv.SetPlotWindowArea(ps, extents);
                                psv.SetPlotType(ps, Db.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, Db.StdScaleType.ScaleToFit);
                                psv.SetPlotCentered(ps, true);
                                psv.SetPlotRotation(ps, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                psv.SetPlotConfigurationName(ps, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                pi.OverrideSettings = ps;
                                Pt.PlotInfoValidator piv = new Pt.PlotInfoValidator();
                                piv.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                piv.Validate(pi);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(pi, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, pi, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                Hs.WorkingDatabase = previewDb;
            }
        }
Example #10
0
        public static bool GetData(Db.ObjectId ObjectId)
        {
            SettingsParser settings = SettingsParser.getInstance();

            Db.Database acCurDb = App.Application.DocumentManager.MdiActiveDocument.Database;

            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.Polyline acPLine = acTrans.GetObject(ObjectId, Db.OpenMode.ForRead) as Db.Polyline;

                //Блокируем повторный выбор линии
                if (curveDict.FirstOrDefault(s => s.ObjId == ObjectId) == null)
                {
                    Curve crv = new Curve(ObjectId);
                    crv.Number     = settings.startNumberCurve;
                    crv.Area       = round(acPLine.Area, settings.areaTolerance);
                    crv.AreaOutput = round(acPLine.Area * settings.allAreaTolerance, settings.coordinateTolerance);

                    settings.startNumberCurve++;

                    if (pointDict.Count > 0)
                    {
                        settings.startNumberPoint = pointDict.Count;
                    }


                    int countVertix = acPLine.NumberOfVertices;

                    for (int i = 0; i < countVertix; i++)
                    {
                        Gem.Point2d pt = acPLine.GetPoint2dAt(i);

                        int iMin = (i == 0) ? iMin = countVertix - 1 : iMin = i - 1;
                        int iMax = (i == countVertix - 1) ? iMax = 0 : iMax = i + 1;

                        //Поучаю все три точки угла


                        Gem.Point3d ptO = new Gem.Point3d(acPLine.GetPoint2dAt(i).X,
                                                          acPLine.GetPoint2dAt(i).Y, 0);
                        Gem.Point3d ptMin = new Gem.Point3d(acPLine.GetPoint2dAt(iMin).X,
                                                            acPLine.GetPoint2dAt(iMin).Y, 0);
                        Gem.Point3d ptMax = new Gem.Point3d(acPLine.GetPoint2dAt(iMax).X,
                                                            acPLine.GetPoint2dAt(iMax).Y, 0);

                        Gem.Vector3d vMin = ptO.GetVectorTo(ptMin);
                        Gem.Vector3d vMax = ptO.GetVectorTo(ptMax);

                        Gem.Vector3d vNormaliseMin = vMin / vMin.Length;
                        Gem.Vector3d vNormaliseMax = vMax / vMax.Length;

                        Gem.Vector3d vNormalise = vNormaliseMin + vNormaliseMax;
                        vNormalise = vNormalise / vNormalise.Length;

                        //Тут нужно проверять, попадает ли точка нормализованного вектора внутрь фигуры или наружу
                        using (Db.Ray cl = new Db.Ray())
                        {
                            cl.BasePoint = ptO + vNormalise;
                            cl.UnitDir   = vNormalise;
                            Gem.Point3dCollection pnt3dCol = new Gem.Point3dCollection();
                            acPLine.IntersectWith(cl, Db.Intersect.OnBothOperands, pnt3dCol, IntPtr.Zero, IntPtr.Zero);
                            if ((pnt3dCol.Count % 2) != 0)
                            {
                                vNormalise = vNormalise * (-1);
                            }
                        }

                        int namb = 0; //Номер вершины
                        if (pointDict.FirstOrDefault(s => s.IsEqualTo(pt, settings.coordinateTolerance)) == null)
                        {
                            Point pnt = new Point(round(pt.X, settings.coordinateTolerance),
                                                  round(pt.Y, settings.coordinateTolerance),
                                                  settings.startNumberPoint);

                            //Добавляем нормализованный вектор биссектриссы угла
                            pnt.vNormalise = vNormalise;
                            //Добавляем в список точек
                            pointDict.Add(pnt);
                            //Добавляем в кривую
                            crv.Vertixs.Add(pnt);

                            namb = settings.startNumberPoint;
                            settings.startNumberPoint++;
                        }
                        else
                        {
                            //Добавляем в список вершин уже обраотанную точку
                            crv.Vertixs.Add(pointDict.FirstOrDefault(s => s.IsEqualTo(pt, settings.coordinateTolerance)));
                        }
                    }

                    //Добавляем в список линий
                    curveDict.Add(crv);
                    //Вывожу данные линии в чертеж
                    View.TextToDwg(crv);
                    //View.AddText(crv.textPoint(), $"{crv.Number} \\P S={crv.Area} кв.м.");
                }
                acTrans.Commit();
            }
            return(true);
        }