INDIRA COLLEGE OF ENGINEERING AND MANAGEMENT
AutoLISP Lessons Compiled by Swapnil A. Kale & Sachin B. Gawade Department of Mechanical Engineering, ICEM
[S.E.Mech.]
Z:Swapnil A. Kale/MDCG/LISP/Notes2
AutoLISP AN INTRODUCTION Auto LISP is a dialect of the LISP programming languages (LIST processing ) . LISP is the oldest high-level programming language, second only to FORTRAN. LISP has been the language of choice for the artificial intelligence in robotics. It is built into Auto-cad. It is an integral part of AutoCAD and can only be used after acquiring a through knowledge of this software since AutoCAD commands are used in the Auto LISP for drawing , without a familiarity with the AutoCAD commands, an auto LISP program cannot be constructed . it is based on the LISP programming language which is simple to learn and very powerful. Auto LISP closely resemble the syntax and convention of LISP. Auto LISP is subset of LISP, having many additional function specified to AutoCAD What is program? A program is a list of instructions for your computer to carry out . What you need? To program in LISP you will need a text editor capable of saving files in ASCII format, and AutoCAD to run *.lsp file you create. Programming Phases
1) Problem defining 2) Requirements analysis 3) Arch Archit itec ectu ture re 4) Cons Constr tru uctio ction n 5) Sys System tem tes testi tin ng Auto LISP is a powerful tool at the hands of a design engineer. Those who have some proficiency in AutoCAD know how it is possible to draw lines, c urves, polyline, circle, spheren, boxen , and various other objects by using AutoCAD command prompt. All these may be parts of the drawing of a big engineering object. To draw a large object a user has to replicate replicate several smaller object which is time consuming and monotonous. Consider another aspect. Say you have drawn the front view of a steam stop valve by AutoCAD. Now if it is required to draw the same object with some modification in dimension or shape or something else, you have to start a new and do almost the same repetitive job. To avoid such tedious works you can write a computer a program , which may to do all sorts of of modifications. Auto LISP is such a high-level computer language supported by AutoCAD. “Auto LISP programs are parametric. All functions are used in parenthesis (round brackets ’()’). All brackets should be evenly closed. Function and symbol names are not case sensitive and thus both upper and lower case letters can be used. The expressions can multiple lines.” LISP CAN ONLY BE USED AFTER ACQUIRING A THOROUGH KNOWLEDGE OF AUTOCAD SOFTWARE.
Mr. Swapnil A. Kale Department of Mechanical Engineering Engineering “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes3
The AutoLISP environment The AutoLISP environment is entered when AutoCAD receives a "(" symbol at the command line. When AutoCAD sees the opening parentheses, it runs the AutoLISP interpreter. The interpreter then evaluates, as a list, what is between the opening "(" symbol and the closing ")" symbol. Data types There are three basic data types in AutoLISP. They are functions, symbols, and lists. Function: is the first item in every list. The remainder of the list is used as the parameters or arguments to the function. If the first item in the list is not a function you will re ceive an error message stating: "bad function." Symbol: is what other programming languages call a variable, and from this point on when I refer to a variable I am really talking about a symbol. A symbol in LISP however can be a whole lot more than just a value, as a normal variable would hold. A symbol can contain a list or a function definition. A symbol has a value bound to it. If it has no binding it is said to be "nil". All symbols should be set to nil upon ending a program or encountering an e rror. List: is anything that is not a symbol. Errors If an error occurs while running an AutoLISP program, the interpreter will return a trace of the function starting with the most recent function and continuing to the top of the program. This is handy for debugging. You should define your own error handler so the user doesn't have to see this and wonder what is going on. Special characters There are some characters in AutoLISP, like any language, which cannot be used under certain circumstances. •
Symbol names can contain any sequence of printable characters exce pt the following:
().'"; •
Certain characters terminate a symbol name or numeric constant, they are as follows:
()'"; • • •
•
A minus (-) sign can be used to signify negative integers or reals. The plus (+) sign is optional when signifying positive integers or reals. Literal strings are entered between double quotes (""). Within quotes strings, the backslash (\) character may be used to enter control characters. The control c haracters are as follows: \\ Gives a normal backslash character. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes4 • • • • • •
\" Gives a normal double quote character. \e Gives an escape character. \n Gives a new line character. \r Gives a return character. \t Gives the tab character. \nnn Gives a character who’s octal code is nnn.
The single quote character can be used in place of the quote function such as: 'This is equivalent to (quote this) Every comment in LISP must start with the semicolon character: ; This is a comment Comments will be discussed in depth later in the lessons. Lists: This function takes any number of expressions and makes a list out of t hem, and returns the result. The expression can be integers, intege rs, real numbers, strings, variable names or even other lists. The coordinate of a point is a commonly used list in AutoLISP. Coordinates can be 2-dimensional or 3dimn. Let us see some examples. 2-dimensional coordinates: (10.5 30.98) 3-dimensional coordinates: (10.5 30.98 50.84) The following syntax is used to create lists: (Setq p (list 7 8 6)) here ‘p’ is assigned the value (7 8 6) 6) Command: (Setq p (list 7 8 6)) returns (7 8 6) An alternative method of writing a list is to use single quote: (quote (a b c)) or ‘(a b c) each of which returns (A B C), ‘(a b “c”) that returns (A B “c”) ‘(a 5 “c”) that returns (A 5 “c”) This signifies that (list a b c) & ‘(a b c) are same but there is a difference also. Take an example command: (setq a 100 b 200 c 300) returns 300 command: (setq pt (list a b c)) returns (100 200 300) command: (setq pt ‘(a b c)) returns (A B C) so for the first expression, it returns (100 200 300), while fothe second it returns (A B C). That means evaluation is not done for the second case. Here double quoted “c” which is returned as it is returned as it is, is an AutoLISP expression called string. List Functions: Lets see the example, (Setq p (list 7 8 6)) here ‘p’ is assigned the value (7 8 6) car : This function separates the first element out of a list. Syntax and command: Command: (setq q(car p)) 7 ‘q’ is assigned the first element ‘7’ of the point ‘p’. cdr : This function separates the remaining elements other than first. If the list is empty, “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes5 cdr returns nil. Syntaxand command: Command:(setq t(cdr p)) (8 6)’t’ is assigned the remaining elements(8 6) of ‘p’ cadr: This functions car & cdr can be used in a combined form to get the t he element of ‘p’. Suntax and command: Command: (setq u(car (cdr p))) 8 ‘u’ is is assigned the mi middle el eleme ement 8 of of ‘p’. An trial programme to more understand list functions (defun c:BOX ( / pt1 pt2 pt3 pt4 ) (setq pt1 (getpoint "Pick first corner: ")) (setq pt3 (getcorner pt1 "Pick opposite corner: ")) (setq pt2 (list (car pt3) (cadr pt1))) (setq pt4 (list (car pt1) (cadr pt3))) (Command "line" pt1 pt2 pt3 pt4 "c" ) )
Running a Loaded Program
Once you have loaded the box program, you can run it at any time during the current editing session. However, once you exit AutoCAD the program is not saved with the file. You must re -load the program file in subsequent editing sessions before it c an be used again. Now try running the program. 1. First, set the snap mode and the dynamic coordinate readout on. 2. Enter the word Box B ox at the command prompt. You should get the following prompt: Pick first corner: 3. If your screen is in text mode, use the F2 key to shift to the graphic screen. Move the cursor so that the coordinate readout reads 2.0000,3.0000 and pick that point. The next prompt appears: Pick opposite corner: 4. Now move your cursor. A window follows the motion of your cursor (see figure 2. 2). Move the corner of the window to the so that the coordinate 8.0000,6.000 is displayed on the coordinate readout then pick that point. The box is drawn and the Command prompt returns. Figure 2 .3 gives you a general description of how this box program works.
Figure 2.2: The Getcorner window Understanding How a Program Works
Up until now, you have been dealing with very simple AutoLISP expressions that perform simple tasks such as adding or multiplying numbers or setting system variables. Now that you know how to save AutoLISP code in a file, you can begin to create larger large r programs. The box program is really nothing more than a collection of expressions that are designed to work together to obtain specific results. In this section, we will examine the Box program to see how it works. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes6 The Box program draws the box by first obtaining a corner point using Getpoint: (setq pt1 (getpoint pt1 "Pick first corner: '')) The user will see only the prompt portion of t his expression: Pick first corner: Next, the opposite corner point is obtained using Getcorner (see Figure 2.3). (setq pt3 (getcorner pt1 "Pick opposite corner: '')) Again, the user only sees the prompt string: Pick opposite corner:
Figure 2.3: The workings of the box program
You may recall that Getcorner will display a window as the user move the cursor. In I n this box program, this window allows the user to visually see the shape of the box before the opposite corner is selected (see figure 2.2). Once the second point is selected, the Box program uses the point coordinates of the first and opposite corners to de rive the other two corners of the box. This is done by manipulating the known coordinates using Car, Cadr, and List (see Figure 2.4). pt2 (list (car pt3) (cadr pt1))) pt4 (list (car pt1) (cadr pt3)))
Figure 2.4: Using Car, Cadr, and List t o derive the remaining box corners
Pt2 is derived by combining the X component of Pt3 with the Y component of Pt1. Pt 4 is derived from combining the X component of Pt1 with t he Y component of Pt3 (see figure 2.5).
Figure 2.5: Using Car and Cadr to derive Pt2 and Pt4 Using AutoCAD Commands in AutoLISP
The last line in the box program: “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes7 (command "line'' pt1 pt2 pt3 pt4 "c'') shows you how AutoCAD commands are used in an AutoLISP expression (see figure 2.6). Command is an AutoLISP function that calls standard AutoCAD commands. The command to be called following the Command function is enclosed in quotation marks. Anything in quotation marks after the Command function is treated as keyboard input. Variables follow, but unlike accessing variables from the command prompt, they do not have to be preceded by an exclamation ex clamation point. The C enclosed in quotation marks at the end of the expression indicates a Close option for the Line command (see Figure 2.7.
Figure 2.6: Using AutoCAD commands in a function.
Figure 2.7: Variables help move information from one expression to another. How to Create a Program
The box program is like a collection of expressions working together to perform a single task. Each individual expression performs some operation who's resulting value is passed to the next expression through the use of variables (see figure 2.8).
Assignment Function: Variable assignment is done through the function ‘setq’, concise form of ‘SET Quotes’. By using this function, a value can be assigned to any variable. Syntax: (setq a 20) means an integer value is assigned to the variable ‘a’.
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes8
A partial list of AutoLISP functions
MATH FUNCTIONS THAT ACCEPT MULTIPLE ARGUMENTS (+ number number ...) (- number number ...) (* number number ...) (/ number number ...) (max number number ...) ..) (min number number ...) ..) (rem number number ...)
add subtract multiply divide find find larg larges estt of of num numbe berrs giv given en find find sma smalles llestt of of num numbe bers rs given iven find find the the re remaind ainder er of numbe umberrs
MATH FUNCTIONS THAT ACCEPT SINGLE ARGUMENTS (1+ number ) (1© number ) (abs number ) (exp nth) (expt number nth) (fix real ) (float integer ) (gcd integer integer ) (log number ) (sqrt number )
add 1 subtract 1 find the absolute value e raised to the nth power number raised to the nth power convert real to integer convert integer to real find greatest common de denominator find natural log of number find square root of number
FUNCTIONS FOR BINARY OPERATIONS (~ integer )
find logical bitwise NOT of integer
(logand int. int . ...)
find logical bitwise AND of integers find logical bitwise OR of integers
(logior int. int. ...) (lsh int. bits)
find logical bitwise shift of int.by bits
(terpri) :- This function function prints a new line to the command command line
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes9
getpoiont at the command prompt, type : computer response: computer response: computer response:
Lesson 1 setq defun
command
line from point pick a point on the screen to point pick a point on the screen to point press Enter key
Above are the steps in AutoCAD A utoCAD to use the Aline@ command. getpoint
an AutoLisp function to request an input of a point. getpoint also echos a preassigned message.
In order to understand the use of getpoint and setq, setq, at the command prompt, type : computer response:
(getpoint "Pick 1st point") Pick 1st point pick a point on the screen
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes10 setq
an AutoLisp function to assign variables in AutoLisp.
In order to assign a point to t o a variable name for later retrieval ret rieval at the command command prompt, prompt, type: (setq A (getpoin (getpointt "Pick 1st point") point"))) computer response: Pick 1st point pick a point on the screen A point was picked, and the use of setq allows later retrieval of the point. In order to assure you did assign the point to the variable name A at the command prompt, type: !A the computer should print the co-ordinates of the point you picked last. last. The factorial symbol, ! , is used to get the value of any defined AutoLisp variables.
At the command prompt, prompt, type: (setq B (getpoint (getpoint "Pick 2nd point") point"))) computer response: Pick 2nd point pick a point on the screen The AutoLisp function command is used to call up a standard AutoCAD command. It should precede a standard AutoCAD command enclosed by a pair of double quotation marks. In order to see how this function works, at the command prompt, type:
(command "line" A B "") press Enter key A line connecting two points, points, A and B, is drawn. The start point and end point of the line line will be point A and point B respectively.
What you have done was to draw a line by means of AutoLisp function. AutoLisp could be executed line by line, just like what you have done, but a formal AutoLisp routine to draw a line should be: (defun c:line1 () (setq A (getpoint "Pick 1st point")) (setq B (getpoint "Pick 2nd point")) (command "line" A B "") )
Use Note Pad, Word Pad, or any any other available window version text-editor and type: (defun c:line1 () (setq A (getpoint "Pick 1st point")) (setq B (getpoint "Pick 2nd point")) (command "line" A B "") ) When done, save the file as “A:LINE1.LSP” The file must be saved as text file. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes11 Explanation of the lines typed: (defun is a standard standard way to start an AutoLisp AutoLisp programme. c: means to define a customized command; nothing to do with drive C: line1 the customized command will be known as line1 () a pair of bracket means there will be variables in the programme and the variables will stay in in the memory after execution of the AutoLisp routine. ) this is the closing bracket for the whole programme. Minimize the text editor and return to AutoCAD,
Now is the time to load and run the AutoLisp AutoLisp routine, LINE1.LSP, you just typed. at the comman command d prompt prompt typ type: e: computer will response:
(load (load "A:lin "A:line1" e1")) c:line1
now LINE1 becomes your customized command to draw a line. Whenever you want to use it to draw a line you could type LINE1 Improvement Improvement of above AutoLisp routine:Maximize the text editor and modify the file, line1.lsp to read: (defun c:line1 () (setq A (getpoint "Pick 1st point")) (setq B (getpoint "Pick 2nd point" A)) (command "line" A B "") ) This modification will produce an elastic band originating from point A. Load the AutoLisp file again. Execute the file and appreciate the difference.
LINE1.LSP, though not a very ve ry practical file, does illustrate the principles of input and output in an AutoLisp programme. The best way to learn AutoLisp is by doing exercises. By applying the AutoLisp functions learned, you should be able to do the following tutorial. Tutorial for Lesson 1:1.
Writ Write e an Auto AutoLi Lisp sp rout routin ine e whi which ch wil willl ask ask the the use userr to pick pick 5 poin points ts and then draw a 5 - vertice star. (STAR5.LSP)
2.
Writ Write e an an Aut AutoL oLis isp p rou routi tine ne wh whic ich h wil willl ask ask the the use userr to to pic pickk 20 20 points and then the first picked point will joint all subsequently picked points. (BUSH.LSP)
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes12
Lesson 2 getreal distance prompt terpri getint getint getstring getstring at the command prompt, type : computer response:
getreal
(getreal "Type a number") Type a number type a number and press Enter key
an AutoLisp function to request an input of a real number from the user. It, like getpoint, getpoint, also echos a predetermined message.
Most of the time we want to save the number under a variable name so that the value could be retrieved for use later. Thus, we have to combine setq and getreal together like the following:. at the command prompt type:
(setq A (getr etreal eal "Type a number ")) type a number and press Enter key
in order to confirm that the number you typed is indeed stored under the variable name A, at the command prompt type: computer response:
!A [the number you typed in]
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes13
The following example, example, LINECIR.LSP, asks for 2 points and a real number as input and and then draws a line with 2 circles at its ends. It illustrates the the use of the getreal. getreal. function. The terpri function issues a carriage return. The prompt function prints a predetermined predetermined message to the screen.Use Note Pad, Word Pad or any other Windows text editor and type type the following file and then save as: A:LINECIR.LSP defun c:linecir () (setq A (getpoint "Pick 1st point")) (terpri) (setq B (getpoint "Pick 2nd point" A)) (terpri) (setq R (getreal "Input radius")) (terpri) (command "line" A B "") (command "circle" A R) (command "circle" B R) (prompt "Thank you!") ) Above example use information input directly by the operator. A real number could be input directly by getreal or indirectly by the distance function. The distance function in AutoLisp will return a real number based on 2 input points. If we want the previous 2 circles to touch each other, we could use the distance function to obtain a real number and then calculate the required radii. AutoLisp built-in mathematical mathematical feature is extremely useful in in programming. AutoLisp perform calculations in the following formats: Algebra format 4 + 5 9 - 2 2 x 4 12 / 3
AutoLisp format (+ 4 5) (- 9 2) (* 2 4) (/ 12 3)
Besides Algebraic functions, functions, AutoLisp also also support most most of the trigonometrical functions too. The following example draws 2 circles, radius of the smaller smaller one will be half half of of the big one. one. Use Note Pad, Word Pad or any other Windows text editor to type the following file and then save as A:BSCIR.LSP
(defun c:bscir () (setq A (getpoint "Pick 1st point"))(terpri) (setq B (getpoint "Pick 2nd point" A))(terpri) (setq D (distance A B)) (setq R1 (/ D 3)) (setq R2 (* R1 2)) (command "circle" A R1) (command "circle" B R2) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes14 (prompt "Thank you!") )
The above AutoLisp programme could be further improved by adding the layering command so that the big circle and small circle could be drawn on different layers. The proper input sequence to use the layer command should be found out before the AutoLisp programme is is to be prepared.. (defun c:bscir2 () (setq A (getpoint "Pick 1st point"))(terpri) (setq B (getpoint "Pick 2nd point" A))(terpri) (setq D (distance A B)) (setq R1 (/ D 3)) (setq R2 (* R1 2)) (command "layer" "m" "smallcir" "c" "green" "" "") (command "circle" A R1) (command "layer" "m" "largecir" "c" "yellow" "" "") (command "circle" B R2) (prompt "Thank you!") )
Sometimes we need to input text to the programme. This could be done by the getstring function. When getstring function is used, even if the user type a number by the keyboard the number would be taken as a string in AutoLisp. Any mathematical performance on that input number will not work. Just like any other programming language real number and integ er number should be distinguished. AutoLisp calculation could mix up integers and real numbers but for AutoCAD to work properly some of the input must be integer rather than real number. number. For example, in the Aarray@ operation, the number of rows and number of columns must must be integers. The following examples demonstrates the use of getstring and ge tint functions. Use Note Pad, Word Pad or any other Windows text editor and and type FAN.LSP , COLARC.LSP AND CIRPAT :Save all the files in Drive A: getstring
an AutoLisp function to request an input of characters from the user. It, like getreal, getreal, also could echo a predetermined message.
FAN.LSP (defun c:fan () (setq C (getstring "type a standard color: red, yellow, green, cyan, or blue ")) (terpri) (setq D (getpoint "pick first point of line.."))(terpri) (setq E (getpoint "pick second point of line" D))(terpri) (command "color" C) (command "line" D E "") (command "array" "l" "" "p" D 50 160 "y") ) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes15
COLARC.LSP (defun c:colarc () (setq C (getstring "type a standard color: red, yellow, green, cyan, or blue")) (terpri) (setq D (getpoint "pick first point of arc.."))(terpri) (setq E (getpoint "pick second point of arc.."))(terpri) (setq F (getpoint "pick third point of arc.."))(terpri) (command "color" C) (command "arc" D E F) (command "array" "l" "" "p" D 20 30 "y") ) getint
an AutoLisp function to request an input of an integer from the user. It, like getreal, getreal, also echos a predetermined message.
CIRPAT LSP (defun c:cirpat () (setq C (getstring "type a standard AutoCAD c olor: red, yellow, green, cyan or blue..")) (terpri) (setq D (getpoint "pick first point"))(terpri) (setq E (getpoint "pick second point"))(terpri) (setq F (getint "type a number larger than 10 :")) (command "color" C) (command "circle" "2P" D E) (command "array" "l" "" "p" D F 360 "y") )
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes16
Tutorial: Write an AutoLisp programme which will ask user to pick 2 points and then will draw draw 2 donuts touching each other; and also 2 circles each at the centers of donuts The inside radius of the donut will be half of that of the outside one. Radius of the circles to be 1/16 of the distance between the two picked points.Draw the donuts on the layer called tire and draw the circles on the layer called axle. File name to use: WHEEL2.LSP
Lesson 3 getangle polar angle if nil Prepare a grid layout as shown as right, using 10000 drawing drawing units between between grid lines. We are going to draw columns on this plan at intersection of grid lines.. Use Note Pad, Pad, Word Pad or any other other Windows Windows text editor editor to type the following file and then save as A:COLUMN.LSP (defun c:column () (setq CEN (getpoint "Centroid of column: ")) (terpri) (setq HOR (getreal "X Dimension of column: ")) (terpri) (setq VRT (getreal "Y Dimension of column: ")) (terpri) (setq ANG (getangle "Rotation angle of the X side: " CEN)) (terpri) (setq M (polar CEN (- ANG (/ pi 2)) (/ VRT 2))) (setq A (polar M (- ANG pi) (/ HOR 2))) (setq AM (angle A M)) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes17 (setq B (polar A AM HOR)) (setq C (polar B (+ AM (/ pi 2)) VRT)) (setq D (polar C (+ AM pi) HOR)) (command "pline" A B C D "c") ) Exit text editor Load the AutoLisp file, A:COLUMN.LSP Computer should response response by displaying displaying C:COLUMN COLUMN becomes your customized command. at the command prompt, type : computer response:
column Centroid of column pick a point at the intersect of grids grids
computer response: type
X dimension of column 1500 press Enter key computer response:
dimension type
2000 press Enter key
computer response: type
Y dimension 2000 press Enter key
computer response:
Rotation angle of the X side use osnap Anear@ pick a point on the grid to define orientation .
A column is drawn, nice and square to the grid. grid . The ease to draw column by AutoLisp is obvious. This routine introduces the use of getangle of getangle,, angle and polar. getangle
is the AutoLisp function that lets you find an angle by pointing to two points or bv entering the the angl angle e from from the the keyb keyboa oard rd.. There Therefo fore re,, instead of picking two points, like what we have done, we could type the value of the angle through the keyboard.
polar
is the AutoLisp function that derive a poin pointt at a give given n dist distan ance ce and and angl angle e from from another known point.In the above example we based on the known point CEN with a known angle, pi /2, and and a known known distance, distance, VER /2 to get the point M. By the same token, we based on M to get A, B, C and D. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Y
Z:Swapnil A. Kale/MDCG/LISP/Notes18
angle
is the AutoLisp function that measures the angle of two known points.The value of the angle returned by AutoLisp AutoLisp functions is always in radian. radian. The angle to be used in the polar function should be in radian also. Therefore, if the angle obtained by AutoLisp functions is to be used in AutoCAD commands then the values of the angle should be converted from radian to degrees.
The next example, is an AutoLisp routine to draw a line with an arrow at both ends. It makes use of the polylin polyline e and polyline polyline width features features to prepare prepare arrows and and the line between between arrows. arrows. Therefore, the steps to use Apline@ command and its width feature should be found out before preparing the AutoLisp routine. It is very difficult to predetermine a good size for the arrows. Thus, in this programme programme we try to make the arrow size relative to the final plotting scale scale of the drawing. The if fuction if fuction is used here so that user needs to input the scale of drawing only once as long as the the user remains in the the same drawing. drawing. This programm programming ing technique technique is very very useful whenever whenever AutoLisp AutoLisp is used to draw draw entities which size should should be be relative to the scale of the drawing such as the insertion of direction symbols, or other graphical symbols on a drawing. if
The if function followed by either two or three statements. The first statement statement after if is if function is followed if is the condition to evaluate. The second statement is the step for the routine to execute if condition condition is true. true. The third statemen statement, t, if exist, is the step for the routine routine to execute execute if condition is false.
nil
in AutoLisp nil represent an empty set or non-existing condition.
Use Note Pad, Word Pad or any other Windows text editor to type type the following file and then save as A:DARR.LSP
(defun c:DARR () (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")) ) (setq SPT (getpoint "Starting point")) (setq EPT (getpoint "End point" SPT)) (setq APT1 (polar SPT (angle SPT EPT) (* SC 2))) (setq APT2 (polar EPT (angle EPT SPT) (* SC 2))) (command "pline" "pline" SPT "w" 0.0 SC APT1 "w" 0.0 0.0 APT2 "w" SC 0.0 EPT "") )
Tutorial: 1. When we prepare structural steel drawings, in order to indi indica cate te a pinn pinned ed join jointt conn connec ecti tion on betw betwee een n two two main main “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes19 members we need to draw draw a line which is a little bit shorter shorter than the two points we we pick. Write an AutoLisp programme to do this. When activated the programme should prompt you to pick two points, then a line should be drawn with a gap between the ends of the line and the points picked. Size of the gap should be the same value as the scale of the drawing. If the scale is 1:100 , gap size is 100 or if the scale is 1:200 then then the gap should be be 200. file name: SHORTER.LSP
2.
Very Very simi simila larr to to abo above ve,, writ write e a pro progr gram amme me wh whic ich h wil willl pro promp mptt for for 2 points and then it will draw a line which will exceed the length between the two picked points points by a distance distance of SC at both ends. SC will be 100 for 1:100 or 50 for 1:50 scale drawing file name: LONGER.LSP
3.
Writ Write e an an Aut AutoL oLis isp p pro progr gram amme me,, in in whi which ch the the use userr nee needs ds to pick pick two p points oints and a line line with with two arrows at one one end (as shown shown by Fig. Fig. 3.6) will will be drawn drawn FARARR.LSP.
file:
Lesson 4 getcorner graphscr graphscr list car cadr At the the comm comman and d pro prompt, mpt, typ type: (setq setq A (getp getpoi oint nt "1st 1st cor corne nerr of of rect rect") "))) computer response: 1st corner of rect pick a point on the screen at bottom left left
computer response: [displays the co-ordinate of the point picked] At the the com comma man nd p pro romp mpt, t, typ type: (setq setq C (ge (getc tcor orn ner "2nd 2nd cor corn ner of rec recta tang ngle le " A) A)) computer response: 2nd corner of rect (and display an elastic rectangle) pick a point on the screen at upper upper right
Now two points were input. These two points represent the diagonal corners of a rectangle. getcorner
the function function to acquir acquire e a second second point basing basing on a define defined d first first point. point. and it provides the user with an elastic rectangle.
Points are variables with x and y coordinates. W ith the two diagonal points established, we try to get the x, y values and form the remaining points of the rectangle. Any variable with with more than one value is called a list. list. Point A is a list because it contains contains x and y coordinates. Same does does point C. We are going to combine x coordinate of A and y coordinate of C to form point B. graphscr car cadr list
is the AutoLisp function to switch the computer to graphic mode, if it is in text mode. is the AutoLisp function to get the first element of a list. list. is the AutoLisp function to get the 2nd element of a list. is the AutoLisp function to group individual elements together. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes20 At the command prompt, typ type: computer response:
(setq B (list (ca (carr A) (cadr C) C))) [displays a set of coordinate for point B]
At the command prompt, typ type: (setq D (list (c (car C) C)(cadr A)) A))) computer response: [displays a set of coordinate for point D] Now all points for the rectangle are defined. at the command prompt, type : computer response: type: computer response: type: computer response: type: computer response: type: computer response: type: computer response: type: computer response: type:
pline from point !A ARC/CLOSE/........../Width/
: w Starting width <0.050> 0.0 Ending width <0.00> 0.0 ARC/CLOSE/........../Width/: !B ARC/CLOSE/........../Width/: !C ARC/CLOSE/........../Width/: !D press Enter key
A rectangle is drawn. Now try to type the the following file, rectan.lsp. Then, load the programme and and see how it works. (defun c:rectan () (graphscr) (setq A (getpoint "Pick corner of rectangle "))(terpri) (setq C (getcorner "2nd corner of rectangle " A))(terpri) (setq B (list (car A)(cadr C))) (setq D (list (car C)(cadr A))) (command "pline" A "w" 0.0 0.0 B C D "c") ) The next example will make full use of what you have learned to draw the symbol of a broken line. The The prog progra ramm mme e uses uses the the draw drawin ing g scale cale to determine size of the broken symbol at the middle of the two picked points. It uses car and cadr to locate mid-pont of the symbol. From the mid-point it uses uses polar polar to to find find 4 other points points then it uses uses pline to draw the complete broken line symbol. symbol. Use a Windows text editor to t o type the following file, bline1.lsp:(defun c:bline1 () (GRAPHSCR) (setq SC (getreal "scale of dwg. 1:")) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes21 (setq BPT (getpoint "start point of break line ")) (terpri) (setq EPT (getpoint BPT "point of break line line ")) (setq ANG (angle BPT EPT)) (setq MPTX (/ (+ (car BPT) (car EPT)) 2)) (setq MPTY (/ (+ (cadr BPT) (cadr EPT)) 2)) (setq MPT (list MPTX MPTY)) (setq PT1 (polar MPT (- ANG pi) (* SC 0.5))) (setq PT3 (polar MPT ANG (* SC 0.5))) (setq PT2 (polar MPT (+ ANG (/ pi 2)) (* SC 2))) (setq PT4 (polar MPT (- ANG (/ pi 2)) (* SC 2))) (command "pline" BPT "w" 0.0 0.0 PT1 PT2 PT4 PT3 EPT "") ) Tutorial 1.
Write an AutoLisp
programme, in which when the user picks 2 diagonal diagonal points a rectangle with round corners will will be drawn. drawn. Radius Radius for the round corners corners will will be 1/10th 1/10th of the shorter shorter side side of the rectangle. See See Fig. 4.3 (Hints: use AutoLisp to draw a rectangle; find the shorter side and calculate for the fillet radius; use the polar function to determine points to be used for the fillet command.)
file:RECRND.LSP
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes22 2.
Writ Write e an Auto AutoLi Lisp sp pro progra gramm mme e to draw draw a rect rectan angl gle e and and its its sha shado dow w at at its its low lower er rig right ht sid side e as shown on Fig. 4.4 Width Width of the shadow to be be 1/25th of the length of the shorter side of the rectangle. file: RECSHD.LSP
Lesson 5 repeat while getdist All computer languages have loops to do repetitive jobs. In AutoLisp both the repeat and while function create loops to repeat a series of procedures. repeat
The function to repeat a series of procedure according to a specified number of times.
while
The function to invoke a loop while a variable or expression is not nil or invalid.
getdist
The function to request input as a real number, either through the keyboard or by pointing.
The following example demonstrate the usage of the repeat function. Once loaded and executed, it will will ask user to pick pick two points points and draw 5 concen concentri tricc circle circless with with decrea decreasin sing g radius radius.. Each Each
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes23 subsequent radius will be 50% of the previous one. And the circles are in different colors beginning with red (color 1). Use a Windows text editor and type the following:(defun c:conc () (setq A (getpoint "Pick center of circle "))(terpri) (setq R (getdist "Pick circum of outside circle" A))(terpri) (setq C 1) (repeat 5 (command "color" c) (command "circle" A R) (setq R (* R 0.5)) (setq C (+ C 1)) ) (command "color" "bylayer") )
“bylayer” “bylayer” means the entity entity color will be same as the color of the layer layer on which it is drawn. The default feature for color is bylayer on the original acad.dwg. In order not to modify this feature, at the end of the programme, we try to return the drawing to have its entity color to be Abylayer@. The while loop carries on and on as long as a specified condition is satisfied. The number of loops is not necessarily to be known. The following example bases on the previous one. It demonstrates the use of the while loop. The while loop will draw circles as long as the radius is larger than 0.1. Use a Windows text editor and type the following:(defun c:conc2 () (setq A (getpoint "Pick center of circle "))(terpri) (setq R (getdist "Pick circum of outside circle" A))(terpri) (setq C 1) (while (> R 0.1) (command "color" c) (command "circle" A R) (setq R (* R 0.5)) (setq C (+ C 1)) ) (command "color" "bylayer") ) Above examples show that repeat and while have their places. They are used at different situations. The last example example limits the smallest smallest circle to be 0.1. Whether radius radius 0.1 is too small to see or not depends depends very much on the final plotting plotting scale of the drawing. A better way would be to draw the smallest circle according to the final plotting scale. In 1:100 drawing 100 units will be represented by 1mm, and in 1:200 drawing, 200 will be represented by 1mm. In order to have have the smallest smallest circle visible its radius should be relative to the final plotting scale of the drawing. The next example uses the while loop to control the smallest circle to be drawn. Save the previous AutoLisp file file to another name, conc3.lsp, and revise it as follow:follow: “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes24
(defun c:conc3 () (setq A (getpoint "Pick center of circle "))(terpri) (setq R (getdist "Pick circum of outside circle" A))(terpri) (if (= SC nil) (setq SC (getreal "Scale of the dwg dwg is 1: ")) ) (if (= COL nil) (setq COL 1) ) (while (> R SC) (if (> COL 6) (setq COL 1) ) (command "color" COL) (command "circle" A R) (setq R (* R 0.5)) (setq COL (+ COL 1)) ) (command "color" "bylayer") ) The outermost circle drawn by the above revised programme, conc3.lsp, may not be red unless it is the first time to use this programme in that drawing editor. Tutorial 1.
Wri Write an AutoL AutoLis isp p progr rogram amm me to dra draw step stepss. Inp Input allo allowe wed: d: two two poi points, nts, one one poi point at bottom of steps another point at top of last step; number of steps.
file: STEPS.LSP
2.
Write an AutoLisp programme to draw a happy face. Allowed input input would would be only only two points points.. The first point dictates the center of the face. The second point will defi define ne the the circu circumf mfer eren ence ce of the the circle. Orientation of the happy face should should be accordi according ng to the angle angle defined by the two points picked.
file:HAPFACE.LSP
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes25
Lesson 6 getvar setvar rtos strcat strlen strlen substr progn strcase /= In this lesson we are going to use AutoLisp to put text on the drawing. Many a time we need to know the coordinate of a point on the drawing. Nowadays due to the advance technology in land surveying most of the site plans are actually done with coordinates.AutoCAD is a very accurate software software in this respect. After a designer drew a roadway on a topographical topographical AutoCAD AutoCAD drawing, drawing, coordinates for all the important points such as BC( beginning of curve), EC(end of curve), PCC(point on compound curve) are actually known and readily available for surveyors to use for site layout. The following example will write the coordinates of a selected point directly on the drawing. Whenever Whenever AutoCAD command command Atext@ Atext@ is used, it is good to define define the text style to be used. If textstyle is not defined in the same programme, current text style of the drawing will be used and it may not be the right one for your programme. getvar AutoLisp function to get the existing value of a system variable. setvar AutoLisp function to set an AutoCAD system variable. AutoLisp function to convert convert a number or variable variable to a string. rtos strcat AutoLisp function to joint two strings to become one string. Use a Windows text editor to t o type the following file:(defun c:pid () (graphscr) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes26 (if (= SC nil) (setq SC (getreal "Scale of the dwg dwg is 1: ")) ) (setq B (getvar "blipmode")) (setvar "blipmode" 1) (setq C (getpoint "Select point for I.D. ")) (terpri) (setq ST1 (getpoint "Select point for beginning of text. ")) (terpri) (setq ANG (getangle "Rotation of text " ST1)) (terpri) (setq TS (* SC 2.5)) (command "style" "COOR" "SIMPLEX" TS 1.0 0.0 "n" "n" "n") (setq VDT (* 1.50 TS)) (setq ST2 (polar ST1 (- ANG (/ pi 2)) VDT)) (setq ANGD (/ (* ANG 180) pi)) (setq X (car C)) (setq Y (cadr C)) (setq EAST (rtos X )) (setq NORTH (rtos Y )) (setq ECOOR (strcat "E " EAST)) (setq NCOOR (strcat "N " NORTH)) (command "text" ST1 ANGD ECOOR) (command "text" ST2 ANGD NCOOR) (command "redraw") (setvar "blipmode" B) )
The following example is an AutoLisp AutoLisp routine routine to do text along a circular path. This strlen functio function n returns returns an integer that is the number of char charac actters ers in a string. substr The function returns a substring of a string. e.g. (substr "abcde" 2) returns (substr "abcde" 2 1) returns "b" (substr "abcde" 3 2) returns "cd"
"bcde"
This not equal to. /= Use a Windows text editor and type the file as below:-
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes27 (defun c:CURTEX () (setq PT1 (getpoint "Pick the starting point of text"))(terpri) (setq PT2 (getpoint "Pick the center of arc for the text" PT1)) (terpri) (setq TEX (getstring T "Please start to type the text....")) (terpri) (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: "))) (setq TXZ (* SC 2.54)) (setq STY (getvar "textstyle")) (if (/= STY "curtex") (command "style" "curtex" "complex" TXZ 1.0 0.0 "n" "n" "n") ) (setq TXL (strlen TEX)) (setq N 1) (repeat TXL (setq TTC (angle PT1 PT2)) (setq RAD (distance PT1 PT2)) (setq TAN (+ (/ pi 2) TTC)) (setq TANG (* TAN 57.2958)) (setq PT3 (polar PT1 TAN TXZ)) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) (setq CTX (substr TEX N 1)) (command "text" PT1 TANG CTX) (setq PT1 PT4) (setq N (+ N 1)) ) ) FIG. 6.2 shows the text done by CURTEX.LSP As we can see the spacing for some of the alphabets is not very well proportioned. There are certain letters, letters, we have to pay extra attention to. The following AutoLisp programme bases on the previous one but spacings for the letters, m, i, and l are adjusted to make the text look better. progn This function evaluates each expression sequentially, usually used with the if function. strcase
This function evaluates all characters in a variable as uppercase.
(defun c:CURTEX2 () (setq PT1 (getpoint "Pick the starting point of text"))(terpri) (setq PT2 (getpoint "Pick the center of arc for the text" text " PT1))(terpri) (setq TEX (getstring T "Please start to type the text...."))(terpri) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes28 (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: "))) (setq TXZ (* SC 2.54)) (setq STY (getvar "textstyle")) (if (/= STY "curtex") (command "style" "curtex" "complex" TXZ 1.0 0.0 "n" "n" "n") ) (setq TXL (strlen TEX)) (setq N 1) (repeat TXL (setq TTC (angle PT1 PT2)) (setq RAD (distance PT1 PT2)) (setq TAN (+ (/ pi 2) TTC)) (setq TANG (* TAN 57.2958)) (setq PT3 (polar PT1 TAN TXZ )) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) (setq CTX (substr TEX N 1)) (command "text" PT1 TANG CTX) (if (= CTX "m") (progn (setq PT3 (polar PT1 TAN (* TXZ 1.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) ) (if (= CTX "l") (progn (setq PT3 (polar PT1 TAN (* TXZ 0.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) ) (setq CHK (strcase CTX)) (if (= CHK "I") (progn (setq PT3 (polar PT1 TAN (* TXZ 0.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) ) (setq PT1 PT4) (setq N (+ N 1)) ) ) Tutorial: 1. Writ Write e an Aut AutoL oLis isp p prog progra ramm mme e whic which h will will pro promp mptt to p pic ickk up poin points ts and and a lin line e will will con conne nect ct each subsequently picked points with the length of the line writte n at its side. The process will continue continue as long long as points are being picked. file: LINETX.LSP
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes29
2.
Write an AutoLisp programme which will ask user to pick 2 points to define a rectangular area and input the verical load (e.g. 15KN/M); then it will start filling the defined area by downward arrows and put put the the vert vertic ical al load load valu value e abo above ve the the arr arrow ows. s.(A (Ass show shown n in Fig. Fig. 6.5) 6.5) file file:: VLOA VLOADA DAR. R.LSP LSP
3. Similar to above, write an AutoLisp programme which will ask user to pick 2 points to define a rectangular rectangular area and input the horizontal horizontal load (e.g. 15KN/M); then it will start filling the defined area by horizontal arrows and put the horizontal load value value close to the arrows.(As shown in Fig. 6.6) file: HLOADAR.LSP
4.. 4..
Writ Write e an Auto AutoLi Lisp sp prog progra ramm mme e whi which wil willl dra draw w the the shap shape e of of horizontal triangular load (earth load). The input will be bottom and top of triangular triangular load, end of the bottom arrow and value of of force at botto ottom. m. (As (As sho shown in in Fig. Fig. 6.7) 6.7) fil file: TLO TLOADAR ADAR.L .LSP SP
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes30
Lesson 7 Math & AutoLisp or cons foreach AutoLisp include all trigonometrical and mathematical functions. Using the built-in functions many geometrical shapes could be drawn easily by means of of AutoLisp. The following example is an AutoLisp routine to draw a star of any specified vertices.The ability to write this kind of programme depends very much on the programmer=s mathematical and g eometrical skill. In order to write this programme, we need to understand how the angles within a polygon are related to each other.
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes31
In FIG. 7.1 < INCLAN = 360 NC < ANIN =
Where NC = number of vertices (or sides) Substended by half arc length Exteri Exterior or angle angle of a triang triangle le
Bottom of issoc.
use sine formula for PNT1 PNT2 CEN IRAD / SIN (180 - ANIN - ANOUT) = SRAD / SIN ANOUT SRAD = SIN ANOUT * IRAD / SIN (180 - ANIN - ANOUT)
Where IRAD is the distance from CEN to PNT1 SRAD is the distance distance from CEN TO PNT2 After After PNT2 PNT2 is esta establ blis ishe hed d and and conn connec ected ted to PNT1 PNT1,, comm comman and d Amirror@ is used to form the second line. These two lines are then central-arrayed to complete the programme.
Use a text editor and type the following file: (defun c:STAR () (graphscr) (setq NC (getint "Input number number of vertices for the star ")) (setq CEN (getpoint (getpoint "Centroid of star ")) (setq PNT1 (getpoint "One "One vertex of the star " cen)) (setq INCLAN (/ (* 2 pi) NC)) ;included angle at center (setq ANOUT (/ (/ (* 2 pi) NC) 4)) 4)) (setq ANIN (* 2 ANOUT)) (setq ANG (angle CEN PNT1)) (setq IRAD (distance CEN PNT1)) (setq SRAD (* IRAD (/ (sin ANOUT) (sin (- pi (+ ANOUT ANIN)))))) (setq PNT2 (polar CEN (+ ANG ANIN) SRAD)) (command "line" PNT1 PNT2 "" "mirror" PNT1 "" CEN PNT2 "") (setq INCLAND (* (/ INCLAN pi) 180)) (command "array" "l" PNT1 "" "c" CEN INCLAND NC "y") ) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes32
FIG. 7.2 Shows the stars drawn by this this programme.
AutoLisp could be used to draw the graph of a equation. Programming for a graph would include: the evaluatin of X & Y coordinates, coordinates, the combining combining of X & Y to form points, points, the construction of a list for all these calculated points, and finally use the Apline@ command and step through all the points in the list. The following example uses AutoLisp to draw a graph : Y = X2 5 for the range -10 < X < 10 To begin with, a list with all the calculated points is needed. The list has to be assigned a name. Here let us call it PNTLIST. PNTLIST. Before the list list has any calculated calculated value, value, we always set it to nil in order to ensure it starts as an empty list. (setq PNTLIST nil) Before a calculation calculation loop, the lower lower limit of X value should be specified. specified. (setq X -10) or
a condition function in AutoLisp
The while loop is then used to calculate t he points, and to specify the upper limit of X (while (or (< X 10) (= X 10)) 10)) .....
....)
The equation Y = X 2 5 in AutoLisp is: (setq Y (/ (* X X) 5)) points are formed by using the list function. (setq PNT (list X Y)) cons
AutoLisp function to construct the list by adding adding new data to the list (setq PNTLIST (cons PNT PNTLIST))
After each point is added added to the list, list, increment of X is applied. applied. (setq X (+ X 0.2)) After the list is completed, the following 4 lines work together to draw the polyline and fit the curve. (command "pline") (foreach P PNTLIST (command P)) (command "") (command "pedit" "l" "s" "w" 0.0 "x") “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes33 foreach
AutoLisp function to cause execution of a command on each element of a list.
The whole programme should read as the following: (defun c:SQC () (setq PNTLIST nil) (setq X -10) (while (or (< X 10) (= X 10)) (setq Y (/ (* X X) 5)) (setq PNT (list X Y)) (setq PNTLIST (cons PNT PNTLIST)) (setq X (+ X 0.2)) ) (command "pline") (foreach P PNTLIST (command P)) (command "") (command "pedit" "l" "f" "w" 0.0 "x") ) Shell out and type the above programme. The above method is a handy way to draw any graph for an explicit equation on a drawing. Coordinates of the points dictate where the curve will be drawn. But many a time we would like to put the curve at any convenient convenient location on the drawing, drawing, regardless of the drawing global coordinate system. This could be done simply by using the UCS features of AutoCAD. The above programme could be revised to read as follow: (defun c:SQC () (set (setq q B (getp getpoi oint nt "Pick Pick ori origin gin of grap graph. h."")) (setq PNTLIST nil) (setq X -10) (while (or (< X 10) (= X 10)) (setq Y (/ (* X X) 5)) (setq PNT (list X Y)) (setq PNTLIST (cons PNT PNTLIST)) (setq X (+ X 0.2)) ) (command "ucs" "o" B) (command "pline") (foreach P PNTLIST (command P)) (command "") (command "pedit" "l" "f" "w" 0.0 "x") (command "ucs" "p") )
;ad ;added ded line ine
;added line
;added line
Now the programme will ask the user to pick a point which will be used as the origin (0,0) for the curve anywhere on the drawing. Tutorial: “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes34 1
Writ Write e an Auto AutoLi Lisp sp pro progr gram amme me to to draw draw the the fol follo lowi wing ng cur curve ve on on th the e draw drawin ing: g:-3 a) y=x /5 for -5 < x < 5 b)
Y=Cos X
for 0 < X < 2 pi
c)
Y=Sin X
for 0 < X < 2 pi
d)
Y=Sin2X
for 0
e)
Y=Sin X/2
for 0 < X < 2 pi
Lesson 8 fix entlast
Fig. 8-1 is the building block for Fig. 8-2. The drawing of insulation is always necessary on architectural drawings. This AutoLisp makes use of an existing block inserted on the drawing with a scale calculated according to input from the user and then copied to fill a specified area. In this example, the object selection method, Alast@, is not used. Instead of Alast@, the AutoLisp function entlast is used. In object selection mode, Alast@ means the last entity created and visible on the screen. If the entity e ntity created last is outside the display area, the n Alast@ will not select the entity you want. However, enlast will return the name of the last nondeleted main entity whether visible or not.. AutoLisp function to convert a real number to an integer. fix entlast AutoLisp function to return the name of the last nondeleted main entity. Use a text editor to type the following file:(defun c:insulate () (setq a nil) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes35 (setq PT1 (getpoint "Starting Point of Insulation ")) (setq PT2 (getpoint PT1 "\nEnd Point of Insulation ")) (setq THK (getdist PT1"\nThickness of insulation: ")) (setq L1 (distance PT1 PT2)) (setq ANGR (angle PT1 PT2)) (setq ANGD (* ANGR (/ 180. pi))) (setq NUM (/ L1 50)) (setq NUM (fix NUM)) (setq L2A (/ L1 NUM)) (setq L2 50.0) ;original block is 50wide (setq FACTOR (/ L2A L2)) (setq THKF (/ THK 75.0));original block is 75high (command "layer" "m" "AR-INSUL-RD" "c" "1" "" "") (command "insert" "insulate" PT1 FACTOR THKF ANGD) (setq N 1) (while (< N NUM) (setq E1 (entlast)) (setq PT3 (polar PT2 ANGR (* FACTOR L2))) (command "copy" E1 "" PT2 PT3) (setq PT2 PT3) (setq N (+ N 1)) Figure 8-3 ) (command "redraw") ) To understand the above example is very important, because this method could be used to prepare other useful graphics, for example, layer of gravel, layer of solid insulation, insulation, or corrugate steel steel plate section....etc. section....etc.
Fig. 8-3 shows the fence symbol by AutoLisp. AutoCAD allows the preparation of linetype with a symbol as part of it. To prepare that kind of linetype you need to prepare a shape first. If you do not want to prepare a shape, the alternative is to use AutoLisp as shown by the example below: (defun c:fence () (graphscr) (setq STY (getvar "textstyle")) (COMMAND "LAYER" "M" "ST-MISCL-YE" "C" "2" "" "") (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")) ) (setq TXTSZ (* SC 1.0)) (command "style" "fence" "simplex" TXTSZ 1.0 0.0 "n" "n" "n") (setq PT1 (getpoint "First point of fence ")) (terpri) (setq PT2 (getpoint "2nd point of fence" PT1)) (terpri) (while PT2 (setq LL (* SC 1.0)) (setq ANG1T2 (angle PT1 PT2)) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes36 (setq ANG2T1 (angle PT2 PT1)) (setq ANG1T2D (* ANG1T2 57.29578)) (setq LEN (distance PT1 PT2)) (setq SEC (/ LEN (* LL 10.0))) (setq FSEC (fix SEC)) (setq SECL (/ LEN FSEC)) (setq PTALIST nil) (setq DLEN SECL) (repeat FSEC (setq PTA (polar PT1 ANG1T2 DLEN)) (setq PTALIST (cons PTA PTALIST)) (setq DLEN (+ SECL DLEN)) ) (foreach PTA PTALIST (setq PTA2 (polar PTA PTA ang2T1 (- SECL TXTSZ ))) (setq PTA1 (polar PTA ang2T1 TXTSZ)) (command "text" "m" PTA ANG1T2D ANG1T2D "X" ) (command "line" PTA1 PTA2 "") ) (command "redraw") (setq PT1 PT2) (setq PT2 (getpoint "2nd point of fence" PT1)) (terpri) ) (setvar "textstyle" STY) ) The above programme could be easily modified to include include other text to indicate utility lines on the drawing. It is wis logics are fully understood. Tutorial: 1.
Draw the symbol of the section of a cut-off pipe and write an AutoLisp programme to fit the symbol to two selected points. file: PEND.LSP
2.
Wri Write an an Aut AutoL oLiisp pro program gramm me to to dra draw w rai raillway way lin lines es.. file: RAIL.LSP
3. Writ Write e an Auto AutoLi Lisp sp pro progra gramm mme e to draw draw a symb symbol ol to to repr represe esent nt an an exha exhaus ustt fan fan,, as show shown n on Fig. 8-6. The user input input will include include the location location for center of fan, and a point at the edge of fan only. Draw the grille and the blades on different layers. file: EXFAN.LSP “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes37
LESSON 9 entsel entget assoc ssget ssname ssname sslength subst subst entmod cdr
Open a drawing named AENTITIES@ which consist consist of 3 lines and 2 layers, layers, ROADEP ROADEP and ROADCL. At the command command prompt, prompt, type: type: (setq a2 a2 (entsel)) (entsel)) Computer response:
Select object: pick the solid line at right of the centerline.
Computer response:
( (8.51974 2.20869 0.0)
entsel
AutoLisp function to select an entity, and it ret urns the entity name and the coordinate of the point you picked.
On the drawing database all entities are identified by an alphanumeric name as shown above. It is by using this entity name we could tap into the information specific for that entity. AutoLisp function to extract the entity list which contains all information neccessary to describe the entity on the drawing database.
entget
At the command command prompt, prompt, type type (setq b2 (entget (entget (car (car a2))) a2))) Computer response:
((-1 . ) (0.@Line@))
Now all the information of the entity are assigned to the variable name, b2. When ! b2 is type, the whole list will be displayed. Each item in the list is really in two parts. The first is a code number that tells the function of that entity=s aspect. Listed below are a few code c ode numbers :0 description 6 line type name 7 text style name 8 layer name assoc
An AutoLisp function that searches for a sublist within any list. With an entity list, assoc uses the entity code number as key. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes38 at command prompt type:
(setq L1 (assoc 8 b2))
computer response:
(8 . AROADEP@)
at the command prompt type:
(setq L2 (cdr L1))
computer response:
AROADEP@
As shown, by using entsel, entget, car, assoc and cdr we could find the layer name of a selected entity. Therefore, it would not be too complicate to write an AutoLisp to set the current layer to a selected entity. Use text editor to type the following file: (defun c:setlayer () (graphscr) (setq A2 (entsel "Select object to set current layer: ")) (setq B2 (entget (car A2))) (setq L1 (assoc 8 B2)) (setq L2 (cdr L1)) (command "layer" "s" L2 "") ) The above example uses entsel to select an object. When many entities have to be selected at the same time, the function to use should be ssget. Usually after ssget is used, the number of objects selected has to be known so that a repeat function could be used to perform a certain task for each of the selected entity. sslength is the function to find out how many selected entities are there. Each selected entity also carry an index which starts from 0. ssname followed by the variable name of a selected set and the index will secure the name of an entity entity on the drawing database.. database.. Properties of an entity could be changed by changing the values of their sublist. subst and entmod are the functions to achieve this operation. ssget
AutoLisp function to select entities.
ssname
AutoLisp function to secure the name of an entity.
sslength
The function to determine the number of entities in a selection set.
subst
AutoLisp command the substitutes on entity sublist for another within an entity list. AutoLisp function that updates the drawing database with the new e ntity list. entmod Use a text editor to type the following file: (defun c:chlayer () (graphscr) (prompt Aselect objects to change to another layer@) (setq A1 (ssget)) (terpri) (setq A2 (entsel "Select object in the right layer:")) (setq N (sslength A1)) (setq INDEX 0) (setq B2 (entget (car A2))) (setq D2 (assoc 8 B2)) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes39 (repeat N (setq B1 (entget (ssname A1 INDEX))) IND EX))) (setq D1 (assoc 8 B1)) (setq B3 (subst D2 D1 B1)) (entmod B3) (setq INDEX (+ INDEX 1)) ) ) The following is another example to use the AutoLisp functions just introduced. cdr
AutoLisp function that produces the second and remaining elements in a list. e.g. if a is a list (4 (4 5 6 7), then (cdr a) will return (5 6 7).
(defun c:chtexth () (prompt Aselect the texts to be change...@) (setq A (ssget))(terpri) (setq TH (getreal "Enter new text height: ")) (setq N (sslength A)) (setq INDEX 0) (repeat N (setq B1 (entget (ssname A INDEX))) (setq INDEX (+ 1 INDEX)) (setq B (assoc 0 B1)) (if (= "TEXT" (cdr B)) (progn (setq C (assoc 40 B1)) (setq D (cons (car C) TH)) (setq B2 (subst D C B1)) (entmod B2) ) ) ) )
Data Type Programme ; Assignment no-1 ; data types (defun c:data() (setq a(getpoint "\n enter the co-ordinates") b(getint"\n enter the integer value =") c(getreal"\n enter the real value=")
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes40 d(getstring "\n enter the text/ number=") e(list 10 20 30 40 50 60 70 80 90 100 ) ) (print a) (print b) (print c) (print d) (print e) )
Math Programme ;my program ;math ;sachin gawade ;date 17/08/2010 (defun c:math() (setq a 10 b 50 c 12 d(+ a b c) e(- b c) f(* a b) g(/ b a) h(max a b c) i(min a b c) k(rem c a) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes41 l(sqrt a) n(log c) o(sin i) ) (princ d) (princ e) (princ f) (princ g) (princ h) (princ i) (princ k) (princ l) (princ n) (princ o)
DataConversion ;my program ;data conversion (defun c:data() (setq a(getint"\n enter width:") b(getreal"\n enter lenth:") c(getint"\n enter height:") h(fix a) d(float b) e(itoa a) f(rtos b) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes42 g(gcd a c) i(list a) j(list b) p(log a) q(exp a) ) (princ h) (princ d) (princ e) (princ f) (princ g) (princ i) (princ j) (princ p) (princ q) )
Descision Making (Using if Function) ;-----Program 6b ;----- Program on Descision Making (Using if Function) (defun C:DECI2 () (setq l(getreal "\n "\n Enter Length Length : ") h(getreal "\n Enter Height Height : ") ) (if (= h l) (progn “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes43 (prompt "The diagram is Square ") (setq x(* h h)) (print x) ) (progn (prompt "The diagram is Rectangle ") (setq x(* l h)) (print x))))
PROGRAM FOR LOOPING USING ;PROGRAM FOR LOOPING USING (defun c:conrect() (setq l(getreal "\n enter the length of rectangle")) (setq h(getreal "\n enter the hight of rectangle")) (setq pt1(list 0 0)) (setq n(getint "\n enter number of rectangles")) (setq pt2(list(+ (car pt1) l) (+ (cadr pt1) h))) (setq count 1) (while (<= count n) (command "rectangle" pt1 pt2) (setq pt1(list (- (car pt1) 10) (- (cadr pt1) 10))) (setq pt2(list (+ (car pt2) 10) (+ (cadr pt2) 10))) (setq count(+ count 1)) ) (command "zoom" "e") ) “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes44
I know – When I am teaching, I am learning more.
Questions on topic 7 1. Input the length of sides of triangle and check whether it forms a triangle or not. If it forms a triangle draw the triangle. 2. Input the diameter of flange. According to diameter of the flange create no of holes on the flange. 3. Input the end points of diagonal of the quadrilateral. Find out where it is square or rectangle. If it is a square or rec tangle then draw the same. Assume base of quadrilateral is parallel to x-axis. 4. Input the length of sides of triangle and find out which type of triangle it is and draw the same. 5. Draw a circle and pick a point on the screen. Find out whether the point lies inside or outside the circle. 6. Select a geometrical entity (line/circle). If it is line find the length angle of line. If it is a circle find radius and center points coordinate. 7. Draw a circle. Select option for hatching (1/2). If it is 1, draw hatch using select object option and if it is 2, then draw the hatch with pick point option. 8. Draw an arc. Find out the included angle of the arc. Depending upon the angle decide the no of division of the arc and divide the arc. 9. Draw square and circle (inscribe of circumscribe). Find out who is circumscribing what according to dimension. 10. Draw a line and pick a point on the line with mouse. Find F ind out whether that point lie left or right of the midpoint of the line. 11. Find the summation of series like: Sum=x+x^2+x^3+x^4+….. Sum= x-x^2+x^3-x^4+….. Sum= x-x^2/2!+x^3/3!-x^4/4!+….. 12. Input number of forces and find the resultant (magnitude and direction). Draw the force polygon. 13. Input the number of sides and draw polygon. (create polygon command) 14. Create polar array command for circle. 15. Create rectangular array command for circle. 16. Create multiple copy command for circle. 17. Draw f(x) curve for given limits. 18. Creating bill of material. 19. Move the object, if the object is selected is not nil with entsel. 20. Input x and y coordinates of n points and draw curve/line through them. 21. Select multiple entities of various types with ssget and find the types of entities. 1. Select line from screen and find coordinates of end points and length of line. Questions on topic 1-6 2. Select circle from screen and find coordinates of centre point, radius and area. 3. Select entity with w ith ssget and find the types of entities. 4. Draw rectangle. 5. Draw triangle. 6. Draw hexagon. 7. Input two strings from the user and perform various string operations. “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes45 8. Input two points from the user and perform various list filtering operations. 9. Find f(x) for two/three x values. 10. Input height of equilateral triangle and find the length of side, area and perimeter. Draw the same triangle. 11. Input height and base of isosceles triangle and find the length of side, area and perimeter. Draw the same triangle. 12. Input diagonal of square and find the length of side, area and perimeter. Draw D raw the same triangle. 13. Input area of equilateral triangle and find the length of side and perimeter. Draw the same triangle. 15. Parametric program of nut, bolt, surface roughness symbols etc. 16. Input two points from mouse and find distance and angle between the points. 17. Using string and data conversion functions draw rectangle. 18. Using string and data conversion functions draw hexagon. 19. Using string and data conversion functions draw pentagon. 20. Input string and number and perform various string functions.14. Input area of circle and find radius and perimeter. Draw the same circle. References’ ABC’s of AutoLISP by George Omura www.google.com AutoLISP by T.K.Naskar MDCG by F. Haideri Visual LISP AutoDESK
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes46
NOTICE FOR S.E. Mech. Mech. Engg. Engg. X AND Y Year - 2010-11 2010-11 SUBJECT :- FINAL TERM WORK CONTENT ASSIGNMENT NO 1
DRAWING ASPECTS WHAT IS CAD ? AUTOCAD ENTITIES WHAT AUTOCAD PROVIDES DRAWING AIDS, EDIT COMMANDS, DRAW COMMADS, MODIFY COMMANDS , ASSIGNMENT NO 2
LAYER AND ITS ADVANTAGES, REGEN, REDRAW. ASSIGNMENT NO 3
BLOCKS, SNAP, OSNAP, ASSIGNMENT NO 4
SCRIPT FILE PROGRAMMING, PROGRAMMING, ADVANTAGES AND LIMITATIONS , FLOW CHART ASSIGNMENT NO 5
a) INTR INTROD ODUC UCTI TION ON TO AUT AUTOL OLIS ISP P WORKING WITH AUTOLISP USING LIST FUNCTION “I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"
Z:Swapnil A. Kale/MDCG/LISP/Notes47
b) c) d)
e) f) g) f)
CREATING – PASSING INFORMATION – RUN PROGRAM – IN AUTOCAD AUTOLISP SUMMARY DATA TYPE: - List, String, Real, Integer, File Descriptor, Descriptor, Object Name, PICK SET MATH MATH FUNCT FUNCTION IONS:S:- All Functi Functions ons DATA CONVERSI CONVERSION:ON:- Integer Integer to real , Integer Integer to string string , integer integer to list, list, real to integer Real to string, real to list LIST LIST FILTER FILTERING ING::- car car , cdr cdr , cadr cadr , caddr caddr PARA PARAME METR TRIC IC PRO PROGR GRAM AMMI MING NG::LOOPING FILE HANDELLING
“I hear and I forget. I see and I remember. I do and I unders understand." tand." -Confucius"