Search

How to automatically generate a cutting list for your 3D model in AutoCAD.

January 14, 2024

In the dynamic world of AutoCAD customization, the ability to automate tedious tasks can significantly enhance productivity and streamline design workflows. I recently created a 3D wardrobe in AutoCAD and had a need to create a cutting list for my model. Considering that I will be doing this task for various designs, doing it manually was not an option. In this post, I will share with you how to automate this task using the AutoCAD .NET API.

As a prerequisite, you must have a Visual Studio and AutoCAD installed on your system.

In a previous video on my YouTube Chanel, I demonstrated how to create your first plugin for AutoCAD.

This tutorial is built upon the foundation laid in our previous video, where we set up the project in Visual Studio, this tutorial focuses on a main method called "CuttingList" with the CommandMethod attribute and introduces two essential private methods.

The first method, named "GetElementInfo," plays a crucial role in extracting key information from the model elements—length, width, height, layer, and material. This information is intelligently stored in a dictionary, laying the groundwork for our cutting list.

The second method, "CreateCuttingListTable," takes the extracted data and transforms it into a comprehensive table directly within the AutoCAD environment. Imagine the time saved and the potential for accuracy improvement as this automated process replaces manual compilation.

Without any further delay, let's get started.

Step 1 : Project setup in Visual Studio

Please refer to this video on my YouTube Channel: Create Your First Plugin for AutoCAD

Step 2 : Implementation  of  GetElementInfo Method

This method is responsible for extracting the element's information from the 3D model and stored in a dictionary for further processing. It takes two parameters:

  • An objectId: the id of the element we need the information from.
  • A string : this is a Ref parameter ; the key to be used for our dictionary.

This method returns a tuple containing the Length, Width and Height of the element under consideration.

  private Tuple<double,double,double> GetElementInfo(ObjectId id,ref string key)
        {
            var dims=new Tuple<double,double, double>(0,0,0);    
            using(Transaction tr=id.Database.TransactionManager.StartTransaction())
            {
                var dbobj = tr.GetObject(id, OpenMode.ForRead);

                if(dbobj != null && dbobj is Solid3d solid3D)
                {
                    //Get the bounding box of the current element
                    Extents3d ext = (Extents3d)solid3D.Bounds;

                    // Calculate the required dimensions
                    double Length = ext.MaxPoint.X - ext.MinPoint.X;
                    double Width = ext.MaxPoint.Y - ext.MinPoint.Y;
                    double Height = ext.MaxPoint.Z - ext.MinPoint.Z;

                    dims=Tuple.Create(Length, Width, Height);

                    //Assigning the value of the dictionary string Key
                    key = $"{Length:F2},{Width:F2},{Height:F2},{solid3D.Layer},{solid3D.Material}";

                }

                tr.Commit();
            }

            return dims;
        }
Step 3 : Implementation  of  CreateCuttingListTable Method

This method is responsible for creating a table in AutoCAD and populate it with the dictionary content.

It takes two parameters:

  • A Database: the database of the current AutoCAD document.
  • A Dictionary : the dictionary of the information of all the elements of our model.
 private void CreateCuttingListTable(Database db,Dictionary<string,List<Tuple<double,double,double>>> GroupedElements)
        {
            using(Transaction tr=db.TransactionManager.StartTransaction())
            {
                BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord blktblrecord = tr.GetObject(blockTable[BlockTableRecord.ModelSpace],OpenMode.ForWrite) as BlockTableRecord;

                Table tbl = new Table();
                tbl.TableStyle = db.Tablestyle;
                tbl.SetSize(GroupedElements.Count + 1, 6);

                tbl.Cells[0, 0].TextString = "Length";
                tbl.Cells[0, 1].TextString = "Width";
                tbl.Cells[0, 2].TextString = "Height";
                tbl.Cells[0, 3].TextString = "Layer";
                tbl.Cells[0, 4].TextString = "Material";
                tbl.Cells[0, 5].TextString = "Count";

                if (tbl.Rows[0].IsMerged.HasValue)
                {
                    tbl.UnmergeCells(tbl.Rows[0]);
                }

                int rowindex = 1;
                foreach (var item in GroupedElements)
                {
                    string[] key=item.Key.Split(',');

                     string length = key[0];
                    string width = key[1];
                    string height = key[2]; 
                    string layer = key[3];
                    string material= key[4];
                    int count=item.Value.Count;

                    tbl.Cells[rowindex, 0].TextString = length;
                    tbl.Cells[rowindex, 1].TextString = width;
                    tbl.Cells[rowindex, 2].TextString = height;
                    tbl.Cells[rowindex, 3].TextString = layer;
                    tbl.Cells[rowindex, 4].TextString = material;
                    tbl.Cells[rowindex, 5].TextString = count.ToString();

                    rowindex++;
                }

                tbl.Columns[0].Width = 30;
                tbl.Columns[1].Width = 30;
                tbl.Columns[2].Width = 30;
                tbl.Columns[3].Width = 50;
                tbl.Columns[4].Width = 50;
                tbl.Columns[5].Width = 30;

                blktblrecord.AppendEntity(tbl);
                tr.AddNewlyCreatedDBObject(tbl, true);

                tbl.Position=new Autodesk.AutoCAD.Geometry.Point3d(0, 0, 0);

                tbl.GenerateLayout();


                tr.Commit();

            }
        }
Step 4 : Implementation  of  the main Method : CuttingList

This is the entry point of our plugin and the previous methods are called withing this method. It selects all the elements of our model then loop through the selection set and extract the required information for each element of the model by calling the GetElementInfo method on each element. This information is then stored in a dictionary.

Once the process of extracting the information is completed, the CreateCuttingListTable  method is called to display the information in AutoCAD.

 

[CommandMethod("CL")]
        public void CuttingList()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed=doc.Editor;
            Database db=doc.Database;

            var result=ed.SelectAll();

            Dictionary<string, List<Tuple<double, double, double>>> GroupedElements = new Dictionary<string, List<Tuple<double, double, double>>>();


            for (int i = 0; i < result.Value.Count; i++)
            {
                string key = null;

                var dims = GetElementInfo(result.Value[i].ObjectId,ref key);
                 
                if(key!=null)
                {
                    if(!GroupedElements.ContainsKey(key))
                    {
                        GroupedElements.Add(key, new List<Tuple<double, double, double>>());
                    }

                    GroupedElements[key].Add(dims);
                }

            }

           CreateCuttingListTable(db, GroupedElements);
        }

 

Now, the only thing left is to build the project and test our code in AutoCAD by using the command NETLOAD.

Please try the above code and let me know your thought.

Check out the YouTube Video for this Tutorial.

Next week I would post a tutorial on how to export any table in AutoCAD to Excel.

I hope you enjoyed this tutorial.

  • Version 1.0.0
  • Download
  • File Size 2.46 MB
  • File Count 1
  • Create Date January 14, 2024
  • Last Updated April 15, 2024
FilePasswordAction
FirstPluginForAutocad.zipDownload

If you believe my tools are helping you and would like to support me, please use the below button to donate.

Sharing is caring:

Leave a Reply

Your email address will not be published. Required fields are marked *