SuperAPI AI Directory

autocad-automation

General & other

View repository

Updated 10-16 08:11

About this skill

AutoCAD automation skill

This directory serves as the solidworks-automation-skill AutoCAD/DWG sub-skill. The parent skill handles SolidWorks modeling, assembly, engineering drawings, and 3D export; this sub-skill handles AutoCAD 2D DWG/DXF drafting, batch drawing modification, line art vectorization, plot previews, and drawing self-checks. When native SolidWorks part/assembly modeling is involved, return to the parent skill; when AutoCAD drawings or DWG/DXF are involved, read this sub-skill.

Objectives

Enable the agent to reliably control AutoCAD in the local Windows desktop environment, rather than improvising commands from memory each time. The default route is Python + COM/ActiveX, but native writes must first pass the capabilities.yaml gate and local real-machine regression; the current AutoCAD 2024 Documents/Layers/SelectionSets dynamic proxies are unstable, so native COM DWG drafting is handled as not_implemented . Headless DXF reading, preview, and structural review can be used directly. The AutoCAD 2024 .NET whitelist backend has continuously passed real DWG save-reopen, PDF/PNG, and entity/layer/dimension regression; when runtime evidence is complete, it is verified; only fixed commands are allowed and must not be generalized into arbitrary code execution.

Applicable scenarios

Use this skill to handle:

  • Create or modify DWG/DXF drawings, drawing lines, circles, arcs, polylines, rectangles, text, blocks, layers, and simple dimensions.
  • Batch-open DWGs, check layers, entity counts, text, block references, external references, or output files.
  • Let Codex directly connect to the local AutoCAD, save DWGs, export DXF/PDF, and generate review reports.
  • Write AutoLISP,.scr command scripts, or C# AutoCAD .NET plugins.
  • Need to look up Autodesk official APIs, ADN/GitHub examples, ObjectARX SDK, or APS Design Automation patterns.

Do not use this skill for pure rendering visualizations, BIM/Revit models, mechanical STEP-first modeling, CAM toolpaths, or engineering certification conclusions; these needs should be prioritized to the corresponding CAD, BIM, simulation, or manufacturing workflows.

Default assumptions

  • Operating system: Windows.
  • AutoCAD: already installed on the user's machine, preferably manually launched once to complete COM registration.
  • Automation entry point:AutoCAD.Application COM ProgID。
  • Visualization default: new drafting tasks default to first showing and activating AutoCAD, then progressively placing entities; only disable this for batch processing or when the user explicitly requests speedup.
  • Drawing units: understood as millimeters by default; the AutoCAD database itself is unitless numeric values, so units must be recorded in the drawing notes.
  • Space: geometry goes into ModelSpace by default; layouts, title blocks, and plot configurations are handled separately.
  • Coordinates: WCS by default, 2D objects use Z=0。
  • Output: prefer saving DWG, while exporting DXF/PDF according to user needs; all output paths use absolute paths.
  • File safety: before modifying an existing DWG, save a copy first, unless the user explicitly allows overwriting.

When version, units, drawing standards, output paths, or whether overwriting is allowed are missing, first make a brief confirmation. For simple sketches, you may directly assume millimeters, ModelSpace, and a new DWG, and state this in the result.

Entry self-check

Before executing AutoCAD automation, first run:

python subskills\autocad-automation\scripts\acad_preflight.py

If the user allows AutoCAD to start automatically:

python subskills\autocad-automation\scripts\acad_preflight.py --launch

When self-check fails:

  • Missing pywin32: prompt the user to install python -m pip install pywin32, and install only after obtaining explicit consent.
  • AutoCAD COM not found: prompt the user to install AutoCAD, launch AutoCAD once, or confirm that the installed version is LT/a restricted environment.
  • AutoCAD is running but has no active document: a new document can be created; do not misjudge this as a connection failure.

Core workflow

  1. Classify the task: determine whether it is creating a new drawing, modifying an existing DWG, batch processing, plotting/exporting, API development, plug-in development, or troubleshooting.
  2. Confirm key constraints: units, version, target file, output format, whether overwriting is allowed, layer/linetype/dimension standards, and whether drawing according to the enterprise template is required.
  3. Run the self-check: first use acad_preflight.py to confirm the Python COM and AutoCAD status.
  4. Verify the API: for APIs that have not been wrapped, you must first read references/api-lookup.md, then check Autodesk official documentation or trusted GitHub examples; do not guess long parameters, enum values, or command behavior.
  5. Formulate a drawing plan: specify layers, coordinate datum, object list, dimensions, text, output path, and review points.
  6. Start the software first: connect to or launch AutoCAD, ensure the window is visible and bring it to the foreground as much as possible, then begin drawing.
  7. Prefer reusing scripts: for simple geometry, use the JSON input of scripts/acad_draw.py ; for complex logic, use scripts/acad_session.py combined with COM calls.
  8. Execute COM serially: do not parallelize AutoCAD desktop COM operations; one script should connect, draw step by step, save, review, and then exit.
  9. Save and export: before saving DWG/DXF/PDF, ensure the directory exists; when modifying the original drawing, keep a backup or save as a new file.
  10. Review the results: run scripts/acad_review.py to count entities, layers, bounding boxes, and target files; then run scripts/acad_preview.py to export AutoCAD native BMP/PNG previews, and use an image viewing tool for visual review. Window screenshots can be supplementary, but if they are obscured by other windows, they cannot be used as a basis for passing. If the input is DXF and only a headless read-only check is needed, you can first run scripts/acad_headless.py; it does not support DWG writing, and the final DWG/PDF must still go through AutoCAD COM.
  11. Accumulate experience: when encountering new pitfalls, command differences, version limitations, or stable wrappers, add them to references/troubleshooting.md or the script.

Hard requirements for mechanical part drawings and 3D printing hole drawings

When the user requests "strictly comply with the specification", "a format that Chinese people normally like", "national standard drawings", "machining drawings", "3D printing holes", or similar mechanical drafting deliverables, it must be handled as a mechanical drawing rather than a schematic:

  1. Prefer the user's or enterprise template; if there is no template, produce drawings in the commonly used domestic GB/T style, including at least A3/A4 sheet sizes, binding edge, lower-right title block, FangSong Chinese text, and separate layers for thick continuous lines/thin continuous lines/centerlines/dashed lines/dimensions/text/holes, and state clearly in the delivery notes that it "references the national standard style and does not replace enterprise drawing review".
  2. All actual cuts, holes, slots, interfaces, gates, screw holes, and screw bosses must be given both specifications and positioning dimensions. Writing only 4×φ3.4、7×4×30、2×φ13.5 without relative datum edges, center distances, pitches, or height positioning is considered incomplete.
  3. When holes/slots are dense or would cause long leaders to cross views, prioritize using a "hole/slot detail table / hole table / slot table"; the table must at least include location, specification, quantity, and positioning; the drawing's dimension lines are responsible for key datums, center distances, and overall dimensions.
  4. Arbitrary long leaders are not allowed to replace dimension chains; leaders must not cross other views, centerlines, hole contours, or dimension text. When clean annotation is impossible, move the view, split the view, or switch to a table.
  5. 3D printed enclosure drawings must clearly dimension wall thickness, bottom thickness, overall external dimensions, interface opening dimensions, interface center positioning, assembly hole center distances, and sprue/heat dissipation slot positioning; otherwise users cannot open holes according to the drawing.
  6. Annotation must prioritize using AutoCAD real dimension entities, such as AcDbRotatedDimension, do not hand-draw dimension lines to impersonate dimensions.
  7. Visual acceptance cannot rely only on entity statistics. You must export a preview and visually inspect: whether dimensions are missing, whether text overlaps, whether dimension lines press on views, whether leaders cross views, whether hole tables are readable, and whether the title block is intruded by dimensions. If problems are found, rework first before reporting.

Codex Direct Drawing

For simple tasks, Codex can generate a drawing JSON, then call:

python subskills\autocad-automation\scripts\acad_draw.py `
  --input C:\temp\plate_plan.json `
  --output C:\temp\plate.dwg `
  --new

This entry point defaults to "visible step-by-step drawing" mode: it will first open or switch to AutoCAD, then draw entities little by little. Only for batch tasks, when playback is too slow, or when the user explicitly requests speed, add --fast:

python subskills\autocad-automation\scripts\acad_draw.py `
  --input C:\temp\batch_plan.json `
  --output C:\temp\batch.dwg `
  --new `
  --fast

JSON structure example:

{
  "units": "mm",
  "live_preview": true,
  "live_zoom_every": 6,
  "layers": [
    {"name": "OUTLINE", "color": 7},
    {"name": "CENTER", "color": 1},
    {"name": "TEXT", "color": 3}
  ],
  "entities": [
    {"type": "rectangle", "origin": [0, 0], "width": 120, "height": 80, "layer": "OUTLINE"},
    {"type": "circle", "center": [20, 20, 0], "radius": 4.5, "layer": "CENTER"},
    {"type": "text", "text": "MOUNTING PLATE", "point": [8, 88, 0], "height": 5, "layer": "TEXT"}
  ]
}

Use Python for complex tasks:

import sys
sys.path.insert(0, r"subskills\autocad-automation\scripts")
from acad_session import AutoCADSession

session = AutoCADSession(create_if_missing=True, visible=True).connect()
session.new_document()
session.activate_window()
session.create_layer("OUTLINE", color=7)
session.add_rectangle((0, 0), width=120, height=80, layer="OUTLINE")
session.live_update(step_delay_s=0.15, zoom=True)
session.save_as(r"C:\temp\plate.dwg")

Technical Route Selection

Requirement Preferred route Description
Quick drawing, drawing modification, batch inspection Python COM/ActiveX Default route for this skill, can be executed directly by Codex through shell
Execute AutoCAD commands, invoke existing command habits SendCommand / .scr / AutoLISP Commands may be asynchronous; results must be saved and reviewed
Large numbers of database transactions, complex selection filtering, plugin menus AutoCAD .NET Suitable for C# plugins; follow the official .NET Developer Guide for transactions and document locking
High-performance native extensions, deep database/graphics system ObjectARX C++ High cost, strong version binding; confirm necessity first
Cloud batch processing DWG APS Design Automation Suitable for headless, batch production, or CI, but requires Autodesk APS credentials

Engineering Rules

  • Create layers before drawing, use ACI numbers for colors; do not pile all objects onto the 0 layer.
  • Clarify units and scale, draw 1:1 in model space; put print scale in Layout/Plot.
  • Write key parameters such as coordinates, dimensions, text height, and hole diameters as variables; do not scatter magic numbers throughout the code.
  • For mechanical drawings, do not treat "understandable" as "manufacturable". Holes and slots must have reviewable datums and complete positioning dimensions; when drawing space is insufficient, use hole tables/slot tables, do not fool people with flying-lead-style exported text.
  • When generating line art from images, the final delivery of ordinary "draw CAD by copying the picture" must be based on vectorized lines from the original image. Do not use large arcs, long polylines, ellipses, triangles, colored wavy lines, substitute text, or other manually guessed elements to fill in character contours, facial features, logos, clothing folds, or splashes; these lines easily look like erroneous CAD construction lines, and users will interpret them as "what is all this".
  • If, for positioning, debugging, or temporary enhanced recognition, you have drawn BODY_OUTLINE、JERSEY_OUTLINE、PORTRAIT_OUTLINE、OUTER_GUIDE、CONSTRUCTION、FACE_FEATURES、LOGO_GEOMETRY、WATER_SPLASH、JERSEY_STRIPE、TEXT_LOGO、TEXT_BRAND and other construction/enhancement layers must be deleted, frozen, turned off, or set to non-plotting before final saving, previewing, and scoring, and must be confirmed as invisible with an entity count of 0 in the preview and layer statistics.
  • Only when the user explicitly requests creative modifications such as "restructure the logo," "enhance the facial features," "add water splashes," or "add text/annotations" may manually enhanced layers be retained; before retaining them, explain that these are not natural vector lines of the original image, and prefer using independent layers so they can be turned off with one click.
  • Put review notes, scores, and generation parameters into a JSON/Markdown report; do not write them as visible text into the final CAD model space unless the user explicitly requests in-drawing annotations.
  • COM-returned objects must be checked, and after saving/exporting, check whether the file exists and whether its size is reasonable.
  • SendCommand is a last resort; prefer calling object model methods, and command scripts should use the _.COMMAND form to reduce the impact of the interface language.
  • When the user explicitly says "I want to watch it draw," do not generate silently in the background; first open AutoCAD and bring it to the foreground, then place entities step by step.
  • SelectionSet names may persist; delete any selection set with the same name before creating one.
  • When batch processing DWGs, use a separate try/finally for each drawing, and on failure record the file name, error, and stage.
  • By default, open the user's original drawing read-only or save a copy; overwriting must have explicit authorization.
  • Do not expose arbitrary Python/VBA/AutoLISP execution entry points as general MCP tools; if building an MCP, provide only whitelisted drawing/export/review tools.

GitHub and Official Documentation Strategy

Preferred sources:

  • Autodesk AutoCAD API overview, ActiveX/VBA, Managed .NET, ObjectARX, and APS official documentation.
  • ADN-DevTech / Autodesk Platform Services GitHub examples.
  • pyautocad and other mature open-source projects can be referenced for coordinate, iteration, and COM wrapper patterns, but do not copy code with unclear licenses.
  • Forums, blogs, and Stack Overflow are only supplementary for troubleshooting; key APIs should still be confirmed against official documentation.

When sources conflict, the official documentation for the target AutoCAD version and local test results take precedence.

Progressive Reference

Read on demand; do not stuff the entire context at once:

  • references/api-lookup.md: official documentation, GitHub examples, and API verification routes.
  • references/engineering-patterns.md: senior engineer experience with drawing, layers, units, blocks, annotations, and batch processing.
  • references/troubleshooting.md: troubleshooting for COM, AutoCAD sessions, SendCommand, saving/exporting, and version issues.

Acceptance and Reporting

After completing AutoCAD operations, the final reply must include:

  • Input assumptions: units, version, template, whether to create new/modify the original drawing.
  • Output files: absolute paths of DWG/DXF/PDF/JSON reports and BMP/PNG previews.
  • Verification actually performed: self-check, entity statistics, layer statistics, bounding box, save/export checks, AutoCAD native preview image review; when generating line art from an image, also confirm that the final preview shows no extra peripheral auxiliary contour lines, internal auxiliary geometry, colored decorative lines, or in-drawing review notes; if window screenshots are used, also state whether there is any occlusion.
  • Items still requiring manual confirmation: title block, printer, company standards, line weights, fonts, scale, professional drawing review.