예제 #1
0
        void getConnectionsWithSelection()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a wall ");
                entopts.SetRejectMessage("Must select a wall, please!");
                entopts.AddAllowedClass(typeof(Wall), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

                if (ent.Status == PromptStatus.OK)
                {
                    ObjectId entId = ent.ObjectId;

                    Wall     wall     = trans.GetObject(entId, OpenMode.ForRead, false) as Wall;
                    Manager  mgr      = new Manager(db);
                    Graph    theGraph = mgr.FindGraph(wall);
                    Matrix3d mat      = theGraph.WcsToEcsMatrix.Inverse();
                    for (int i = 0; i < theGraph.WallJointCount; i++)
                    {
                        Joint joint = theGraph.GetWallJoint(i);
                        ConnectionCollection connections = joint.Connections;
                        foreach (Connection connection in connections)
                        {
                            ed.WriteMessage("\nConnection in wall system for wall id: " + connection.Section.WallId.ToString());
                            ed.WriteMessage("\n  Direction from here: " + connection.DirectionFromHere.ToString());
                            foreach (double elevation in connection.ElevationVariations)
                            {
                                ed.WriteMessage("\n  Elevation Variations: " + elevation.ToString());
                            }
                            ed.WriteMessage("\n  Start Elevation: " + connection.StartElevation.ToString());
                            ed.WriteMessage("\n  End Elevation: " + connection.EndElevation.ToString());
                            ed.WriteMessage("\n  Section Starts Here: " + connection.SectionStartsHere.ToString());
                        }
                    }
                }

                trans.Commit();
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
    /// <summary>
    /// Let user select a wall and override one display properties of this wall.
    /// User can see the different display of this wall.
    /// </summary>
    public void DisplayPropertiesWallSample()
    {
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDisplay Properties Wall Sample:\n");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n");

        Database db = Application.DocumentManager.MdiActiveDocument.Database;

        //MaterialUtility.
        TransactionManager tm    = db.TransactionManager;
        Transaction        trans = tm.StartTransaction();
        Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;

        try
        {
            PromptEntityOptions optEnt = new PromptEntityOptions("Select an AEC Wall entity");
            optEnt.SetRejectMessage("Selected entity is NOT an AEC Wall entity, try again...");
            optEnt.AddAllowedClass(typeof(Autodesk.Aec.Arch.DatabaseServices.Wall), false);  // Geo is the base class of AEC entities.

            PromptEntityResult resEnt = ed.GetEntity(optEnt);
            if (resEnt.Status != PromptStatus.OK)
            {
                throw new System.Exception("Selection error - aborting");
            }

            Wall pickedWall = trans.GetObject(resEnt.ObjectId, OpenMode.ForWrite) as Wall;

            DisplayRepresentationManager displayManager = new DisplayRepresentationManager(db);
            ObjectIdCollection           ids            = displayManager.GetDisplayRepresentationIdsFromCurrentViewport(RXClass.GetClass(typeof(Wall)));

            ObjectId activeDisplayRepId = ids[0];

            DisplayPropertiesWallPlan wallProperties = new DisplayPropertiesWallPlan();

            wallProperties.SubSetDatabaseDefaults(db);
            wallProperties.SetToStandard(db);
            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();

            DisplayComponent[] components = wallProperties.GetDisplayComponents(out sc);
            int index = -1;
            for (int i = 0; i < sc.Count; i++)
            {
                string componentName = sc[i];
                //Here, we override the display properties for "shrink wrap" and display it on the screen.
                if (componentName == "Shrink Wrap")
                {
                    index = i;
                    break;
                }
            }
            if (index == -1)
            {
                throw new System.Exception("Lack of display component.");
            }

            DisplayComponentEntity component = components[index] as DisplayComponentEntity;
            component.IsApplicable  = true;
            component.IsVisible     = true;
            component.ByMaterial    = false;
            component.ColorIndex    = 30;
            component.LinetypeScale = 2;
            component.LineWeight    = LineWeight.LineWeight070;

            ObjectId dispWallId = Override.AddToOverrideExtensionDictionaryAndClose(pickedWall, wallProperties);
            OverrideDisplayProperties overrideProperties = new OverrideDisplayProperties();
            overrideProperties.ViewId            = activeDisplayRepId;
            overrideProperties.DisplayPropertyId = dispWallId;
            pickedWall.Overrides.Add(overrideProperties);

            trans.Commit();
        }
        catch (System.Exception e)
        {
            trans.Abort();
            ed.WriteMessage("\n" + e.Message + "\n");
        }
    }
예제 #3
0
        void wallSpaceDraw()
        {
            Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;
            Database           db    = Application.DocumentManager.MdiActiveDocument.Database;
            TransactionManager tm    = db.TransactionManager;
            Transaction        trans = tm.StartTransaction();

            try
            {
                PromptEntityOptions entopts = new PromptEntityOptions("Select a space ");
                entopts.SetRejectMessage("Must select a space, please!");
                entopts.AddAllowedClass(typeof(Space), true);
                PromptEntityResult ent = null;
                try
                {
                    ent = ed.GetEntity(entopts);
                }
                catch
                {
                    ed.WriteMessage("You did not select a valid entity");
                    return;
                }

                if (ent.Status == PromptStatus.OK)
                {
                    ObjectId entId = ent.ObjectId;

                    Space space = trans.GetObject(entId, OpenMode.ForRead, false) as Space;
                    if (space != null)
                    {
                        Manager mgr = new Manager(db);
                    }
                    else
                    {
                        ed.WriteMessage("\nSomething bad has happened...");
                    }
                }

                trans.Commit();
                Point3d centerPt = new Point3d(0.0, 0.0, 0.0);

                using (Transaction trans1 = tm.StartTransaction())
                {
                    BlockTable       bt    = (BlockTable)(trans1.GetObject(db.BlockTableId, OpenMode.ForWrite));
                    BlockTableRecord btr   = (BlockTableRecord)trans1.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    double           distX = 4800;
                    double           distY = 2400;

                    Point3d[] pts = new Point3d[5];
                    pts[0] = centerPt + new Vector3d(-(distX / 2), -(distY / 2), 0);
                    pts[1] = centerPt + new Vector3d((distX / 2), -(distY / 2), 0);
                    pts[2] = centerPt + new Vector3d((distX / 2), (distY / 2), 0);
                    pts[3] = centerPt + new Vector3d(-(distX / 2), (distY / 2), 0);
                    pts[4] = pts[0];


                    for (int i = 0; i < 4; i++)
                    {
                        Wall wall = new Wall();
                        wall.SetDatabaseDefaults(db);
                        wall.SetToStandard(db);
                        wall.SetDefaultLayer();
                        wall.Normal = new Vector3d(0, 0, 1);
                        wall.Set(pts[i], pts[i + 1], Vector3d.ZAxis);

                        btr.AppendEntity(wall);
                        trans1.AddNewlyCreatedDBObject(wall, true);
                    }
                    trans1.Commit();
                }
            }
            catch (System.Exception e)
            {
                trans.Abort();
                ed.WriteMessage(e.Message);
            }
            finally
            {
                trans.Dispose();
            }
        }
예제 #4
0
파일: DwgPlot.cs 프로젝트: tianzhifeng/EPC
        public static void GetCurSpaceAllEntLength(ref double life, ref double right, ref double up, ref double down)
        {
            List <ObjectId> objIdLst = new List <ObjectId>();
            Document        curDoc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager transactionManager = curDoc.Database.TransactionManager;
            using (Autodesk.AutoCAD.DatabaseServices.Transaction transaction = transactionManager.StartTransaction())
            {
                BlockTableRecord curSpaceBlkRec = transactionManager.GetObject(curDoc.Database.CurrentSpaceId, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId objId in curSpaceBlkRec)
                {
                    Entity ent;
                    try
                    {
                        ent = transaction.GetObject(objId, OpenMode.ForRead) as Entity;
                    }
                    catch (System.Exception e)
                    {
                        continue;
                    }
                    if (ent == null)
                    {
                        continue;
                    }
                    if (ent is Line)
                    {
                        Line line = ent as Line;
                        if (line.StartPoint.X < life)
                        {
                            life = line.StartPoint.X;
                        }
                        if (line.StartPoint.X > right)
                        {
                            right = line.StartPoint.X;
                        }
                        if (line.StartPoint.Y > up)
                        {
                            up = line.StartPoint.Y;
                        }
                        if (line.StartPoint.Y < right)
                        {
                            down = line.StartPoint.Y;
                        }
                    }

                    if (ent is Circle)
                    {
                        Circle circle = ent as Circle;
                        if (circle.Center.X < life)
                        {
                            life = circle.Center.X;
                        }
                        if (circle.Center.X > right)
                        {
                            right = circle.Center.X;
                        }
                        if (circle.Center.Y > up)
                        {
                            up = circle.Center.Y;
                        }
                        if (circle.Center.Y < right)
                        {
                            down = circle.Center.Y;
                        }
                    }

                    if (ent is Polyline)
                    {
                        Polyline polyline = ent as Polyline;
                        for (int i = 0; i < polyline.NumberOfVertices; i++)
                        {
                            Point2d temPt = polyline.GetPoint2dAt(i);
                            if (temPt.X < life)
                            {
                                life = temPt.X;
                            }
                            if (temPt.X > right)
                            {
                                right = temPt.X;
                            }
                            if (temPt.Y > up)
                            {
                                up = temPt.Y;
                            }
                            if (temPt.Y < right)
                            {
                                down = temPt.Y;
                            }
                        }
                    }
                }
                transaction.Commit();
            }
        }
    /// <summary>
    /// Create a material style and override the display properties of this style.
    /// Use Stylemanager to see the overrided display properties.
    /// </summary>
    public void DisplayPropertiesMaterialSample()
    {
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDisplay Properties for Material Sample:\n");
        Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("====================================================\n");

        Database db = Application.DocumentManager.MdiActiveDocument.Database;

        //MaterialUtility.
        TransactionManager tm    = db.TransactionManager;
        Transaction        trans = tm.StartTransaction();
        Editor             ed    = Application.DocumentManager.MdiActiveDocument.Editor;

        Autodesk.Aec.DatabaseServices.Dictionary dict = new DictionaryMaterialDefinition(db);

        MaterialDefinition materialDefinition = null;

        try
        {
            string name        = "ACADotNetMaterialDefination";
            string description = "Material def created through .NET API";

            if (!dict.Has(name, trans))
            {
                materialDefinition             = dict.NewEntry() as MaterialDefinition;
                materialDefinition.Description = description;
                dict.AddNewRecord(name, materialDefinition);
                trans.AddNewlyCreatedDBObject(materialDefinition, true);
            }
            else
            {
                materialDefinition = trans.GetObject(dict.GetAt(name), OpenMode.ForWrite) as MaterialDefinition;
            }



            DisplayPropertiesMaterial materialProperties = new DisplayPropertiesMaterial();

            materialProperties.SubSetDatabaseDefaults(db);
            materialProperties.SetToStandard(db);

            ObjectId materialId = AddMaterial("wood");
            materialProperties.SurfaceRenderingMaterialId       = materialId;
            materialProperties.SectionRenderingMaterialId       = materialId;
            materialProperties.SectionedBodyRenderingMaterialId = materialId;
            DisplayComponentHatch displayComponentHatch = new DisplayComponentHatch();

            materialProperties.SurfaceHatch.HatchType   = HatchType.UserDefined;
            materialProperties.SurfaceHatch.PatternName = "NETAPITESTPatternName";
            materialProperties.SurfaceHatch.Angle       = 90.0;

            ObjectId dispMaterialId = Override.AddToOverrideExtensionDictionaryAndClose(materialDefinition, materialProperties);

            DisplayRepresentationManager displayManager = new DisplayRepresentationManager(db);
            ObjectIdCollection           ids            = displayManager.GetDisplayRepresentationIdsFromCurrentViewport(RXObject.GetClass(typeof(MaterialDefinition)));

            ObjectId idActiveDispRep = ids[0];

            OverrideDisplayProperties overrideProperties = new OverrideDisplayProperties();
            overrideProperties.ViewId            = idActiveDispRep;
            overrideProperties.DisplayPropertyId = dispMaterialId;
            materialDefinition.Overrides.Add(overrideProperties);

            trans.Commit();
            ed.WriteMessage("\n" +
                            "One new style for material \"ACADotNetMaterialDefination\"is created and the display properties are overrided.\n" +
                            "Use StyleManager to see the settings."
                            + "\n");
        }
        catch (System.Exception e)
        {
            trans.Abort();
            ed.WriteMessage("\n" + e.Message + "\n");
            return;
        }
    }
예제 #6
0
        private bool commandExec(string cmdString)
        {
            if (cmdString.ToLower() == "initsample")
            {
                InitSample();
                return(true);
            }
            if (cmdString.ToLower() == "clear")
            {
                Clear();
                return(true);
            }
            if (cmdString.ToLower() == "quit")
            {
                return(false);
            }

            bool     result = true;
            Database db     = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            Transaction      t   = tm.StartTransaction();
            BlockTable       bt  = tm.GetObject(db.BlockTableId, OpenMode.ForRead, false) as BlockTable;
            BlockTableRecord btr = tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false) as BlockTableRecord;

            foreach (Autodesk.AutoCAD.DatabaseServices.ObjectId id in btr)
            {
                MassElement me = tm.GetObject(id, OpenMode.ForWrite) as MassElement;

                if (me == null)
                {
                    continue;
                }

                Autodesk.Aec.Modeler.Body b  = me.Body;
                Autodesk.Aec.Modeler.Body b2 = null;

                if (cmdString.ToLower() == "subbody")
                {
                    Autodesk.Aec.Modeler.Body subB = Autodesk.Aec.Modeler.Body.Cone(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(0, 0, 5)), 1, 1.5, 10);
                    b2 = b - subB;
                    me.SetBody(b2, true);
                }
                else if (cmdString.ToLower() == "multiplybody")
                {
                    Autodesk.Aec.Modeler.Body bb = Autodesk.Aec.Modeler.Body.Cone(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(0, 0, 5)), 1, 1.5, 10);
                    b2 = b * bb;
                    me.SetBody(b2, true);
                }
                else if (cmdString.ToLower() == "sectionbody")
                {
                    b.Section(new Plane(new Point3d(0, 0, 0), new Vector3d(0, 1, 1)), true);
                    me.SetBody(b, false);
                }
                else if (cmdString.ToLower() == "listbody")
                {
                    ListBody(me);
                }
                else if (cmdString.ToLower() == "addbody")
                {
                    Autodesk.Aec.Modeler.Body bb = Autodesk.Aec.Modeler.Body.Cylinder(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(10, 0, 0)), 5, 20);
                    b2 = b + bb;
                    me.SetBody(b2, true);
                }
                else if (cmdString.ToLower() == "stretchbody")
                {
                    b.Stretch(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(0, 10, 0)));
                    me.SetBody(b, false);
                }
                else if (cmdString.ToLower() == "booleanop")
                {
                    Autodesk.Aec.Modeler.Body bb = Autodesk.Aec.Modeler.Body.Cylinder(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(10, 0, 0)), 5, 20);
                    b2 = b.BooleanOperation(bb, BooleanOperatorType.Intersect);
                    me.SetBody(b2, false);
                }
                else if (cmdString.ToLower() == "combinebody")
                {
                    Autodesk.Aec.Modeler.Body bb = Autodesk.Aec.Modeler.Body.Box(new Point3d(0, 0, 0), new Vector3d(11, 11, 11));
                    b2 = bb.Combine(b);
                    me.SetBody(b2, false);
                }
                else if (cmdString.ToLower() == "translatebody")
                {
                    b2 = b.Translate(new Vector3d(0, 10, 0));
                    me.SetBody(b2, false);
                }
                else if (cmdString.ToLower() == "rotatebody")
                {
                    b2 = b.Rotate(new LineSegment3d(new Point3d(0, 0, 0), new Point3d(1, 1, 1)), 30);
                    me.SetBody(b2, false);
                }
                else if (cmdString.ToLower() == "scalebody")
                {
                    b2 = b.Scale(new Point3d(0, 0, 0), 2);
                    me.SetBody(b2, true);
                }
                else if (cmdString.ToLower() == "listpickbody")
                {
                    MassElement[] ms = GetSelectedMassElement();
                    if (null != ms)
                    {
                        foreach (MassElement m in ms)
                        {
                            ListBody(m);
                        }
                    }
                }
                else
                {
                    Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Wrong command!\n");
                    result = false;
                }
            }
            t.Commit();
            t.Dispose();
            return(result);
        }
예제 #7
0
        public void NestedEntityTest()
        {
            ObjectIdCollection        coll    = new ObjectIdCollection();
            Editor                    ed      = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptNestedEntityOptions entopts = new PromptNestedEntityOptions("prompt nested entity");

            entopts.AllowNone = true;
            entopts.Keywords.Add("Done");
            PromptNestedEntityResult ent = null;
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

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

            using (Transaction myT = tm.StartTransaction())
            {
                while (true)
                {
                    entopts.Message = "\nPick an entity of your choice from the drawing or type Done";

                    try
                    {
                        ent = ed.GetNestedEntity(entopts);
                    }
                    catch
                    {
                        ed.WriteMessage("\nYou did not select a valid nested entity");
                        break;
                    }
                    if (ent.Status == PromptStatus.Keyword)
                    {
                        if (ent.StringResult.Equals("Done"))
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (ent.GetContainers().Length > 0)
                        {
                            Entity entity;
                            foreach (ObjectId oid in ent.GetContainers())
                            {
                                entity = (Entity)tm.GetObject(oid, OpenMode.ForRead, true);
                                ed.WriteMessage("You selected: " + entity.GetType().FullName);
                            }
                            break;
                        }
                        else
                        {
                            ed.WriteMessage("You did not select any nested entity");
                        }
                    }
                    catch
                    {
                        ed.WriteMessage("You are Done or did not select any nested entity");
                        myT.Commit();
                        return;
                    }
                }

                entopts.NonInteractivePickPoint    = new Point3d(30.4, 11.6, 0);
                entopts.UseNonInteractivePickPoint = true;

                try
                {
                    ent = ed.GetNestedEntity(entopts);
                    if (ent.GetContainers().Length > 0)
                    {
                        Entity entity;
                        foreach (ObjectId oid in ent.GetContainers())
                        {
                            entity = (Entity)tm.GetObject(oid, OpenMode.ForRead, true);
                            ed.WriteMessage(entity.GetType().FullName + " has been selected");
                        }
                    }
                    else
                    {
                        ed.WriteMessage("No nested entity was selected");
                    }
                }
                catch
                {
                    ed.WriteMessage("\nNo entity was selected");
                }
                myT.Commit();
            }
        }
예제 #8
0
        static public void DoIt()
        {
            List <RoadwayWrapper> roadwayarray = new List <RoadwayWrapper>();

            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            //输入名字
            string name = "";
            PromptStringOptions opts2 = new PromptStringOptions("\nEnter Roadway name");
            PromptResult        res2  = ed.GetString(opts2);

            if (res2.Status == PromptStatus.Cancel)
            {
                return;
            }
            else
            {
                name = res2.StringResult;
            }


            //输入起点坐标
            PromptPointOptions opts = new PromptPointOptions("\nEnter Roadway Start Point:");
            PromptPointResult  res  = ed.GetPoint(opts);

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

            Point3d tmpPoint = res.Value;

            while (true)
            {
                //create roadway
                RoadwayJig     jig       = new RoadwayJig(tmpPoint, tmpPoint);
                RoadwayWrapper CurrentRW = (RoadwayWrapper)jig.GetEntity();
                jig.SetName(name);

                jig.setPromptCounter(0);
                PromptResult drag = ed.Drag(jig);
                if (drag.Status == PromptStatus.Cancel || drag.Status == PromptStatus.None)
                {
                    return;
                }
                else if (drag.Status == PromptStatus.OK)
                {
                    Database db = Application.DocumentManager.MdiActiveDocument.Database;

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

                    PROJECT pro = new PROJECT();
                    using (Transaction myT = tm.StartTransaction())
                    {
                        pro.AppendEntity(CurrentRW);

                        RoadwayNodeWrapper sttNd;
                        if (roadwayarray.Count > 0)
                        {
                            RoadwayWrapper PreviousRW =
                                (RoadwayWrapper)myT.GetObject(roadwayarray[roadwayarray.Count - 1].ObjectId, OpenMode.ForRead, false);
                            //Point3dCollection pc = new Point3dCollection();
                            // CurrentRW.IntersectWith(PreviousRW, Intersect.OnBothOperands, pc, IntPtr.Zero, IntPtr.Zero);
                            // CurrentRW.StartNodeHandle = PreviousRW.EndNodeHandle;
                            ObjectId tmpid = db.GetObjectId(false, PreviousRW.EndNodeHandle, 0);
                            sttNd = (RoadwayNodeWrapper)myT.GetObject(tmpid, OpenMode.ForWrite, false);
                            sttNd.appendRoadway(CurrentRW.Handle, 1);

                            CurrentRW.StartNodeHandle = sttNd.Handle;
                        }
                        else
                        {
                            sttNd = new RoadwayNodeWrapper();
                            pro.AppendEntity(sttNd);
                            sttNd.CreateSphere(15);
                            sttNd.init(CurrentRW.Handle, 1);
                            sttNd.Position = CurrentRW.StartPoint;

                            CurrentRW.StartNodeHandle = sttNd.Handle;
                        }

                        RoadwayNodeWrapper endNd = new RoadwayNodeWrapper();
                        pro.AppendEntity(endNd);
                        endNd.CreateSphere(15);
                        endNd.init(CurrentRW.Handle, -1);
                        endNd.Position          = CurrentRW.EndPoint;
                        CurrentRW.EndNodeHandle = endNd.Handle;

                        roadwayarray.Add(CurrentRW);
                        myT.Commit();
                    }

                    tmpPoint = jig.GetEndPoint();
                }
            }
        }
예제 #9
0
        static public void transformToTunnel()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;
            PromptSelectionResult res = ed.SelectAll();

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

            Autodesk.AutoCAD.EditorInput.SelectionSet SS = res.Value;

            var tmpidarray = SS.GetObjectIds();
            var idArray    = SS.GetObjectIds();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            List <DBTunnel> inList = new List <DBTunnel>();

            Utils.TransactionControl(() =>
            {
                foreach (ObjectId id in tmpidarray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForWrite, true);

                    if (!(entity is Line) && !(entity is Autodesk.AutoCAD.DatabaseServices.Polyline))
                    {
                        continue;
                    }

                    if (entity is Line)
                    {
                        Line line           = entity as Line;
                        DBTunnel dbTunnel   = new DBTunnel();
                        dbTunnel.BasePoints = new List <DBVertice>
                        {
                            new DBVertice(line.StartPoint), new DBVertice(line.EndPoint)
                        };
                        inList.Add(dbTunnel);
                        line.Erase();
                    }
                    else if (entity is Autodesk.AutoCAD.DatabaseServices.Polyline)
                    {
                        Autodesk.AutoCAD.DatabaseServices.Polyline polyline =
                            entity as Autodesk.AutoCAD.DatabaseServices.Polyline;

                        DBTunnel dbTunnel   = new DBTunnel();
                        dbTunnel.BasePoints = new List <DBVertice>();

                        for (int i = 0; i < polyline.NumberOfVertices; i++)
                        {
                            dbTunnel.BasePoints.Add(new DBVertice(polyline.GetPoint3dAt(i)));
                        }

                        if (polyline.Closed == true)
                        {
                            dbTunnel.IsClosed = true;
                        }

                        inList.Add(dbTunnel);
                        polyline.Erase();
                    }
                }
            });
            var resList = DrawTunnel.StaticDrawSquareTunnel(inList);
        }
예제 #10
0
        public void Retrive_Plant3DPart_data()
        {
            //file name to save different data
            string partDataFromObjPath = @"C: \Users\LinP3\source\repos\Plant3DApiTester\Resource\partDataFromObj.txt";
            string partDataFromDBPath  = @"C: \Users\LinP3\source\repos\Plant3DApiTester\Resource\partDataFromDB.txt";

            ///all available drawing type
            string DwgType_Piping = "Piping";
            string DwgType_PnId   = "PnId";
            string DwgType_Ortho  = "Ortho";
            string DwgType_Iso    = "Iso";

            //get current drawing
            Document doc = AcadApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            ///create a clean file, prepare to write
            File.WriteAllText(partDataFromObjPath, $"{doc.Name}\n");
            File.WriteAllText(partDataFromDBPath, $"{doc.Name}\n");

            //get current project
            PlantProject     mainPrj = PlantApplication.CurrentProject;
            Project          prj     = mainPrj.ProjectParts[DwgType_Piping];
            DataLinksManager dlm     = prj.DataLinksManager;

            //get current drawing type
            string dwgtype = PnPProjectUtils.GetActiveDocumentType();

            if (dwgtype != DwgType_PnId && dwgtype != DwgType_Piping)
            {  //"PnId", "Piping", "Ortho", "Iso"
                ed.WriteMessage("This drawing is not a P&ID or 3D Model in the current project.\n");
                return;
            }

            //method to get PnPDatabase for project
            PnPDatabase pnpDB = dlm.GetPnPDatabase();

            #region get all object in cad and check if it is plant 3d object, if it is, get its PnPId
            string msg = string.Empty;

            ///get just current project and the datalink
            Project          prjPart = PnPProjectUtils.GetProjectPartForCurrentDocument();
            DataLinksManager dlmPart = prjPart.DataLinksManager;
            //PnPDatabase dbPart = dlmPart.GetPnPDatabase();

            //check all information
            msg = getHeaderText("check PnPTable");
            PnPRowIdArray aPid = dlmPart.SelectAcPpRowIds(db);
            int           numberOfObjsInCurrentProj = aPid.Count();
            msg += "Number of objects in current project database =" + numberOfObjsInCurrentProj;
            int no = 1;
            foreach (int rid in aPid)
            {
                StringCollection sKeys = new StringCollection();
                sKeys.Add("Tag");
                sKeys.Add("Description");
                sKeys.Add("PartFamilyLongDesc");
                sKeys.Add("Line Number");
                StringCollection sVals = dlm.GetProperties(rid, sKeys, true);
                msg += $"\n[{no}]PnPId {rid} ?(rid), Tag = {sVals[0]} ({sVals[1]}) {sVals[2]} <{ sVals[3]}>.";
                no++;
            }
            File.AppendAllText(partDataFromDBPath, msg);
            #endregion

            #region to check all objects in current drawings
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\nSelect " + dwgtype + " objects to <All>:";

            ///select object in drawing
            PromptSelectionResult result = ed.GetSelection(pso);
            if (result.Status == PromptStatus.Cancel)
            {
                return;
            }
            if (result.Status != PromptStatus.OK)
            {
                result = ed.SelectAll();
            }
            SelectionSet ss     = result.Value;
            ObjectId[]   objIds = ss.GetObjectIds();

            ///traves over all objects
            Autodesk.AutoCAD.DatabaseServices.TransactionManager tranMag = db.TransactionManager;
            int numberOfObjsInCurrentDrawing = objIds.Count();
            File.AppendAllText(partDataFromObjPath, $"Number of Plant element in Selection ={numberOfObjsInCurrentDrawing}");
            int numberOfPlantObjsInCurrentDrawing = 1;
            msg = getHeaderText("traves over all objects on selection");
            no  = 1;
            using (Transaction tran = tranMag.StartTransaction())
            {
                foreach (ObjectId objId in objIds)
                {
                    DBObject obj = tran.GetObject(objId, OpenMode.ForRead);
                    msg += getHeaderText($"({no})ClassID = {obj.ClassID}");

                    //return if it is not a plant object
                    if (!dlm.HasLinks(objId))
                    {
                        continue;
                    }

                    Handle handle = objId.Handle;
                    File.AppendAllText(partDataFromObjPath, $"({no})Handle = {handle.Value}, handle string = {handle.ToString()}\n");/////////////////// handle string is what is shown in Navisworks

                    try
                    {
                        //ObjectIdCollection objectIdCollection = dlm.GetRelatedAcDbObjectIds(objId);
                        File.AppendAllText(partDataFromObjPath, $"({no})ObjectId = {objId}, Id ={obj.Id}, ClassID ={obj.ClassID}\n");

                        //find row id
                        int rowId = dlmPart.FindAcPpRowId(objId);
                        File.AppendAllText(partDataFromObjPath, $"({no})rowId ={rowId}\n");
                        dlmPart.GetObjectClassname(rowId);

                        //find ppobjectid
                        PpObjectIdArray ppObjectIds = dlmPart.FindAcPpObjectIds(rowId);
                        foreach (PpObjectId ppObjectId in ppObjectIds)
                        {
                            File.AppendAllText(partDataFromObjPath, $"({no})dbHandle = {ppObjectId.dbHandle}, DwgId = {ppObjectId.DwgId}\n");
                        }

                        ///get property
                        //properties to lookup
                        StringCollection props = new StringCollection();
                        props.Add("WBS_Level1");
                        props.Add("WBS_Level2");
                        props.Add("WBS_Level3");
                        props.Add("WBS_Level4");
                        props.Add("WBS_Level5");
                        props.Add("WBS_Level6");
                        props.Add("WBS_Level7");
                        props.Add("PnPGuid");
                        //properties values
                        StringCollection propsValue = dlmPart.GetProperties(objId, props, true);

                        //update value
                        for (int i = 0; i < props.Count; i++)
                        {
                            ///set property when value is empty
                            if (string.IsNullOrEmpty(propsValue[i]))
                            {
                                propsValue[i] = $"WBS_Level{i}_Value";
                            }
                        }
                        ///set property
                        dlmPart.SetProperties(objId, props, propsValue);

                        ///print out to see
                        for (int i = 0; i < props.Count; i++)
                        {
                            File.AppendAllText(partDataFromObjPath, $"({no})props = {props[i]}, Value = {propsValue[i]}\n");
                        }

                        numberOfPlantObjsInCurrentDrawing++;
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString()); }

                    Part part = obj as Part;
                    if (part != null)
                    {
                        print(part, $"({no})Part", partDataFromObjPath);
                        File.AppendAllText(partDataFromObjPath, $"({no})GetType = {part.GetType()}\n");

                        ///type:
                        ///Autodesk.ProcessPower.PnP3dObjects.Connector
                        ///Autodesk.ProcessPower.PnP3dObjects.Pipe
                        ///Autodesk.ProcessPower.PnP3dObjects.PipeInlineAsset
                        ///Autodesk.ProcessPower.PnP3dObjects.Equipment
                        if (part.GetType() == typeof(Connector))
                        {
                            try
                            {
                                Connector item = part as Connector;
                                print(item, typeof(Connector).ToString(), partDataFromObjPath);
                            }
                            catch { }
                        }
                        if (part.GetType() == typeof(Pipe))
                        {
                            try
                            {
                                Pipe item = part as Pipe;
                                print(item, typeof(Pipe).ToString(), partDataFromObjPath);
                            }
                            catch { }
                        }
                        if (part.GetType() == typeof(PipeInlineAsset))
                        {
                            try
                            {
                                PipeInlineAsset item = part as PipeInlineAsset;
                                print(item, typeof(PipeInlineAsset).ToString(), partDataFromObjPath);
                            }
                            catch { }
                        }
                    }

                    File.AppendAllText(partDataFromObjPath, $"({no})++++++++++++++++++++++++++++++++\n");
                    no++;
                }
            }

            File.AppendAllText(partDataFromObjPath, $"Number of Plant element in drawing ={numberOfPlantObjsInCurrentDrawing}");
            #endregion
        }