Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - fixo

Pages: 1 2 [3] 4 5 ... 8
31
Polylines / Write polyline points to CSV file
« on: February 19, 2013, 04:37:10 PM »
Code: [Select]
        [CommandMethod("PolylineToCSV", "plcsv",CommandFlags.Modal | CommandFlags.UsePickSet)]
        public static void ExportPolyPointsToCSV()
        {
            Document doc =Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            try
            {

                using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {
                    string dec = ((short)Autodesk.AutoCAD.ApplicationServices.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:\Test\";
                    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 (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
            }
        }

32
3D entities / Create extruded cylinder
« on: February 19, 2013, 03:20:13 PM »
        [CommandMethod("testCylinder")]
        public void DrawExtrudedCylinder()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Point3d cp;

            PromptPointOptions ptopts = new PromptPointOptions("\nSelect center point of circel: ");

            PromptPointResult ptres = ed.GetPoint(ptopts);

            // Exit if the user presses ESC or cancels the command
            if (ptres.Status != PromptStatus.OK) return;

            cp = ptres.Value;
            //base point
           
            PromptDistanceOptions pdo = new PromptDistanceOptions("\nEnter a radius: ");
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 100.0;
            pdo.BasePoint = cp;
            pdo.UseBasePoint = true;
            pdo.UseDashedLine = true;
           
            PromptDoubleResult res;
            res = ed.GetDistance(pdo);
            if (res.Status != PromptStatus.OK)
                return;

            double rad = res.Value;

            ed.WriteMessage("\nRadius Entered\t{0}", rad);
            pdo = new PromptDistanceOptions("\nEnter cylinder height: ");
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 1000.0;
            pdo.BasePoint = cp;
            pdo.UseBasePoint = true;
            pdo.UseDashedLine = true;

            res = ed.GetDistance(pdo);
            if (res.Status != PromptStatus.OK)
                return;

            double height = res.Value;
 
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                Circle circ = new Circle(cp, Vector3d.ZAxis, rad);
               

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

                ObjectId objId = btr.AppendEntity(circ);

                tr.AddNewlyCreatedDBObject(circ, true);

                // Get the boundary curves to create a region
                DBObjectCollection regs = new DBObjectCollection();

                regs.Add(circ);

                // Create a region from the circle.

                DBObjectCollection regions = new DBObjectCollection();

                regions = Region.CreateFromCurves(regs);
               
                if (regions.Count == 0)
                {
                    ed.WriteMessage("\nFailed to create region\n");
                    return;
                }

                Region reg = (Region)regions[0];

                // Extrude the region to create a solid.

                Solid3d sol = new Solid3d();

                sol.RecordHistory = true;// important

                sol.ShowHistory = true;// important

                sol.Extrude(reg, height, 0.0);// < --- set taper angle here

                ObjectId solId = ObjectId.Null;

                solId = btr.AppendEntity(sol);

                tr.AddNewlyCreatedDBObject(sol, true);

                if (!circ.IsWriteEnabled) circ.UpgradeOpen();

                circ.Erase();

                tr.Commit();
            }

        }

33
Dimensions / Display sum of selected dimensions
« on: February 15, 2013, 09:30:41 PM »
Code: [Select]
        [CommandMethod("DisplayDimSum", "dds", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public void SumOfDims()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            double sum = 0;
            TypedValue[] values = new TypedValue[] { new TypedValue(0, "DIMENSION") };
            SelectionFilter filter = new SelectionFilter(values);
            PromptSelectionOptions opts = new PromptSelectionOptions();

            opts.MessageForRemoval = "\nMust be a type of Dimension!";
            opts.MessageForAdding = "\nSelect dimensions to reset : ";
            opts.PrepareOptionalDetails = false;
            opts.SingleOnly = false;
            opts.SinglePickInSpace = false;
            opts.AllowDuplicates = true;
            PromptSelectionResult result = ed.GetSelection(opts, filter);
            if (result.Status != PromptStatus.OK) return;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet sset = result.Value;
                    foreach (SelectedObject selobj in sset)
                    {
                        DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;
                        Dimension dim = obj as Dimension;

                        if (dim != null)
                        {
                            sum += dim.Measurement;

                        }
                    }

                    tr.Commit();
                }
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("Sum of dimensions = {0:f3}", sum));
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nProblem with selection dimensions.\n");
                ed.WriteMessage(ex.Message);
            }
        }

34
Layers / Load base or custom linetypes
« on: February 14, 2013, 06:40:08 PM »
This code allow user to load both linetypes from "acad.lin" or "acadiso.lin" file
and from the custom linetype file,
see attachment, both C# and VB.NET code included

35
Dimensions / Extend leader to selected curve
« on: February 05, 2013, 11:50:26 AM »
 
Code: [Select]
       [CommandMethod("Lex")]
        public void testLeaderExtend()
        {
            // Get active document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // Prompt the user to select a leader.
            PromptEntityOptions pso = new PromptEntityOptions("\nPlease select a leader ");
            pso.SetRejectMessage("\nSelect leader only ");
            pso.AddAllowedClass(typeof(Leader), false);
            PromptEntityResult res = ed.GetEntity(pso);
            if (res.Status != PromptStatus.OK) return;
            // Prompt the user to select a curve.
            PromptEntityOptions pno = new PromptEntityOptions("\nPlease select a single curve to extend leader to: ");
            pso.SetRejectMessage("\nSelect curve only ");
            pso.AddAllowedClass(typeof(Curve), false);
            PromptEntityResult nres = ed.GetEntity(pno);
            if (nres.Status != PromptStatus.OK) return;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // open current space for write to modify leader
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                ObjectId ldid;
                ldid = res.ObjectId;
                ObjectId crid;
                crid = nres.ObjectId;
                Leader leader = tr.GetObject(ldid, OpenMode.ForRead) as Leader;
                if (leader == null) return;
                Point3d arrPt = leader.VertexAt(0);
                ed.WriteMessage("\nPoint on arrow:\t({0:f3}\n", arrPt);
                Curve curv = tr.GetObject(crid, OpenMode.ForRead) as Curve;
                if (curv == null) return;
                // Get point on curve
                Point3d nearPt = curv.GetClosestPointTo(nres.PickedPoint, false).TransformBy(Matrix3d.Identity);
                ed.WriteMessage("\nPoint on line:\t({0:f3}\n", nearPt);
                leader.UpgradeOpen();
                leader.SetVertexAt(0, nearPt);
                leader.RecordGraphicsModified(true);
                // Commit transaction
                tr.Commit();
            }
        }

36
Tables / Create block table summary
« on: February 03, 2013, 12:48:27 PM »
The code is similar on command ATTOUT,
start command with 'CRAT' in the command line,
please use second attached file, because first one have a bug
when just one block selected on screen

37
Text / place Mtext to middle between two curves
« on: January 25, 2013, 09:03:36 PM »
This code allow to add many lines in the command line one by another in loop
To start command type : mit
 
Code: [Select]
      [CommandMethod("PlaceMtextToMidpoint","mit", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void PlaceMtextToMiddle()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            PromptEntityOptions peo = new PromptEntityOptions("\nSelect the first curve: ");
            peo.SetRejectMessage("Only a curve !");
            peo.AddAllowedClass(typeof(Curve), false);
            PromptEntityResult per = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK) return;
            ObjectId id1 = per.ObjectId;
            Point3d p1 = per.PickedPoint;
            peo.Message = "\nSelect the second curve: ";
            per = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK) return;
            ObjectId id2 = per.ObjectId;

            PromptStringOptions pso = new PromptStringOptions("\nEnter first line of Mtext: ");
            pso.AllowSpaces = true;
            PromptResult res;
            res = ed.GetString(pso);
            if (res.Status != PromptStatus.OK)
                return;

            string txtStr = res.StringResult;
            do
            {
                pso.Message = "\nEnter next line of Mtext: ";
                res = ed.GetString(pso);
                if (res.Status != PromptStatus.OK)
                    return;
                txtStr = txtStr + "\\P" + res.StringResult;
            } while (res.Status != PromptStatus.OK);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

                DBObject obj1 = (DBObject)tr.GetObject(id1, OpenMode.ForRead, false);
                Curve curve1 = obj1 as Curve;

                if (curve1 == null)
                {
                    ed.WriteMessage("\nNo curve selected\n");
                    return;
                }
                DBObject obj2 = (DBObject)tr.GetObject(id2, OpenMode.ForRead, false);
                Curve curve2 = obj2 as Curve;

                if (curve2 == null)
                {
                    ed.WriteMessage("\nNo curve selected\n");
                    return;
                }
                Point3d p2 = curve2.GetClosestPointTo(p1, false);

                Plane plan = curve1.GetPlane();

                Vector3d norm = plan.Normal;

                p1 = p1.TransformBy(Matrix3d.WorldToPlane(norm));

                p2 = p2.TransformBy(Matrix3d.WorldToPlane(norm));
                // calculate middle point one way
                Point3d mp = p1.Add(p2 - p1).ScaleBy(0.5, p1).TransformBy(Matrix3d.WorldToPlane(norm));

                double ang = (p2 - p1).AngleOnPlane(plan);
                // draw vectors for imagination
                ed.DrawVector(p1, mp, 1, true);

                ed.DrawVector(p2, mp, 5, true);
                // set angle to be more readable
                if ((ang > Math.PI / 2) && (ang < Math.PI * 1.5))
                    ang = ang + Math.PI;
                // create mtext
                MText mtxt = new MText();
                mtxt.SetDatabaseDefaults();
                mtxt.Attachment = AttachmentPoint.MiddleCenter;
                mtxt.Location = mp;
                mtxt.TextHeight = db.Textsize;
                mtxt.Width = 0.0;
                mtxt.Contents = txtStr;
                mtxt.Layer = "0";
                mtxt.ColorIndex = 256;
                Matrix3d mx = Matrix3d.Rotation(ang, norm, mp);
                mtxt.TransformBy(mx);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                // add mtext to database and transaction
                btr.AppendEntity(mtxt);
                tr.AddNewlyCreatedDBObject(mtxt, true);

                tr.Commit();
            }
        }

38
Dimensions / Get the geometry from a dimension entity
« on: January 17, 2013, 11:04:00 PM »
Code: [Select]
        // Get the geometry from a dimension entity
        // translated on C# from article by  Augusto Goncalves:
        // http://adndevblog.typepad.com/autocad/2013/01/get-the-geometry-from-a-dimension-entity.html
        [CommandMethod("dgeom", CommandFlags.UsePickSet)]
        public void GetDimensionLinesData()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Transaction tr = doc.TransactionManager.StartOpenCloseTransaction();

            using (tr)
            {

                Dimension diment = null;

                PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Dimension>>");
                peo.SetRejectMessage("\nSelect Dimension only >>");
                peo.AddAllowedClass(typeof(Dimension), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                diment = (Dimension)ent as Dimension;
                if (diment == null)
                {
                    ed.WriteMessage("\nError: selected entity is not a Dimension");
                    return;
                }
                //get current space
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                //get dimension block definition
                BlockTableRecord dimbtr = tr.GetObject(diment.DimBlockId, OpenMode.ForRead) as BlockTableRecord;
                MessageBox.Show(dimbtr.Name);
                BlockTableRecordEnumerator iter = dimbtr.GetEnumerator();
                Entity obj;
                // Iterate every entity stored in the
                // block definition of the dimension.
                while (iter.MoveNext())
                {
                   
                    obj = tr.GetObject((ObjectId)iter.Current, OpenMode.ForRead) as Entity;

                    Line ln = obj as Line;

                    if (ln != null)
                    {

                        // Get the start and end point. 

                        Point3d sp, ep;

                        sp = ln.StartPoint;
                        ep = ln.EndPoint;


                        //     // Transform the start and end point.   

                        //     // Get the transformation matrix.   

                        Matrix3d mat = new Matrix3d();

                        // Get the axis of the dimension entity.

                        Vector3d zAxis = diment.Normal;

                        Vector3d xAxis = zAxis.GetPerpendicularVector();

                        Vector3d yAxis = zAxis.CrossProduct(xAxis);

                        // Build the transformation matrix.   
                       
                        mat = Matrix3d.AlignCoordinateSystem(Point3d.Origin, new Vector3d(1.0, 0.0, 0.0),

                          new Vector3d(0.0, 1.0, 0.0),

                          new Vector3d(0.0, 0.0, 1.0),

                          Point3d.Origin,

                          xAxis, yAxis, zAxis);
                     

                        // To test this matrix create a new line   

                        // using the start and endpoint of the line

                        // from the block definition, and transform   

                        // the line using the calculated transformation matrix.     

                        Line newln = new Line(sp, ep);

                        newln.TransformBy(mat);

                        Point3d nptStart, nptEnd;

                        nptStart = newln.StartPoint;

                        nptEnd = newln.EndPoint;

                        newln.ColorIndex = 4;

                        // Append the new line to the model space and close it.   

                        // The new line should be at the location     

                        // of the dimension entity.     

                       
                        btr.AppendEntity(newln);
                        tr.AddNewlyCreatedDBObject(newln, true);
               
                    }

                    tr.Commit();

                }
            }
        }

39
Blocks / How to place blocks in a rectangular area evenly
« on: January 15, 2013, 09:43:33 PM »
This one is written on C# only
Please, change block name and sizes to your suit

40
Polylines / Create 3d polyline from points
« on: January 12, 2013, 11:03:35 PM »
Code: [Select]
        [CommandMethod("c3p")]
        static public void Create3dPolyline()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

         Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get blocktable and modelspace (for write)
                BlockTable bt =  (BlockTable)tr.GetObject(   db.BlockTableId, OpenMode.ForRead,  false);

                BlockTableRecord btr =(BlockTableRecord)tr.GetObject( bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false );
               
                // Create a 3D polyline with 6 segments (closed)
                Point3d[] pts = new Point3d[]
                        { new Point3d(0,0,0),
                          new Point3d(60,0,0),
                         new Point3d(60,0,60),
                         new Point3d(60,60,60),
                         new Point3d(0,60,60),
                         new Point3d(0,0,60)
                        };
                Point3dCollection points = new Point3dCollection(pts);

                Polyline3d poly = new Polyline3d();
                // First add polyline to model space and transaction
                btr.AppendEntity(poly);

                tr.AddNewlyCreatedDBObject(poly, true);
                // Then add all vertices to polyline from point collection
                foreach (Point3d pt in points)
                {
                    // Now create the vertices

                    PolylineVertex3d vex3d = new PolylineVertex3d(pt);

                    // And add them to the 3dpoly (this adds them to the db also)

                    poly.AppendVertex(vex3d);

                    tr.AddNewlyCreatedDBObject(vex3d, true);
                   
                }
                // Make polyline closed
                poly.Closed = true;
                // Change color
                poly.ColorIndex = 14;
                // Commit transaction
                tr.Commit();

            }
        }

41
 
Code: [Select]
              public static ErrorStatus fixoGetEntity(Transaction tr, Editor ed, RXClass rx, string msg, out ObjectId id)
        {
            ErrorStatus es;
            Entity ent;
            id = ObjectId.Null;
            PromptEntityOptions peo = new PromptEntityOptions(msg);
            peo.SetRejectMessage("\nYou're missing, try again >>");
            peo.AddAllowedClass(typeof(Entity), false);
            PromptEntityResult res;
            res = ed.GetEntity(peo);
            if (res.Status != PromptStatus.OK)
                es = ErrorStatus.PointNotOnEntity;
            id = res.ObjectId;
            if (id == ObjectId.Null)
                es = ErrorStatus.NullObjectId;
            ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
            if (ent.GetRXClass() != rx)
            {
                ed.WriteMessage("\n{0}Must be a \"{0}\" type of only!",rx.DxfName);
                es = ErrorStatus.NotThatKindOfClass;
            }
            if (ent == null)
                es = ErrorStatus.NotAnEntity;
            else es = ErrorStatus.OK;
            return es;
        }
         

        // Use function above this way
        [CommandMethod("tef")]
        public static void testSelectFunction()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            ObjectId id = ObjectId.Null;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
               if (fixoGetEntity(tr, ed, RXClass.GetClass(typeof(MText)), "\nSelect MTEXT to edit", out id) == ErrorStatus.OK)
                {
                    ed.WriteMessage("\nObjectId: {0}\n", id);
                    ed.WriteMessage("\nEntity Name: {0}\n", id.ObjectClass.DxfName);
                    // get entity by direct cast
                    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                    ent.ColorIndex = 121;// do whatever you need with entity here
                    tr.Commit();
                }
            }
        }

42
Polylines / Getting the Midpoint of each Polyline Segment
« on: January 10, 2013, 03:08:32 PM »
        Getting the Midpoint of each Polyline Segment
        based on article by Fenton Webb here:
        http://adndevblog.typepad.com/autocad/2013/01/getting-the-midpoint-of-each-polyline-segment-using-objectarx.html
 
Code: [Select]
      [CommandMethod("smp")]
        public void ShowMidPointOnEachSegment()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;

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

                Entity ename;

                PromptEntityOptions peo = new PromptEntityOptions("\nSelect Polyline: ");

                peo.SetRejectMessage("\nMust be a Polyline.");

                peo.AddAllowedClass(typeof(Polyline), false);
               
                PromptEntityResult retval = ed.GetEntity(peo);

                if (retval.Status != PromptStatus.OK)   return;

                Curve curv;

                ObjectId id;

                id = retval.ObjectId;

                ename = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                curv = ename as Curve;
                if (curv == null)
                {
                    ed.WriteMessage("\nCould not cast object as Curve.");

                    return;
                }
                if (!curv.IsWriteEnabled)

                    curv.UpgradeOpen();

                double startParam, endParam;

                // get the start param, usually it starts at 0 or 1

                startParam = curv.StartParam;

                ed.WriteMessage("\nStartParam is: {0:f3}\n", startParam);

                // get the end param, for a polyline it's the total number of

                // vertex's -1

                endParam = curv.EndParam;

                ed.WriteMessage("\nEndParam is: {0:f3}\n", endParam);

                // now loop the parameters, adding 1.0 each iteration

               
                for (double i = startParam; i < endParam; ++i)
                {
                    Point3d pt;

                    pt = curv.GetPointAtParameter(i + 0.5);
                  //  DBPoint dp = new DBPoint(pt);
                    Circle cr = new Circle(pt, Vector3d.ZAxis, 2.5);
                    btr.AppendEntity(cr);
                    tr.AddNewlyCreatedDBObject(cr, true);

                    ed.WriteMessage("\nPoint: {0}, {1}, {2}\n", pt[0], pt[1], pt[2]);

                }
                tr.Commit();
            }
        }

43
Polylines / Create region from connected arcs and lines
« on: January 10, 2013, 08:23:44 AM »
Code: [Select]
        //Create region from connected arcs and lines
        [CommandMethod("craw")]
        public static void CreateRegionFromConnected()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            DBObjectCollection objs = new DBObjectCollection();

            DBObjectCollection regcoll = new DBObjectCollection();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

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

                TypedValue[] tvs = new TypedValue[] { new TypedValue(0, "line,arc") };

                Point3dCollection points = new Point3dCollection();

                SelectionFilter sf = new SelectionFilter(tvs);

                PromptSelectionResult sres = ed.GetSelection(sf);

                if (sres.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nInvalid selection!");

                    return;
                }

                foreach (SelectedObject selobj in sres.Value)
                {
                    DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;

                    objs.Add(obj);

                }

                regcoll = Region.CreateFromCurves(objs);

                Region reg = regcoll[0] as Region;

                btr.AppendEntity(reg);

                tr.AddNewlyCreatedDBObject(reg, true);
                // you might be want to remove the parent objects here,
                // because of DELOBJ variable did not effect :
                //foreach (DBObject obj in objs)
                //    obj.Erase();  // uncomment this code block if needs

                tr.Commit();
            }
        }

44
Blocks / How to insert multiline attributes
« on: January 09, 2013, 08:07:58 PM »

Code: [Select]
        // based on code example from article by by Gopinath Taget here:
        //  http://adndevblog.typepad.com/autocad/2013/01/how-to-mimic-the-autocad-insert-command-in-arx-without-acedcommand-call.html

        [CommandMethod("testInsertCommand", "doi", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void DoInsert()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // set your block name here
            string blockName = "UserName";

            ObjectId blockId;
            // dictionary to store pairs of tag-string
            Dictionary<string, string> dict = new Dictionary<string, string>();
            //populate dictionary with exact values to your block
            string[,] pairs = new string[,] { { "TAG1", "VALUE 1" },
            { "TAG2", "VALUE 2" },
            { "TAG3", "VALUE 3" },
            { "TAG4",
          "Some text in the default colour...\\P" +
          "{\\C1;Something red}\\P" +
          "{\\C2;Something yellow}\\P" +
          "{\\C3;And} {\\C4;something cyan}" } };

            for (int i=0;i<=pairs.GetUpperBound(0);i++)
                dict.Add(pairs[i,0], pairs[i,1]);
            //------------------------------------------------------------
            //  debug only:
            //  foreach (KeyValuePair<string, string> kvp in dict)
            //    ed.WriteMessage("\n{0}\t{1}\n", kvp.Key, kvp.Value);
            //------------------------------------------------------------

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if (!bt.Has(blockName)) return;
                blockId = bt[blockName];
               
                PromptPointOptions ppo = new PromptPointOptions("\nPlease specify insertion point of block: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                Point3d basePoint = ppr.Value;
                AddBlockWithAttributes(db, dict, blockId, basePoint);         
                tr.Commit();
                ed.UpdateScreen();
            }

        }


        //Here is the code for addBlockWithAttributes:

        // NOTE: You will have to update the code to properly set the

        // attribute values. The code below sets the value of each

        // attribute from dictionary.

        static public void AddBlockWithAttributes(Database db, Dictionary<string, string> dict, ObjectId blockId, Point3d basePoint)
        {
            try
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    //----- Step 1: Allocate a block reference object

                    BlockReference bref = new BlockReference(basePoint, blockId);

                    //----- Step 2: Set up the block reference to the newly

                    //----- created block definition

                    // pBlkRef.BlockTableRecord =blockId ;

                    //---- Give it the current UCS normal.

                    bref.Rotation = 0.0;

                    bref.Normal = new Vector3d(0.0, 0.0, 1.0);

                    //----- Step 3: Open current database's Model Space

                    //----- blockTableRecord

                    BlockTable bt;

                    BlockTableRecord btr;

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

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

                    //----- Append the block reference to the model space

                    //----- block table record

                    ObjectId newEntId;

                    newEntId = btr.AppendEntity(bref);

                    tr.AddNewlyCreatedDBObject(bref, true);

                    //----- Step 4: Open the block definition for read

                    BlockTableRecord blkDef;

                    blkDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);

                    Entity ent;

                    AttributeDefinition attDef;

                    AttributeCollection attColl = bref.AttributeCollection;

                    foreach (ObjectId id in blkDef)
                    {
                        // Commented, you can use 'foreach' instead:
                        // BlockTableRecordEnumerator ienum = blkDef.GetEnumerator();
                        //while (ienum.MoveNext())
                        //{

                        //----- Get the next entity

                        // ent = (Entity)tr.GetObject(ienum.Current, OpenMode.ForRead);// commented
                        ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        //----- Make sure the entity is an attribute definition

                        //----- and not a constant

                        attDef = ent as AttributeDefinition;

                        if (attDef != null && !attDef.Constant)
                        {

                            //----- We have a non-constant attribute definition

                            //----- so build an attribute entity

                            AttributeReference attRef = new AttributeReference();

                          //  attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                            attRef.SetPropertiesFrom(attDef);

                            attRef.Visible = attDef.Visible;

                            //----- Translate attribute by block reference.

                            //----- To be really correct, entire block

                            //----- reference transform should be applied here.

                            basePoint = attDef.Position;

                            basePoint += bref.Position.GetAsVector();

                            attRef.Position = basePoint;

                            attRef.Height = attDef.Height;

                            attRef.Rotation = attDef.Rotation;

                            attRef.Tag = attDef.Tag;

                            attRef.FieldLength = attDef.FieldLength;

                            //----- Database Column value should be displayed

                            //----- INSERT would prompt for this...

                            //------ Update attribute value from dictionary by tag
                            if (attDef.IsMTextAttributeDefinition)
                            {
                                attRef.IsMTextAttribute = true;
                             
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                                attRef.ForceAnnoAllVisible = true;
                                attRef.UpdateMTextAttribute();
                               
                            }
                            else
                            {
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                            }
                            //----- Set Alignments

                            attRef.HorizontalMode = attDef.HorizontalMode;

                            attRef.VerticalMode = attDef.VerticalMode;

                            attRef.AdjustAlignment(db);
                            //----- Insert the attribute in the DWG

                            attColl.AppendAttribute(attRef);


                        }
                    }

                    bref.RecordGraphicsModified(true);//    optional
                   
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                // MessageBox.Show(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
                Console.WriteLine(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { }
        }

45
Math and Geometry / Create arc by 3 points
« on: January 08, 2013, 07:43:41 PM »
Code: [Select]
        [CommandMethod("CreateArcBy3Points", "cra3p", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void CreateArcByThreePoints()
        {
            short osm = (short)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("osmode");
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            // get the points

            Point3d p1, p2, p3;
            PromptPointOptions ppo = new PromptPointOptions("\nFirst point: ");
            PromptPointResult ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p1 = ppr.Value;

            ppo = new PromptPointOptions("\nSecond point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p2 = ppr.Value;

            ppo = new PromptPointOptions("\nThird point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p3 = ppr.Value;

            // create a CircularArc3d
           
            CircularArc3d carc = new CircularArc3d(p1, p2, p3);

            Arc arc = null;

            // now convert the CircularArc3d to an Arc
            Point3d cpt = carc.Center;
            Vector3d normal = carc.Normal;
            Vector3d refVec = carc.ReferenceVector;
            Plane plan = new Plane(cpt, normal);
            double ang = refVec.AngleOnPlane(plan);
            arc = new Arc(cpt, normal, carc.Radius, carc.StartAngle + ang, carc.EndAngle + ang);

            arc.SetDatabaseDefaults();
 
            // dispose CircularArc3d
            carc.Dispose();


            // get the current database

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // get the current space
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    // append arc to space
                    btr.AppendEntity(arc);
                    // add arc to transaction
                    tr.AddNewlyCreatedDBObject(arc, true);
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
                }
                finally
                {
                    //do nothing (optional)
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", osm);
                }
            }

        }

Pages: 1 2 [3] 4 5 ... 8