The parabola and the polyline

The Autocad VBA polyline uses a single array with an index large enough and only large enough to contain x and y values for every point in the polyline. The array is filled in the loop, then the polyline is drawn with a single statement outside the loop. The only difference between AddLightWeightPolyline and AddPolyLine is the former takes only x and y and the latter x, y and z. Make a mental note we can make the plots 3D later. For now we will use the 2D polyline.

The critical items are dimensioning the array of doubles with the right number, and controlling the loop that fills the array. The loop is controlled by the numpts integer variable which is calculated from max_x, min_x and x_inc. That gives the number of line segments. One is added to it to give the number of points. The dynamic array to hold the points is then dimensioned with numpts times 2, to give space for both x and y values.

This looks good for the loop counter, straightforward and logical,
For x = min_x To max_x Step x_inc
but there can be a rounding error and early exit with a floating point counter.
So we derive the same number and put it into the integer numpts
and remember the rule – control for next loops with an integer.

Sub testparabola()
Call connect_acad
Call parabola(-3, 3, 2, 3, 4, 0.1)
Call parabola(-3, 3, 1, 0, 0, 0.1)
End Sub

Sub parabola(min_x As Double, max_x As Double, a As Double, b As Double, c As Double, x_inc As Double)
'y = ax^2 + bx + c
Dim x As Double, y As Double
Dim i As Integer, numpts As Integer

Dim plineobj As AcadLWPolyline
Dim pt() As Double

numpts = (max_x - min_x) / x_inc 'this is the number of line segments
numpts = numpts + 1  'there is always one more pt than line segment
ReDim pt(1 To numpts * 2) 'to store both x and y for one pt

For i = 1 To numpts
x = min_x + ((i - 1) * x_inc)
y = a * x ^ 2 + b * x + c
pt(i * 2 - 1) = x: pt(i * 2) = y
Next i

Set plineobj = acadApp.ActiveDocument.ModelSpace.AddLightWeightPolyline(pt)
End Sub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.