000

Index Labels

Dynamically Draw An Array Of Entities

.
One of the exciting things when an AutoCAD VBA programmer moves into AutoCAD .NET API world is that he/she suddenly gain a capability to create dynamic visual hint (ghost image) when the code ask user to interact with the drawing editor, namely the capability to create JIG. Besides, since AutoCAD 2009 introduced TransientGraphics, it is even easier do add visual hint in the code when the user has to interact with AutoCAD editor during code execution.

In this post I am going to show a piece of code that creates an array of entities in following operation steps:

1. User pick an entity he/she wants to create an array of copy of this entity;
2. The user does not know how many entities could fit into a space, but he/she has a desired distance between each 2 entities. Or the user simply does not bother to calculate how many entities could fit in, he/she just want to move the mouse and see how the array of entities fits in a give space. So, the user would enter a desired space increment for the entities in the array;
3. The user pick a base point;
4. The user moves the mouse around, the ghost image of an array of entities shows dynamically, which automatically show the count of entities in the array, depending on how far the mouse pointer is from the base point;
5. If user clicks the mouse again, an array of entity copies is created. If user cancels the pick for the second point, the ghost image is gone, no entity array is created.

There is a link at the bottom of this article that leads you to see a video clip of the result of running the code.

Again, I use TransientGraphics (I just love it!) to achieve my goal. Here is the code.

Firstly, I created an Interface IDynamicDrawTool. It is not a must. Currently, the code only create an array of entities along a straight line. Later I could create the array along an arc, circle...I would like all the later possible tool all implement this interface.

namespace DynamicDrawTool
{
public interface IDynamicDrawTool
{
void DrawEntities();
}
}

Then here is the command class:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[assembly: CommandClass(typeof(DynamicDrawTool.DynamicDrawCommands))]

namespace DynamicDrawTool
{
public class DynamicDrawCommands
{
[CommandMethod("DynDraw")]
public static void RunThisMethod()
{
Document dwg = Autodesk.AutoCAD.ApplicationServices.
Application.DocumentManager.MdiActiveDocument;

Editor ed = dwg.Editor;

//Pick and entity
PromptEntityOptions opt = new PromptEntityOptions
("\nPick a source entity:");

PromptEntityResult res = ed.GetEntity(opt);

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

IDynamicDrawTool drawTool = new LinearDynamicDrawTool(dwg, res.ObjectId);

try
{
drawTool.DrawEntities();

dwg.Editor.WriteMessage(
"\nMyCommand executed successfully.");
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
dwg.Editor.WriteMessage(
"\nMyCommand execution failed:\n" + ex.Message);
}
}
}
}

Finally, the code doing the real work:

using System;
using System.Collections.Generic;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;

namespace DynamicDrawTool
{
public class LinearDynamicDrawTool : IDynamicDrawTool
{
private Document _dwg;
private Editor _editor;
private ObjectId _sourceEntId;

private Point3d _startPoint;
private Point3d _endPoint;
private double _increment = 0.0;

private Line _guideLine = null;
private List _clonedEntities = new List();

private int _colorIndex = 1;
private int _originalColorIndex = 0;

public LinearDynamicDrawTool(Document dwg, ObjectId sourceEntId)
{
_dwg = dwg;
_editor = _dwg.Editor;
_sourceEntId = sourceEntId;
}

public int GuideLineColorIndex
{
set { _colorIndex = value; }
get { return _colorIndex; }
}

public void DrawEntities()
{
//Pick start point
if (!GetPoint("Pick start point:", out _startPoint)) return;

//Get incremting distance
if (!GetIncrement(out _increment)) return;

//Hook up to PointerMoniter event
_editor.PointMonitor +=
new PointMonitorEventHandler(_editor_PointMonitor);

try
{
//Pick end point
if (GetPoint("Pick end point:", out _endPoint))
{
//Draw real entities exactly as
//the transient graphics shows
AddEntities();
}
}
finally
{
//Clear transient graphics and remove PointMonitor handler
ClearTransientGraphics();
_editor.PointMonitor -= _editor_PointMonitor;
}
}

#region private methods: draw transient graphics

private void _editor_PointMonitor(
object sender, PointMonitorEventArgs e)
{
DrawTransientGrapgics(e.Context.RawPoint);
}

private void DrawTransientGrapgics(Point3d pt)
{
//Clear existing transient graphics
ClearTransientGraphics();

//Draw guideline
_guideLine = new Line(_startPoint, pt);
_guideLine.SetDatabaseDefaults(_dwg.Database);
_guideLine.ColorIndex = _colorIndex;

IntegerCollection col = new IntegerCollection();
TransientManager.CurrentTransientManager.AddTransient(
_guideLine, TransientDrawingMode.DirectShortTerm, 128, col);

//Draw cloned entities
DrawClonedEntityTransientGraphics(pt);
}

private void DrawClonedEntityTransientGraphics(Point3d pt)
{
//Calculate count of cloned entities
int count = CalculateCloneCount(pt);
if (count < 1) return;

Entity sourceEnt = GetSourceEntity();
_originalColorIndex = sourceEnt.ColorIndex;

//Draw cloned entities as transient graphics
for (int i = 1; i <= count; i++)
{
Entity ent = sourceEnt.Clone() as Entity;
ent.ColorIndex = _colorIndex;

//Move to target location
SetClonedEntityPosition(i, ent);

//Draw as transient graphics
IntegerCollection col = new IntegerCollection();
TransientManager.CurrentTransientManager.AddTransient(
ent, TransientDrawingMode.DirectShortTerm, 128, col);

_clonedEntities.Add(ent);
}
}

private int CalculateCloneCount(Point3d pt)
{
double dis = _startPoint.DistanceTo(pt);

if (dis <= _increment)
return 0;
else
return Convert.ToInt32(Math.Floor(dis / _increment));
}

private Entity GetSourceEntity()
{
Entity ent = null;

using (Transaction tran =
_dwg.Database.TransactionManager.StartTransaction())
{
ent = (Entity)tran.GetObject(_sourceEntId, OpenMode.ForRead);
tran.Commit();
}

return ent;
}

private void SetClonedEntityPosition(int index, Entity ent)
{
double dist = _increment * index;
Point3d pt = _guideLine.GetPointAtDist(dist);

ent.TransformBy(
Matrix3d.Displacement(_startPoint.GetVectorTo(pt)));
}

private void ClearTransientGraphics()
{
//Clear guide line
if (_guideLine != null)
{
IntegerCollection col = new IntegerCollection();
TransientManager.CurrentTransientManager.
EraseTransient(_guideLine, col);

_guideLine.Dispose();
_guideLine = null;
}

//Clear cloned entities
foreach (Entity ent in _clonedEntities)
{
if (ent != null)
{
IntegerCollection col = new IntegerCollection();
TransientManager.CurrentTransientManager.
EraseTransient(ent, col);

ent.Dispose();
}
}

_clonedEntities.Clear();
}

private void AddEntities()
{
using (DocumentLock lk = _dwg.LockDocument())
{
using (Transaction tran =
_dwg.Database.TransactionManager.StartTransaction())
{
BlockTableRecord br =
(BlockTableRecord)tran.GetObject(
_dwg.Database.CurrentSpaceId, OpenMode.ForWrite);

foreach (Entity ent in _clonedEntities)
{
Entity newEnt = ent.Clone() as Entity;
newEnt.SetDatabaseDefaults(_dwg.Database);
newEnt.ColorIndex = _originalColorIndex;

br.AppendEntity(newEnt);
tran.AddNewlyCreatedDBObject(newEnt, true);
}

tran.Commit();
}
}
}

#endregion

#region private methods: miscellaneous

private bool GetPoint(string prompt, out Point3d point)
{
point = new Point3d(0.0, 0.0, 0.0);

PromptPointOptions opt =
new PromptPointOptions("\n" + prompt);
opt.AllowNone = false;

PromptPointResult res = _editor.GetPoint(opt);

if (res.Status == PromptStatus.OK)
{
point = res.Value;
return true;
}

return false;
}

private bool GetIncrement(out double increment)
{
increment = 0.0;

PromptDoubleOptions opt =
new PromptDoubleOptions("\nIncrementing distance:");

PromptDoubleResult res = _editor.GetDouble(opt);

if (res.Status == PromptStatus.OK)
{
increment = res.Value;
return true;
}

return false;
}

#endregion
}
}

Click here to see the a video clip showing how it works.

Obviously, there are more can be done to improve it. I have exposed ColorIndex as public property so that we can set the color of guide line/ghost image of the entities prior to calling DrawEntities() method. We can also do the similar thing to set LineWeight or line width (if it is polyline), LineType (use dash line would be more in line with AutoCAD standard).

Of course the user input part could also be enhanced to allow user to try different distance increment during mouse move.

Blog Archive

Labels

.NET Programming 2D Drafting 3D Animation 3D Art 3D Artist 3D design 3D effects 3D Engineering 3D Materials 3D Modeling 3D models 3D presentation 3D Printing 3D rendering 3D scanning 3D scene 3D simulation 3D Sketch Inventor 3D Texturing 3D visualization 3D Web App 3ds Max 4D Simulation ACC Adaptive Clearing adaptive components Add-in Development Additive Manufacturing Advanced CAD features Advanced Modeling AEC Technology AEC Tools affordable Autodesk tools AI AI animation AI Assistance AI collaboration AI Design AI Design Tools AI Experts AI for Revit AI Guide AI in CAD AI in CNC AI in design AI in engineering AI in Manufacturing AI in Revit AI insights AI lighting AI rigging AI Tips AI Tools AI troubleshooting AI workflow AI-assisted AI-assisted rendering AI-Assisted Workflow AI-enhanced Animation animation pipeline animation tips Animation workflow annotation Annotation Scaling AR architectural design architectural modeling architectural preservation architectural visualization Architecture architecture design Architecture Engineering Architecture Firm Architecture Productivity architecture software architecture technology Architecture Workflow Arnold Renderer Arnold Shader Artificial Intelligence As-Built Model Asset Management augmented reality AutoCAD AutoCAD advice AutoCAD API AutoCAD Basics AutoCAD Beginner AutoCAD Beginners AutoCAD Civil 3D AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD Expert Advice AutoCAD features AutoCAD File Management AutoCAD Layer AutoCAD Layers AutoCAD learning AutoCAD print settings AutoCAD productivity AutoCAD Teaching AutoCAD Techniques AutoCAD tips AutoCAD tools AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk 2026 Autodesk 3ds Max Autodesk AI Autodesk AI Tools Autodesk Alias Autodesk AutoCAD Autodesk BIM Autodesk BIM 360 Autodesk Certification Autodesk Civil 3D Autodesk Cloud Autodesk community forums Autodesk Construction Cloud Autodesk Docs Autodesk Dynamo Autodesk features Autodesk for Education Autodesk Forge Autodesk FormIt Autodesk Fusion Autodesk Fusion 360 Autodesk help Autodesk InfraWorks Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Knowledge Network Autodesk License Autodesk Maya Autodesk mistakes Autodesk Navisworks Autodesk news Autodesk plugins Autodesk productivity Autodesk Recap Autodesk resources Autodesk Revit Autodesk Software Autodesk support ecosystem Autodesk Takeoff Autodesk Tips Autodesk training Autodesk tutorials Autodesk update Autodesk Upgrade Autodesk Vault Autodesk Video Autodesk Viewer Automated Design Automation Automation Tutorial automotive design automotive visualization Backup Basic Commands Basics Batch Plot Beginner Beginner Tips beginner tutorial beginners guide Big Data BIM BIM 360 BIM Challenges BIM collaboration BIM Compliance BIM Coordination BIM Data BIM Design BIM Efficiency BIM for Infrastructure BIM Implementation BIM Library BIM Management BIM modeling BIM software BIM Standards BIM technology BIM tools BIM Trends BIM workflow Block Editor Block Management Block Organization Building Design Software Building Efficiency Building Maintenance building modeling Building Systems Building Technology ByLayer CAD CAD API CAD assembly CAD Automation CAD Blocks CAD CAM CAD commands CAD comparison CAD Customization CAD Data Management CAD Design CAD errors CAD Evolution CAD File Size Reduction CAD Integration CAD Learning CAD line thickness CAD management CAD Migration CAD mistakes CAD modeling CAD Optimization CAD plugins CAD Productivity CAD Rendering CAD Security CAD Skills CAD software CAD software 2026 CAD software training CAD standards CAD technology CAD Tips CAD Tools CAD tricks CAD Tutorial CAD workflow CAM CAM strategies car design software Case Study CEO Guide CGI design Character Rig cinematic lighting Civil 3D Civil 3D hidden gems Civil 3D productivity Civil 3D tips civil design software civil engineering Civil engineering software Clash Detection Class-A surfacing clean CAD file cleaning command client engagement Cloud CAD Cloud Collaboration Cloud design platform Cloud Engineering Cloud Management Cloud Storage Cloud-First CNC CNC machining collaboration command abbreviations Complex Renovation concept car conceptual workflow Connected Design construction Construction Analytics Construction Automation Construction BIM Construction Cloud Construction Planning Construction Scheduling Construction Technology contractor tools Contractor Workflow Contraints corridor design Cost Effective Design cost estimation Create resizable blocks Creative Teams CTB STB Custom visual styles Cutting Parameters Cybersecurity Data Backup data management Data Protection Data Reference Data Security Data Shortcut Design Automation Design Career Design Collaboration Design Comparison Design Coordination design efficiency Design Engineering Design Hacks Design Innovation design optimization Design Options design productivity design review Design Rules design software design software tips Design Technology design tips Design Tools Design Workflow design-to-construction Designer Designer Tools Digital Art Digital Assets Digital Construction Digital Construction Technology Digital Content Digital Design Digital engineering digital fabrication Digital Manufacturing digital marketing digital takeoff Digital Thread Digital Tools Digital Transformation Digital Twin Digital Twins digital workflow dimension dimensioning Disaster Recovery drafting drafting automation Drafting Efficiency Drafting Shortcuts Drafting Standards Drafting Tips Drawing Drawing Automation drawing tips Dref Dynamic Block Dynamic Block AutoCAD Dynamic Blocks Dynamic doors Dynamic windows Dynamics Dynamo Dynamo automation early stage design eco design editing commands Electrical Systems Emerging Features Energy Analysis energy efficiency Energy Simulation Engineering Engineering Automation engineering data Engineering Design Engineering Innovation Engineering Productivity Engineering Skills engineering software Engineering Technology engineering tools Engineering Tools 2025 Engineering Workflow Excel Export Workflow Express Tools External Reference facial animation Facial Rigging Facility Management Families Fast Structural Design Field Documentation File Optimization File Recovery Fire Flame flange tips flat pattern Fluid Effects Fluid Simulation Forge Development Forge Viewer FreeCAD Fusion 360 Fusion 360 API Fusion 360 tutorial Future of Design Future Skills Game Development Gamification Generative Design Geospatial Data GIS Global design teams global illumination GPU Acceleration grading optimization Green Architecture green building Green Technology Grips Handoff HDRI health check Healthcare Facilities heavy CAD file Heavy CAD Files heritage building conservation hidden commands Hospital Design HVAC HVAC Design Tools HVAC Engineering HVAC Optimization Hydraulic Modeling IK/FK iLogic Import Workflow Industry 4.0 Infrastructure infrastructure design Infrastructure Monitoring Infrastructure Planning Infrastructure Technology InfraWorks innovation Insight intelligent modeling Interactive Design interactive presentation Interior Design Inventor Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Inventor Tutorial IoT ISO 19650 joints Keyboard Shortcuts keyframe animation Keyframe generation Landscape Design Large Projects Laser Scan Layer Management Layer Organization Learn AutoCAD Legacy CAD Licensing light techniques Lighting and shading Lighting Techniques Linked Models Liquid Machine Learning Machine Learning in CAD Machine Optimization Machining Efficiency machining productivity maintenance command Management manufacturing Manufacturing Innovation Manufacturing Technology Mapping Technology marketing visuals Material Creation Maya Maya character animation Maya lighting Maya Shader Maya Tips Maya tutorial measurement Mechanical Design Mechanical Engineering Media & Entertainment MEP MEP Modeling Mesh-to-BIM Metal Structure modal analysis Model Management Model Optimization Modeling Secrets Modular Housing Motion capture motion graphics motion simulation MotionBuilder Multi Office Workflow multi-axis machining Multi-User Environment multileader Navisworks Navisworks Best Practices Net Zero Design ObjectARX .NET API Open Source CAD Organization OVERKILL OVERKILL AutoCAD Page Setup Palette Parametric Components parametric design parametric family Parametric Modeling particle effects particle systems PDF PDM system Personal Brand Phasing PlanGrid Plot Settings Plot Style Plot Style AutoCAD Plotting Plugin Tutorial Plumbing Design point cloud Portfolio Post Construction Post-Processing Practice Drawing precision machining preconstruction workflow predictive analysis predictive animation Predictive Maintenance Predictive rigging Prefabrication Presentation-ready visuals Printing Printing Quality Problem Solving Procedural animation procedural motion Procedural Rig Procedural Textures Product Design Product Development product lifecycle product rendering Productivity productivity tools Professional 3D design Professional CAD Professional Drawings professional printing Professional Tips Project Documentation project efficiency project management Project Management Tools Project Visualization PTC Creo PURGE PURGE AutoCAD Rail Transit Rapid Prototyping realistic rendering ReCap Redshift Shader reduce CAD file size Render Render Passes Render Quality Render Settings Rendering rendering engine Rendering Engines Rendering Optimization rendering software Rendering Tips Rendering Workflow RenderMan Renewable Energy Renovation Project Renovation Workflow Reports Resizable Block restoration workflow Revit Revit add-ins Revit API Revit automation Revit Best Practices Revit Collaboration Revit Documentation Revit Family Revit integration Revit MEP Revit Performance Revit Phasing Revit Plugins Revit Scripting Revit skills Revit Standards Revit Template Revit Tips Revit tutorial Revit Workflow Ribbon Rigging Rigid Body robotics ROI Scale Autodesk Schedules screen Sculpting Secure Collaboration Sensor Data Shader Networks Sheet Metal Design Sheet Metal Tricks Sheet Set Manager shortcut keys Shortcuts Siemens NX Simulation simulation tools Sketch Sketching Tricks Small Firms Smart Architecture Smart Block Smart Building Design Smart City Smart Design smart dimensioning Smart Engineering Smart Factory Smart Infrastructur Smoke Soft Body Software Compliance software ecosystem Software Management Software Trends software troubleshooting Software Update Solar Energy Solar Panels SolidWorks Startup Design static stress Steel Structure Design Structural Optimization subscription model Subscription Value surface finish Surface Modeling sustainability sustainable design Sustainable Manufacturing system performance T-Spline team training guide Technical Drawing technical support Template Setup text style Texture Mapping Texturing thermal analysis Time Management time saving tools Title Blocks toolbar toolpath Toolpath Optimization Toolpaths Topography Troubleshooting Tutorial Tutorials urban planning User Interface (UI) UV Mapping UV Unwrap V-Ray Vault Best Practices Vault Lifecycle Vault Mistakes Vector Plotting vehicle modeling VFX Viewport configuration Virtual Environments virtual reality visual effects visualization workflow VR VR Tools VRED Water Infrastructure Water Management Weight Painting What’s New in Autodesk Wind Energy Wind Turbines Workbook workflow Workflow Automation workflow efficiency Workflow Optimization Workflow Tips Worksets Worksharing Workspace XLS Xref Xrefs เขียนแบบ