Macro ProgrammingGuide PowerMill
Macro ProgrammingGuide PowerMill
Trademarks
The following are registered trademarks or trademarks of Autodesk, Inc., and/or
its subsidiaries and/or affiliates in the USA and other countries: 123D, 3ds Max,
Alias, ArtCAM, ATC, AutoCAD LT, AutoCAD, Autodesk, the Autodesk logo,
Autodesk 123D, Autodesk Homestyler, Autodesk Inventor, Autodesk MapGuide,
Autodesk Streamline, AutoLISP, AutoSketch, AutoSnap, AutoTrack, Backburner,
Backdraft, Beast, BIM 360, Burn, Buzzsaw, CADmep, CAiCE, CAMduct, Civil 3D,
Combustion, Communication Specification, Configurator 360, Constructware,
Content Explorer, Creative Bridge, Dancing Baby (image), DesignCenter,
DesignKids, DesignStudio, Discreet, DWF, DWG, DWG (design/logo), DWG
Extreme, DWG TrueConvert, DWG TrueView, DWGX, DXF, Ecotect, Ember,
ESTmep, FABmep, Face Robot, FBX, FeatureCAM, Fempro, Fire, Flame, Flare,
Flint, ForceEffect, FormIt 360, Freewheel, Fusion 360, Glue, Green Building
Studio, Heidi, Homestyler, HumanIK, i-drop, ImageModeler, Incinerator, Inferno,
InfraWorks, Instructables, Instructables (stylized robot design/logo), Inventor,
Inventor HSM, Inventor LT, Lustre, Maya, Maya LT, MIMI, Mockup 360, Moldflow
Plastics Advisers, Moldflow Plastics Insight, Moldflow, Moondust, MotionBuilder,
Movimento, MPA (design/logo), MPA, MPI (design/logo), MPX (design/logo), MPX,
Mudbox, Navisworks, ObjectARX, ObjectDBX, Opticore, P9, PartMaker, Pier 9,
Pixlr, Pixlr-o-matic, PowerInspect, PowerMill, PowerShape, Productstream,
Publisher 360, RasterDWG, RealDWG, ReCap, ReCap 360, Remote, Revit LT,
Revit, RiverCAD, Robot, Scaleform, Showcase, Showcase 360, SketchBook,
Smoke, Socialcam, Softimage, Spark & Design, Spark Logo, Sparks,
SteeringWheels, Stitcher, Stone, StormNET, TinkerBox, Tinkercad, Tinkerplay,
ToolClip, Topobase, Toxik, TrustedDWG, T-Splines, ViewCube, Visual LISP, Visual,
VRED, Wire, Wiretap, WiretapCentral, XSI
All other brand names, product names or trademarks belong to their respective
holders.
Disclaimer
THIS PUBLICATION AND THE INFORMATION CONTAINED HEREIN IS MADE
AVAILABLE BY AUTODESK, INC. "AS IS." AUTODESK, INC. DISCLAIMS ALL
WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE REGARDING THESE MATERIALS.
Contents
Macros 1
Creating macros ................................................................................................. 1
Recording macros in PowerMill .......................................................................... 2
Running macros ......................................................................................... 3
Editing macros............................................................................................ 3
Running macros from within macros .......................................................... 4
Writing your own macros .................................................................................... 5
PowerMill commands for macros ............................................................... 6
Adding comments to macros ...................................................................... 7
Macro User Guide ...................................................................................... 8
Variables in macros .................................................................................. 27
Using expressions in macros.................................................................... 47
Operator precedence ............................................................................... 48
Executing a macro string variable as a command using DOCOMMAND . 50
Macro functions ........................................................................................ 51
IF statement ............................................................................................. 55
IF - ELSE statement ................................................................................. 56
IF - ELSEIF - ELSE statement.................................................................. 57
SWITCH statement .................................................................................. 58
Running macros without displaying GUI items ......................................... 61
BREAK statement in a SWITCH statement .............................................. 61
Repeating commands in macros .............................................................. 62
Creating sequences ................................................................................. 66
RETURN statement .................................................................................. 67
Printing the value of an expression .......................................................... 68
Constants ................................................................................................. 69
Built-in functions ....................................................................................... 69
Entity based functions ............................................................................ 103
Model hierarchy .............................................................................................. 107
Model Component Functions.................................................................. 107
Model Hierarchies .................................................................................. 108
Nodes ..................................................................................................... 108
Walking the hierarchy ............................................................................. 109
Getting a Node by its Path...................................................................... 109
Getting the Hierarchy as a List ............................................................... 110
Model metadata...................................................................................... 110
Feature Parameters ........................................................................................ 111
Working with files and directories ................................................................... 112
File reading and writing in macros .................................................................. 113
Frequently asked questions ............................................................................ 116
Organising your macros .................................................................................. 118
Index 125
Creating macros
You can create macros by:
Recording (see page 2) a sequence of commands within
PowerMill.
Writing your own macro (see page 5) using a text editor.
Editing macros
You can edit recorded macros to troubleshoot and correct any
errors.
1 Expand Macros and select the macro you want to edit.
Basic macro
This shows you how to create and run a basic macro using
PowerMill's programming language.
1 In a text editor such as WordPad enter:
PRINT "10 green bottles sitting on the wall"
PRINT "10 green bottles sitting on the wall"
PRINT "And if 1 green bottle should accidentally fall"
When you have defined a local variable you can use it as many
times as you want in a macro.
You can define as many local variables as you want in a macro.
The empty lines are not necessary, but they make it easier
to read the macro.
2 Save the file as example.mac.
3 In PowerMill, Run the Macro. The command windows displays:
DO - WHILE loop
1 Edit the PrintBottles function in example.mac to
IF statement
You can use an IF statement to ensure the 10 green bottles sitting on
the wall line is printed at least twice.
1 Edit the Main function in example.mac to:
FUNCTION Main (INT Count) {
Each code block or function can define its own set of local
variables; the scope of the variable is from its declaration
to the end of the enclosing block or function.
4 Add the NumberStr function into example.mac.
FUNCTION PrintBottles(INT Count, INT Number) {
This gives exactly the same output as the Returning values from
macros (see page 19) example. It shows you an alternative way
of creating the same output.
This gives exactly the same output as the Returning values from
macros (see page 19) example. It shows you an alternative way
of creating the same output.
Variables in macros
You can create variables in macros just as you can in a PowerMill
project. When you create a variable in a macro, it has the same
properties as a PowerMill parameter, and can store either a value or
an expression.
Assigning parameters
When you assign a value to a variable the expression is evaluated
and the result is assigned, the actual expression is not retained.
This is the same as using the EVAL modifier in the PowerMill
parameter EDIT PAR command. These two statements are
equivalent:
EDIT PAR "Stepover" EVAL "Tool.Diameter * 0.6"
$Stepover = Tool.Diameter * 0.6
This command returns the name of the tool the user selected.
This example creates two folders, creates two tool in each folder,
then asks the user to select one of the tools:
// Create some tools in folders
CREATE FOLDER 'Tool' 'Endmills'
CREATE IN 'Tool\Endmills' TOOL 'End 20' ENDMILL
EDIT TOOL ; DIAMETER 20
CREATE IN 'Tool\Endmills' TOOL 'End 10' ENDMILL
EDIT TOOL ; DIAMETER 10
CREATE FOLDER 'Tool' 'Balls'
CREATE IN 'Tool\Balls' TOOL 'Ball 12' BALLNOSED
EDIT TOOL ; DIAMETER 12
CREATE IN 'Tool\Balls' TOOL 'Ball 10' BALLNOSED
EDIT TOOL ; DIAMETER 10
// Prompt user to pick one
STRING ToolName = ''
$ToolName = INPUT ENTITY TOOL "Please select a Tool."
You can also ask for the selection of a number of entities. The result
is the list of entities selected, which can be assigned to either a list
of strings, or list of entities.
ENTITY LIST $Selected_Toolpaths = INPUT ENTITY MULTIPLE
toolpath "which toolpaths do you want to check?"
STRING LIST ToolpathNames = INPUT ENTITY MULTIPLE
TOOLPATH "Select toolpaths to check"
You can then iterate over the user selection with a FOREACH loop:
Lists
PowerMill also has a LIST type. The main difference between a list
and an array is that the list does not have a fixed size, so you can
add and remove items to it. You can create lists:
that are empty to start with
from an initialisation list
from an array.
// Create an empty list
STRING LIST MyStrings = {}
// Create a list from an array
STRING LIST MyList = MyArray
// Create a list using an initialisation list
STRING LIST MyListTwo = {'First','Second'}
You can use two inbuilt functions add_first() and add_last() to
add items to a list.
For example using the inbuilt function add_last():
CREATE PATTERN Daffy
CREATE PATTERN Duck
// Create an empty list of strings
STRING LIST Patterns = {}
FOREACH pat IN folder('Pattern') {
// Add the name of the pattern to the list
int s = add_last(Patterns, pat.Name)
}
FOREACH name IN Patterns {
PRINT = $name
}
Prints:
Daffy
Duck
You can also add items to the front of a list by using the inbuilt
function add_first():
CREATE PATTERN Daffy
Using lists
A list, like an array, contains multiple values. You can create a list
with initial values:
INT LIST MyList = {1,2,3,4}
FUNCTION Main() {
INT LIST MyList = {10,20,30,40}
CALL PrintArray(MyList)
}
FOREACH tp IN folder('Toolpath\MyFolder') {
INT Size = add_last(TpNames, tp.name)
}
For more information see Adding comments to macros (see page
88).
Building a list
You can use the inbuilt member() function in a macro function to
build a list of tool names used by toolpaths or boundaries without
any duplicates:
FUNCTION ToolNames(STRING FolderName, OUTPUT STRING LIST
ToolNames) {
Subtract function
You can use the subtract() function to determine what happened
after carrying out a PowerMill command. For example, suppose you
to find out if any new toolpaths are created during a toolpath
verification. If you get the list of toolpath names before the
operation, and the list of names after the operation, and then
subtract the ‘before’ names from the ‘after’ names you are left with
the names of any new toolpaths.
FUNCTION GetNames(STRING FolderName, OUTPUT STRING LIST
Names) {
FOREACH item IN folder(FolderName) {
INT n = add_last(Names, item.Name)
FUNCTION Main() {
IF is_empty(NewNames) {
PRINT "No new toolpaths were created."
} ELSE {
PRINT "The new toolpaths created are:"
FOREACH item IN NewNames {
PRINT = item
}
}
}
Entity variables
PowerMill has a special variable type ENTITY. You can use ENTITY
variables to refer to existing PowerMill entities such as toolpaths,
tools, boundaries, patterns, workplanes, and so on. You cannot use
this command to create new entities.
For example:
// create an entity variable that references boundary
entity 'Duck'
ENTITY Daffy = entity('boundary','Duck')
The inbuilt functions, such as folder() return lists of entities so
you can store the result of the call in your own list and array
variables:
For example:
ENTITY List Toolpaths = folder('toolpath')
When looping over folder items in a FOREACH the loop variable that
is automatically created has the type ENTITY. Therefore the
following code is syntactically correct:
FOREACH tp IN folder('toolpath') {
ENTITY CurrentTP = tp
PRINT = CurrentTP.Name
}
FUNCTION Main() {
ENTITY TP = entity('toolpath','1')
CALL Test(TP)
PRINT = TP.Name
}
Additionally, you can use an ENTITY variable anywhere in PowerMill
that is expecting a entity name.
For example:
ENTITY tp = entity('toolpath','1')
ACTIVATE TOOLPATH $tp
Object variables
PowerMill has a variable type called OBJECT which can hold any
collection of variables that PowerMill pre-defines, such as Block or
Connections.
For example:
// Get the current set of block parameters
OBJECT myObject = Block
// Activate a toolpath (this may change the block)
ACTIVATE TOOLPATH "Daffy"
// Reset the block to its old state
$Block = myObject
Whilst you cannot create an ARRAY of OBJECT you can create a
LIST of OBJECTs:
For example:
OBJECT LIST myObjects = {Block,Connections}
FOREACH ob IN myObjects {
PRINT PAR "ob"
}
As you can see from the above example, each object in a list may
be different. It is the responsibility of the macro writer to keep track
of the different types of OBJECT. PowerMill has an inbuilt function
get_typename() to help with this.
For example:
OBJECT LIST myObjects = {Block,Connections}
FOREACH ob IN myObjects {
PRINT = get_typename(ob)
Logical operators
Logical operators let you to do more than one comparison at a time.
There are four logical operators:
AND
OR
XOR
NOT
Scope of variables
A variable exists from the time it is declared until the end of the
block of code within which it is declared. Blocks of code are macros
and control structures (WHILE, DO - WHILE, SWITCH, IF-ELSEIF-
ELSE, and FOREACH).
A variable, with a specific name, can only be defined once within
any block of code.
For example,
// Define a local variable 'Count'
INT Count = 5
// Define a second local variable 'Count'
INT Count = 2
Gives an error since Count is defined twice.
// Assignments
$Stepover = Tool.Diameter * factor
$factor = 0.75
Operator precedence
The order in which various parts of an expression are evaluated
affects the result. The operator precedence unambiguously
determines the order in which sub-expressions are evaluated.
Multiplication and division are performed before addition and
subtraction.
For example, 3 * 4 +2 is the same as 2 + 3 * 4 and gives the
answer 14.
Exponents and roots are performed before multiplication and
addition.
For example, 3 + 5 ^ 2 is the same as 3 + 5 and gives the
answer 28.
-3 ^ 2 is the same as -3 and gives the answer -9.
Use brackets (parentheses) to avoid confusion.
For example, 2 + 3 * 4 is the same as 2 + (3 * 4) and gives the
answer 14.
Precedence
Order Operation Description
1 () function call, operations
grouped in parentheses
2 [] operations grouped in square
brackets
3 +-! unary prefix (unary operations
have only one operand, such
as, !x, -y)
4 cm mm um ft unit conversion
in th
5 ^ exponents and roots
6 */% multiplication, division, modulo
7 +- addition and subtraction
8 < <= > >= relational comparisons: less
(LT, LE, GT, than, less than or equal,
GE) greater than, greater than or
equal
Macro functions
When you run a macro you can use arguments, such as the name of
a toolpath, tool, or a tolerance. You must structure the macro to
accept arguments by creating a FUNCTION called Main (see page
52) then specify the arguments and their type.
For example, a macro to polygonise a boundary to a specified
tolerance is:
FUNCTION Main(REAL tol) {
EDIT BOUNDARY ; SMASH $tol
}
A macro to set the diameter of a named tool is:
FUNCTION Main(
STRING name
REAL diam
)
{
EDIT TOOL $name DIAMETER $dia
}
To run these macros with arguments add the arguments in the
correct order to the end of the MACRO command:
MACRO MyBoundary.mac 0.5
Main function
If a macro has any functions:
It must have one, and only one, FUNCTION called Main.
The Main function must be the first function called.
Function names are not case sensitive: MAIN, main, and MaIn all
refer to the same function.
FUNCTION Main() {
REAL Par1 = 2
REAL Par2 = 1
CALL Test(Par1, Par2)
// Prints 2 - value is unchanged
PRINT $Par1
// Prints 0 - value has been changed
PRINT $Par2
}
When the CALL command is executed in the MAIN function:
1 PowerMill creates a new REAL variable called aInput. It is
assigned the value of Par1, and passed into Test.
2 PowerMill passes Par2 directly into Test where it is known as
aOutput.
INCLUDE common.inc
FUNCTION Main(input string bound) {
FOREACH bou IN folder(bound) {
CALL CleanBoundary(bou.Name)
}
}
To call this macro from PowerMill:
IF statement
The IF statement executes a series of commands when a certain
condition is met.
The basic control structure is:
IF <expression> {
Commands A
}
Commands B
If expression is true then Commands A are executed, followed by
Commands B.
If expression is false, then only Commands B are executed.
The first brace must be the last item on the line and on the
same line as the IF.
The closing brace must be on a line by itself.
IF - ELSE statement
The IF - ELSE statement executes a series of commands when a
certain condition is met and a different series of commands
otherwise.
The basic control structure is:
IF <expression> {
Commands A
} ELSE {
Commands B
}
Commands C
If expression is true, then Commands A are executed followed by
Commands C.
SWITCH statement
When you compare a variable with a number of possible values and
each value determines a different outcome, it is advisable to use the
SWITCH statement.
The SWITCH statement enables you to compare a variable against a
list of possible values. This comparison determines which
commands are executed.
The basic control structure is:
For example,
FOREACH item IN folder("path") {
Commands A
}
Commands B
Where <path> is a folder in the Explorer such as, Toolpath, Tool,
Toolpath\Finishing.
Within FOREACH loops, you can:
Cancel the loop using the BREAK (see page 66) statement.
Jump directly to the next iteration using the CONTINUE (see page
66) statement.
WHILE loop
A WHILE loop repeatedly executes a block of commands until its
conditional test is false.
The basic control structure is:
WHILE condition {
Commands A
}
Commands B
If condition is true, then Commands A are executed.
While condition remains true, then Commands A are executed.
DO - WHILE loop
The DO - WHILE loop executes a block of commands and then
performs its conditional test, whereas the WHILE loop checks its
conditional test first to decide whether to execute its commands or
not.
The basic control structure is:
DO {
Commands A
} WHILE condition
Commands B
Commands A are executed.
While condition remains true, then Commands A are executed.
When condition is false, Commands B are executed.
Creating sequences
Use the make_sequence and next_in_sequence functions to create
sequences. Sequences contain:
RETURN statement
If a macro contains functions, the RETURN statement immediately
exits the function. If the macro does not contain functions, the
RETURN statement immediately terminates the current macro. This
is useful if an error is detected and you do not want to continue with
the remaining commands in the macro.
The basic control structure is:
EDIT TOOLPATH $tp.Name CALCULATE
IF NOT Computed {
// terminate if toolpath did not calculate
RETURN
}
To immediately exit from a function:
IF NOT active(entity('toolpath',TpName).Tool.TipRadius)
{
// Error if toolpath does not use a tipradius tool
PRINT "Toolpath does not have TipRadius tool"
RETURN
}
FUNCTION Main() {
FOREACH tp IN folder('Toolpath') {
ACTIVATE TOOLPATH $tp.Name)
}
}
Terminating macros
The command MACRO ABORT immediately terminates the current
macro.
The command MACRO ABORT ALL terminates the all the macros that
are currently running. If you call MACRO ABORT ALL from within a
macro that has been called by another macro, then both macros are
terminated.
Built-in functions
This section details all the built-in functions that you can use in your
macros.
General mathematical functions (see page 69).
Trigonometrical functions (see page 70).
Vector and point functions (see page 70).
Workplane functions (see page 73).
String functions (see page 73).
List creation functions (see page 83).
Path functions (see page 93) (Folder (see page 94), Directory
(see page 94), Base (see page 95), and Project (see page 95)
names).
Conditional functions (see page 97).
Evaluation functions (see page 97).
Type conversion functions (see page 99).
Parameter functions (see page 99).
Statistical functions (see page 102).
Trigonometrical functions
The basic structure of the trigonometrical functions are:
Description of return value Function
Trigonometric sine real sin( angle )
Trigonometric cosine real cos( angle )
Trigonometric tangent real tan( angle )
Trigonometric arcsine real asin( real a )
Trigonometric arccosine real acos( real a )
Trigonometric arctangent real atan( real a )
Trigonometric arctangent of real atan2( real a, real
a/b, quadrant is determined b )
by the sign of the two
arguments
Length
The length() function returns the length of a vector.
For example:
REAL ARRAY V[] = {3,4,0}
// Prints 5.0
PRINT = length(V)
The inbuilt function unit() returns a vector that points in the same
direction as the input vector, but has a length of 1:
PRINT PAR "unit(V)"
// [0] (REAL) 0.6
// [1] (REAL) 0.8
// [2] (REAL) 0.0
// prints 1.0
PRINT = length(unit(V))
Parallel
The parallel() function returns TRUE if two vectors are either
parallel (pointing in the same direction) or anti-parallel (pointing in
the opposite direction) to each other.
For example:
// prints 0
PRINT = parallel(VecX,Vecy)
// prints 1
PRINT = parallel(VecX,VecX)
Print = parallel(MVecZ,VecZ)
Normal
The normal() function returns a vector that is normal to the plane
containing its two input vectors. If either vector is zero it returns an
error. If the input vectors are either parallel or anti-parallel a vector
of zero length is returned.
For example:
REAL ARRAY norm = normal(VecX,VecY)
Setting
The set_vector() and set_point() functions return the value 1 if
the vector or point is set.
For example:
REAL ARRAY Vec1[3] = {0,0,1}
REAL ARRAY Vec2[3] = {0,1,0}
REAL X = Block.Limits.XMax
REAL Y = Block.Limits.YMin
REAL Z = Block.Limits.ZMax
ok = set_point(ToolAxis.Origin, X,Y,Z)
Unit vector
The unit() function returns the unit vector equivalent of the given
vector.
For example:
REAL ARRAY V[3] = {3,4,5}
PRINT PAR "unit(V)"
BOOL ok = set_vector(V,0,0,6)
PRINT PAR "unit(V)"
String functions
PowerMill parameters and variables can contain strings of
characters. There are a number of inbuilt functions that you can use
to test and manipulate strings.
The basic structure of string functions are:
Description of return value Function
Returns the number of int length( string str )
characters in the string.
For more information see
Length function in a string
(see page 78).
Returns the position of the int position( string str,
string target from the start of string target[, numeric
the string str, or -1 if the start] )
target string is not found.
If you use the optional
argument start then scanning
begins from that position in
the string.
For more information see
Position function in a string
(see page 78).
Example
The following example shows how to use the time() function to
measure how long an activity takes:
INT old_time = time()
EDIT TOOLPATH ; CALCULATE
INT cumulative_time = time() - old_time
STRING msg = "Toolpath calculation took " +
(cumulative_time) + "secs"
MESSAGE INFO $msg
Example
Getting and formatting the current time:
INT tm=time()
STRING ARRAY $timestamp[] =
tokens(utc_time($tm).timestamp, "-") STRING clock =
$timestamp[3] + ":" + $timestamp[4] $clock = $clock + ":"
+ $timestamp[5] PRINT $clock
Another example:
STRING One = "One"
STRING Two = "Two"
STRING CountToTwo = One + ", " + Two
PRINT = length(CountToTwo)
The command window displays the result, 8.
Substrings
The substring function returns part of the string. You can define
where the substring starts and its length. The original string is
unchanged.
The basic structure is:
string substring( string str, int start, int length)
For example:
PRINT = substring("Scooby doo", 2, 4)
The command window displays the result, ooby.
Previously Draft_ConstZ was not renamed, but it is this time. All the
toolpath names are now upper case.
Whitespace in a string
Use the following functions to remove whitespace from a string:
ltrim()— Removes leading whitespace.
rtrim() — Removes trailing whitespace.
trim() — Removes leading and trailing whitespace.
List functions
List functions control the content of a list or array.
The basic structure of list functions are:
Description Function
Returns the components (see list components( entity
page 84) of another object. entity )
Returns a list of specified size list fill (int size, object
containing elements with value )
specified value.
Returns a list of all the list folder( string folder
entities in the folder (see page )
85).
Determines if the list has any is_empty()
content (see page 86).
Determines if the list contains member()
a specific value (see page 86).
Adding (see page 87) a list or +
array to another list or array
Removes duplicate (see page remove_duplicates()
87) items from a list.
List components
The inbuilt components function returns the components of another
object.
List fill
The fill() function returns a list of a specified size, which contains
elements of a specified value.
The basic structure is:
list fill(int size, object value)
For example, if you wanted to create a list in which abc was
repeated three times:
STRING ARRAY str_arr[] = fill(3, "abc")
// str_arr = {"abc", "abc", "abc"}
If you wanted to create a list in which 5 was repeated five times:
INT LIST int_ls = fill(5, 5)
// int_ls = {5, 5, 5, 5, 5}
List folder
The folder() function returns a list of all entities within a folder,
including those in subfolders.
The basic structure is:
list folder( string folder )
The names of the root folders are:
MachineTool
NCProgram
Toolpath
Tool
The name of the folder is case sensitive, so you must use Tool
and not tool.
You can use a FOREACH loop to process all of the entities within a
folder. For example, to batch process tool holder profiles:
FOREACH tool IN folder ('Tool'){
EDIT TOOL $tool.Name UPDATE_TOOLPATHS_PROFILE
}
An example, to batch process all the boundaries in your project:
FOREACH bou IN folder('Boundary') {
EDIT BOUNDARY $bou.Name CALCULATE
}
Empty list
The is_empty() function queries a list to determine whether it is
empty or not.
REAL LIST MyList = {}
IF is_empty(MyList) {
PRINT "Empty List"
}
List member
The member() function returns TRUE if the given value is one of the
items in the list. For example, to check that a toolpath does not
occur in more than one NC program, you can loop over all
NCProgram and check that each toolpath is only seen once. Do this
by building a list of toolpath names and checking that each time you
add a name you have not already seen it.
// Create an empty list
STRING List names = {}
// Cycle through the NC programs
FOREACH ncp IN folder('NCProgram') {
// loop over the components in the nc program
FOREACH item IN components(ncp) {
Adding lists
The + function adds a list or array to another list or array. For
example, you can add two lists together to get a list of all the tools
used by the toolpaths and boundaries:
STRING LIST UsedToolNames = ToolpathTools + BoundaryTools
The FOREACH loop adds each item to the start of the list. As the
add_first command adds the next pattern to the start of the list.
So you end up with a list
{"Pattern_3","Pattern_2,"Pattern_1"}.
The WHILE loop takes the first item in the list, removes it from the
list and pints it. This gives:
Pattern_3
Pattern_2
Pattern_1
The FOREACH loop adds each item to the end of the list. As the
add_last command adds the next pattern to the end of the list. So
you end up with a list {"Pattern_1","Pattern_2,"Pattern_3"}.
The WHILE loop takes the last item in the list, removes it from the
list and pints it. This gives:
Pattern_3
Pattern_2
Pattern_1
To end up with the patterns in the same order as they are in the
Explorer either:
In the FOREACH loop use the add_last command and in the
WHILE loop use the remove_first command; or
In the FOREACH loop use the add_first command and in the
WHILE loop use the remove_last command.
Sorted list
The sort function sorts lists and arrays of scalars (numerics or
strings) or objects and entities. By default, the functions sort a list
in ascending order. If you want to sort the list in descending order,
you can apply the reverse function to the list.
If you are sorting a list of objects and entities, you must provide a
field name for the sort.
The following examples sort lists of scalar values (numerics and
strings):
STRING LIST l1 = {"The","Twelth","Night"}
$l1 = sort(l1)
// returns the list {"Night", "The", "Twelth"}
REAL ARRAY a1 = {23, 12, 4, 52, 32}
$a1 = sort(a1)
// Returns the list {4, 12, 23, 32, 52}
When sorting non-scalar values, such as entities or objects, you
must provide a sort field that is a scalar value:
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 2.0
CREATE TOOLPATH 'bbb' RASTER
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 1.0
CREATE TOOLPATH 'ccc' RASTER
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 1.5
CREATE TOOLPATH 'aaa' RASTER
For example:
ENTITY LIST ents = sort(folder('toolpath'),'name')
// Returns the list of toolpath {'aaa','bbb','ccc'}
Path functions
The path functions returns part of the pathname of the entity,
The basic structure of the path functions are:
Description of return value Function
The Folder name (see page string pathname( entity
94) function returns the full ref )
folder name of the entity, or
an empty string if the entity
does not exist.
The Folder name (see page string pathname( string
94) function can also be used type, string name)
to return the full folder name
of the entity.
The Directory name (see page string dirname( string
94) function returns the path)
directory prefix from the path.
The Base name (see page 95) string basename( string
function returns the non- path)
directory suffix from the path.
The Project name (see page project_pathname(bool
95) functions returns the basename)
pathname of the current
project on disk.
The Active folder (see page String active_folder()
96) functions returns folder
names of active entities.
The Folder list (see page 96) String
functions returns the names folder_list(folder_name)
of folders in the PowerMill
project.
Directory name
The directory name function returns the directory prefix from the
path.
The basic structure is:
string dirname( string path)
For example you can use this to obtain the argument for the inbuilt
folder() function.
STRING folder = dirname(pathname('toolpath',Name))
Project name
The project pathname function returns the pathname of the current
project on disk.
The basic structure is:
project_pathname(bool basename)
The argument dirname_only gives a different result if it is true to if
it is false.
Conditional functions
The basic structure of conditional functions are:
Description of return value Function
Returns the value of variant select(
expression 1 if the conditional conditional-expression;
expression is true, otherwise expression1;expression2)
it returns the value of
expression 2.
Evaluation functions
The evaluation function evaluate a string argument as an
expression.
For example:
print = evaluate("5*5")
prints 25.
FUNCTION Main() {
/Set up some data
REAL ARRAY Data[] = {9,10,3,4,1,7,2,8,5,6}
// Sort in increasing value
CALL SortReals("List[Idx] > List[Idx+1]", Data)
PRINT PAR "Data"
REAL ARRAY Data1[] = {9,10,3,4,1,7,2,8,5,6}
// Sort in decreasing order
CALL SortReals("List[Idx] < List[Idx+1]", Data1)
PRINT PAR "Data1"
}
Enumerator parameter
The values() function returns a list of display names for an
enumerator parameter, such as Tool.Type, CutDirection, or
Strategy. The names are translated into the current language that a
user is working in. This list can be used to gather input from the
user with the CHOICE dialog. For example, to ask the user which
cut direction they would like to use, you can use the following code:
// Get names for the choices the user can make for this
parameter
STRING ARRAY Opts[] = values(CutDirection)
Parent parameter
The parent() function enables you to access and specigy machine
tool parameters in a more user friendly way. For example:
//To change the opacity of a machine tool/Robot table
with AXIS ADDRESS T, the following syntax can be used
EDIT PAR "parent(machine_axis('T')).ModelList.Opacity"
"25"
//Check the way the 'parent' function works...
CREATE TOOL ; BALLNOSED
EDIT TOOL "1" DIAMETER "20"
real error = 0
$error = ERROR parent(Tool)
print $error
//returns 1.0 as it fails finding the parent of a root -
'TOOL' is the root
$error = ERROR parent(Tool.Diameter)
print $error
//returns 0 as it finds the parent Tool of Tool.Diameter
Statistical functions
The statistical functions enable you to return the minimum and
maximum values of any number of numeric arguments.
The basic structure of the statistical functions are:
Description of return value Function
Returns the largest value in a real max( list numeric a
list of numbers. )
Returns the smallest value in real min( list numeric a
a list of numbers. )
This example finds the maximum and minimum block height of the
toolpaths in the active NC program.
REAL maxz = -100000
REAM minz = abs(maxz)
FOREACH item IN components(entity('ncprogram','')) {
IF item.RootType == 'nctoolpath' {
$maxz = max(maxz,entity('toolpath',item.Name))
$minz - min(minz,entity('toolpath',item.Name))
}
}
MESSAGE "Min = " + string(minz) + ", max = " +
string(maxz)
Equivalence
You can use the inbuilt function geometry_equal() to test whether
two tools, or two workplanes are geometrically equivalent. For a
tool the test is based on the cutting geometry of the tool.
Number of segments
The inbuilt function segments() returns the number of segments in
a pattern or boundary:
IF segments(Pattern) == 0 {
PRINT "The pattern is empty"
}
To return the number of segments in a toolpath, use:
function toolpath_component_count(toolpath,type)
For example:
print par ${toolpath_component_count('toolpath', '1',
'links')}
print par ${toolpath_component_count('toolpath', '1',
'leads')}
print par ${toolpath_component_count('toolpath', '1',
'segments')}
Limits
The inbuilt function limits() returns an array of six elements
containing the XYZ limits of the given entity. The supported entities
are: pattern, boundary, toolpath, feature set, or model.
REAL ARRAY Lims[] = limits('model','MyModel')
The values in the array are:
REAL MinX = Lims[0]
REAL MaxX = Lims[1]
REAL MinY = Lims[2]
REAL MaxY = Lims[3]
REAL MinZ = Lims[4]
REAL MaxZ = Lims[5]
IF NOT entity_exists(entity('toolpath','')) {
PRINT "Please activate a toolpath and try again."
MACRO ABORT ALL
}
// Prints 4
PRINT = new_entity_name('workplane')
DELETE WORKPLANE 2
// Prints 2
PRINT = new_entity_name('workplane')
// Prints 2_1
PRINT = new_entity_name('workplane', '2')
Function Main(
STRING $Selected_Toolpath
)
{
// Create new project parameter to store the holder
clearance
BOOL $chk = 0
$chk = ERROR $project.clearance
Enter line and line without line breaks. The lines only
appear to include line breaks because of the limited page
width.
Model hierarchy
Model Component Functions
INT select_components(DATA components)
INT deselect_components(DATA components)
These functions select or deselect all of the components in the
passed-in data parameter. The data parameter must store a
ModelCompList or ModelCompSet. The return value is numeric, but
carries no information.
Model Hierarchies
Some CAD systems store models in a hierarchical structure. When
PowerMILL reads these CAD files it creates a parameterised
representation of this structure. This structure can be navigated as
a tree, and there are two helper functions, one to retrieve a node
from the hierarchy by its path, and the other to retrieve the
hierarchy (or a subsection of the hierarchy) as a list that can be
filtered or iterated over.
Nodes
The hierarchy of a model is made up of nodes. These are maps with
typename "ModelHierarchyElement". They have the following
properties:
Property Type Description
Name STRING The name associated with the node
in the hierarchy. The root node’s
name will be the same as the
model’s name.
Path STRING The path to the node. It consists of
the names of the node’s ancestors,
starting with the root node,
separated by backslashes. It
includes the node’s name.
Parent MAP The parent of this node in the
(typename: hierarchy. The root node’s Parent is
ModelHierarchyElemen always an error. For all other
t) nodes, it will be a map of this type.
Children ARRAY of MAPs A list of the children of the node in
(typename: the hierarchy. Each child node is a
ModelHierarchyElemen map of this type.
t)
Compone DATA A list of the model components
nts {ModelCompList} associated with the node.
Parameter MAP Key-Value pairs associated with the
s (typename: node.
ModelMetadata)
Model metadata
Exchange can extract the metadata from 3rd party CAD files and
communicate them to PowerMill during the translation process.
Metadata is accessible through parameters which are associated
with groups, workplanes and geometries. These are used to store
information relevant to the machining of an item.
Metadata on geometry
The components() parameter function is extended to include a data
parameter which stores a list of model components, including
surfaces, and returns a list of the components in a parameterised
form.
The parameterized components are objects with the following
properties:
Metadata on workplanes
There are are parameters to represent workplanes in the hierarchy.
These are maps with the following properties:
Name — The name of the workplane.
Origin — The origin of the workplane. This is an array of 3 REALs.
XAxis — The X axis of the workplane. This is an array of 3 REALs.
YAxis — The Y axis of the workplane. This is an array of 3 REALs.
ZAxis — The Z axis of the workplane. This is an array of 3 REALs.
Parameters — A map of the metadata associated with the
workplane.
If a workplane in an imported model has the same name as an
existing workplane in PowerMill but a different origin or orientation,
the parameter will store the original name.
Feature Parameters
You can use the inbuilt components() function to loop over the
features within a feature set. Each feature has the following
parameters:
Name — Name of Feature.
ID — Id of Feature.
RootType — 'feature' as a string.
num_items — Number of sub-holes.
Type — Type of feature (pocket, slot, hole, boss).
Top — Top of feature, z-value relative to Origin.
Bottom — Bottom of feature, z-value relative to Origin.
Depth — Depth of feature, from top to bottom.
Diameter — Diameter of feature.
Draft — Draft angle.
Example
// get a list of all the files in the working directory
STRING LIST files = list_files("files",pwd())
How do I only loop over the items in a parent folder (and exclude any
subfolders)?
As described above, the folder() function returns items from a
parent folder and any subfolders. If you only want to loop over the
items in the parent folder, you need to filter the results. For
example, if you have the folder 'Semi-finishing' and the subfolder
'Not used', which contains temporary or alternative toolpaths, then
to access the toolpaths only in the 'Semi-finishing' folder, you need
to use the pathname and dirname functions:
STRING fld = ‘Toolpath\semi-finishing’
Note the use of ‘this’ in the $filt expression: when used in the
filter function, ‘this’ is an alias for the current list item that is
being filtered. In cases where you need to explicitly use the
list item, such as the one above, you should refer to it as
‘this’ in the expression.
2 To create a macro path, click , and use the Select Path dialog
to select the desired location. The path is added to the top of the
list.
Only the paths that contain at least one macro are shown.
For more information, see Displaying Macros in the Explorer.
e Click on the Main toolbar to display the Safe area tab of the
Toolpath connections dialog.
f Enter a Safe Z of 10 and Start Z of 5.
g Click Accept.
5 From the Macros context menu, select Stop to finish recording.
6 Expand the Macros node. The pmuser.mac macro is added under
pmill4.
7 Close and then restart PowerMill to check that the settings from
the pmuser macro are activated.
Graphics
When you run a macro, PowerMill updates the screen every time a
change is made. If PowerMill updates the screen frequently, this
amount of screen activity can look unpleasant. Use the following to
instruct PowerMill not to update the screen while the commands are
in progress, and instead to update the screen (just the once) after
the commands are complete.
GRAPHICS UNLOCK
GRAPHICS LOCK
A C
Active folder name • 95 Calling from other macros • 4
Adding items to a list • 35, 87 Carriage returns in dialogs • 30
Adding lists • 86 Comparing variables • 41, 43
Adding macro loops • 11 Components
Adding macro variables • 10 List components • 83
Arguments in macros • 51 Compound macros • 4
Function values • 53 Conditrional functions • 96
Running macros with arguments • 12 Constants • 68
Sharing functions • 54 Euler's number • 68
Arrays • 33 Pi • 68
Lists • 33 Converting numerics to strings • 76
Points • 41 Creating macros • 1
Using arrays • 25 Basic macro • 9
Vectors • 41 Creating variables (macros) • 27
Automate a sequence of edits or actions
• 101
D
Date and time functions • 74
B Decision making in macros • 14
Base name • 94 Decisions in macros
Basic macro • 9 BREAK statement • 60, 65
Adding macro loops • 11 IF - ELSE statement • 55
Adding macro variables • 10 IF - ELSEIF - ELSE statement • 56
Decision making in macros • 14 IF command • 54
Returning values from macros • 18 SWITCH statement • 57
Running macros with arguments • 12 Decrease options available to user • 31
Using a FOREACH loop • 22 Delete files or directories • See Working
Using arrays • 25 with files and directories
Using functions in macros • 16 Dialogs in macros • 28
BREAK statement • 60, 65 Carriage returns in dialogs • 30
Building a list • 37 Directory name • 93
Built-in functions • 68 DO - WHILE loop • 64
Decision making in macros • 14
W
Warning and error messages, turn off •
119
WHILE loop • 63
Whitespace in a string • 81
Working with files and directories • 111
Workplane origin • 72
Writing information to files • 112
Writing macros • 5