Ejemplo n.º 1
0
        /// <summary>
        /// <para>Add a group to the current autocad document</para>
        /// <para>Return: Group</para>
        /// </summary>
        /// <param name="name">Group name</param>
        /// <param name="DbObjs">Object Collection to associate with group</param>
        /// <param name="autorename"><para>if a group has already the specified name</para>
        /// <para>This let the function assign an unique generated name</para></param>
        /// <returns></returns>
        public ObjectId addGroup(string name, DBObjectCollection DbObjs, bool autorename)
        {
            Group grp = new Group(name, true);
            ObjectIdCollection ids = new ObjectIdCollection();

            start_Transaction();
            DBDictionary gd = openGroupDictionary(OpenMode.ForWrite);
            if (gd.Contains(name))
            {
                if (autorename)
                {
                    name = name + "_" + Guid.NewGuid().ToString();
                }
                else
                {
                    return ObjectId.Null;
                }
            }
            gd.SetAt(name, grp);
            AC_Tr.AddNewlyCreatedDBObject(grp, true);

            openBlockTables(OpenMode.ForRead, OpenMode.ForWrite);
            foreach (Entity ent in DbObjs)
            {
                ObjectId id = Commit(ent);
                ids.Add(id);
            }
            grp.InsertAt(0, ids);
            gd.Dispose();
            Dispose();

            return grp.ObjectId;
        }
Ejemplo n.º 2
0
 public List<Point3d> pointOffset(Point3d point1, Point3d point2,double offset)
 {
     Line line = new Line(point1,point2);
     List<Point3d> returnList = new List<Point3d>();
     DBObjectCollection offsetLine = new DBObjectCollection();
     try
     {
         offsetLine = line.GetOffsetCurves(offset);
     }
     catch
     {
         offsetLine.Add(new Line(point1, point2));
     }
     if(offsetLine.Count == 1)
     {
         Line oLine = offsetLine[0] as Line;
         returnList.Add(oLine.StartPoint);
         returnList.Add(new LineSegment3d(oLine.StartPoint, oLine.EndPoint).MidPoint);
         returnList.Add(oLine.EndPoint);
         line.Dispose();
         oLine.Dispose();
         return returnList;
     }
     else
     {
         line.Dispose();
         return null;
     }
 }
Ejemplo n.º 3
0
        private bool _drawing;     // Drawing mode active

        public KinectSwitchJig(
          Document doc, Transaction tr, double profSide, double factor
        )
        {
            // Initialise the various members

            _doc = doc;
            _tr = tr;
            _vertices = new Point3dCollection();
            _lastDrawnVertex = -1;
            _resizing = false;
            _drawing = false;
            _created = new DBObjectCollection();
            _profSide = profSide;
            _segFactor = factor;
            switchm = 0;

            Words.Add("red");
            Words.Add("green");
            Words.Add("blue");
            Words.Add("yellow");
            Words.Add("pink");
            Words.Add("magenta");
            Words.Add("cyan");
        }
Ejemplo n.º 4
0
        public void ExtrudedSolidCommand()
        {
            var document = Application.DocumentManager.MdiActiveDocument;

            if (document == null) // don't bother doing anything else
                return;

            using (var polyline = new Polyline())
            {
                var extrudedSquareInputResult = GetExtrusionInputFromUser();

                // convenience variables
                var width = extrudedSquareInputResult.Width;
                var height = extrudedSquareInputResult.Height;
                var depth = extrudedSquareInputResult.Depth;

                // Using the polyline, we add vertices based on the user's input
                polyline.AddVertexAt(0, Point2d.Origin, 0.0, 0.0, 0.0);
                polyline.AddVertexAt(1, new Point2d(width, 0.0), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(2, new Point2d(width, height), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(3, new Point2d(0.0, height), 0.0, 0.0, 0.0);
                polyline.Closed = true;

                // add polyline to DBObjectCollection for us in creating region from curves
                using (var dbObjectCollection = new DBObjectCollection { polyline })
                {
                    using (var regionCollection = Region.CreateFromCurves(dbObjectCollection))
                    {
                        using (var region = (Region)regionCollection[0])
                        {
                            using (var solid = new Solid3d())
                            {
                                // extrude the region to the depth the user specified
                                solid.Extrude(region, depth, 0.0);
                                using (document.LockDocument())
                                {
                                    using (var database = document.Database)
                                    {
                                        using (var transaction = database.TransactionManager.StartTransaction())
                                        {
                                            // get the current space for appending our extruded solid
                                            using (var currentSpace = (BlockTableRecord)transaction.GetObject(database.CurrentSpaceId, OpenMode.ForWrite))
                                            {
                                                currentSpace.AppendEntity(solid);
                                            }

                                            transaction.AddNewlyCreatedDBObject(solid, true);
                                            transaction.Commit();
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    private bool _drawing;     // Drawing mode active

    public KinectPolyJig(Document doc, Transaction tr)
    {
      // Initialise the various members

      _doc = doc;
      _tr = tr;
      _vertices = new Point3dCollection();
      _lineSegs = new List<LineSegment3d>();
      _lines = new DBObjectCollection();
      _cursor = null;
      _calibrating = true;
      _drawing = false;
    }
Ejemplo n.º 6
0
        public static List<int> FindSelfIntersectPline(Polyline polyline)
        {
            List<int> resultPts = new List<int>();

            DBObjectCollection entities = new DBObjectCollection();
            polyline.Explode(entities);

            for (int i = 0; i < entities.Count; ++i)
            {
                for (int j = i + 1; j < entities.Count; ++j)
                {
                    Curve curve1 = entities[i] as Curve;
                    Curve curve2 = entities[j] as Curve;

                    Autodesk.AutoCAD.Geometry.Point3dCollection points = new Autodesk.AutoCAD.Geometry.Point3dCollection();
                    curve1.IntersectWith(
                        curve2,
                        Intersect.OnBothOperands,
                        points,
                        IntPtr.Zero,
                        IntPtr.Zero);

                    foreach (Point3d point in points)
                    {
                        // Make a check to skip the start/end points
                        // since they are connected vertices
                        if (point == curve1.StartPoint ||
                            point == curve1.EndPoint)
                        {
                            if (point == curve2.StartPoint ||
                                point == curve2.EndPoint)
                            {
                                // If two consecutive segments, then skip
                                if (j == i + 1)
                                {
                                    continue;
                                }
                            }
                        }

                        resultPts.Add(j);
                    }
                }

                // Need to be disposed explicitely
                // since entities are not DB resident
                entities[i].Dispose();
            }
            return resultPts;
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Gets the centroid of the closed planar spline.
 /// </summary>
 /// <param name="spl">The instance to which the method applies.</param>
 /// <returns>The centroid of the spline (WCS coordinates).</returns>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNonPlanarEntity is thrown if the Spline is not planar.</exception>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNotApplicable is thrown if the Spline is not closed.</exception>
 public static Point3d Centroid(this Spline spl)
 {
     if (!spl.IsPlanar)
         throw new AcRx.Exception(AcRx.ErrorStatus.NonPlanarEntity);
     if (spl.Closed != true)
         throw new AcRx.Exception(AcRx.ErrorStatus.NotApplicable);
     using (DBObjectCollection curves = new DBObjectCollection())
     {
         curves.Add(spl);
         using (DBObjectCollection dboc = Region.CreateFromCurves(curves))
         {
             return ((Region)dboc[0]).Centroid();
         }
     }
 }
Ejemplo n.º 8
0
        public static void ProxyExplodeInPlace(ResultBuffer rbArgs)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            if (rbArgs.AsArray().Length == 1)
            {
                TypedValue entity = rbArgs.AsArray().First();

                if (entity.TypeCode == (int)LispDataType.ObjectId)
                {
                    using (Transaction tr = doc.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            ObjectId id = (ObjectId)entity.Value;
                            DBObjectCollection objs = new DBObjectCollection();
                            BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                            Entity entx = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                            entx.Explode(objs);

                            entx.Erase();

                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                            foreach (DBObject obj in objs)
                            {
                                Entity ent = (Entity)obj;
                                btr.AppendEntity(ent);
                                tr.AddNewlyCreatedDBObject(ent, true);
                            }

                            tr.Commit();
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex)
                        {
                            tr.Abort();
                            ed.WriteMessage(ex.Message);
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private void Create_strz5()
        {
            string blockName = "strz5";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Line ent1 = new Line(new Point3d(-0.043, 0.043, 0), new Point3d(0.043, -0.043, 0));
            ent1.Layer = "0";
            entityCollection.Add(ent1);

            Line ent2 = new Line(new Point3d(0.095, 0, 0), new Point3d(-0.095, 0, 0));
            ent2.Layer = "0";
            entityCollection.Add(ent2);

            Circle ent3 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.015);
            ent3.Layer = "0";
            entityCollection.Add(ent3);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Ejemplo n.º 10
0
        /**
         * @brief   Metodo que descompone una curva en un conjunto de segmentos de línea que aproximan o recubren la curva original.
         *
         * @param   cur         Entidad curva que debe ser linealizada.
         * @param   numSeg      Número de líneas en las que tiene que ser partida la curva.
         * @param   acBlkTbl    Tabla de bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados.
         * @param   acBlkTblRec Tabla de registros de los bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados.
         * @param   t           Transaccion abierta para manipular la tabla de bloques de AutoCAD.
         * @param   LayerId     Parámetro del tipo ObjectId que identifica la capa a la que tendrán que asociarse las nuevas líneas generadas por el proceso
         *                      de descomposición de la curva.
         * @param   dwfg        Parámetro del tipo dwgFile donde se almacenaran las nuevas líneas creadas a partir del proceso de descomposición de la curva.
         *
         * @return              Devuelve una colección de entidades tipo linea bajo la clase DBObjectCollection.
         **/
        public static DBObjectCollection curvaAlineas(Curve cur, int numSeg, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec,Transaction t, ObjectId LayerId, dwgFile dwfg)
        {
            DBObjectCollection ret = new DBObjectCollection();

            // Collect points along our curve
            Point3dCollection pts = new Point3dCollection();

            // Split the curve's parameter space into
            // equal parts
            double startParam = cur.StartParam;
            double segLen = (cur.EndParam - startParam) / numSeg;

            // Loop along it, getting points each time
            for (int i = 0; i < numSeg + 1; i++)
            {
                Point3d pt = cur.GetPointAtParameter(startParam + segLen * i);
                pts.Add(pt);
            }

            if (pts != null && pts.Count > 0)
            {
                if (pts.Count == 1)
                {
                    // Retornamos un punto.
                }
                else if (pts.Count >= 2)
                {
                    // Retornamos una secuencia de lineas
                    for (int i = 0; i < pts.Count - 1; i++)
                    {
                        Line ln = new Line();
                        ln.StartPoint = pts[i];
                        ln.EndPoint = pts[i + 1];
                        ln.LayerId = LayerId;
                        acBlkTblRec.AppendEntity(ln);
                        t.AddNewlyCreatedDBObject(ln, true);
                        dwfg.objetosArtificiales.Add(ln.ObjectId);
                        ret.Add(ln);
                    }
                }
            }

            return ret;
        }
Ejemplo n.º 11
0
        private void Create_symbol1()
        {
            string blockName = "symbol1";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Line ent1 = new Line(new Point3d(0, 0.12, 0), new Point3d(0, -0.12, 0));
            ent1.Layer = "0";
            entityCollection.Add(ent1);

            Point3dCollection verties = new Point3dCollection();
            verties.Add(new Point3d(0, 0, 0));
            verties.Add(new Point3d(0.077, 0.064, 0));
            verties.Add(new Point3d(0.077, -0.064, 0));
            verties.Add(new Point3d(0, 0, 0));
            Polyline2d ent2 = new Polyline2d(Poly2dType.SimplePoly, verties, 0, false, 0, 0,
                new DoubleCollection(new double[] { 0, 0, 0, 0 }));
            ent2.Layer = "0";
            entityCollection.Add(ent2);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Ejemplo n.º 12
0
        private void PosExplode()
        {
            PromptSelectionResult sel = DWGUtility.SelectAllPosAndBOQTableUser();
            if (sel.Status != PromptStatus.OK) return;

            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                    DBObjectCollection explodedEntites = new DBObjectCollection();

                    // Explode all selected entites
                    foreach (ObjectId id in sel.Value.GetObjectIds())
                    {
                        Entity en = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                        en.Explode(explodedEntites);
                        en.Erase();
                    }

                    // Create new entities
                    foreach (DBObject obj in explodedEntites)
                    {
                        Entity en = (Entity)obj;
                        btr.AppendEntity(en);
                        tr.AddNewlyCreatedDBObject(en, true);
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                tr.Commit();
            }
        }
Ejemplo n.º 13
0
        private void Create_ACMark()
        {
            LayerManager lm = new LayerManager();
            string layerName = lm.GetACMarkLayerCreateIfDoesntExists();
            string blockName = "ACMark";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Circle ent1 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.2);
            ent1.Layer = layerName;
            ent1.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent1);

            Line ent2 = new Line(new Point3d(-0.200, -0.200, 0), new Point3d(0.200, 0.200, 0));
            ent2.Layer = layerName;
            ent2.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent2);

            Line ent3 = new Line(new Point3d(-0.200, 0.200, 0), new Point3d(0.200, -0.200, 0));
            ent3.Layer = layerName;
            ent3.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent3);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Ejemplo n.º 14
0
 public override void Explode(Entity entity, DBObjectCollection entitySet)
 {
    Curve curve = entity as Curve;
    if (curve != null)
    {
       Isoline isoline = new Isoline(curve);
       if (isoline.IsIsoline)
       {
          var lines = isoline.GetLines(curve);
          foreach (var line in lines)
          {
             entitySet.Add(line);
          }
          //isoline.Activate(false); fatal
          Isoline.RemoveXData(entity);
       }
    }
    if (entity is Line)
    {
       entitySet.Add((DBObject)entity.Clone());
       return;
    }
    base.Explode(entity, entitySet);
 }
        //Рисуем таблицу щитка.
        private void b_paint_Click(object sender, EventArgs e)
        {
            this.Hide();
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (DocumentLock doclock = acDoc.LockDocument())
            {
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {

                    PromptPointResult pPtRes;
                    PromptPointOptions pPtOpts = new PromptPointOptions("");
                    pPtOpts.Message = "\nВведи точку: ";
                    pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                    // pPtRes.Value - точка типа Point3D
                    Data.table_x = pPtRes.Value.X;
                    Data.table_y = pPtRes.Value.Y;

                    BlockTableRecord btr;
                    BlockTable bt;
                    DBObjectCollection ObjColl = new DBObjectCollection();

                    //ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y, 0)));

                    //Вставили шапку таблицы.
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 50, 0), new Point3d(Data.table_x + 285, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y - 15, 0), new Point3d(Data.table_x + 285, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 25, Data.table_y, 0), new Point3d(Data.table_x + 25, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 58, Data.table_y, 0), new Point3d(Data.table_x + 58, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 63, Data.table_y, 0), new Point3d(Data.table_x + 63, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 96, Data.table_y, 0), new Point3d(Data.table_x + 96, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y, 0), new Point3d(Data.table_x + 101, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 106, Data.table_y - 15, 0), new Point3d(Data.table_x + 106, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 123, Data.table_y - 15, 0), new Point3d(Data.table_x + 123, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 136, Data.table_y - 15, 0), new Point3d(Data.table_x + 136, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 161, Data.table_y - 15, 0), new Point3d(Data.table_x + 161, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 174, Data.table_y, 0), new Point3d(Data.table_x + 174, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 197, Data.table_y - 15, 0), new Point3d(Data.table_x + 197, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y, 0), new Point3d(Data.table_x + 210, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 226, Data.table_y - 15, 0), new Point3d(Data.table_x + 226, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 238, Data.table_y - 15, 0), new Point3d(Data.table_x + 238, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 250, Data.table_y - 15, 0), new Point3d(Data.table_x + 250, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 285, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 239, Data.table_y - 32, 0), new Point3d(Data.table_x + 249, Data.table_y - 32, 0)));

                    #region Текст в шапке
                    MText objText = new MText();
                    objText.SetDatabaseDefaults();
                    objText.Location = new Point3d(Data.table_x + 2, Data.table_y - 1, 0);
                    objText.Contents = "Распреде-\nлительное устройство";
                    objText.TextStyleId = acCurDb.Textstyle;
                    objText.TextHeight = 3;
                    objText.Height = 50;
                    objText.Width = 25;
                    ObjColl.Add(objText);

                    MText objText1 = new MText();
                    objText1.SetDatabaseDefaults();
                    objText1.TextStyleId = acCurDb.Textstyle;
                    objText1.TextHeight = 3;
                    objText1.Location = new Point3d(Data.table_x + 27, Data.table_y - 1, 0);
                    objText1.Contents = "Аппарат отходящей линии /ввода/, обозначение, тип, Iном, A, расцепитель или плавкая вставка, А.";
                    objText1.Height = 50;
                    objText1.Width = 31;
                    ObjColl.Add(objText1);

                    MText objText2 = new MText();
                    objText2.SetDatabaseDefaults();
                    objText2.TextStyleId = acCurDb.Textstyle;
                    objText2.TextHeight = 3;
                    objText2.Location = new Point3d(Data.table_x + 65, Data.table_y - 1, 0);
                    objText2.Contents = "Пусковой аппарат, обозначение, тип, Iном, A, расцепитель или плавкая вставка А, уставка теплового реле А.";
                    objText2.Height = 50;
                    objText2.Width = 31;
                    ObjColl.Add(objText2);

                    MText objText3 = new MText();
                    objText3.SetDatabaseDefaults();
                    objText3.TextStyleId = acCurDb.Textstyle;
                    objText3.TextHeight = 3;
                    objText3.Location = new Point3d(Data.table_x + 108, Data.table_y - 18, 0);
                    objText3.Contents = "Обозна-\nчение";
                    objText3.Height = 35;
                    objText3.Width = 17;
                    ObjColl.Add(objText3);

                    MText objText4 = new MText();
                    objText4.SetDatabaseDefaults();
                    objText4.TextStyleId = acCurDb.Textstyle;
                    objText4.TextHeight = 3;
                    objText4.Location = new Point3d(Data.table_x + 125, Data.table_y - 18, 0);
                    objText4.Contents = "Марка";
                    objText4.Height = 35;
                    objText4.Width = 13;
                    ObjColl.Add(objText4);

                    MText objText5 = new MText();
                    objText5.SetDatabaseDefaults();
                    objText5.TextStyleId = acCurDb.Textstyle;
                    objText5.TextHeight = 3;
                    objText5.Location = new Point3d(Data.table_x + 138, Data.table_y - 18, 0);
                    objText5.Contents = "Количество, число жил и сечение";
                    objText5.Height = 35;
                    objText5.Width = 25;
                    ObjColl.Add(objText5);

                    MText objText6 = new MText();
                    objText6.SetDatabaseDefaults();
                    objText6.TextStyleId = acCurDb.Textstyle;
                    objText6.TextHeight = 3;
                    objText6.Location = new Point3d(Data.table_x + 162, Data.table_y - 18, 0);
                    objText6.Contents = "Длина, м.";
                    objText6.Height = 35;
                    objText6.Width = 13;
                    ObjColl.Add(objText6);

                    MText objText7 = new MText();
                    objText7.SetDatabaseDefaults();
                    objText7.TextStyleId = acCurDb.Textstyle;
                    objText7.TextHeight = 3;
                    objText7.Location = new Point3d(Data.table_x + 175, Data.table_y - 18, 0);
                    objText7.Contents = "Обозначение на плане";
                    objText7.Height = 35;
                    objText7.Width = 23;
                    ObjColl.Add(objText7);

                    MText objText8 = new MText();
                    objText8.SetDatabaseDefaults();
                    objText8.TextStyleId = acCurDb.Textstyle;
                    objText8.TextHeight = 3;
                    objText8.Location = new Point3d(Data.table_x + 198, Data.table_y - 18, 0);
                    objText8.Contents = "Длина, м.";
                    objText8.Height = 35;
                    objText8.Width = 13;
                    ObjColl.Add(objText8);

                    MText objText9 = new MText();
                    objText9.SetDatabaseDefaults();
                    objText9.TextStyleId = acCurDb.Textstyle;
                    objText9.TextHeight = 3;
                    objText9.Location = new Point3d(Data.table_x + 212, Data.table_y - 18, 0);
                    objText9.Contents = "Обозна-\nчение";
                    objText9.Height = 35;
                    objText9.Width = 16;
                    ObjColl.Add(objText9);

                    MText objText10 = new MText();
                    objText10.SetDatabaseDefaults();
                    objText10.TextStyleId = acCurDb.Textstyle;
                    objText10.TextHeight = 3;
                    objText10.Location = new Point3d(Data.table_x + 227, Data.table_y - 18, 0);
                    objText10.Contents = "Pуст. или Pном., КВт";
                    objText10.Height = 35;
                    objText10.Width = 12;
                    ObjColl.Add(objText10);

                    MText objText11 = new MText();
                    objText11.SetDatabaseDefaults();
                    objText11.TextStyleId = acCurDb.Textstyle;
                    objText11.TextHeight = 3;
                    objText11.Location = new Point3d(Data.table_x + 239, Data.table_y - 18, 0);
                    objText11.Contents = "Iрасч. или Iном. Iпуск., А.";
                    objText11.Height = 35;
                    objText11.Width = 12;
                    ObjColl.Add(objText11);

                    MText objText12 = new MText();
                    objText12.SetDatabaseDefaults();
                    objText12.TextStyleId = acCurDb.Textstyle;
                    objText12.TextHeight = 3;
                    objText12.Location = new Point3d(Data.table_x + 252, Data.table_y - 18, 0);
                    objText12.Contents = "Наименование, тип, обозначение чертежа, принципиальной схемы.";
                    objText12.Height = 35;
                    objText12.Width = 35;
                    ObjColl.Add(objText12);

                    DBText acText = new DBText();
                    acText.SetDatabaseDefaults();
                    acText.Position = new Point3d(Data.table_x + 62, Data.table_y - 48, 0);
                    acText.Height = 3;
                    acText.TextString = "Участок сети 1";
                    acText.Rotation = 1.570796; //Это 90 градусов в радианах.
                    ObjColl.Add(acText);

                    DBText acText1 = new DBText();
                    acText1.SetDatabaseDefaults();
                    acText1.Rotation = 1.570796;
                    acText1.Height = 3;
                    acText1.Position = new Point3d(Data.table_x + 100, Data.table_y - 48, 0);
                    acText1.TextString = "Участок сети 2";
                    ObjColl.Add(acText1);

                    DBText acText2 = new DBText();
                    acText2.SetDatabaseDefaults();
                    acText2.Rotation = 1.570796;
                    acText2.Height = 3;
                    acText2.Position = new Point3d(Data.table_x + 105, Data.table_y - 48, 0);
                    acText2.TextString = "Участок сети";
                    ObjColl.Add(acText2);

                    DBText acText3 = new DBText();
                    acText3.SetDatabaseDefaults();
                    acText3.Height = 3;
                    acText3.Position = new Point3d(Data.table_x + 123, Data.table_y - 8, 0);
                    acText3.TextString = "Кабель, провод";
                    ObjColl.Add(acText3);
                    //acText.WidthFactor = 0.5;

                    DBText acText4 = new DBText();
                    acText4.SetDatabaseDefaults();
                    acText4.Height = 3;
                    acText4.Position = new Point3d(Data.table_x + 185, Data.table_y - 8, 0);
                    acText4.TextString = "Труба";
                    ObjColl.Add(acText4);

                    DBText acText5 = new DBText();
                    acText5.SetDatabaseDefaults();
                    acText5.Height = 3;
                    acText5.Position = new Point3d(Data.table_x + 230, Data.table_y - 8, 0);
                    acText5.TextString = "Электроприемник";
                    ObjColl.Add(acText5);
                    #endregion

                    Data.table_y = Data.table_y - 30;
                    double table_xx = Data.table_x, table_yy = Data.table_y - 20;

                    #region Вставляем строки таблицы
                    for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
                    {
                        Data.table_y = Data.table_y - 20;

                        if (dataGridView1.Rows[j].Cells["Ветвь"].Value.ToString() == "Главная линия")
                        {
                            Line l_gl = new Line(new Point3d(Data.table_x + 25, Data.table_y - 20, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0));
                            l_gl.LineWeight = LineWeight.LineWeight050;
                            l_gl.ColorIndex = 4;
                            ObjColl.Add(l_gl);
                        }

                        if (dataGridView1.Rows[j].Cells["Ветвь"].Value.ToString() == "Ответвление")
                        {
                            Line l_gl = new Line(new Point3d(Data.table_x + 62, Data.table_y, 0), new Point3d(Data.table_x + 60, Data.table_y - 2, 0));
                            l_gl.LineWeight = LineWeight.LineWeight050;
                            l_gl.ColorIndex = 4;
                            ObjColl.Add(l_gl);

                            Line l_gl1 = new Line(new Point3d(Data.table_x + 60, Data.table_y - 2, 0), new Point3d(Data.table_x + 60, Data.table_y - 20, 0));
                            l_gl1.LineWeight = LineWeight.LineWeight050;
                            l_gl1.ColorIndex = 4;
                            ObjColl.Add(l_gl1);

                            Line l_gl2 = new Line(new Point3d(Data.table_x + 60, Data.table_y - 20, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0));
                            l_gl2.LineWeight = LineWeight.LineWeight050;
                            l_gl2.ColorIndex = 4;
                            ObjColl.Add(l_gl2);
                        }

                        if (dataGridView1.Rows[j].Cells["Род тока"].Value.ToString() == "1")
                        {
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 51, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 49, Data.table_y - 22.5, 0)));
                        }

                        if (dataGridView1.Rows[j].Cells["Род тока"].Value.ToString() == "3")
                        {
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 51, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 49, Data.table_y - 22.5, 0)));
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 52, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 50, Data.table_y - 22.5, 0)));
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 50, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 48, Data.table_y - 22.5, 0)));
                        }

                        ObjColl.Add(new Line(new Point3d(Data.table_x + 25, Data.table_y, 0), new Point3d(Data.table_x + 25, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 58, Data.table_y, 0), new Point3d(Data.table_x + 58, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 63, Data.table_y, 0), new Point3d(Data.table_x + 63, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 96, Data.table_y, 0), new Point3d(Data.table_x + 96, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y, 0), new Point3d(Data.table_x + 101, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 106, Data.table_y, 0), new Point3d(Data.table_x + 106, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 123, Data.table_y, 0), new Point3d(Data.table_x + 123, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 136, Data.table_y, 0), new Point3d(Data.table_x + 136, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 161, Data.table_y, 0), new Point3d(Data.table_x + 161, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 174, Data.table_y, 0), new Point3d(Data.table_x + 174, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 197, Data.table_y, 0), new Point3d(Data.table_x + 197, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 226, Data.table_y, 0), new Point3d(Data.table_x + 226, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 238, Data.table_y, 0), new Point3d(Data.table_x + 238, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 250, Data.table_y, 0), new Point3d(Data.table_x + 250, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 285, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y - 10, 0), new Point3d(Data.table_x + 210, Data.table_y - 10, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y - 20, 0), new Point3d(Data.table_x + 285, Data.table_y - 20, 0)));

                        DBText acText6 = new DBText();
                        acText6.SetDatabaseDefaults();
                        acText6.Height = 3;
                        acText6.Position = new Point3d(Data.table_x + 27, Data.table_y - 14, 0);
                        acText6.TextString = dataGridView1.Rows[j].Cells["Аппарат"].Value.ToString();
                        ObjColl.Add(acText6);

                        DBText acText7 = new DBText();
                        acText7.SetDatabaseDefaults();
                        acText7.Height = 3;
                        acText7.Position = new Point3d(Data.table_x + 27, Data.table_y - 18, 0);
                        acText7.TextString = dataGridView1.Rows[j].Cells["Ток"].Value.ToString();
                        ObjColl.Add(acText7);

                        DBText acText8 = new DBText();
                        acText8.SetDatabaseDefaults();
                        acText8.Height = 3;
                        acText8.Position = new Point3d(Data.table_x + 60, Data.table_y - 18, 0);
                        acText8.TextString = dataGridView1.Rows[j].Cells["Фаза"].Value.ToString();
                        ObjColl.Add(acText8);

                        DBText acText9 = new DBText();
                        acText9.SetDatabaseDefaults();
                        acText9.Height = 3;
                        acText9.Position = new Point3d(Data.table_x + 65, Data.table_y - 18, 0);
                        acText9.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 1"].Value.ToString();
                        ObjColl.Add(acText9);

                        DBText acText10 = new DBText();
                        acText10.SetDatabaseDefaults();
                        acText10.Height = 3;
                        acText10.Position = new Point3d(Data.table_x + 65, Data.table_y - 14, 0);
                        acText10.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 2"].Value.ToString();
                        ObjColl.Add(acText10);

                        DBText acText11 = new DBText();
                        acText11.SetDatabaseDefaults();
                        acText11.Height = 3;
                        acText11.Position = new Point3d(Data.table_x + 65, Data.table_y - 10, 0);
                        acText11.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 3"].Value.ToString();
                        ObjColl.Add(acText11);

                        DBText acText12 = new DBText();
                        acText12.SetDatabaseDefaults();
                        acText12.Height = 3;
                        acText12.Position = new Point3d(Data.table_x + 108, Data.table_y - 8, 0);
                        acText12.TextString = dataGridView1.Rows[j].Cells["Обозначение 1"].Value.ToString();
                        ObjColl.Add(acText12);

                        DBText acText13 = new DBText();
                        acText13.SetDatabaseDefaults();
                        acText13.Height = 3;
                        acText13.Position = new Point3d(Data.table_x + 125, Data.table_y - 8, 0);
                        acText13.TextString = dataGridView1.Rows[j].Cells["Марка 1"].Value.ToString();
                        ObjColl.Add(acText13);

                        DBText acText14 = new DBText();
                        acText14.SetDatabaseDefaults();
                        acText14.Height = 3;
                        acText14.Position = new Point3d(Data.table_x + 138, Data.table_y - 8, 0);
                        acText14.TextString = dataGridView1.Rows[j].Cells["Жилы 1"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 1"].Value.ToString();
                        ObjColl.Add(acText14);

                        DBText acText15 = new DBText();
                        acText15.SetDatabaseDefaults();
                        acText15.Height = 3;
                        acText15.Position = new Point3d(Data.table_x + 163, Data.table_y - 8, 0);
                        acText15.TextString = dataGridView1.Rows[j].Cells["Длина 1"].Value.ToString();
                        ObjColl.Add(acText15);

                        DBText acText16 = new DBText();
                        acText16.SetDatabaseDefaults();
                        acText16.Height = 3;
                        acText16.Position = new Point3d(Data.table_x + 108, Data.table_y - 18, 0);
                        acText16.TextString = dataGridView1.Rows[j].Cells["Обозначение 2"].Value.ToString();
                        ObjColl.Add(acText16);

                        DBText acText17 = new DBText();
                        acText17.SetDatabaseDefaults();
                        acText17.Height = 3;
                        acText17.Position = new Point3d(Data.table_x + 125, Data.table_y - 18, 0);
                        acText17.TextString = dataGridView1.Rows[j].Cells["Марка 2"].Value.ToString();
                        ObjColl.Add(acText17);

                        DBText acText18 = new DBText();
                        acText18.SetDatabaseDefaults();
                        acText18.Height = 3;
                        acText18.Position = new Point3d(Data.table_x + 138, Data.table_y - 18, 0);
                        if (dataGridView1.Rows[j].Cells["Жилы 2"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 2"].Value.ToString() != "x")
                            acText18.TextString = dataGridView1.Rows[j].Cells["Жилы 2"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 2"].Value.ToString();
                        else
                            acText18.TextString = "";
                        ObjColl.Add(acText18);

                        DBText acText19 = new DBText();
                        acText19.SetDatabaseDefaults();
                        acText19.Height = 3;
                        acText19.Position = new Point3d(Data.table_x + 163, Data.table_y - 18, 0);
                        acText19.TextString = dataGridView1.Rows[j].Cells["Длина 2"].Value.ToString();
                        ObjColl.Add(acText19);

                        DBText acText20 = new DBText();
                        acText20.SetDatabaseDefaults();
                        acText20.Height = 3;
                        acText20.Position = new Point3d(Data.table_x + 212, Data.table_y - 12, 0);
                        acText20.TextString = dataGridView1.Rows[j].Cells["Обознач. прием."].Value.ToString();
                        ObjColl.Add(acText20);

                        DBText acText21 = new DBText();
                        acText21.SetDatabaseDefaults();
                        acText21.Height = 3;
                        acText21.Position = new Point3d(Data.table_x + 228, Data.table_y - 12, 0);
                        acText21.TextString = dataGridView1.Rows[j].Cells["P"].Value.ToString();
                        ObjColl.Add(acText21);

                        DBText acText22 = new DBText();
                        acText22.SetDatabaseDefaults();
                        acText22.Height = 3;
                        acText22.Position = new Point3d(Data.table_x + 240, Data.table_y - 12, 0);
                        acText22.TextString = dataGridView1.Rows[j].Cells["I"].Value.ToString();
                        ObjColl.Add(acText22);

                        DBText acText23 = new DBText();
                        acText23.SetDatabaseDefaults();
                        acText23.Height = 3;
                        acText23.Position = new Point3d(Data.table_x + 252, Data.table_y - 12, 0);
                        acText23.TextString = dataGridView1.Rows[j].Cells["Наим. прием."].Value.ToString();
                        ObjColl.Add(acText23);

                        DBText acText24 = new DBText();
                        acText24.SetDatabaseDefaults();
                        acText24.Height = 3;
                        acText24.Position = new Point3d(Data.table_x + 103, Data.table_y - 8, 0);
                        acText24.TextString = "1";
                        ObjColl.Add(acText24);

                        DBText acText25 = new DBText();
                        acText25.SetDatabaseDefaults();
                        acText25.Height = 3;
                        acText25.Position = new Point3d(Data.table_x + 103, Data.table_y - 18, 0);
                        acText25.TextString = "2";
                        ObjColl.Add(acText25);
                    }
                    #endregion

                    Line l_ver = new Line(new Point3d(table_xx + 25, table_yy - 20, 0), new Point3d(table_xx + 25, Data.table_y - 26.5, 0));
                    l_ver.LineWeight = LineWeight.LineWeight050;
                    l_ver.ColorIndex = 4;
                    ObjColl.Add(l_ver);

                    Line l_ver1 = new Line(new Point3d(Data.table_x + 22.5, Data.table_y - 26.5, 0), new Point3d(Data.table_x + 27.5, Data.table_y - 26.5, 0));
                    l_ver1.LineWeight = LineWeight.LineWeight100;
                    l_ver1.ColorIndex = 4;
                    ObjColl.Add(l_ver1);

                    ObjColl.Add(new Line(new Point3d(Data.table_x, table_yy, 0), new Point3d(Data.table_x, Data.table_y - 20, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 20, 0), new Point3d(Data.table_x + 63, Data.table_y - 20, 0)));

                    Database wbd = HostApplicationServices.WorkingDatabase;

                    bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    foreach (Entity ent in ObjColl)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }
                    trans.Commit();
                    trans.Dispose();
                }
            }
            this.Show();
        }
Ejemplo n.º 16
0
    public void TestMethod()
    {
        Document activeDoc = Application.DocumentManager.MdiActiveDocument;
        Database db        = activeDoc.Database;
        Editor   ed        = activeDoc.Editor;

        PromptEntityOptions peo = new PromptEntityOptions("Select a polyline : ");

        peo.SetRejectMessage("Not a polyline");
        peo.AddAllowedClass(typeof(Autodesk.AutoCAD.DatabaseServices.Polyline), true);

        PromptEntityResult per = ed.GetEntity(peo);

        if (per.Status != PromptStatus.OK)
        {
            return;
        }

        ObjectId plOid = per.ObjectId;

        PromptPointResult ppr = ed.GetPoint(new PromptPointOptions("Select an internal point : "));

        if (ppr.Status != PromptStatus.OK)
        {
            return;
        }

        Point3d testPoint = ppr.Value;

        PromptAngleOptions pao

            = new PromptAngleOptions("Specify ray direction");

        pao.BasePoint = testPoint;

        pao.UseBasePoint = true;

        PromptDoubleResult rayAngle = ed.GetAngle(pao);

        if (rayAngle.Status != PromptStatus.OK)
        {
            return;
        }
        Point3d tempPoint = testPoint.Add(Vector3d.XAxis);

        tempPoint = tempPoint.RotateBy(rayAngle.Value, Vector3d.ZAxis, testPoint);

        Vector3d rayDir = tempPoint - testPoint;

        ClearTransientGraphics();
        _markers = new DBObjectCollection();
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            Curve plcurve = tr.GetObject(plOid, OpenMode.ForRead) as Curve;

            for (int cnt = 0; cnt < 2; cnt++)
            {
                if (cnt == 1)
                {
                    rayDir = rayDir.Negate();
                }

                using (Ray ray = new Ray())
                {
                    ray.BasePoint = testPoint;

                    ray.UnitDir = rayDir;
                    Point3dCollection intersectionPts = new Point3dCollection();

                    plcurve.IntersectWith(ray, Intersect.OnBothOperands, intersectionPts, IntPtr.Zero, IntPtr.Zero);

                    foreach (Point3d pt in intersectionPts)
                    {
                        Circle marker = new Circle(pt, Vector3d.ZAxis, 0.2);
                        marker.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(0, 255, 0);
                        _markers.Add(marker);

                        IntegerCollection intCol = new IntegerCollection();

                        TransientManager tm = TransientManager.CurrentTransientManager;
                        tm.AddTransient(marker, TransientDrawingMode.Highlight, 128, intCol);

                        ed.WriteMessage("\n" + pt.ToString());
                    }
                }
            }

            tr.Commit();
        }
    }
        private void button12_Click(object sender, EventArgs e)
        {
            this.Hide();

            string textM = "";
            double pointX = 0, pointY = 0;

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (DocumentLock doclock = acDoc.LockDocument())
            {
                // Старт транзакции
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {
                    // Запрос выбора объектов в области чертежа
                    PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();

                    // Если статус запроса равен OK, объекты выбраны
                    if (acSSPrompt.Status == PromptStatus.OK)
                    {
                        SelectionSet acSSet = acSSPrompt.Value;
                        // Перебор объектов в наборе
                        foreach (SelectedObject acSSObj in acSSet)
                        {
                            // Проверка, нужно убедиться в правильности полученного объекта
                            if (acSSObj != null)
                            {
                                // Открытие объекта для чтения
                                Line acEnt = trans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Line;
                                if (acEnt != null)
                                {

                                    int indS = Data.pathPoints.FindIndex(item => item == acEnt.StartPoint);
                                    int indE = Data.pathPoints.FindIndex(item => item == acEnt.EndPoint);

                                    pointX = acEnt.StartPoint.X;
                                    pointY = acEnt.StartPoint.Y;

                                    List<string> tmp = new List<string>();
                                    tmp = Data.pathName[indS];

                                    foreach (String str in tmp)
                                    {
                                        if (Data.pathName[indE].Contains(str))
                                            textM = String.Concat(textM, "/", str);
                                    }

                                }
                            }
                        }
                    }

                    BlockTableRecord btr;
                    BlockTable bt;
                    DBObjectCollection ObjColl = new DBObjectCollection();
                    MText objText = new MText();
                    objText.SetDatabaseDefaults();
                    objText.Location = new Point3d(pointX, pointY + 5, 0);
                    objText.Contents = textM;
                    objText.TextStyleId = acCurDb.Textstyle;
                    objText.TextHeight = 3;
                    objText.Height = 25;
                    objText.Width = 25;
                    ObjColl.Add(objText);

                    Database wbd = HostApplicationServices.WorkingDatabase;

                    bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    foreach (Entity ent in ObjColl)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }
                    trans.Commit();
                    trans.Dispose();
                }
            }

            this.Show();
        }
Ejemplo n.º 18
0
        // [CommandMethod("wblockclone", CommandFlags.Session)]
        //static public void wblockclone()
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    Database db = doc.Database;
        //    Editor ed = doc.Editor;

        //    //PromptEntityOptions peo = new PromptEntityOptions("\nSelect entity to copy: ");

        //    //PromptEntityResult per = ed.GetEntity(peo);

        //    //if (per.Status != PromptStatus.OK)
        //    //    return;
        //    Application.
        //    using (DocumentLock doclock = doc.LockDocument())
        //    {
        //        ObjectIdCollection ObjectcIds = new ObjectIdCollection();
        //        ObjectcIds.Add(per.ObjectId);

        //        Database destDb = new Database(false, true);
        //        destDb.ReadDwgFile(@"C:\Users\Daryl Banks\Downloads\doraltest\2014Doral\Doral-Closed-Polygons\Doral06.DWG", System.IO.FileShare.Read, true, "");

        //        using (Transaction Tx = destDb.TransactionManager.StartTransaction())
        //        {
        //            BlockTable bt = Tx.GetObject(
        //                destDb.BlockTableId,
        //                OpenMode.ForRead) as BlockTable;

        //            BlockTableRecord btr = Tx.GetObject(
        //                bt[BlockTableRecord.ModelSpace],
        //                OpenMode.ForWrite) as BlockTableRecord;

        //            IdMapping oIdMap = new IdMapping();

        //            destDb.WblockCloneObjects(
        //                ObjectcIds,
        //                btr.ObjectId,
        //                oIdMap,
        //                DuplicateRecordCloning.Ignore,
        //                false);

        //            Tx.Commit();
        //        }

        //        destDb.SaveAs(destDb.Filename, DwgVersion.Current);
        //    }
        //}

        public static void GetComplexity()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            using (DocumentLock docLock = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                        PromptEntityOptions peo = new PromptEntityOptions("\nSelect a single polyline  >>");

                        peo.SetRejectMessage("\nSelected object might be of type polyline only >>");

                        peo.AddAllowedClass(typeof(Polyline), false);

                        PromptEntityResult res;

                        res = ed.GetEntity(peo);

                        if (res.Status != PromptStatus.OK)
                        {
                            return;
                        }

                        DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);

                        if (ent == null)
                        {
                            return;
                        }

                        //Polyline poly = (Polyline)ent as Polyline;
                        Curve curv = ent as Curve;

                        DBObjectCollection pcurves = new DBObjectCollection();

                        curv.Explode(pcurves);
                        TypedValue[] values = new TypedValue[]
                        {
                            new TypedValue(0, "lwpolyline")
                            //might be added layer name to select curve:
                            //, new TypedValue(8, "mylayer")
                        };
                        SelectionFilter filter = new SelectionFilter(values);

                        Point3dCollection fence = new Point3dCollection();

                        double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                        // number of divisions along polyline to create fence selection
                        //double step = leng / 256;// set number of steps to your suit
                        double step = leng / pcurves.Count;
                        Application.SetSystemVariable("osmode", 0);// optional
                        // for debug only
                        Application.ShowAlertDialog(string.Format("\nNumber of Steps: {0}", step));

                        tr.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace);
                    }
                }
            }
        }
Ejemplo n.º 19
0
 public void Explode(DBObjectCollection entitySet)
 {
     createInstance();
     BaseEntity.Explode(entitySet);
     tr.Dispose();
 }
Ejemplo n.º 20
0
        public static bool ExcludePolyBasedOnComplexity(ObjectId oid)
        {
            if (oid == null)
            {
                return(true);
            }

            bool result = false; //include by default

            Database db = HostApplicationServices.WorkingDatabase;

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;


            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    DBObject ent = (DBObject)tr.GetObject(oid, OpenMode.ForRead);

                    if (ent == null)
                    {
                        return(false);
                    }

                    //Polyline poly = (Polyline)ent as Polyline;
                    Curve curv = ent as Curve;

                    DBObjectCollection pcurves = new DBObjectCollection();

                    curv.Explode(pcurves);
                    TypedValue[] values = new TypedValue[]
                    {
                        new TypedValue(0, "lwpolyline")
                    };
                    SelectionFilter filter = new SelectionFilter(values);

                    Point3dCollection fence = new Point3dCollection();

                    double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                    // number of divisions along polyline to create fence selection
                    //double step = leng / 256;// set number of steps to your suit
                    double step = leng / pcurves.Count;

                    if ((leng > 1000 || pcurves.Count > 3000) && (step < 1.0))
                    {
                        result = true; // too complex
                    }
                    if (pcurves.Count > 10000)
                    {
                        result = true;
                    }

                    if (result)
                    {
                        ACADLogging.LogMyExceptions(
                            String.Format("\nExcluded Polyline: {0}\nComplexity: {1}\nLayer: {2}\n",
                                          pcurves.Count, step.ToString("n3"), curv.Layer));
                    }
                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    ACADLogging.LogMyExceptions(String.Format("\n{0}\n{1}", ex.Message, ex.StackTrace));
                }

                return(result);
            }
        }
Ejemplo n.º 21
0
 public Dimjig(Point3d basePT, DBObjectCollection entities, DBObjectCollection entitiesL)
 {
     this.mbasePT    = basePT.TransformBy(UCS);
     this.mEntities  = entities;
     this.mEntitiesL = entitiesL;
 }
 /// <summary>
 /// Нарисовать штамп
 /// </summary>
 /// <param name="rb">Точка с координатами правого нижнего угла рамки</param>
 /// <param name="k">Коэффициент увеличения</param>
 private void DrawStampLines(Point3d rb, double k)
 {
     Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
     DocumentLock myLock = myDoc.LockDocument();
     double x0 = rb.X - 185 * k, y0 = rb.Y + 55 * k, z0 = rb.Z;
     double height = y0 - k * 55;
     #region Objects
     Line[][] AOL = new Line[2][]; //ArrayOfLines
     AOL[0] = new Line[15]; //горизонтальные линии
     AOL[0][0] = new Line(new Point3d(x0, y0, z0), new Point3d(x0 + k * 185, y0, z0));
     AOL[0][0].LineWeight = LineWeight.LineWeight030;
     AOL[0][1] = new Line(new Point3d(x0, y0 - k * 5, z0), new Point3d(x0 + k * 65, y0 - k * 5, z0));
     AOL[0][2] = new Line(new Point3d(x0, y0 - k * 10, z0), new Point3d(x0 + k * 65, y0 - k * 10, z0));
     AOL[0][3] = new Line(new Point3d(x0 + k * 65, y0 - k * 10, z0), new Point3d(x0 + k * 185, y0 - k * 10, z0));
     AOL[0][3].LineWeight = LineWeight.LineWeight030;
     AOL[0][4] = new Line(new Point3d(x0, y0 - k * 15, z0), new Point3d(x0 + k * 65, y0 - k * 15, z0));
     AOL[0][5] = new Line(new Point3d(x0, y0 - k * 20, z0), new Point3d(x0 + k * 65, y0 - k * 20, z0));
     AOL[0][5].LineWeight = LineWeight.LineWeight030;
     AOL[0][6] = new Line(new Point3d(x0, y0 - k * 25, z0), new Point3d(x0 + k * 185, y0 - k * 25, z0));
     AOL[0][6].LineWeight = LineWeight.LineWeight030;
     AOL[0][7] = new Line(new Point3d(x0, y0 - k * 30, z0), new Point3d(x0 + k * 65, y0 - k * 30, z0));
     AOL[0][8] = new Line(new Point3d(x0 + k * 135, y0 - k * 30, z0), new Point3d(x0 + k * 185, y0 - k * 30, z0));
     AOL[0][8].LineWeight = LineWeight.LineWeight030;
     AOL[0][9] = new Line(new Point3d(x0, y0 - k * 35, z0), new Point3d(x0 + k * 65, y0 - k * 35, z0));
     AOL[0][10] = new Line(new Point3d(x0, y0 - k * 40, z0), new Point3d(x0 + k * 65, y0 - k * 40, z0));
     AOL[0][11] = new Line(new Point3d(x0 + k * 65, y0 - k * 40, z0), new Point3d(x0 + k * 185, y0 - k * 40, z0));
     AOL[0][11].LineWeight = LineWeight.LineWeight030;
     AOL[0][12] = new Line(new Point3d(x0, y0 - k * 45, z0), new Point3d(x0 + k * 65, y0 - k * 45, z0));
     AOL[0][13] = new Line(new Point3d(x0, y0 - k * 50, z0), new Point3d(x0 + k * 65, y0 - k * 50, z0));
     AOL[0][14] = new Line(new Point3d(x0, y0 - k * 55, z0), new Point3d(x0 + k * 185, (y0 - k * 55), z0));
     AOL[0][14].LineWeight = LineWeight.LineWeight030;
     AOL[1] = new Line[11];
     AOL[1][0] = new Line(new Point3d(x0, y0, z0), new Point3d(x0, y0 - k * 55, z0));
     AOL[1][0].LineWeight = LineWeight.LineWeight030;
     AOL[1][1] = new Line(new Point3d(x0 + k * 10, y0, z0), new Point3d(x0 + k * 10, y0 - k * 25, z0));
     AOL[1][1].LineWeight = LineWeight.LineWeight030;
     AOL[1][2] = new Line(new Point3d(x0 + k * 20, y0, z0), new Point3d(x0 + k * 20, height, z0));
     AOL[1][2].LineWeight = LineWeight.LineWeight030;
     AOL[1][3] = new Line(new Point3d(x0 + k * 30, y0, z0), new Point3d(x0 + k * 30, y0 - k * 25, z0));
     AOL[1][3].LineWeight = LineWeight.LineWeight030;
     AOL[1][4] = new Line(new Point3d(x0 + k * 40, y0, z0), new Point3d(x0 + k * 40, height, z0));
     AOL[1][4].LineWeight = LineWeight.LineWeight030;
     AOL[1][5] = new Line(new Point3d(x0 + k * 55, y0, z0), new Point3d(x0 + k * 55, height, z0));
     AOL[1][5].LineWeight = LineWeight.LineWeight030;
     AOL[1][6] = new Line(new Point3d(x0 + k * 65, y0, z0), new Point3d(x0 + k * 65, height, z0));
     AOL[1][6].LineWeight = LineWeight.LineWeight030;
     AOL[1][7] = new Line(new Point3d(x0 + k * 135, y0 - k * 25, z0), new Point3d(x0 + k * 135, height, z0));
     AOL[1][7].LineWeight = LineWeight.LineWeight030;
     AOL[1][8] = new Line(new Point3d(x0 + k * 150, y0 - k * 25, z0), new Point3d(x0 + k * 150, y0 - k * 40, z0));
     AOL[1][8].LineWeight = LineWeight.LineWeight030;
     AOL[1][9] = new Line(new Point3d(x0 + k * 165, y0 - k * 25, z0), new Point3d(x0 + k * 165, y0 - k * 40, z0));
     AOL[1][9].LineWeight = LineWeight.LineWeight030;
     AOL[1][10] = new Line(new Point3d(x0 + k * 185, y0, z0), new Point3d(x0 + k * 185, (y0 - k * 55), z0));
     AOL[1][10].LineWeight = LineWeight.LineWeight030;
     #endregion
     BlockTableRecord btr;
     BlockTable bt;
     DBObjectCollection ObjColl = new DBObjectCollection(); //коллекция объектов
     Database wbd = HostApplicationServices.WorkingDatabase;
     wbd.LineWeightDisplay = true;
     Transaction trans = wbd.TransactionManager.StartTransaction();
     bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
     btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
     for (int i=0; i<AOL.Length; i++)
         for (int j = 0; j < AOL[i].Length; j++)
         {
             btr.AppendEntity(AOL[i][j]);
             trans.AddNewlyCreatedDBObject(AOL[i][j], true);
         }
     trans.Commit();
     trans.Dispose();
     TextWrite(x0, y0, z0, k);
 }
        private void DrawVRCTable(Point3d pt, int ListIndex)
        {
            Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock myLock = myDoc.LockDocument();
            Database acCurDb = myDoc.Database;
            Editor ed = myDoc.Editor;
            List<Line> lines = new List<Line>();
            DBObjectCollection ObjColl = new DBObjectCollection();
            double x0 = pt.X, y0 = pt.Y - 10 * K, z0 = pt.Z;
            #region Objects
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0 + 185 * K, y0, z0)));
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 15 * K, y0, z0), new Point3d(x0 + 15 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0, z0), new Point3d(x0 + 155 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            MText Header = new MyText(new Point3d(x0 + 92.5 * K, pt.Y - 5 * K, z0), "Ведомость рабочих чертежей", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text1 = new MyText(new Point3d(x0 + 7.5 * K, y0 - 7.5 * K, z0), "Лист", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text2 = new MyText(new Point3d(x0 + 85 * K, y0 - 7.5 * K, z0), "Наименование", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text3 = new MyText(new Point3d(x0 + 170 * K, y0 - 7.5 * K, z0), "Примечание", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText[,] texts = new MText[WDIList.Count, 3];
            for (int v = 0; v < WDIList.Count; v++)
            {
                texts[v, 0] = new MText();
                texts[v, 1] = new MText();
                texts[v, 2] = new MText();
            }
            double realH = y0 - 15 * K;
            int i = 0, thisRows = 0, thisRows2 = 0, rowsCount = 0; //счетчик  thisRows - в столбце Наименований, thisRows2 - примечаний
            double h = 0, hm;
            i = ListIndex;
            h += (P1.Y - pt.Y) + 25 * K;
            if (185 * K + pt.X <= P2.X + 185 * K) //если есть место для колонки
            {
                if (185 * K + pt.X < P2.X) //колонка левее штампа
                    hm = P1.Y - P3.Y;
                else hm = P1.Y - P3.Y - 55 * K;

                while (h < hm && i < WDIList.Count)
                {
                    texts[i, 0] = new MyText(new Point3d(x0 + 7.5 * K, realH - 3 * K, z0), WDIList[i].PNum, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    texts[i, 1] = new MyText(new Point3d(x0 + (15 + 2.5) * K, realH - 3 * K, z0), WDIList[i].Name, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    thisRows = (int)RowCount(texts[i, 1], 135);
                    texts[i, 1].LineSpaceDistance = 8;
                    texts[i, 2] = new MyText(new Point3d(x0 + (155 + 1) * K, realH - 3 * K, z0), WDIList[i].Note, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    thisRows2 = (int)RowCount(texts[i, 2], 28);
                    texts[i, 2].LineSpaceDistance = 8;
                    thisRows = Math.Max(thisRows, thisRows2);
                    if (h + thisRows * 8 * K > hm) break;
                    ObjColl.Add(texts[i, 0]);
                    ObjColl.Add(texts[i, 1]);
                    ObjColl.Add(texts[i, 2]);

                    for (int x = 0; x < thisRows; x++)
                    {
                        lines.Add(new Line(new Point3d(x0, realH - 8 * K, z0), new Point3d(x0 + 185 * K, realH - 8 * K, z0)));
                        realH -= 8 * K;
                    }
                    rowsCount += thisRows;
                    h += thisRows * 8 * K;
                    i++;
                }

                lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 15 * K, y0 - 15 * K, z0), new Point3d(x0 + 15 * K, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 155 * K, y0 - 15 * K, z0), new Point3d(x0 + 155 * K, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 185 * K, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - K * (15 + 8 * rowsCount), z0)));

            #endregion
                BlockTableRecord btr;
                BlockTable bt;
                //DBObjectCollection ObjColl = new DBObjectCollection(); //коллекция объектов
                #region AddObjects to collection
                ObjColl.Add(Text1); ObjColl.Add(Text2); ObjColl.Add(Text3); ObjColl.Add(Header);
                //for (int m=0; m<i; m++)
                //foreach (MText m in texts) ObjColl.Add(m);
                foreach (Line l in lines) ObjColl.Add(l);
                #endregion

                Database wbd = HostApplicationServices.WorkingDatabase;
                wbd.LineWeightDisplay = true;
                Transaction trans = wbd.TransactionManager.StartTransaction();
                bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
                foreach (Entity ent in ObjColl)
                {
                    btr.AppendEntity(ent);
                    trans.AddNewlyCreatedDBObject(ent, true);
                }
                trans.Commit();
                trans.Dispose();

                if (i < WDIList.Count)
                    DrawVRCTable(new Point3d(pt.X + 186 * K, pt.Y, pt.Z), i);
            }
            else if (i < WDIList.Count && PageW >= 185)//места для колонки нет - создаем новый лист
            {
                DrawBorders(new Point3d(P1.X + (-10 + PageW) * K, P1.Y + (5 - PageH) * K, P1.Z));
                DrawVRCTable(P1, i);
            }
            else MessageBox.Show("Лист слишком узок для таблицы");
        }
Ejemplo n.º 24
0
        public void Update()
        {
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            Transaction tr = acCurDb.TransactionManager.TopTransaction;

            //Centre line
            Curve c = tr.GetObject(ObjectId, OpenMode.ForRead) as Curve;

            //Delete existing
            NegativeFoundationId.GetObject(OpenMode.ForWrite, true).Erase();
            PositiveFoundationId.GetObject(OpenMode.ForWrite, true).Erase();

            //Offset it
            LayerTable acLyrTbl = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
            ObjectId   current  = acCurDb.Clayer;

            acCurDb.Clayer = acLyrTbl[Utilities.FoundationLayer];

            // Open the Block table for read
            BlockTable acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

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

            DBObjectCollection offsets  = c.GetOffsetCurves(FoundationWidth / 2);
            DBObjectCollection offsets2 = c.GetOffsetCurves(-(FoundationWidth / 2));

            foreach (Entity e in offsets)
            {
                acBlkTblRec.AppendEntity(e);
                tr.AddNewlyCreatedDBObject(e, true);
                e.LayerId            = acCurDb.Clayer;
                PositiveFoundationId = e.ObjectId;
            }
            foreach (Entity e in offsets2)
            {
                acBlkTblRec.AppendEntity(e);
                tr.AddNewlyCreatedDBObject(e, true);
                e.LayerId            = acCurDb.Clayer;
                NegativeFoundationId = e.ObjectId;
            }


            acCurDb.Clayer = current;

            //Update formation tag
            if (FormationTagId != null)
            {
                BlockReference acBlkRef = tr.GetObject(FormationTagId, OpenMode.ForRead) as BlockReference;

                //Set value
                AttributeCollection attCol = acBlkRef.AttributeCollection;
                foreach (ObjectId attId in attCol)
                {
                    AttributeReference att = tr.GetObject(attId, OpenMode.ForRead) as AttributeReference;
                    if (att.Tag == "LEVEL")
                    {
                        att.UpgradeOpen();
                        att.TextString = Parent.FormationLevel.ToString("F3");
                    }
                }
            }
        }
        private void DrawLDTable(Point3d pt)
        {
            Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock myLock = myDoc.LockDocument();
            Database acCurDb = myDoc.Database;
            Editor ed = myDoc.Editor;
            List<Line> lines = new List<Line>();
            double x0 = pt.X, y0 = pt.Y - 10 * K, z0 = pt.Z;
            //double height = y0 - k * 55;
            #region Objects
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0 + 185 * K, y0, z0)));
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 60 * K, y0, z0), new Point3d(x0 + 60 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0, z0), new Point3d(x0 + 155 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            MText Header = new MyText(new Point3d(x0 + 92.5 * K, pt.Y - 5 * K, z0), "Ведомость прилагаемых документов", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text1 = new MyText(new Point3d(x0 + 30 * K, y0 - 7.5 * K, z0), "Обозначение", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text2 = new MyText(new Point3d(x0 + 107.5 * K, y0 - 7.5 * K, z0), "Наименование", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text3 = new MyText(new Point3d(x0 + 170 * K, y0 - 7.5 * K, z0), "Примечание", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText[,] texts = new MText[LDIList.Count, 3];
            double realH = y0 - 15 * K;
            int i = 0, thisRows = 0, thisRows2 = 0, rowsCount = 0; //счетчик  thisRows - в столбце Наименований, thisRows2 - примечаний

            //считаем кол-во строк
            for (i = 0; i < LDIList.Count; i++)
            {
                texts[i, 0] = new MyText(new Point3d(x0 + 30 * K, realH - 3 * K, z0), LDIList[i].Label, 3 * K, acCurDb, AttachmentPoint.TopCenter);
                texts[i, 1] = new MyText(new Point3d(x0 + (60 + 2.5) * K, realH - 3 * K, z0), LDIList[i].Name, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                thisRows = (int)RowCount(texts[i, 1], 90);
                texts[i, 1].LineSpaceDistance = 8;
                texts[i, 2] = new MyText(new Point3d(x0 + (155 + 1) * K, realH - 3 * K, z0), LDIList[i].Note, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                thisRows2 = (int)RowCount(texts[i, 2], 28);
                texts[i, 2].LineSpaceDistance = 8;
                thisRows = Math.Max(thisRows, thisRows2);
                for (int x = 0; x < thisRows; x++)
                {
                    lines.Add(new Line(new Point3d(x0, realH - 8 * K, z0), new Point3d(x0 + 185 * K, realH - 8 * K, z0)));
                    realH -= 8 * K;
                }
                rowsCount += thisRows;
            }
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 60 * K, y0 - 15 * K, z0), new Point3d(x0 + 60 * K, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0 - 15 * K, z0), new Point3d(x0 + 155 * K, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - K * (15 + 8 * rowsCount), z0)));

            #endregion
            BlockTableRecord btr;
            BlockTable bt;
            DBObjectCollection ObjColl = new DBObjectCollection(); //коллекция объектов
            #region AddObjects to collection
            ObjColl.Add(Text1); ObjColl.Add(Text2); ObjColl.Add(Text3); ObjColl.Add(Header);
            foreach (MText m in texts) ObjColl.Add(m);
            foreach (Line l in lines) ObjColl.Add(l);
            #endregion

            Database wbd = HostApplicationServices.WorkingDatabase;
            wbd.LineWeightDisplay = true;
            Transaction trans = wbd.TransactionManager.StartTransaction();
            bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
            btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
            foreach (Entity ent in ObjColl)
            {
                btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
            }
            trans.Commit();
            trans.Dispose();
        }
Ejemplo n.º 26
0
        public static string GetAreaBound()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            //PromptKeywordOptions pkOp = new PromptKeywordOptions("");
            //pkOp.Message = "\nUse Island Detection ";
            //pkOp.Keywords.Add("Yes");
            //pkOp.Keywords.Add("No");
            //pkOp.AllowNone = false;
            //PromptResult pr = ed.GetKeywords(pkOp);
            //if (pr.Status == PromptStatus.Cancel)
            //{
            //    return null;
            //}
            //string pkostr = pr.StringResult;
            //bool flagIsland = false;
            //if (pkostr == "Yes") { flagIsland = true; } else { flagIsland = false; }
            PromptPointResult ppr = ed.GetPoint("\nSelect Internal Point on Closed Area: ");
            if (ppr.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\n" + ppr.StringResult);
            }
            string value = null;
            DBObjectCollection dbObjColl = ed.TraceBoundary(ppr.Value, false);
            Double area = 0;
            try
            {
                if (dbObjColl.Count > 0)
                {
                    Transaction tr = doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        BlockTable bt = (BlockTable)
                           tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = (BlockTableRecord)
                            tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                        ObjectIdCollection objIds = new ObjectIdCollection();
                        foreach (DBObject Obj in dbObjColl)
                        {
                            Entity ent = Obj as Entity;
                            if (ent != null)
                            {
                                // ent.GetField("Area");
                                if (ent is Polyline)
                                {
                                    Polyline p = (Polyline)ent;
                                    if (p.Closed)
                                    {
                                        area = p.Area;
                                        string presisi = "#";
                                        switch (db.Auprec)
                                        {
                                            case 0:
                                                presisi = "#";
                                                break;
                                            case 1:
                                                presisi = "#0.0";
                                                break;
                                            case 2:
                                                presisi = "#0.00";
                                                break;
                                            case 3:
                                                presisi = "#0.000";
                                                break;
                                            case 4:
                                                presisi = "#0.0000";
                                                break;
                                            case 5:
                                                presisi = "#0.00000";
                                                break;
                                            default:
                                                presisi = "#0.00";
                                                break;
                                        }
                                        value = area.ToString(presisi);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {

                throw;
            }
            return value;
        }
Ejemplo n.º 27
0
        public void MyCommand2() // This method can have any name
        {
            Matrix3d UCS = ed.CurrentUserCoordinateSystem;

            ObjectId StyleID = CreatMyTextStyle();

            db.Textstyle = StyleID;
            ObjectId TableID = CreateZBDic();

            if (TableID != ObjectId.Null)
            {
                CurrentZBConfig(TableID);
                PromptPointOptions opt = new PromptPointOptions("\n插入点或[更改设置(S)]:", "S");
                opt.AllowNone = false;
                PromptPointResult result = ed.GetPoint(opt);
                while (result.Status == PromptStatus.Keyword)
                {
                    ChangeZBConfig(TableID);
                    result = ed.GetPoint(opt);
                }
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }

                DBObjectCollection EntityList = CreateDimOnlyXY(result.Value.TransformBy(UCS), result.Value.TransformBy(UCS), TableID);
                Dimjig             jigger     = new Dimjig(result.Value, EntityList, EntityList);
                Line dragline = new Line(jigger.basePT, jigger.basePT);
                jigger.leader = dragline;

                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    PromptResult jigresult = ed.Drag(jigger);
                    if (jigresult.Status == PromptStatus.OK)
                    {
                        jigger.TransformEnties();
                        Line Leader = new Line(jigger.basePT, jigger.dragPT);
                        try
                        {
                            BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                            if (jigger.IsRight)
                            {
                                foreach (Entity ent in jigger.EntityList)
                                {
                                    btr.AppendEntity(ent);
                                    trans.AddNewlyCreatedDBObject(ent, true);
                                }
                            }
                            else
                            {
                                foreach (Entity ent in jigger.EntityListL)
                                {
                                    btr.AppendEntity(ent);
                                    trans.AddNewlyCreatedDBObject(ent, true);
                                }
                            }
                            btr.AppendEntity(Leader);
                            trans.AddNewlyCreatedDBObject(Leader, true);
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception EX)
                        {
                            ed.WriteMessage("\n出错了!" + EX.ToString());
                        }
                        trans.Commit();
                    }
                    else
                    {
                        trans.Abort();
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public DBObjectCollection CreateDimL(Point3d basePT, Point3d insPT, ObjectId tableID)
        {
            DBObjectCollection DimEntity = new DBObjectCollection();

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    DataTable dt    = (DataTable)trans.GetObject(tableID, OpenMode.ForRead);
                    NodeDim   Dim   = new NodeDim(basePT, insPT, (double)dt.GetCellAt(0, 0).Value, (int)dt.GetCellAt(0, 1).Value);
                    Line      Cline = new Line(Dim.ClineStartPT, Dim.ClineEndPT);
                    Line      Hline = new Line(Dim.HlineStartPTL, Dim.HlineEndPTL);
                    DBText    XText = new DBText();
                    XText.TextString  = Dim.Xstring;
                    XText.Position    = Dim.XTextPT;
                    XText.Height      = Dim.TextHeight;
                    XText.WidthFactor = 0.7;

                    DBText YText = new DBText();
                    YText.TextString = Dim.Ystring;

                    YText.Position    = Dim.YTextPT;
                    YText.Height      = Dim.TextHeight;
                    YText.WidthFactor = 0.7;

                    DBText GHText = new DBText();
                    GHText.TextString  = Dim.GHeight;
                    GHText.Position    = Dim.GHTextPTL;
                    GHText.Height      = Dim.TextHeight;
                    GHText.WidthFactor = 0.7;

                    DBText PHText = new DBText();
                    PHText.TextString = Dim.PHeight;

                    PHText.Position    = Dim.PHTextPTL;
                    PHText.Height      = Dim.TextHeight;
                    PHText.WidthFactor = 0.7;

                    DBText EXText = new DBText();
                    EXText.TextString  = Dim.Extrastring;
                    EXText.Position    = Dim.ExtraTextPT;
                    EXText.Height      = Dim.TextHeight;
                    EXText.WidthFactor = 0.7;



                    DimEntity.Add(Cline);
                    DimEntity.Add(Hline);
                    DimEntity.Add(XText);
                    DimEntity.Add(YText);
                    DimEntity.Add(GHText);
                    DimEntity.Add(PHText);
                    DimEntity.Add(EXText);
                }

                catch (Autodesk.AutoCAD.Runtime.Exception EX)
                {
                    ed.WriteMessage("出错了!" + EX.ToString());
                }
                trans.Commit();
            }
            return(DimEntity);
        }
Ejemplo n.º 29
0
        //[CommandMethod("PolylineToCSV", "plcsv", CommandFlags.Modal | CommandFlags.UsePickSet)]
        //public static void ExportPolyPointsToCSV()
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;

        //    Database db = doc.Database;

        //    Editor ed = doc.Editor;

        //    try
        //    {
        //        using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
        //        {
        //            string dec = ((short)Application.GetSystemVariable("LUPREC")).ToString();

        //            PromptSelectionOptions pso = new PromptSelectionOptions();

        //            pso.MessageForRemoval = "\n >>  Nothing selected....";

        //            pso.MessageForAdding = "\n  >>  Select a single polyline >> ";

        //            pso.AllowDuplicates = false;

        //            pso.SingleOnly = true;

        //            SelectionFilter sf = new SelectionFilter
        //                (new TypedValue[] { new TypedValue(0, "lwpolyline") });

        //            PromptSelectionResult res = ed.GetSelection(pso, sf);

        //            if (res.Status != PromptStatus.OK) return;

        //            StringBuilder sb = new StringBuilder();
        //            ObjectId[] ids = res.Value.GetObjectIds();

        //            Polyline poly = (Polyline)tr.GetObject(ids[0], OpenMode.ForRead, false);
        //            for (int i = 0; i < poly.NumberOfVertices; i++)
        //            {
        //                Point2d pt = poly.GetPoint2dAt(i);
        //                string vexstr = string.Format("{0:f" + dec + "};{1:f" + dec + "}", pt.X, pt.Y);
        //                sb.AppendLine(vexstr);
        //            }
        //            String csvFile = String.Empty;

        //            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
        //            sfd.ValidateNames = true;
        //            sfd.Title = "Save polyline vertices to CSV file";
        //            sfd.DefaultExt = ".csv";
        //            sfd.InitialDirectory = @"C:\PGA\";
        //            sfd.RestoreDirectory = true;

        //            if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

        //            csvFile = sfd.FileName;

        //            // write point to defined file
        //            using (StreamWriter sw = new StreamWriter(csvFile))
        //            {
        //                sw.Write(sb.ToString());

        //                sw.Flush();
        //            }
        //            sfd.Dispose();// non resident object, so kill 'em

        //            tr.Commit();
        //        }
        //    }
        //    catch (AcadRuntime.Exception ex)
        //    {
        //        ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
        //    }
        //}


        //[CommandMethod("gi")]
        public static void GetIntersections()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            using (DocumentLock docLock = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                        PromptEntityOptions peo = new PromptEntityOptions("\nSelect a single polyline  >>");

                        peo.SetRejectMessage("\nSelected object might be of type polyline only >>");

                        peo.AddAllowedClass(typeof(Polyline), false);

                        PromptEntityResult res;

                        res = ed.GetEntity(peo);

                        if (res.Status != PromptStatus.OK)
                        {
                            return;
                        }

                        DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);

                        if (ent == null)
                        {
                            return;
                        }

                        //Polyline poly = (Polyline)ent as Polyline;
                        Curve curv = ent as Curve;

                        DBObjectCollection pcurves = new DBObjectCollection();

                        curv.Explode(pcurves);
                        TypedValue[] values = new TypedValue[]
                        {
                            new TypedValue(0, "lwpolyline")
                            //might be added layer name to select curve:
                            //, new TypedValue(8, "mylayer")
                        };
                        SelectionFilter filter = new SelectionFilter(values);

                        Point3dCollection fence = new Point3dCollection();

                        double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                        // number of divisions along polyline to create fence selection
                        double step = leng / 256;// set number of steps to your suit

                        int num = Convert.ToInt32(leng / step);

                        int i = 0;

                        for (i = 0; i < num; i++)
                        {
                            Point3d pp = curv.GetPointAtDist(step * i);

                            fence.Add(curv.GetClosestPointTo(pp, false));
                        }

                        PromptSelectionResult selres = ed.SelectFence(fence, filter);

                        if (selres.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3dCollection intpts = new Point3dCollection();

                        DBObjectCollection qcurves = new DBObjectCollection();

                        foreach (SelectedObject selobj in selres.Value)
                        {
                            DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                            if (selobj.ObjectId != curv.ObjectId)
                            {
                                DBObjectCollection icurves = new DBObjectCollection();
                                Curve icurv = obj as Curve;
                                icurv.Explode(icurves);
                                foreach (DBObject dbo in icurves)
                                {
                                    if (!qcurves.Contains(dbo))
                                    {
                                        qcurves.Add(dbo);
                                    }
                                }
                            }
                        }
                        ed.WriteMessage("\n{0}", qcurves.Count);



                        int j = 0;
                        Point3dCollection polypts = new Point3dCollection();

                        for (i = 0; i < pcurves.Count; ++i)
                        {
                            for (j = 0; j < qcurves.Count; ++j)
                            {
                                Curve curve1 = pcurves[i] as Curve;

                                Curve curve2 = qcurves[j] as Curve;

                                Point3dCollection pts = new Point3dCollection();

                                // curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, (int)IntPtr.Zero, (int)IntPtr.Zero);
                                curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);
                                foreach (Point3d pt in pts)
                                {
                                    if (!polypts.Contains(pt))
                                    {
                                        polypts.Add(pt);
                                    }
                                }
                            }
                        }

                        Application.SetSystemVariable("osmode", 0);// optional
                        // for debug only
                        Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count));
                        // test for visulization only
                        foreach (Point3d inspt in polypts)
                        {
                            Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                            circ.ColorIndex = 1;
                            btr.AppendEntity(circ);
                            tr.AddNewlyCreatedDBObject(circ, true);
                        }
                        tr.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace);
                    }
                }
            }
        }
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
Ejemplo n.º 31
0
        public static List <Entity> BreakAndDelete(this Entity breakEnt, Entity edgeEnt, string strDir)
        {
            List <Entity> lstTotal = new List <Entity>();

            List <Entity> lstBreak = new List <Entity>();
            List <Entity> lstEdag  = new List <Entity>();

            DBObjectCollection dbObjs = new DBObjectCollection();

            breakEnt.Explode(dbObjs);
            foreach (DBObject dBObject in dbObjs)
            {
                Entity ent = dBObject as Entity;
                lstBreak.Add(ent);
            }

            Dictionary <Curve, List <double> > objpts;

            objpts = new Dictionary <Curve, List <double> >(lstBreak.Count);

            foreach (Entity entBreak in lstBreak)
            {
                Curve             cvBreak = entBreak as Curve;
                Point3dCollection points  = new Point3dCollection();
                cvBreak.IntersectWith(edgeEnt, Intersect.OnBothOperands, points, IntPtr.Zero, IntPtr.Zero);
                if (points.Count == 0)
                {
                    lstTotal.Add(cvBreak);
                    continue;
                }

                List <double> pas = new List <double>();
                if (!objpts.ContainsKey(cvBreak))
                {
                    objpts.Add(cvBreak, pas);
                }

                foreach (Point3d pt in points)
                {
                    double para = 0;
                    try
                    {
                        para = cvBreak.GetParameterAtPoint(pt);
                        pas.Add(para);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            foreach (KeyValuePair <Curve, List <double> > var in objpts)
            {
                Curve cv = var.Key;
                if (var.Value.Count == 0)
                {
                    continue;
                }
                if (var.Value.Count == 1 && cv.IsPeriodic && cv.IsPersistent)
                {
                    continue;
                }
                var.Value.Sort();
                double[]           arrpt = var.Value.ToArray();
                DoubleCollection   pts   = new DoubleCollection(arrpt);
                DBObjectCollection objs  = cv.GetSplitCurves(pts);
                var query = from DBObject dbObj in objs
                            let curve = dbObj as Curve
                                        select curve;
                int m = 0;
                foreach (Curve brks in query)
                {
                    #region 判断逻辑
                    if (query.Count() > 1)
                    {
                        if (query.Count() == 2)
                        {
                            switch (strDir)
                            {
                            case "Right":
                                if (m == 0)
                                {
                                    m++; continue;
                                }
                                break;

                            case "Left":
                                if (m == 1)
                                {
                                    continue;
                                }
                                break;

                            case "Up":
                                if (m == 0)
                                {
                                    m++; continue;
                                }
                                break;

                            case "Down":
                                if (m == 1)
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        if (query.Count() > 2)
                        {
                            if (m != 0 && m != query.Count() - 1)//只留第1和最后
                            {
                                m++;
                                continue;
                            }
                        }
                    }
                    #endregion

                    if (cv.GetDistanceAtParameter(brks.EndParam) > 1e-6)
                    {
                        m++;
                        lstTotal.Add(brks);
                    }
                }
            }
            return(lstTotal);
        }
Ejemplo n.º 32
0
        public bool TryInsertBlockRecord(string blockName, DBObjectCollection geometricEntities, List<AttributeDefinition> attCollection)
        {
            Transaction trans = db.TransactionManager.StartTransaction();
            using (trans)
            {
                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                if (!bt.Has(blockName))
                {
                    BlockTableRecord btr = new BlockTableRecord();
                    btr.Name = blockName;

                    bt.UpgradeOpen();
                    bt.Add(btr);
                    trans.AddNewlyCreatedDBObject(btr, true);

                    foreach (Entity ent in geometricEntities)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }

                    foreach (AttributeDefinition atd in attCollection)
                    {
                        btr.AppendEntity(atd);
                        trans.AddNewlyCreatedDBObject(atd, true);
                    }

                    trans.Commit();
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
Ejemplo n.º 33
0
        public static TypedValue ProxyExplodeToBlock(ResultBuffer rbArgs)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            TypedValue res = new TypedValue((int)LispDataType.Text,"");

            if (rbArgs.AsArray().Length == 2)
            {
                TypedValue entity = rbArgs.AsArray()[0];
                TypedValue blkPrefix = rbArgs.AsArray()[1];

                if ((entity.TypeCode == (int)LispDataType.ObjectId) && (blkPrefix.TypeCode == (int)LispDataType.Text))
                {
                    using (Transaction tr = doc.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            ObjectId id = (ObjectId)entity.Value;
                            DBObjectCollection objs = new DBObjectCollection();
                            BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                            Entity entx = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                            entx.Explode(objs);

                            string blkName = blkPrefix.Value.ToString() + entx.Handle.ToString();

                            if (bt.Has(blkName) == false)
                            {
                                BlockTableRecord btr = new BlockTableRecord();
                                btr.Name = blkName;

                                bt.UpgradeOpen();
                                ObjectId btrId = bt.Add(btr);
                                tr.AddNewlyCreatedDBObject(btr, true);

                                foreach (DBObject obj in objs)
                                {
                                    Entity ent = (Entity)obj;
                                    btr.AppendEntity(ent);
                                    tr.AddNewlyCreatedDBObject(ent, true);
                                }
                            }
                            res = new TypedValue((int)LispDataType.Text, blkName);

                            tr.Commit();
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex)
                        {
                            tr.Abort();
                            ed.WriteMessage(ex.Message);
                        }
                    }
                }
            }
            return res;
        }
        public void StretchPolylineEdge_V2()
        {
            Document doc = GetDocument();
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            ObjectId           currentId       = ObjectId.Null;
            int                currentParam    = -1;
            Polyline           currentPolyline = null;
            DBObjectCollection transientColl   = null;
            double             requiredArea    = 0.0;
            bool               isNotEnoughArea = false;
            Point3d?           currPoint       = null;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    PromptDoubleOptions pdo = new PromptDoubleOptions(
                        "\nSpecify the required area: ")
                    {
                        AllowNegative   = false,
                        AllowNone       = false,
                        AllowZero       = false,
                        DefaultValue    = defaultArea,
                        UseDefaultValue = defaultArea == 0 ? false : true
                    };
                    PromptDoubleResult pdr = ed.GetDouble(pdo);
                    if (pdr.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    requiredArea = defaultArea = pdr.Value;

                    ed.TurnForcedPickOn();
                    ed.PointMonitor += Ed_PointMonitor;
                    Polyline pline = SelectPolyline(ed, trans,
                                                    "\nSelect a closed polyline: ", "\n>>>Select a closed polyline: ", true,
                                                    out Point3d pickPt);
                    if (pline == null)
                    {
                        return;
                    }

                    var pts = GetStretchPoints(pline, pickPt, out int par);
                    if (pts == null)
                    {
                        ed.WriteMessage("\n not enough area...");
                        return;
                    }
                    pline.UpgradeOpen();
                    pline.SetPointAt(par, pts[1]);
                    pline.SetPointAt(pline.ParameterAfter(par), pts[2]);
                    trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message + ex.StackTrace);
                }
                finally
                {
                    ed.PointMonitor -= Ed_PointMonitor;
                    if (currentPolyline != null)
                    {
                        EraseTransient();
                        currentPolyline = null;
                    }
                }
            }



            Polyline CreateTransient(Transaction tr, ObjectId id, PointMonitorEventArgs e
                                     , out int par)
            {
                var rawPoint = e.Context.RawPoint;
                var pline    = tr.GetObject(id, OpenMode.ForRead) as Polyline;
                var pickPt   = pline.GetClosestPointTo(rawPoint, true);
                var res      = GetStretchPoints(pline, pickPt, out par);

                transientColl = new DBObjectCollection();
                if (res != null)
                {
                    isNotEnoughArea = false;
                    Polyline drawable = new Polyline();
                    drawable.AddVertexAt(0, res[0], 0, 0, 0);
                    drawable.AddVertexAt(1, res[1], 0, 0, 0);
                    drawable.AddVertexAt(2, res[2], 0, 0, 0);
                    drawable.AddVertexAt(3, res[3], 0, 0, 0);

                    drawable.ColorIndex = 3;

                    transientColl.Add(drawable);
                }
                else
                {
                    isNotEnoughArea = true;
                    Point2d pixels    = e.Context.DrawContext.Viewport.GetNumPixelsInUnitSquare(rawPoint);
                    int     glyphSize = CustomObjectSnapMode.GlyphSize;
                    glyphHeight = glyphSize / pixels.Y * 1.0;

                    radius = glyphHeight / 2.0;
                    center = e.Context.RawPoint + new Vector3d(3 * radius, 3 * radius, 0);

                    Point2d  p1  = (center + new Vector3d(-radius, -radius, 0)).GetPoint2d();
                    Point2d  p2  = (center + new Vector3d(+radius, +radius, 0)).GetPoint2d();
                    Point2d  p3  = (center + new Vector3d(-radius, +radius, 0)).GetPoint2d();
                    Point2d  p4  = (center + new Vector3d(+radius, -radius, 0)).GetPoint2d();
                    Polyline pl1 = new Polyline
                    {
                        ColorIndex = 1
                    };
                    pl1.AddVertexAt(0, p1, 0, 0, 0);
                    pl1.AddVertexAt(1, p2, 0, 0, 0);


                    Polyline pl2 = new Polyline()
                    {
                        ColorIndex = 1
                    };
                    pl2.AddVertexAt(0, p3, 0, 0, 0);
                    pl2.AddVertexAt(1, p4, 0, 0, 0);

                    transientColl.Add(pl1);
                    transientColl.Add(pl2);
                }

                for (int i = 0; i < transientColl.Count; i++)
                {
                    GI.TransientManager.CurrentTransientManager.AddTransient(
                        transientColl[i], GI.TransientDrawingMode.Contrast,
                        128, new IntegerCollection());
                }
                return(pline);
            }

            void UpdateTransients(Point3d lastPt, Point3d currPt)
            {
                if (transientColl == null)
                {
                    return;
                }
                if (isNotEnoughArea)
                {
                    Matrix3d mat = Matrix3d.Displacement(lastPt.GetVectorTo(currPt));
                    foreach (Entity e in transientColl)
                    {
                        e.TransformBy(mat);
                        GI.TransientManager.CurrentTransientManager.UpdateTransient(e,
                                                                                    new IntegerCollection());
                    }
                }
            }

            void EraseTransient()
            {
                if (transientColl == null)
                {
                    return;
                }
                GI.TransientManager.CurrentTransientManager.EraseTransients(
                    GI.TransientDrawingMode.Contrast,
                    128, new IntegerCollection());
                foreach (GI.Drawable drawable in transientColl)
                {
                    drawable.Dispose();
                }
                transientColl.Clear();
                transientColl = null;
            }

            void Ed_PointMonitor(object sender, PointMonitorEventArgs e)
            {
                try
                {
                    var fsPaths = e.Context.GetPickedEntities();
                    // nothing under the mouse cursor.
                    if (fsPaths == null || fsPaths.Length == 0)
                    {
                        if (currentPolyline != null)
                        {
                            EraseTransient();
                            currentPolyline = null;
                        }
                        return;
                    }

                    var rawPoint = e.Context.RawPoint;
                    var oIds     = fsPaths[0].GetObjectIds();
                    var id       = oIds[oIds.GetUpperBound(0)];

                    if (currPoint.HasValue)
                    {
                        UpdateTransients(currPoint.Value, rawPoint);
                    }
                    currPoint = rawPoint;

                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        var pline    = tr.GetObject(id, OpenMode.ForRead) as Polyline;
                        var pickedPt = pline.GetClosestPointTo(rawPoint, true);
                        var par      = (int)pline.GetParameterAtPoint(pickedPt);
                        if (currentPolyline != pline || currentParam != par)
                        {
                            EraseTransient();
                            currentPolyline = CreateTransient(tr, id, e, out currentParam);
                        }
                        //else if (currentPolyline == pline && currentParam == par)
                        //{

                        //}
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message);
                }
            }

            Point2d[] GetStretchPoints(
                Polyline pline, Point3d pickPt, out int par)
            {
                var area = pline.GetArea();

                par = (int)pline.GetParameterAtPoint(pickPt);
                int pre1 = par > 0 ? par - 1 : (int)pline.EndParam - 1;
                int pos1 = par + 1 == (int)pline.EndParam ? 0 : par + 1;
                int pos2 = pos1 == (int)pline.EndParam ? 1 : pos1 + 1;
                // get the the surrounding points
                var    p1 = pline.GetPointAtParameter(pre1).GetPoint2d();
                var    p2 = pline.GetPointAtParameter(par).GetPoint2d();
                var    p3 = pline.GetPointAtParameter(pos1).GetPoint2d();
                var    p4 = pline.GetPointAtParameter(pos2).GetPoint2d();
                double l1 = p2.GetDistanceTo(p3);

                double dA    = requiredArea - Math.Abs(area);
                double ang1  = p1.GetVectorTo(p2).Angle;
                double ang2  = p4.GetVectorTo(p3).Angle;
                double ang   = p2.GetVectorTo(p3).Angle;
                double dAng1 = (area > 0) ? ang - ang1 : ang1 - ang;
                double dAng2 = (area > 0) ? ang - ang2 : ang2 - ang;
                double f     = 0.5 * (1.0 / Math.Tan(dAng2) - 1.0 / Math.Tan(dAng1));
                double v     = l1 * l1 + 4 * dA * f;

                if (v < 0)
                {
                    return(null);
                }
                double h;

                if (Math.Abs(ang1 - ang2) < 0.00001)
                {
                    h = dA / l1;
                }
                else
                {
                    h = (-l1 + Math.Sqrt(v)) / (2.0 * f);
                }
                var pt2 = p2.Polar(ang1, h / Math.Sin(dAng1));
                var pt3 = p3.Polar(ang2, h / Math.Sin(dAng2));

                return(new Point2d[] { p2, pt2, pt3, p3 });
            }
        }
Ejemplo n.º 35
0
        private void Create_opis21()
        {
            string blockName = "opis-21";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Circle ent1 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.2);
            ent1.Color = Color.FromColorIndex(ColorMethod.ByColor, 7);
            entityCollection.Add(ent1);

            List<AttributeDefinition> attDefCollection = new List<AttributeDefinition>();

            AttributeDefinition attDef1 = new AttributeDefinition();
            attDef1.Position = new Point3d(-0.117, -0.085, 0);
            attDef1.Tag = "NN";
            attDef1.Prompt = "numer_preta";
            attDef1.TextString = "nic";
            attDef1.Height = 0.17;
            attDef1.WidthFactor = 0.8;
            attDef1.Justify = AttachmentPoint.MiddleCenter;
            attDef1.Layer = "0";

            AttributeDefinition attDef2 = new AttributeDefinition();
            attDef2.Tag = "OPIS1";
            attDef2.Prompt = "opis_preta1";
            attDef2.TextString = "nic";
            attDef2.Height = 0.125;
            attDef2.WidthFactor = 1;
            attDef2.Justify = AttachmentPoint.MiddleLeft;
            attDef2.HorizontalMode = TextHorizontalMode.TextLeft;
            attDef2.Layer = "0";
            attDef2.AlignmentPoint = new Point3d(0.276, 0, 0);

            Transaction trans = db.TransactionManager.StartTransaction();
            using (trans)
            {
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;

                if (!tst.Has("SIMPLEX8"))
                {
                    System.Windows.Forms.MessageBox.Show("W pliku nie ma definicji stylu tekstu!", "Error",
                        System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    ObjectId textStyleId;
                    textStyleId = tst["SIMPLEX8"];
                    attDef1.TextStyleId = textStyleId;
                    attDef2.TextStyleId = textStyleId;
                }
            }

            attDefCollection.Add(attDef1);
            attDefCollection.Add(attDef2);
            TryInsertBlockRecord(blockName, entityCollection, attDefCollection);
        }
Ejemplo n.º 36
0
        public void ReplaceTitle()
        {
            // Step 1: CREATE INSTANCE OF SUBCLASS
            SubClass acSC = new SubClass();

            // Step 2: GET ALL DOCUMENT NAME OPENED
            DocumentCollection acDocMgr = Application.DocumentManager;

            if (acFrm == null)
            {
                acFrm = new ChangeForm();
            }
            acFrm.DocumentNameCollection = acSC.GetAllDocumentNameInDocumentCollection(acDocMgr);
            //Application.ShowAlertDialog("1");
            acFrm.BlockTableRecordNameCollection = acSC.GetBlockTableRecordNameCollection(acDocMgr);
            // Application.ShowAlertDialog("2");
            acBlkTblRecCol = acSC.GetBlockTableRecordCollection(acDocMgr);
            //Application.ShowAlertDialog("3");
            acFrm.CreateDocumentNameCollection();
            //Application.ShowAlertDialog("4");
            //Application.ShowAlertDialog(acFrm.BlockTableRecordNameCollection[0]);
            //Application.ShowAlertDialog(acFrm.BlockTableRecordNameCollection[1]);
            acFrm.CreateBlockTableNameCollection();
            //acFrm.ShowDialog();
            //Application.ShowAlertDialog("5");
            acFrm.AttributeDefinitionCollection = acSC.GetAttributeDefinitionNameAllCollection(acDocMgr, acBlkTblRecCol);
            //Application.ShowAlertDialog("6");
            acFrm.cbbBlkTblRec1.SelectedIndex = 0;
            //acFrm.CreateAttributeDefinitionCollectionRemoved();
            //Application.ShowAlertDialog("7");
            acFrm.cbbBlkTblRec2.SelectedIndex = 0;
            //acFrm.CreateAttributeDefinitionCollectionReplaced();
            //Application.ShowAlertDialog("8");
            acFrm.IsButtonOkClicked = false;
            acFrm.ShowDialog();
            while (acFrm.IsClosed == false)
            {
                if (acFrm.IsButtonBlockTableRecordName1Clicked)
                {
                    string txt;
                    using (Transaction acTrans = acDocMgr.MdiActiveDocument.Database.TransactionManager.StartTransaction())
                    {
                        txt = (acSC.GetBlockReference(acDocMgr.MdiActiveDocument, acTrans, "Select a Title Block", "Select a Title Block")).Name;
                    }
                    int select = 0;
                    for (int i = 0; i < acFrm.cbbBlkTblRec1.Items.Count; i++)
                    {
                        if (acFrm.cbbBlkTblRec1.Items[i].ToString() == txt)
                        {
                            select = i;
                        }
                    }
                    acFrm.cbbBlkTblRec1.SelectedIndex = select;
                }

                if (acFrm.IsButtonBlockTableRecordName2Clicked)
                {
                    string txt;
                    using (Transaction acTrans = acDocMgr.MdiActiveDocument.Database.TransactionManager.StartTransaction())
                    {
                        txt = (acSC.GetBlockReference(acDocMgr.MdiActiveDocument, acTrans, "Select a Title Block", "Select a Title Block")).Name;
                    }
                    int select = 0;
                    for (int i = 0; i < acFrm.cbbBlkTblRec2.Items.Count; i++)
                    {
                        if (acFrm.cbbBlkTblRec2.Items[i].ToString() == txt)
                        {
                            select = i;
                        }
                    }
                    acFrm.cbbBlkTblRec2.SelectedIndex = select;
                }
            }
            if (acFrm.IsButtonOkClicked)
            {
                //Application.ShowAlertDialog("Start");
                BlockTableRecord acBlkTblRecReplaced = new BlockTableRecord();
                for (int i = 0; i < acBlkTblRecCol.Count; i++)
                {
                    if (((BlockTableRecord)acBlkTblRecCol[i]).Name.Equals(acFrm.cbbBlkTblRec2.SelectedItem.ToString()))
                    {
                        //Application.ShowAlertDialog("");
                        acBlkTblRecReplaced = ((BlockTableRecord)acBlkTblRecCol[i]);
                        //Application.ShowAlertDialog(acBlkTblRecReplaced.Name);
                        foreach (Document acDoc in acDocMgr)
                        {
                            using (Transaction acTrans = acDoc.Database.TransactionManager.StartTransaction())
                            {
                                BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acDoc.Database.BlockTableId, OpenMode.ForRead);
                                if (acBlkTbl.Has(acBlkTblRecReplaced.Name))
                                {
                                    BlockTableRecord acBlkTblRecReplacedClone = (BlockTableRecord)acTrans.GetObject(acBlkTbl[acBlkTblRecReplaced.Name], OpenMode.ForRead);
                                    string[]         acAttDefNamCol           = acSC.GetAttributeDefinitionNameCollection(acDoc, acTrans, acBlkTblRecReplacedClone);
                                    acAttRefIDCol = new int[acAttDefNamCol.Length];
                                    for (int j = 0; j < acAttDefNamCol.Length; j++)
                                    {
                                        int count = 0;
                                        for (int l = j; l < acAttDefNamCol.Length; l++)
                                        {
                                            if (acAttDefNamCol[j].Equals(acAttDefNamCol[l]))
                                            {
                                                count++;
                                            }
                                        }
                                        //Application.ShowAlertDialog(acAttDefNamCol[j]+"\ncount \n"+count.ToString());
                                        int  count1      = 0;
                                        bool IsCheckedOk = false;
                                        for (int k = 0; k < acFrm.gpbAttDefNamCol.Controls.Count; k++)
                                        {
                                            if (acAttDefNamCol[j].Equals(((System.Windows.Forms.ComboBox)(acFrm.gpbAttDefNamCol.Controls[k])).SelectedItem.ToString()))
                                            {
                                                IsCheckedOk = true;
                                                if (count < 2)
                                                {
                                                    acAttRefIDCol[j] = k;
                                                }
                                                //Application.ShowAlertDialog(k.ToString());
                                                else
                                                {
                                                    count1 = 0;
                                                    for (int l = k; l < acFrm.gpbAttDefNamCol.Controls.Count; l++)
                                                    {
                                                        string txt1 = ((System.Windows.Forms.ComboBox)acFrm.gpbAttDefNamCol.Controls[k]).SelectedItem.ToString();
                                                        string txt2 = ((System.Windows.Forms.ComboBox)acFrm.gpbAttDefNamCol.Controls[l]).SelectedItem.ToString();
                                                        if (txt1.Equals(txt2))
                                                        {
                                                            count1++;
                                                        }
                                                    }
                                                    if (count == count1)
                                                    {
                                                        acAttRefIDCol[j] = k;
                                                    }
                                                }
                                            }
                                        }
                                        if (!IsCheckedOk)
                                        {
                                            acAttRefIDCol[j] = acAttDefNamCol.Length * 2;
                                        }
                                        //Application.ShowAlertDialog(acAttDefNamCol[j]+"\ncount1 \n"+count1.ToString());
                                    }
                                }
                            }
                        }
                        //Application.ShowAlertDialog("Finish");
                        break;
                    }
                }
                foreach (Document acDoc in acDocMgr)
                {
                    //Application.ShowAlertDialog("");
                    bool check = false;
                    foreach (string item in acFrm.DocumentNameCollection)
                    {
                        if (item.Equals(acSC.DocumentShortName(acDoc.Database.OriginalFileName)))
                        {
                            check = true;
                        }
                        //Application.ShowAlertDialog(item + "/ncompare to /n" + DocumentShortName(acDoc1.Database.OriginalFileName));
                    }
                    //Application.ShowAlertDialog(check.ToString());
                    if (check)
                    {
                        if (acDocMgr.MdiActiveDocument != acDoc)
                        {
                            acDocMgr.MdiActiveDocument = acDoc;
                        }
                        Database acCurDb = acDoc.Database;
                        //HostApplicationServices.WorkingDatabase = acCurDb;
                        Editor acDocEd = acDoc.Editor;
                        using (DocumentLock acDocLck = acDocMgr.MdiActiveDocument.LockDocument())
                        {
                            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                            {
                                BlockTable         acBlkTbl          = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                                DBObjectCollection acBlkTblRecSPcCol = acSC.GetBlockTableRecordSpaceCollection(acDoc, acTrans);
                                //Application.ShowAlertDialog("Ready to Get into");
                                foreach (DBObject acDbObj in acBlkTblRecSPcCol)
                                {
                                    BlockTableRecord acBlkTblRecSPc = (BlockTableRecord)acDbObj;
                                    //Application.ShowAlertDialog("Already Get into");
                                    DBObjectCollection acDbObjCol = acSC.GetObjectsInBLockTableRecordSpace(acTrans, acBlkTblRecSPc);
                                    foreach (DBObject acDbObj2 in acDbObjCol)
                                    {
                                        //Application.ShowAlertDialog("Already Get into Object");
                                        try
                                        {
                                            //Application.ShowAlertDialog("Already AcTrnas");
                                            if (acDbObj2 is BlockReference)
                                            {
                                                BlockReference acBlkRefRemoved = (BlockReference)acDbObj2;
                                                if (acBlkRefRemoved.Name.Equals(acFrm.cbbBlkTblRec1.SelectedItem.ToString()))
                                                {
                                                    //Application.ShowAlertDialog("Ready To Change");
                                                    acSC.ReplaceBlockReferenceWithBlockTableRecord(acDocMgr, acDoc, acTrans, acBlkTblRecSPc, acBlkRefRemoved, acBlkTblRecReplaced, acAttRefIDCol);
                                                    //Application.ShowAlertDialog("Already Changed");
                                                    continue;
                                                }
                                            }
                                        }
                                        catch (Autodesk.AutoCAD.Runtime.Exception e)
                                        {
                                            Application.ShowAlertDialog("Message \n" + e.Message);
                                            Application.ShowAlertDialog("StackTrace \n" + e.StackTrace.ToString());
                                            Application.ShowAlertDialog("HelpLink \n" + e.HelpLink.ToString());
                                            Application.ShowAlertDialog("Source \n" + e.Source.ToString());
                                        }
                                    }
                                }
                                acTrans.Commit();
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 37
0
        ABC(string nameCmd)
        {
            Arc arc0 = null;

            Point3d pnt3dBeg = Pub.pnt3dO, pnt3dEnd = Pub.pnt3dO, pnt3dX = Pub.pnt3dO;

            ObjectId idCgPntEnd = ObjectId.Null;
            ObjectId idPoly     = ObjectId.Null;

            List <Point3d> pnts3d = null, pnts3dEntX = null;

            bool              escape    = true;
            Object            xRefPathX = null;
            PromptStatus      ps;
            FullSubentityPath path;
            Point3d           pnt3dPick;
            bool              isClosed = false;

            double grd = 0.0;
            Entity ent = xRef.getNestedEntity("\nSelect ARC: ", out escape, out xRefPathX, out ps, out pnts3dEntX, out path, out pnt3dPick, out isClosed);

            if (ent.GetType().ToString() != "Autodesk.AutoCAD.DatabaseServices.Arc")
            {
                Application.ShowAlertDialog(string.Format("Selected object was type of: {0} - Exiting...", ent.GetType().ToString()));
                return;
            }
            else
            {
                arc0 = (Arc)ent;
            }

            pnt3dX = UserInput.getPoint("\nPick point Back of Curb adjacent to arc segment", arc0.StartPoint, out escape, out ps, osMode: 8);

            double distX = arc0.Center.getDistance(pnt3dX);

            if (distX == arc0.Radius)
            {
                Application.ShowAlertDialog("Selected point is on arc.  Select point away from street side: ");
                pnt3dX = UserInput.getPoint("\nPick point Back of Curb adjacent to arc segment", pnt3dBeg, out escape, out ps, osMode: 8);
                distX  = arc0.Center.getDistance(pnt3dX);
                if (distX == arc0.Radius)
                {
                    return;
                }
            }

            int side = -1;
            int n    = (arc0.Normal.Z > 0) ? 1 : -1;

            switch (n)
            {
            case 1:                     //right hand direction
                if (distX > arc0.Radius)
                {
                    side = 1;
                }
                break;

            case -1:                    //left hand direction
                if (distX < arc0.Radius)
                {
                    side = 1;
                }
                break;
            }

            string elev = "", prompt = "\nSelect Cogo Point for begin elevation at beginning of curve (as indicated by guideline): ";

            ObjectId idCgPntBeg = getEndPoint(pnt3dBeg, out elev, prompt);

            if (elev == "")
            {
                return;
            }

            List <ObjectId> idsCgPnt = new List <ObjectId>();

            idsCgPnt.Add(idCgPntBeg);

            pnt3dBeg = idCgPntBeg.getCogoPntCoordinates();
            BaseObjs.write(string.Format("\nBegin Elevation = {0:F2}", elev));

            if (arc0.EndPoint.isEqual(pnt3dBeg, 0.1))
            {
                Curve curve = arc0;
                curve.ReverseCurve();                                     //*****************************************************************************
            }
            else if (arc0.StartPoint.isEqual(pnt3dBeg, 0.1))
            {
            }
            else
            {
                Application.ShowAlertDialog("Selected Begin point is not at either end of the arc.  Revise and retry...");
                return;
            }

            uint pntNum = 0;

            ObjectId idCgPntX = ObjectId.Null;

            List <double> userInput = null;

            userInput = cmdBC.getUserInput(nameCmd);
            if (userInput == null)
            {
                return;
            }

            double offH1 = 0.5 * 1.25 * side;
            double offV1 = userInput[0] + 0.0208;
            double offH2 = userInput[1] * side;
            double offV2 = userInput[2] * userInput[1];
            double offH3 = 0;
            double offV3 = 0;

            List <double> offHs = new List <double> {
                0.0, offH1, offH2
            };
            List <double> offVs = new List <double> {
                0.0, offV1, offV2
            };

            List <Arc> arcs = new List <Arc>();

            arcs.Add(arc0);

            DBObjectCollection dbObjs = arc0.GetOffsetCurves(offH1);
            Arc arc1 = (Arc)dbObjs[0];

            arcs.Add(arc1);
            dbObjs = arc1.GetOffsetCurves(offH2);
            Arc arc2 = (Arc)dbObjs[0];

            arcs.Add(arc2);
            Arc arc3 = null;

            if (nameCmd == "cmdABG")
            {
                offH3 = (userInput[3] * side * -1) - offH1 - offH2;  //offset from bench
                offV3 = userInput[4] - offV1 - offV2;                //offset from bench
                offHs.Add(offH3);
                offVs.Add(offV3);

                dbObjs = arc0.GetOffsetCurves(userInput[3] * side * -1);
                arc3   = (Arc)dbObjs[0];
                arcs.Add(arc3);
            }

            string cmdDefault = "R";

            prompt = string.Format("\nStraight grade(two or more points)/slope Intercept/Vertical curve/Plane method/Modified plane method/Reinhard plane method: S/I/V/P/M/R <{0}> [S/I/V/P/M/R]:", cmdDefault);
            escape = UserInput.getUserInputKeyword(cmdDefault, out cmdDefault, prompt, "S I V P M R");
            if (escape)
            {
                return;
            }

            Vector3d v3dBeg = new Vector3d(0, 0, 0);
            Vector3d v3dEnd = new Vector3d(0, 0, 0);

            List <arcInfo> arcInfos = new List <arcInfo>();

            arcInfo aInfo = getArcInfo(pnt3dBeg, arc0, nameCmd, offHs, offVs, idCgPntBeg);

            arcInfos.Add(aInfo);


            Point3d pnt3d = pnt3dBeg;

            switch (cmdDefault)
            {
                #region "S"

            case "S":                                                                   // Assuming points are set at both ends, with optional points set at intermediate locations on arc
                bool Done = false;
                do
                {
                    prompt     = "\nSelect Cogo Point on Arc (Arc endpoint or intermediate point) ENTER when done: ";
                    idCgPntEnd = getEndPoint(pnt3d, out elev, prompt);
                    if (elev == "")
                    {
                        Done = true;
                    }
                    else
                    {
                        pnt3d = idCgPntEnd.getCogoPntCoordinates();
                        idsCgPnt.Add(idCgPntEnd);

                        aInfo = getArcInfo(pnt3d, arc0, nameCmd, offHs, offVs, idCgPntEnd);
                        arcInfos.Add(aInfo);
                    }
                }while (!Done);

                var sortByLen = from a in arcInfos
                                orderby a.distFromBeg ascending
                                select a;
                int i = -1;
                foreach (var b in sortByLen)
                {
                    arcInfos[++i] = b;
                }

                processArcInfo(ref arcInfos);

                switch (idsCgPnt.Count)
                {
                case 1:
                    return;

                default:
                    processArcs(arcs, arcInfos, arc0, idsCgPnt, nameCmd, offHs, offVs);
                    break;
                }

                break;

                #endregion "S"

                #region "I"

            case "I":

                double m1 = Pub.slp1;
                double m2 = Pub.slp2;

                prompt     = "\nSelect Cogo Point for end elevation: ";
                idCgPntEnd = getEndPoint(pnt3dBeg, out elev, prompt);
                if (elev == "")
                {
                    return;
                }
                pnt3dEnd = idCgPntEnd.getCogoPntCoordinates();
                idsCgPnt.Add(idCgPntEnd);

                grd = (pnt3dEnd.Z - pnt3dBeg.Z) / arc0.Length;
                BaseObjs.write(string.Format("\nSlope along curve is: {0:P2}", grd));

                m1 = Pub.slp1;
                m2 = Pub.slp2;

                UserInput.getUserInput("\nEnter slope from FIRST POINT: ", out m1, m1);
                if (m1 == -99.99)
                {
                    return;
                }
                UserInput.getUserInput("\nEnter slope from SECOND POINT: ", out m2, m2);
                if (m2 == -99.99)
                {
                    return;
                }

                Pub.slp1 = m1;
                Pub.slp2 = m2;

                double elev1 = pnt3dBeg.Z;
                double elev2 = pnt3dEnd.Z;
                distX = cmdSSP.getSlopeInterceptArc(arc0.Length, elev1, elev2, m1, -m2);
                if (distX == 0)
                {
                    return;
                }

                Point3d pnt3dInt = arc0.GetPointAtDist(distX);
                pnt3dInt = new Point3d(pnt3dInt.X, pnt3dInt.Y, elev1 + distX * m1);
                ObjectId idCgPntInt = pnt3dInt.setPoint(out pntNum);
                idsCgPnt.Add(idCgPntInt);

                Application.ShowAlertDialog(string.Format("The elevation of the slope\nintercept is {0:F2}", pnt3dInt.Z));


                aInfo = getArcInfo(pnt3dInt, arc0, nameCmd, offHs, offVs, idCgPntInt);
                arcInfos.Add(aInfo);


                aInfo = getArcInfo(pnt3dEnd, arc0, nameCmd, offHs, offVs, idCgPntEnd);
                arcInfos.Add(aInfo);


                processArcInfo(ref arcInfos);

                processArcs(arcs, arcInfos, arc0, idsCgPnt, nameCmd, offHs, offVs);

                break;

                #endregion "I"

                #region "V"

            case "V":
                prompt     = "\nSelect Cogo Point for end elevation: ";
                idCgPntEnd = getEndPoint(pnt3dBeg, out elev, prompt);
                if (elev == "")
                {
                    return;
                }
                pnt3dEnd = idCgPntEnd.getCogoPntCoordinates();
                idsCgPnt.Add(idCgPntEnd);

                grd = (pnt3dEnd.Z - pnt3dBeg.Z) / arc0.Length;
                BaseObjs.write(string.Format("\nSlope along curve is: {0:P2}", grd));

                m1 = Pub.slp1;
                m2 = Pub.slp2;

                UserInput.getUserInput("\nEnter slope from FIRST POINT: ", out m1, m1);
                if (m1 == -99.99)
                {
                    return;
                }
                UserInput.getUserInput("\nEnter slope from SECOND POINT: ", out m2, m2);
                if (m2 == -99.99)
                {
                    return;
                }
                string lenVC = "20";
                escape = UserInput.getUserInputDoubleAsString("\nEnter length of vertical curve: ", out lenVC, lenVC);
                if (escape)
                {
                    return;
                }

                Pub.slp1 = m1;
                Pub.slp2 = m2;

                elev1 = pnt3dBeg.Z;
                elev2 = pnt3dEnd.Z;
                distX = cmdSSP.getSlopeInterceptArc(arc0.Length, elev1, elev2, m1, -m2);
                if (distX == 0)
                {
                    return;
                }

                pnt3dInt = arc0.GetPointAtDist(distX);
                pnt3dInt = new Point3d(pnt3dInt.X, pnt3dInt.Y, elev1 + distX * m1);

                Application.ShowAlertDialog(string.Format("The elevation of the slope\nintercept is {0:F2}", pnt3dInt.Z));

                double lVC = double.Parse(lenVC);
                if ((distX - lVC / 2) < 0 || (distX + lVC / 2) > arc0.Length)
                {
                    double lenMax = distX * 2;
                    if ((arc0.Length - distX) < lenMax / 2)
                    {
                        lenMax = (arc0.Length - distX) * 2;
                        Application.ShowAlertDialog(string.Format("Maximum length of Vertical Curve length with current inputs is {0:F2}", lenMax));
                    }
                }

                pnts3d = arc0.traverse(m1, -m2, distX, lVC, pnt3dBeg);

                BrkLine.makeBreakline(apps.lnkBrks, nameCmd, out idPoly, idsCgPnt, pnts3dL: pnts3d);
                break;

                #endregion "V"

                #region "M"

            case "M":
                prompt = "\nSelect Begin Curve backsight Cogo Point for grade and direction: ";
                Point3d pnt3dBegBS = UserInput.getPoint(prompt, pnt3dBeg, out escape, out ps, osMode: 8);
                if (pnt3dBegBS == Pub.pnt3dO)
                {
                    return;
                }

                prompt     = "\nSelect Cogo Point for end elevation: ";
                idCgPntEnd = getEndPoint(pnt3dBeg, out elev, prompt);
                if (elev == "")
                {
                    return;
                }
                pnt3dEnd = idCgPntEnd.getCogoPntCoordinates();

                grd = (pnt3dEnd.Z - pnt3dBeg.Z) / arc0.Length;
                BaseObjs.write(string.Format("\nSlope along curve is: {0:P2}", grd));

                prompt = "\nSelect End Curve backsight Cogo Point for grade and direction: ";
                Point3d pnt3dEndBS = UserInput.getPoint(prompt, pnt3dEnd, out escape, out ps, osMode: 8);
                if (pnt3dEndBS == Pub.pnt3dO)
                {
                    return;
                }

                Point3d pnt3dPI = Geom.getPntInt(pnt3dBegBS, pnt3dBeg, pnt3dEndBS, pnt3dEnd, true, extend.both);

                double g1 = pnt3dBegBS.getSlope(pnt3dBeg);
                double g2 = pnt3dEnd.getSlope(pnt3dEndBS);

                double el1 = pnt3dBeg.Z + g1 * pnt3dBeg.getDistance(pnt3dPI);
                double el2 = pnt3dEnd.Z - g2 * pnt3dEnd.getDistance(pnt3dPI);

                double ratio = 0;

                double aDiff = g1 - g2;
                double el    = 0;

                if (g1 < 0 && g2 < 0)
                {
                    ratio = g1 / (g1 + g2);
                    if (g1 <= g2)
                    {     //g1 controls
                        if (el1 < el2)
                        {
                            el = el1 + (el2 - el1) * ratio;
                        }
                        else if (el1 > el2)
                        {
                            el = el1 - (el1 - el2) * ratio;
                        }
                    }
                    else if (g2 < g1)
                    {     //g2 controls
                        if (el2 < el1)
                        {
                            el = el2 + (el1 - el2) * (1 - ratio);
                        }
                        else if (el2 > el1)
                        {
                            el = el2 - (el2 - el1) * (1 - ratio);
                        }
                    }
                }
                else if (g1 > 0 && g2 > 0)
                {
                    ratio = g1 / (g1 + g2);
                    if (g1 >= g2)
                    {     //g1 controls
                        if (el1 < el2)
                        {
                            el = el1 + (el2 - el1) * ratio;
                        }
                        else if (el1 > el2)
                        {
                            el = el1 - (el1 - el2) * ratio;
                        }
                    }
                    else if (g2 > g1)
                    {     //g2 controls
                        if (el2 < el1)
                        {
                            el = el2 + (el1 - el2) * (1 - ratio);
                        }
                        else if (el2 > el1)
                        {
                            el = el2 - (el2 - el1) * (1 - ratio);
                        }
                    }
                }
                else
                {
                    ratio = g1 / aDiff;
                    if (ratio >= (1 - ratio))
                    {     //g1 controls
                        if (el1 < el2)
                        {
                            el = el1 + (el2 - el1) * ratio;
                        }
                        else if (el1 > el2)
                        {
                            el = el1 - (el1 - el2) * ratio;
                        }
                    }
                    else if ((1 - ratio) > ratio)
                    {     //g2 controls
                        if (el2 < el1)
                        {
                            el = el2 + (el1 - el2) * (1 - ratio);
                        }
                        else if (el2 > el1)
                        {
                            el = el2 - (el2 - el1) * (1 - ratio);
                        }
                    }
                }

                pnt3dPI = new Point3d(pnt3dPI.X, pnt3dPI.Y, el);
                pnt3dPI.setPoint(out pntNum);
                BaseObjs.updateGraphics();

                double g1Mod = pnt3dBeg.getSlope(pnt3dPI);
                double g2Mod = pnt3dPI.getSlope(pnt3dEnd);

                g1 = (g1 + g1Mod) / 2;
                g2 = (g2 + g2Mod) / 2;

                Point3d pnt3dChordMid = pnt3dBeg.getMidPoint3d(pnt3dEnd);

                Vector3d v3dM = pnt3dPI - pnt3dChordMid;

                pnts3d = arc0.planeMethodModified(pnt3dBeg, pnt3dEnd, pnt3dPI, v3dM, g1, g2, ref idsCgPnt);
                idsCgPnt.Add(idCgPntEnd);

                arcInfos = new List <arcInfo>();
                for (int s = 0; s < pnts3d.Count; s++)
                {
                    pnt3dX = pnts3d[s];
                    aInfo  = getArcInfo(pnt3dX, arc0, nameCmd, offHs, offVs, idsCgPnt[s]);
                    arcInfos.Add(aInfo);
                }

                processArcInfo(ref arcInfos);
                processArcs(arcs, arcInfos, arc0, idsCgPnt, nameCmd, offHs, offVs);

                break;

                #endregion "M"

                #region "R"

            case "R":
                prompt     = "\nSelect Begin Curve backsight Cogo Point for grade and direction: ";
                pnt3dBegBS = UserInput.getPoint(prompt, pnt3dBeg, out escape, out ps, osMode: 8);
                if (pnt3dBegBS == Pub.pnt3dO)
                {
                    return;
                }

                prompt     = "\nSelect Cogo Point for end elevation: ";
                idCgPntEnd = getEndPoint(pnt3dBeg, out elev, prompt);
                if (elev == "")
                {
                    return;
                }
                pnt3dEnd = idCgPntEnd.getCogoPntCoordinates();

                grd = (pnt3dEnd.Z - pnt3dBeg.Z) / arc0.Length;
                BaseObjs.write(string.Format("\nSlope along curve is: {0:P2}", grd));

                prompt     = "\nSelect End Curve backsight Cogo Point for grade and direction: ";
                pnt3dEndBS = UserInput.getPoint(prompt, pnt3dEnd, out escape, out ps, osMode: 8);
                if (pnt3dEndBS == Pub.pnt3dO)
                {
                    return;
                }

                pnt3dPI = Geom.getPntInt(pnt3dBegBS, pnt3dBeg, pnt3dEndBS, pnt3dEnd, true, extend.both);

                g1 = pnt3dBegBS.getSlope(pnt3dBeg);
                g2 = pnt3dEnd.getSlope(pnt3dEndBS);
                string resOut = "";

                prompt = string.Format("\nUse g1={0:P2} or g2={1:P2}?: [1/2]", g1, g2);
                escape = UserInput.getUserInputKeyword("1", out resOut, prompt, "1 2");
                if (escape)
                {
                    return;
                }

                el = 0;
                switch (resOut)
                {
                case "1":
                    el = pnt3dBeg.Z + g1 * pnt3dBeg.getDistance(pnt3dPI);
                    break;

                case "2":
                    el = pnt3dEnd.Z - g2 * pnt3dEnd.getDistance(pnt3dPI);
                    break;
                }

                pnt3dPI = new Point3d(pnt3dPI.X, pnt3dPI.Y, el);
                pnt3dPI.setPoint(out pntNum);
                BaseObjs.updateGraphics();

                pnts3d = arc0.planeMethodReinhard(pnt3dBeg, pnt3dEnd, pnt3dPI, ref idsCgPnt);
                idsCgPnt.Add(idCgPntEnd);

                arcInfos = new List <arcInfo>();
                for (int s = 0; s < pnts3d.Count; s++)
                {
                    pnt3dX = pnts3d[s];
                    aInfo  = getArcInfo(pnt3dX, arc0, nameCmd, offHs, offVs, idsCgPnt[s]);
                    arcInfos.Add(aInfo);
                }

                processArcInfo(ref arcInfos);
                processArcs(arcs, arcInfos, arc0, idsCgPnt, nameCmd, offHs, offVs);

                break;

                #endregion "R"

                #region "P"

            case "P":
                prompt     = "S\nelect Begin Curve backsight Cogo Point for grade and direction: ";
                pnt3dBegBS = UserInput.getPoint(prompt, pnt3dBeg, out escape, out ps, osMode: 8);
                if (pnt3dBegBS == Pub.pnt3dO)
                {
                    return;
                }

                prompt     = "\nSelect Cogo Point for end elevation: ";
                idCgPntEnd = getEndPoint(pnt3dBeg, out elev, prompt);
                if (elev == "")
                {
                    return;
                }
                pnt3dEnd = idCgPntEnd.getCogoPntCoordinates();

                grd = (pnt3dEnd.Z - pnt3dBeg.Z) / arc0.Length;
                BaseObjs.write(string.Format("\nSlope along curve is: {0:P2}", grd));

                prompt     = "\nSelect End Curve backsight Cogo Point for grade and direction: ";
                pnt3dEndBS = UserInput.getPoint(prompt, pnt3dEnd, out escape, out ps, osMode: 8);
                if (pnt3dEndBS == Pub.pnt3dO)
                {
                    return;
                }

                pnt3dPI = Geom.getPntInt(pnt3dBegBS, pnt3dBeg, pnt3dEndBS, pnt3dEnd, true, extend.both);

                g1 = pnt3dBegBS.getSlope(pnt3dBeg);
                g2 = pnt3dEndBS.getSlope(pnt3dEnd);

                el1 = pnt3dBeg.Z + g1 * pnt3dBeg.getDistance(pnt3dPI);
                el2 = pnt3dEnd.Z + g2 * pnt3dEnd.getDistance(pnt3dPI);

                el = (el1 + el2) / 2;

                pnt3dPI = new Point3d(pnt3dPI.X, pnt3dPI.Y, el);

                pnt3dChordMid = pnt3dBeg.getMidPoint3d(pnt3dEnd);

                v3dM = pnt3dPI - pnt3dChordMid;

                pnts3d = arc0.planeMethod(pnt3dBeg, pnt3dEnd, pnt3dPI, v3dM, ref idsCgPnt, nameCmd);
                idsCgPnt.Add(idCgPntEnd);

                arcInfos = new List <arcInfo>();
                for (int s = 0; s < pnts3d.Count; s++)
                {
                    pnt3dX = pnts3d[s];
                    aInfo  = getArcInfo(pnt3dX, arc0, nameCmd, offHs, offVs, idsCgPnt[s]);
                    arcInfos.Add(aInfo);
                }

                processArcInfo(ref arcInfos);
                processArcs(arcs, arcInfos, arc0, idsCgPnt, nameCmd, offHs, offVs);

                break;

                #endregion "P"
            }
        }
Ejemplo n.º 38
0
 //
 // Fonction de tracé des lignes entre les points pour afficher les blocks
 //
 private DBObjectCollection RacksOfLines(int height, int deep)
 {
     // A function to generate a set of entities for our block
     var ents = new DBObjectCollection();
     Point3d[] pts = {
                             new Point3d(0, 0, 0),
                             new Point3d(0, height, 0),
                             new Point3d(deep, height, 0),
                             new Point3d(deep, 0, 0)
                     };
     // first square
     const byte red = 255;
     const byte green = 255;
     const byte blue = 255;
     for (int i = 0; i <= 3; i++)
     {
         int j = (i == 3 ? 0 : i + 1);
         var ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     return ents;
 }
Ejemplo n.º 39
0
        private void Create3dProfile(object arg)
        {
            try
            {
                if (doc != null)
                {
                    List <ObjectId> toHighlight = new List <ObjectId>();

                    using (doc.LockDocument())
                    {
                        Editor   ed = doc.Editor;
                        Database db = doc.Database;

                        using (Transaction tr = db.TransactionManager.StartTransaction())
                        {
                            //найти координату X начала профиля (крайнюю левую)
                            double          minx        = double.PositiveInfinity;
                            List <ObjectId> allSelected = new List <ObjectId>(soilHatchIds);
                            foreach (ObjectId id in allSelected)
                            {
                                Entity ent = null;
                                try
                                {
                                    ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                                }
                                catch (Autodesk.AutoCAD.Runtime.Exception) { continue; }
                                Extents3d?ext = ent.Bounds;
                                if (ext != null)
                                {
                                    Point3d minPt = ext.Value.MinPoint;
                                    if (minx > minPt.X)
                                    {
                                        minx = minPt.X;
                                    }
                                }
                            }


                            //Штриховки должны быть заранее раскиданы по слоям в соответствии с ИГЭ!

                            //пересчет всех точек штриховок в координаты:
                            //X - положение отностиельно начала профиля с учетом горизонтального масштаба профиля,
                            //Y - отметка расчитанная согласно базовой отметке с учетом вертикального масштаба профиля
                            Matrix2d transform =
                                new Matrix2d(new double[]
                            {
                                HorScaling, 0, 0,
                                0, VertScaling, 0,
                                0, 0, 1
                            })
                                * Matrix2d.Displacement(new Vector2d(-minx, -ElevBasePoint.Value.Y + ElevationInput / VertScaling));

                            C5.IntervalHeap <HatchEvent> eventQueue            = new C5.IntervalHeap <HatchEvent>();
                            List <HatchData>             allHatchData          = new List <HatchData>();
                            List <Point2dCollection>     selfintersectingLoops = new List <Point2dCollection>();
                            foreach (ObjectId id in soilHatchIds)
                            {
                                //получить все точки штриховок с учетом возможных дуг, сплайнов и проч
                                //Для каждой штриховки создается набор композитных кривых, состоящих из линейных сегментов
                                Hatch hatch = null;
                                try
                                {
                                    hatch = (Hatch)tr.GetObject(id, OpenMode.ForRead);
                                }
                                catch (Autodesk.AutoCAD.Runtime.Exception) { continue; }
                                List <CompositeCurve2d>  boundaries   = new List <CompositeCurve2d>();
                                List <Extents2d>         extends      = new List <Extents2d>();
                                List <Point2dCollection> ptsCollList  = new List <Point2dCollection>();
                                List <List <double> >    ptParamsList = new List <List <double> >();
                                for (int i = 0; i < hatch.NumberOfLoops; i++)
                                {
                                    HatchLoop hl = hatch.GetLoopAt(i);
                                    if (!hl.LoopType.HasFlag(HatchLoopTypes.SelfIntersecting) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.Textbox) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.TextIsland) &&
                                        !hl.LoopType.HasFlag(HatchLoopTypes.NotClosed))
                                    {
                                        List <Curve2d>   curves = Utils.GetHatchLoopCurves(hl);
                                        List <Curve2d>   compositeCurveElems = new List <Curve2d>();
                                        double           _minx         = double.PositiveInfinity;
                                        double           _miny         = double.PositiveInfinity;
                                        double           _maxx         = double.NegativeInfinity;
                                        double           _maxy         = double.NegativeInfinity;
                                        Action <Point2d> updateExtends = new Action <Point2d>(p =>
                                        {
                                            _minx = p.X < _minx ? p.X : _minx;
                                            _miny = p.Y < _miny ? p.Y : _miny;
                                            _maxx = p.X > _maxx ? p.X : _maxx;
                                            _maxy = p.Y > _maxy ? p.Y : _maxy;
                                        });

                                        Point2dCollection ptsColl   = new Point2dCollection();
                                        List <double>     ptParams  = new List <double>();
                                        double            currParam = 0;
                                        foreach (Curve2d c in curves)
                                        {
                                            if (!(c is LineSegment2d))
                                            {
                                                Interval         interval  = c.GetInterval();
                                                PointOnCurve2d[] samplePts = c.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.02);

                                                Point2d[] pts = samplePts.Select(p => transform * p.Point).ToArray();
                                                for (int n = 0; n < pts.Length - 1; n++)
                                                {
                                                    LineSegment2d lineSeg = new LineSegment2d(pts[n], pts[n + 1]);
                                                    compositeCurveElems.Add(lineSeg);

                                                    ptsColl.Add(pts[n]);
                                                    ptParams.Add(currParam);
                                                    updateExtends(pts[n]);
                                                    currParam += lineSeg.Length;
                                                }
                                            }
                                            else
                                            {
                                                LineSegment2d lineSeg = (LineSegment2d)c;
                                                lineSeg.TransformBy(transform);
                                                compositeCurveElems.Add(lineSeg);

                                                ptsColl.Add(lineSeg.StartPoint);
                                                ptParams.Add(currParam);
                                                updateExtends(lineSeg.StartPoint);
                                                currParam += lineSeg.Length;
                                            }
                                        }


                                        CompositeCurve2d boundary = new CompositeCurve2d(compositeCurveElems.ToArray());
                                        Extents2d        ext      = new Extents2d(_minx, _miny, _maxx, _maxy);
                                        boundaries.Add(boundary);
                                        ptsCollList.Add(ptsColl);
                                        ptParamsList.Add(ptParams);
                                        extends.Add(ext);
                                    }
                                }

                                //контуры штриховок не могут иметь самопересечений!
                                #region Проверка на пересечения
                                //проверка на самопересечения
                                //bool badBoundaries = false;
                                HashSet <int> badBoundaries   = new HashSet <int>();
                                HashSet <int> splitBoundaries = new HashSet <int>();//Если 2 контура в одной штриховке пересекаются, то разносить их по разным штриховкам
                                //List<HatchData> decomposeHatchData = new List<HatchData>();//TODO: самопересекающиеся полигоны нужно разбить на отдельные по количеству самопересечний.

                                for (int i = 0; i < boundaries.Count; i++)
                                {
                                    CompositeCurve2d        b           = boundaries[i];
                                    CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(b, b);
                                    if (intersector.NumberOfIntersectionPoints > 0)
                                    {
                                        //если происходит только наложение???
                                        badBoundaries.Add(i);
                                        selfintersectingLoops.Add(ptsCollList[i]);
                                    }
                                }

                                if (boundaries.Count > 1)
                                {
                                    //проверка на взаимные пересечения.
                                    //Исп RBush для того чтобы избежать проверки на пересечение каждого с каждым и квадратичной сложности
                                    //(работает только если контуры разнесены)
                                    //Не брать в расчет пересечения по касательной
                                    RBush <Spatial> boundariesRBush = new RBush <Spatial>();
                                    List <Spatial>  spatialData     = new List <Spatial>();
                                    for (int i = 0; i < extends.Count; i++)
                                    {
                                        spatialData.Add(new Spatial(extends[i], i));
                                    }
                                    boundariesRBush.BulkLoad(spatialData);
                                    foreach (Spatial s in spatialData)
                                    {
                                        IReadOnlyList <Spatial> nearestNeighbors = boundariesRBush.Search(s.Envelope);
                                        if (nearestNeighbors.Count > 1)
                                        {
                                            CompositeCurve2d thisCurve = boundaries[(int)s.Obj];
                                            foreach (Spatial n in nearestNeighbors)
                                            {
                                                if (!s.Equals(n))
                                                {
                                                    CompositeCurve2d        otherCurve = boundaries[(int)n.Obj];
                                                    CurveCurveIntersector2d intersector
                                                        = new CurveCurveIntersector2d(thisCurve, otherCurve);
                                                    if (intersector.NumberOfIntersectionPoints > 0 ||
                                                        intersector.OverlapCount > 0)
                                                    {
                                                        bool matches = false;
                                                        //Проверить, что кривые не накладываются друг на друга по всей длине (то есть полностью совпадают)
                                                        if (intersector.OverlapCount > 0)
                                                        {
                                                            //сумма длин всех интервалов перекрытия равна общей длине кривой
                                                            double thisCurveOverlapLength  = 0;
                                                            double otherCurveOverlapLength = 0;
                                                            for (int i = 0; i < intersector.OverlapCount; i++)
                                                            {
                                                                Interval[] intervals           = intersector.GetOverlapRanges(i);
                                                                Interval   thisOverlapInterval = intervals[0];
                                                                thisCurveOverlapLength += thisOverlapInterval.Length;
                                                                Interval otherOverlapInterval = intervals[1];
                                                                otherCurveOverlapLength += otherOverlapInterval.Length;
                                                            }

                                                            Interval thisCurveInterval  = thisCurve.GetInterval();
                                                            Interval otherCurveInterval = otherCurve.GetInterval();

                                                            if (Utils.LengthIsEquals(thisCurveOverlapLength, thisCurveInterval.Length) &&
                                                                Utils.LengthIsEquals(otherCurveOverlapLength, otherCurveInterval.Length))
                                                            {
                                                                matches = true;
                                                            }
                                                        }

                                                        if (!matches)
                                                        {
                                                            splitBoundaries.Add((int)s.Obj);
                                                            splitBoundaries.Add((int)n.Obj);
                                                        }
                                                        else
                                                        {
                                                            badBoundaries.Add((int)s.Obj);
                                                            badBoundaries.Add((int)n.Obj);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                splitBoundaries.ExceptWith(badBoundaries);
                                List <HatchData> splitHatchData = new List <HatchData>();
                                if (badBoundaries.Count > 0 || splitBoundaries.Count > 0)
                                {
                                    List <CompositeCurve2d>  boundariesClear   = new List <CompositeCurve2d>();
                                    List <Extents2d>         extendsClear      = new List <Extents2d>();
                                    List <Point2dCollection> ptsCollListClear  = new List <Point2dCollection>();
                                    List <List <double> >    ptParamsListClear = new List <List <double> >();

                                    for (int i = 0; i < boundaries.Count; i++)
                                    {
                                        if (!badBoundaries.Contains(i) && !splitBoundaries.Contains(i))
                                        {
                                            boundariesClear.Add(boundaries[i]);
                                            extendsClear.Add(extends[i]);
                                            ptsCollListClear.Add(ptsCollList[i]);
                                            ptParamsListClear.Add(ptParamsList[i]);
                                        }
                                    }

                                    foreach (int index in splitBoundaries)
                                    {
                                        splitHatchData.Add(new HatchData(
                                                               new HatchNestingNode(
                                                                   boundaries[index],
                                                                   extends[index],
                                                                   ptsCollList[index],
                                                                   ptParamsList[index], hatch)));
                                    }


                                    boundaries   = boundariesClear;
                                    extends      = extendsClear;
                                    ptsCollList  = ptsCollListClear;
                                    ptParamsList = ptParamsListClear;
                                }
                                #endregion

                                //определяется вложенность контуров штриховки
                                //ЕСЛИ ШТРИХОВКА СОСТОИТ ИЗ 2 И БОЛЕЕ КОНТУРОВ, КОТОРЫЕ НЕ ВЛОЖЕНЫ ДРУГ В ДРУГА,
                                //ТО ЭТИ КОНТУРЫ ДОЛЖНЫ РАССМАТРИВАТЬСЯ КАК ОТДЕЛЬНЫЕ ШТРИХОВКИ!!!
                                HatchNestingTree hatchNestingTree
                                    = new HatchNestingTree(boundaries, extends, ptsCollList, ptParamsList, hatch);
                                List <HatchData> currHatchData = hatchNestingTree.GetHatchData();
                                currHatchData.AddRange(splitHatchData);//добавить контуры, полученные из взаимно пересекающихся контуров
                                //currHatchData.AddRange(decomposeHatchData);

                                allHatchData.AddRange(currHatchData);

                                //Каждая штриховка имеет диапазон по X от начала до конца по оси.
                                //В общую очередь событий сохраняются события начала и конца штриховки
                                foreach (HatchData hd in currHatchData)
                                {
                                    hd.AddEventsToQueue(eventQueue);
                                }
                            }



                            //Трассу разбить на отрезки, на которых будут вставлены прямолинейные сегменты штриховок
                            Polyline alignmentPoly = null;
                            try
                            {
                                alignmentPoly = (Polyline)tr.GetObject(AlignmentPolyId, OpenMode.ForRead);
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception)
                            {
                                return;
                            }
                            int segments = alignmentPoly.NumberOfVertices - 1;
                            List <AlignmentSegment>   alignmentSegments   = new List <AlignmentSegment>();
                            Action <Point2d, Point2d> addAlignmentSegment = new Action <Point2d, Point2d>((p0, p1) =>
                            {
                                double start = alignmentPoly.GetDistAtPoint(new Point3d(p0.X, p0.Y, 0));
                                double end   = alignmentPoly.GetDistAtPoint(new Point3d(p1.X, p1.Y, 0));
                                if (Math.Abs(start - end) > Tolerance.Global.EqualPoint)//TODO: Это спорный момент - ведь может быть большое множество очень коротких участков подряд!
                                {
                                    Vector2d startDir = p1 - p0;
                                    alignmentSegments.Add(new AlignmentSegment(start, end, p0, startDir));
                                }
                            });
                            for (int i = 0; i < segments; i++)
                            {
                                SegmentType segmentType = alignmentPoly.GetSegmentType(i);
                                Point2d     startLoc    = alignmentPoly.GetPoint2dAt(i);
                                Point2d     endLoc      = alignmentPoly.GetPoint2dAt(i + 1);
                                switch (segmentType)
                                {
                                case SegmentType.Line:
                                    addAlignmentSegment(startLoc, endLoc);
                                    break;

                                case SegmentType.Arc:
                                    CircularArc2d    arc       = new CircularArc2d(startLoc, endLoc, alignmentPoly.GetBulgeAt(i), false);
                                    Interval         interval  = arc.GetInterval();
                                    PointOnCurve2d[] samplePts = arc.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.1);
                                    for (int n = 0; n < samplePts.Length - 1; n++)
                                    {
                                        addAlignmentSegment(samplePts[n].Point, samplePts[n + 1].Point);
                                    }
                                    break;
                                }
                            }


                            //проход по каждому отрезку трассы (диапазон отрезка - диапазон длины полилинии)
                            HashSet <HatchData> currentHatchData = new HashSet <HatchData>();
                            foreach (AlignmentSegment alignmentSegment in alignmentSegments)
                            {
                                if (eventQueue.Count == 0)
                                {
                                    break;                       //штриховки закончились
                                }
                                //Получить те штриховки, диапазон по X которых пересекается с диапазоном текущего отрезка
                                //(СКАНИРУЮЩАЯ ЛИНИЯ: события - начало, конец штриховки)
                                HashSet <HatchData> intervalHatchData = new HashSet <HatchData>(currentHatchData);//штриховки пришедшие из предыдущего участка остаются все

                                //Собрать все события до конца сегмента
                                //Если при проходе от начала до конца сегмента какая-то штриховка проходится полностью от начала до конца, то
                                //все ее контуры без изменений должны быть переданы для создания М-полигона!!! (для них обход графа не нужен!)
                                HashSet <HatchData> startedInsideInterval           = new HashSet <HatchData>();
                                List <HatchData>    hatchesCompletelyInsideInterval = new List <HatchData>();
                                while (eventQueue.Count > 0)
                                {
                                    HatchEvent nextEvent = eventQueue.FindMin();
                                    if (nextEvent.Position > alignmentSegment.End)
                                    {
                                        break;
                                    }
                                    else if (nextEvent.Start)
                                    {
                                        //добавить штриховку в текущий набор
                                        HatchData hd = eventQueue.DeleteMin().HatchData;
                                        currentHatchData.Add(hd);
                                        //добавлять в набор текущего интервла только в том случае,
                                        //если сканирующая линия еще не дошла до конца интервала
                                        if (nextEvent.Position < alignmentSegment.End &&
                                            !Utils.LengthIsEquals(nextEvent.Position, alignmentSegment.End))   //Допуск нужен
                                        {
                                            startedInsideInterval.Add(hd);
                                            intervalHatchData.Add(hd);
                                        }
                                    }
                                    else
                                    {
                                        //убрать штриховку из текущего набора
                                        HatchData hd = eventQueue.DeleteMin().HatchData;
                                        currentHatchData.Remove(hd);

                                        if (startedInsideInterval.Contains(hd))
                                        {
                                            hatchesCompletelyInsideInterval.Add(hd);
                                        }
                                    }
                                }

                                foreach (HatchData hd in hatchesCompletelyInsideInterval)
                                {
                                    HatchSegmentData hsd = new HatchSegmentData(hd);
                                    alignmentSegment.HatchSegmentData.Add(hsd);

                                    hsd.Polygons = hd.GetAllBoundaries();
                                }


                                intervalHatchData.ExceptWith(hatchesCompletelyInsideInterval);
                                foreach (HatchData hd in intervalHatchData)
                                {
                                    HatchSegmentData hsd = new HatchSegmentData(hd);
                                    alignmentSegment.HatchSegmentData.Add(hsd);
                                    //для каждой штриховки выполнить построение и обход графа сегмента штриховки
                                    HatchSegmentGraph graph = new HatchSegmentGraph(alignmentSegment.Start, alignmentSegment.End, hd, doc.Editor);

                                    //сохранить наборы полигонов для текущего диапазона
                                    hsd.Polygons = graph.Result;
                                }
                            }



                            //для каждого диапазона создать полученные полигоны в 3d
                            BlockTable       bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                            BlockTableRecord ms
                                = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                            BlockTableRecord btr = new BlockTableRecord();//Каждый профиль в отдельный блок
                            btr.Name = Guid.NewGuid().ToString();
                            ObjectId btrId = bt.Add(btr);
                            tr.AddNewlyCreatedDBObject(btr, true);

                            foreach (AlignmentSegment alignmentSegment in alignmentSegments)
                            {
                                List <Entity> flatObjs = new List <Entity>();

                                foreach (HatchSegmentData hsd in alignmentSegment.HatchSegmentData)
                                {
                                    //PlaneSurface
                                    hsd.GetNesting();
                                    Dictionary <Point2dCollection, List <Point2dCollection> > bwhs = hsd.GetBoundariesWithHoles();
                                    foreach (KeyValuePair <Point2dCollection, List <Point2dCollection> > bwh in bwhs)
                                    {
                                        //создать Region
                                        Region region = null;
                                        using (Polyline poly = new Polyline())
                                        {
                                            for (int i = 0; i < bwh.Key.Count; i++)
                                            {
                                                poly.AddVertexAt(i, bwh.Key[i], 0, 0, 0);
                                            }
                                            poly.Closed = true;
                                            DBObjectCollection coll = new DBObjectCollection();
                                            coll.Add(poly);
                                            try
                                            {
                                                DBObjectCollection regionColl = Region.CreateFromCurves(coll);
                                                foreach (DBObject dbo in regionColl)
                                                {
                                                    region = (Region)dbo;
                                                    break;
                                                }
                                            }
                                            catch { }
                                        }

                                        //из Region создать PlaneSurface
                                        if (region != null)
                                        {
                                            using (PlaneSurface planeSurface = new PlaneSurface())
                                            {
                                                planeSurface.CreateFromRegion(region);
                                                planeSurface.LayerId    = hsd.Hatch.LayerId;
                                                planeSurface.ColorIndex = 256;



                                                ObjectId planeSurfaceId = ms.AppendEntity(planeSurface);
                                                tr.AddNewlyCreatedDBObject(planeSurface, true);


                                                //вырезать отверстия в PlaneSurface

                                                foreach (Point2dCollection holePts2d in bwh.Value)
                                                {
                                                    if (holePts2d.Count < 3)
                                                    {
                                                        continue;
                                                    }

                                                    using (Polyline poly = new Polyline())
                                                    {
                                                        for (int i = 0; i < holePts2d.Count; i++)
                                                        {
                                                            poly.AddVertexAt(i, holePts2d[i], 0, 0, 0);
                                                        }
                                                        poly.Closed = true;

                                                        ObjectIdCollection trimPolyColl = new ObjectIdCollection();
                                                        trimPolyColl.Add(ms.AppendEntity(poly));
                                                        tr.AddNewlyCreatedDBObject(poly, true);

                                                        List <Point2d> ptsList  = new List <Point2d>(holePts2d.ToArray());
                                                        Point2d        pickPt2d = Utils.GetAnyPointInsidePoligon(ptsList,
                                                                                                                 Utils.DirectionIsClockwise(ptsList));

                                                        try
                                                        {
                                                            AcadDB.Surface.TrimSurface(planeSurfaceId, new ObjectIdCollection(), trimPolyColl,
                                                                                       new Vector3dCollection()
                                                            {
                                                                Vector3d.ZAxis
                                                            }, new Point3d(pickPt2d.X, pickPt2d.Y, 0),
                                                                                       -Vector3d.ZAxis, false, false);
                                                        }
                                                        catch /*(Exception ex)*/
                                                        {
                                                            //Вывод в командную строку
                                                            Utils.ErrorToCommandLine(doc.Editor,
                                                                                     "Ошибка при попытке вырезания отверстия в поверхности" /*, ex*/);
                                                        }

                                                        //Удалить все объекты, добавленные в чертеж!
                                                        poly.Erase();
                                                    }
                                                }


                                                flatObjs.Add((Entity)planeSurface.Clone());

                                                //Удалить все объекты, добавленные в чертеж!
                                                planeSurface.Erase();
                                            }
                                            region.Dispose();
                                        }
                                    }
                                }



                                foreach (Entity ent in flatObjs)
                                {
                                    ent.TransformBy(alignmentSegment.Transform);
                                    /*ms*/
                                    btr.AppendEntity(ent);
                                    tr.AddNewlyCreatedDBObject(ent, true);
                                    ent.Dispose();
                                }
                            }

                            BlockReference br = new BlockReference(Point3d.Origin, btrId);
                            ms.AppendEntity(br);
                            tr.AddNewlyCreatedDBObject(br, true);


                            if (selfintersectingLoops.Count > 0)
                            {
                                Utils.ErrorToCommandLine(doc.Editor,
                                                         "Отбраковано самопересекающихся контуров штриховок - " + selfintersectingLoops.Count + " (отмечены на профиле)");

                                ObjectId layerId = Utils.CreateLayerIfNotExists("САМОПЕРЕСЕКАЮЩИЙСЯ КОНТУР ШТРИХОВКИ", db, tr,
                                                                                color: Color.FromColorIndex(ColorMethod.ByAci, 1), lineWeight: LineWeight.LineWeight200);
                                Matrix2d returnTransform = transform.Inverse();
                                foreach (Point2dCollection pts in selfintersectingLoops)
                                {
                                    using (Polyline selfIntersectingPoly = new Polyline())
                                    {
                                        selfIntersectingPoly.LayerId    = layerId;
                                        selfIntersectingPoly.ColorIndex = 256;
                                        for (int i = 0; i < pts.Count; i++)
                                        {
                                            Point2d pt = pts[i].TransformBy(returnTransform);
                                            selfIntersectingPoly.AddVertexAt(i, pt, 0, 0, 0);
                                        }

                                        toHighlight.Add(ms.AppendEntity(selfIntersectingPoly));
                                        tr.AddNewlyCreatedDBObject(selfIntersectingPoly, true);

                                        //selfIntersectingPoly.Highlight();
                                    }
                                }
                            }


                            tr.Commit();
                        }
                    }
                    ps.Visible = false;

                    if (toHighlight.Count > 0)
                    {
                        using (Transaction tr = doc.Database.TransactionManager.StartTransaction())
                        {
                            foreach (ObjectId id in toHighlight)
                            {
                                Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                                ent.Highlight();
                            }
                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                GeologyConvertationCommand.ClosePalette(null, null);
                CommonException(ex, "Ошибка при создании 3d профиля геологии");
            }
        }
Ejemplo n.º 40
0
 private DBObjectCollection SquareOfLines(double height, double width, double deep, int type)
 {
     // A function to generate a set of entities for our block
     var ents = new DBObjectCollection();
     Point3d[] pts = {
                             new Point3d(0, 0, 0),
                             new Point3d(0, 0, width),
                             new Point3d(height, 0, width),
                             new Point3d(height, 0, 0),
                             new Point3d(0, deep, 0),
                             new Point3d(0, deep, width),
                             new Point3d(height, deep, width),
                             new Point3d(height, deep, 0)
                         };
     // first square
     byte red = 0, green, blue = 0;
     switch (type)
     {
         case 1:
             red = 255; green = 150; break;
         case 2:
             green = 255; break;
         case 3:
             green = 255; blue = 255; break;
         default:
             red = 255; green = 255; blue = 255;
             break;
     }
     Line ln;
     for (int i = 0; i <= 3; i++)
     {
         int j = (i == 3 ? 0 : i + 1);
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     // second square
     for (int i = 4; i <= 7; i++)
     {
         int j = (i == 7 ? 4 : i + 1);
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     // Complete cube
     for (int i = 0; i <= 3; i++)
     {
         int j = i + 4;
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     return ents;
 }
        public static void InsertDrawers()
        {
            Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = activeDoc.Database;

            //double drawerW = W;
            double drawerH = (H - doorH) / N;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                for (int cnt = 0; cnt < N; cnt++)
                {
                    // 2*t-(D/N) * (N-cnt) for placing the drawers in open position.
                    // 0.0 for shut drawers.

                    Point3d pos1 = new Point3d(0.0, 2 * t - (D / N) * (N - cnt), drawerH * cnt);
                    BlockReference bref1 = new BlockReference(pos1, bt["Drawer"]);
                    DBObjectCollection explodeSet1 = new DBObjectCollection();
                    bref1.Explode(explodeSet1);
                    foreach (DBObject dbObj in explodeSet1)
                    {
                        btr.AppendEntity(dbObj as Entity);
                        tr.AddNewlyCreatedDBObject(dbObj, true);
                    }

                    // Handle
                    if (splitDrawers)
                    {
                        BlockReference bref11 = new BlockReference(new Point3d(0.25 * W, 2 * t - (D / N) * (N - cnt), drawerH * cnt + drawerH * 0.5), bt["Handle"]);
                        btr.AppendEntity(bref11 as Entity);
                        tr.AddNewlyCreatedDBObject(bref11, true);
                    }
                    else
                    {
                        BlockReference bref11 = new BlockReference(new Point3d(0.5 * W, 2 * t - (D / N) * (N - cnt), drawerH * cnt + drawerH * 0.5), bt["Handle"]);
                        btr.AppendEntity(bref11 as Entity);
                        tr.AddNewlyCreatedDBObject(bref11, true);
                    }

                    if (splitDrawers)
                    {
                        // 2*t-(D/N) * (N-cnt) for placing the drawers in open position.
                        // 0.0 for shut drawers.

                        Point3d pos2 = new Point3d(W * 0.5, 2 * t - (D / N) * (N - cnt), drawerH * cnt);
                        BlockReference bref2 = new BlockReference(pos2, bt["Drawer"]);
                        DBObjectCollection explodeSet2 = new DBObjectCollection();
                        bref2.Explode(explodeSet2);
                        foreach (DBObject dbObj in explodeSet2)
                        {
                            btr.AppendEntity(dbObj as Entity);
                            tr.AddNewlyCreatedDBObject(dbObj, true);
                        }

                        // Handle
                        BlockReference bref22 = new BlockReference(new Point3d(W * 0.75, 2 * t - (D / N) * (N - cnt), drawerH * cnt + drawerH * 0.5), bt["Handle"]);
                        btr.AppendEntity(bref22 as Entity);
                        tr.AddNewlyCreatedDBObject(bref22, true);
                    }
                }
                tr.Commit();
            }
        }
Ejemplo n.º 42
0
        public void Generate()
        {
            Database acCurDb;

            acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
            ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");

            Transaction acTrans = acCurDb.TransactionManager.TopTransaction;

            //Centre line
            Curve c = acTrans.GetObject(ObjectId, OpenMode.ForRead) as Curve;

            //Offset it
            LayerTable acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
            ObjectId   current  = acCurDb.Clayer;

            acCurDb.Clayer = acLyrTbl[Utilities.FoundationLayer];

            // Open the Block table for read
            BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

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

            DBObjectCollection offsets  = c.GetOffsetCurves(FoundationWidth / 2);
            DBObjectCollection offsets2 = c.GetOffsetCurves(-(FoundationWidth / 2));

            foreach (Entity e in offsets)
            {
                acBlkTblRec.AppendEntity(e);
                acTrans.AddNewlyCreatedDBObject(e, true);
                e.LayerId            = acCurDb.Clayer;
                PositiveFoundationId = e.ObjectId;
            }
            foreach (Entity e in offsets2)
            {
                acBlkTblRec.AppendEntity(e);
                acTrans.AddNewlyCreatedDBObject(e, true);
                e.LayerId            = acCurDb.Clayer;
                NegativeFoundationId = e.ObjectId;
            }


            acCurDb.Clayer = current;

            //Tag it
            acCurDb.Clayer = acLyrTbl[Utilities.FoundationTextLayer];

            //Add foundation tag
            Matrix3d           curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem;
            CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

            //Get lable point
            Point3d labelPoint3d = c.GetPointAtDist(c.GetDistanceAtParameter(c.EndParam) / 2);
            Point3d labelPoint   = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0);

            BlockTableRecord blockDef = acBlkTbl["FormationTag"].GetObject(OpenMode.ForRead) as BlockTableRecord;

            // Insert the block into the current space
            using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["FormationTag"]))
            {
                //Calculate Line Angle
                double y     = c.EndPoint.Y - c.StartPoint.Y;
                double x     = c.EndPoint.X - c.StartPoint.X;
                double angle = Math.Atan(Math.Abs(y) / Math.Abs(x));
                if (angle >= Math.PI / 4)
                {
                    acBlkRef.TransformBy(Matrix3d.Rotation(0, curUCS.Zaxis, labelPoint));
                }
                else
                {
                    acBlkRef.TransformBy(Matrix3d.Rotation(Math.PI / 2, curUCS.Zaxis, labelPoint));
                }
                acBlkRef.AddContext(occ.GetContext("10:1"));

                acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                acBlkTblRec.AppendEntity(acBlkRef);
                acTrans.AddNewlyCreatedDBObject(acBlkRef, true);

                // AttributeDefinitions
                foreach (ObjectId id in blockDef)
                {
                    DBObject            obj    = id.GetObject(OpenMode.ForRead);
                    AttributeDefinition attDef = obj as AttributeDefinition;
                    if ((attDef != null) && (!attDef.Constant))
                    {
                        //This is a non-constant AttributeDefinition
                        //Create a new AttributeReference
                        using (AttributeReference attRef = new AttributeReference())
                        {
                            attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform);
                            attRef.TextString = Parent.FormationLevel.ToString("F3");
                            //Add the AttributeReference to the BlockReference
                            acBlkRef.AttributeCollection.AppendAttribute(attRef);
                            acTrans.AddNewlyCreatedDBObject(attRef, true);
                        }
                    }
                }

                FormationTagId = acBlkRef.ObjectId;
            }

            acCurDb.Clayer = current;
        }
Ejemplo n.º 43
0
        public static void AccessSpace()
        {

            AcadApp.Document acDoc = AcadApp.Application.DocumentManager.MdiActiveDocument;

            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord acBlkTblRec;

                // Request which table record to open询问打开哪条表记录(空间)

                PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");

                pKeyOpts.Message = "\nEnter whichspace to create the line in ";

                pKeyOpts.Keywords.Add("Model");

                pKeyOpts.Keywords.Add("Paper");

                pKeyOpts.Keywords.Add("Current");

                pKeyOpts.AllowNone = false;

                pKeyOpts.AppendKeywordsToMessage = true;

                PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

                if (pKeyRes.StringResult == "Model")                    //从Block表获取Model空间的ObjectID
                {

                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                }

                else if (pKeyRes.StringResult == "Paper")              //从Block表获取Paper空间的ObjectID
                {

                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord;
                }
                else
                {
                    //从数据库获取当前空间的ObjectID
                    acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                }


                ////设置图形中所有点对象的样式

                acCurDb.Pdmode = 34;

                acCurDb.Pdsize = 1;

                //******************************
                // Create an in memory circle在内存创建一个圆

                using (Circle acCirc = new Circle())
                {

                    acCirc.Center = new Point3d(2, 2, 0);

                    acCirc.Radius = 5;

                    // Adds the circle to an object array将圆添加到对象数组

                    DBObjectCollection acDBObjColl = new DBObjectCollection();

                    acDBObjColl.Add(acCirc);

                    // Calculate the regions based oneach closed loop

                    //基于每个闭环计算面域

                    DBObjectCollection myRegionColl = new DBObjectCollection();

                    myRegionColl = Region.CreateFromCurves(acDBObjColl);

                    Region acRegion = myRegionColl[0] as Region;

                    acBlkTblRec.AppendEntity(acRegion);

                    acTrans.AddNewlyCreatedDBObject(acRegion, true);

                    acCirc.ColorIndex = 1;
                    acBlkTblRec.AppendEntity(acCirc);

                    acTrans.AddNewlyCreatedDBObject(acCirc, true);

                    // Dispose of the in memory circlenot appended to the database

                    //处置内存中的圆,不添加到数据库;

                }

                acTrans.Commit();

            }

        }
Ejemplo n.º 44
0
        internal static Polyline ProjectPolyline(Curve pline, Plane plane, Vector3d direction)
        {
            if (!(pline is Polyline) && !(pline is Polyline2d) && !(pline is Polyline3d))
            {
                return(null);
            }
            plane = new Plane(Point3d.Origin.OrthoProject(plane), direction);
            using (var oldCol = new DBObjectCollection())
                using (var newCol = new DBObjectCollection())
                {
                    pline.Explode(oldCol);
                    foreach (DBObject obj in oldCol)
                    {
                        if (obj is Curve crv)
                        {
                            var flat = crv.GetProjectedCurve(plane, direction);
                            newCol.Add(flat);
                        }

                        obj.Dispose();
                    }

                    var psc = new PolylineSegmentCollection();
                    for (var i = 0; i < newCol.Count; i++)
                    {
                        if (newCol[i] is Ellipse)
                        {
                            psc.AddRange(new PolylineSegmentCollection((Ellipse)newCol[i]));
                            continue;
                        }

                        var crv   = (Curve)newCol[i];
                        var start = crv.StartPoint;
                        var end   = crv.EndPoint;
                        var bulge = 0.0;
                        if (crv is Arc arc)
                        {
                            var angle = arc.Center.GetVectorTo(start).GetAngleTo(arc.Center.GetVectorTo(end), arc.Normal);
                            bulge = Math.Tan(angle / 4.0);
                        }

                        psc.Add(new PolylineSegment(start.Convert2d(plane), end.Convert2d(plane), bulge));
                    }

                    foreach (DBObject o in newCol)
                    {
                        o.Dispose();
                    }
                    var projectedPline = psc.Join(new Tolerance(1e-9, 1e-9))[0].ToPolyline();
                    projectedPline.Normal    = direction;
                    projectedPline.Elevation =
                        plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z;
                    if (!pline.StartPoint.Project(plane, direction).IsEqualTo(projectedPline.StartPoint, new Tolerance(1e-9, 1e-9)))
                    {
                        projectedPline.Normal    = direction = direction.Negate();
                        projectedPline.Elevation =
                            plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z;
                    }

                    return(projectedPline);
                }
        }
Ejemplo n.º 45
0
        public static DBObject Create(this Grevit.Types.Slab s, Transaction tr)
        {
            try
            {
                BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead);
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                // Polyline acPoly = new Polyline();
                //acPoly.SetDatabaseDefaults();

                //int i = 0;

                DBObjectCollection objColl = new DBObjectCollection();
                Point3dCollection ptcol = new Point3dCollection();
                foreach (Grevit.Types.Loop loop in s.surface.profile)
                {
                    foreach (Grevit.Types.Component p in loop.outline)
                        ptcol = p.To3dPointCollection();


                    //Curve3dCollection collt = parse3dCurve(p);
                    //acPoly.AppendVertex(new PolylineVertex3d(new Point3d(p.x, p.y, p.z)));
                    //acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0);
                    //i++;

                    //foreach (Curve3d curve in collt)
                    //{ 
                    //    objColl.Add(Autodesk.AutoCAD.DatabaseServices.Curve.CreateFromGeCurve(curve));
                    //}
                }

                Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, ptcol, true);
                objColl.Add(face);
                //Polyline3d face = new Polyline3d();
                //ETC...
                // or from your settings
                // Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, vertices, true);





                DBObjectCollection myRegionColl = new DBObjectCollection();
                // create a single region
                Autodesk.AutoCAD.DatabaseServices.Region objreg = new Autodesk.AutoCAD.DatabaseServices.Region();
                DBObjectCollection objRegions = new DBObjectCollection();
                try
                {
                    objRegions = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(objColl);
                    objreg = objRegions[0] as Autodesk.AutoCAD.DatabaseServices.Region;

                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    // eInvalidInput exception
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Error: unable to create region collection:\n" + ex.Message);

                }






                //acPoly.Closed = true;
                //ms.AppendEntity(acPoly);
                //tr.AddNewlyCreatedDBObject(acPoly, true);

                //atrix3d mm = Matrix3d.Displacement(new Vector3d(0, 0, r.outline[0].z));
                //acPoly.TransformBy(mm);


                //Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, ed.CurrentUserCoordinateSystem);

                //Slab slab = new Slab();
                //slab.SetDatabaseDefaults(db);
                //slab.SetToStandard(db);         
                //slab.Location = new Point3d(0, 0, 0);

                //slab.SetBaseProfile(myProfile, Matrix3d.Identity);

                //DBObjectCollection col = acPoly.GetOffsetCurves(0);


                //DBObjectCollection res = Region.CreateFromCurves(coll);

                //Region reg = res[0] as Region;

                Solid3d solid = new Solid3d();
                solid.Extrude(objreg, s.height, s.slope);


                LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead);
                if (s.TypeOrLayer != "") { if (lt.Has(s.TypeOrLayer)) solid.LayerId = lt[s.TypeOrLayer]; }
                //if (ss.Has(r.family, tr)) slab.StyleId = ss.GetAt(r.family);


                ms.AppendEntity(solid);
                tr.AddNewlyCreatedDBObject(solid, true);
                return solid;
            }

            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
            }

            return null;
        }
Ejemplo n.º 46
0
        public void TraceBoundaryAndHatch()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor   ed = doc.Editor;

            // Select a seed point for our boundary

            PromptPointResult ppr =
                ed.GetPoint("\nSelect internal point: ");

            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }

            // Get the objects making up our boundary

            DBObjectCollection objs =
                ed.TraceBoundary(ppr.Value, false);

            if (objs.Count > 0)
            {
                Transaction tr =
                    doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    // We'll add the objects to the model space

                    BlockTable bt =
                        (BlockTable)tr.GetObject(
                            doc.Database.BlockTableId,
                            OpenMode.ForRead
                            );

                    BlockTableRecord btr =
                        (BlockTableRecord)tr.GetObject(
                            bt[BlockTableRecord.ModelSpace],
                            OpenMode.ForWrite
                            );

                    // Add our boundary objects to the drawing and
                    // collect their ObjectIds for later use

                    ObjectIdCollection ids = new ObjectIdCollection();
                    foreach (DBObject obj in objs)
                    {
                        Entity ent = obj as Entity;
                        if (ent != null)
                        {
                            // Set our boundary objects to be of
                            // our auto-incremented colour index

                            ent.ColorIndex = _index;

                            // Set our transparency to 50% (=127)
                            // Alpha value is Truncate(255 * (100-n)/100)

                            ent.Transparency = new Transparency(127);

                            // Add each boundary object to the modelspace
                            // and add its ID to a collection

                            ids.Add(btr.AppendEntity(ent));
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }
                    }

                    // Create our hatch

                    Hatch hat = new Hatch();

                    // Solid fill of our auto-incremented colour index

                    hat.SetHatchPattern(
                        HatchPatternType.PreDefined,
                        "SOLID"
                        );
                    hat.ColorIndex = _index++;

                    // Set our transparency to 50% (=127)
                    // Alpha value is Truncate(255 * (100-n)/100)

                    hat.Transparency = new Transparency(127);

                    // Add the hatch to the modelspace & transaction

                    ObjectId hatId = btr.AppendEntity(hat);
                    tr.AddNewlyCreatedDBObject(hat, true);

                    // Add the hatch loops and complete the hatch

                    hat.Associative = true;
                    hat.AppendLoop(
                        HatchLoopTypes.Default,
                        ids
                        );

                    hat.EvaluateHatch(true);

                    // Commit the transaction

                    tr.Commit();
                }
            }
        }
Ejemplo n.º 47
0
        public void GetLongestSegment()
        {
            Editor ed = dwg.Editor;
            PromptPointResult res = ed.GetPoint("Укажите корневую точку");
            if (res.Status!= PromptStatus.OK)
            {
                return;
            }
            using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction())
            {
                GroupsInformation groupsEntities = new GroupsInformation(tr, CurrentDatabase);
                string group = AskForGroup(false, groupsEntities.GroupList);
                if (group == null)
                {
                    return;
                }

                List<ObjectId> groupLines = groupsEntities.GetObjectsOfGroup(group);
                var plineSegments = groupLines
                    .Where(n => n.GetObject(OpenMode.ForRead) is Polyline)
                    .SelectMany(n => {
                                    DBObjectCollection coll = new DBObjectCollection();
                                    ((Polyline)n.GetObject(OpenMode.ForRead)).Explode(coll);
                                    return coll.Cast<DBObject>();
                                })
                    .Concat(
                        groupLines
                        .Where(n => n.GetObject(OpenMode.ForRead) is Line)
                        .Select(n => (DBObject)n.GetObject(OpenMode.ForRead)));
                Line[] lines = (from DBObject l in plineSegments
                    where l is Line
                    select l as Line).ToArray();
                DepthFirstSearch.GraphTree tree = new DepthFirstSearch.GraphTree(res.Value, lines);
                ed.WriteMessage("\nСамый длинный участок - {0}",tree.FarestNode.PathCostFromRoot);
            }
        }
Ejemplo n.º 48
0
        public void CreateBlock()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get the block table from the drawing
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                // Check the block name, to see whether it's
                // already in use
                PromptStringOptions pso = new PromptStringOptions("\nEnter new block name: ");
                pso.AllowSpaces = true;

                // A variable for the block's name
                string blkName = "";

                do
                {
                    PromptResult pr = ed.GetString(pso);

                    // Just return if the user cancelled
                    // (will abort the transaction as we drop out of the using
                    // statement's scope)
                    if (pr.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    try
                    {
                        // Validate the provided symbol table name
                        SymbolUtilityServices.ValidateSymbolName(pr.StringResult, false);

                        // Only set the block name if it isn't in use
                        if (bt.Has(pr.StringResult))
                        {
                            ed.WriteMessage("\nA block with this name already exists.");
                        }
                        else
                        {
                            blkName = pr.StringResult;
                        }
                    }
                    catch
                    {
                        // An exception has been thrown, indicating the
                        // name is invalid
                        ed.WriteMessage("\nInvalid block name.");
                    }
                } while (blkName == "");

                // Create our new block table record...
                BlockTableRecord btr = new BlockTableRecord();

                // ... and set its properties
                btr.Name = blkName;

                // Add the new block to the block table
                bt.UpgradeOpen();
                ObjectId btrId = bt.Add(btr);
                tr.AddNewlyCreatedDBObject(btr, true);

                // Add some lines to the block to form a square
                // (the entities belong directly to the block)
                DBObjectCollection ents = SquareOfLines(5);
                foreach (Entity ent in ents)
                {
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }

                // Add a block reference to the model space
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                BlockReference   br = new BlockReference(Point3d.Origin, btrId);
                ms.AppendEntity(br);
                tr.AddNewlyCreatedDBObject(br, true);

                // Commit the transaction
                tr.Commit();

                // Report what we've done
                ed.WriteMessage("\nCreated block named \"{0}\" containing {1} entities.", blkName, ents.Count);
            }
        }