Macro Script Reference Guide
Macro Script Reference Guide
This manual, as well as the software described in it, is furnished under license and may be
used or copied only in accordance with the terms of such license. The content of this
document is furnished for informational use only, and is subject to change without notice.
InnovMetric Software Inc. assumes no responsibility or liability for any errors or inaccuracies
that may appear in this document.
Except as permitted by such license, reproduction in whole or in part in any way without
written permission from InnovMetric Software is strictly prohibited.
7 1. Introduction
8 1.1 Introduction
8 1.2 Chapter contents
9 1.3 Related documentation
9 1.4 Technical support
11 2. Overview
12 2.1 Introduction
12 2.1.1 The PolyWorks approach to scripting
13 2.1.2 Task automation
13 2.2 Tools
15 2.3 Commands
17 2.4 Resources
17 2.4.1 Macro Script Reference guide
17 2.4.2 Command Reference Guide
17 2.4.2.1 Organization
19 2.4.2.2 Command syntax
21 2.4.3 Obsolete command update
21 2.4.4 Other resources
151 Glossary
152 Index
1.1 Introduction
The Macro Scripting Reference Guide is intended for users of the PolyWorks® Metrology
Suite. It explains how to build powerful macros that allow automating tasks in the
IMAlign™, the PolyWorks|Modeler™, and the PolyWorks|Inspector™ modules. Macros
can also be built in the Workspace Manager that execute local scripts in, and send
commands to, one or more of those modules.
Commands that are useful for most macro scripts are presented and basic but
important programming concepts are presented. Finally, examples of macro scripts for
the IMAlign, the PolyWorks|Modeler, and the PolyWorks|Inspector modules are
presented.
This guide provides concepts that are illustrated using examples of the scripting
language. As users works through the examples, they should gain understanding and
confidence that will serve in building their own scripts. The only real way to learn is to
start simple and build toward personal objectives. Eventually, gains in time,
repeatability, and productivity will be the rewards.
1. Introduction
This chapter introduces macro scripting in the PolyWorks Metrology Suite.
2. Overview
This chapter presents the PolyWorks approach to scripting and then introduces the
tools, commands, and resources used to create macro scripts in the PolyWorks
Metrology Suite.
7. Application commands
This chapter presents applications commands that are useful to get started writing
macro scripts.
The PolyWorks® Reference Guide presents the PolyWorks Metrology Suite, including
the Workspace Manager, and explains how to customize the user interface by means
of visual layouts. It also explains how to open modules from the Workspace Manager.
Finally, it describes the installation procedure for both node-locked and floating
license key files.
All reference documentation can be accessed from the Workspace Manager. See its
Help > Reference Guides submenu.
2.1 Introduction
This chapter presents the PolyWorks approach to scripting. It then presents the tools
and types of commands that are used to write scripts and describes the resources that
are available for each.
The key choices made in designing the scripting language were to use a command-
based approach and to keep it simple. PolyWorks users are familiar with using menu
items to perform actions. So, it was only natural to make available commands that
mimic the menu items. For example, the Edit > Delete > Objects menu item has the
following equivalent application command in a script:
where string is an optional argument (i.e., the name of the object to delete); if no name
is provided, the current object selection in the project is considered.
Care was taken to incorporate help items for the user as well:
There are command completion and command help tools directly available in the
Macro Script Editor.
The Macro Script Editor also offers the Command Reference guide in HTML format
that provides the syntax for all commands.
Each time the user performs an action using the GUI (e.g., using menu items,
toolbars, shortcut keys), the resulting application command appears in the
Command History pane.
Application commands can be run in a macro script to do the same actions in the
application (e.g., PolyWorks|Inspector).
Scripting is available to all users immediately – the learning curve is shorter than the
one associated with object-oriented scripting languages.
The scripting language itself has been kept simple – only a limited number of
commands are offered, so again the learning curve is kept to a minimum.
The Workspace Manager has its own Macro Script Editor tool, and as the Workspace
Manager sits above the executing modules and knows what is going on, it is the natural
site for the development of scripts for an entire workflow in the PolyWorks Metrology
Suite.
Basic commands are available that allow opening the IMAlign, the
PolyWorks|Modeler™, and the PolyWorks|Inspector™ modules, and
PolyWorks|Reviewer™, executing remote commands in the modules, executing scripts
written for each module, and then closing each module. Another command allows
making the necessary specifications to run the IMMerge module. As a result, the tools
exist to script a complete PolyWorks process.
A task can be simple but useful, such as a combination of keystrokes used repeatedly, or
more complex such as changing the value of a parameter for all circles in a project.
Scripting allows creating a personal set of tools to save time and perform tasks in a
predefined, controlled manner. And scripts can be run on the shop floor by employees
who don’t need to understand the PolyWorks Metrology Suite to produce exact results.
User actions in a module can be automatically recorded and saved to a macro script as
application commands to be played back. Macro scripts are Unicode files that can be
edited in the Macro Script Editor, or by using any text editor that supports Unicode.
Module-specific commands will be referred to as application commands. Other
commands, called utility commands, are also offered that are not module specific; they
are available in all modules. For example, a utility command that allows querying the
user for a numeric value by way of a dialog box.
Real-world tasks require that certain commands in a macro script be used repetitively,
or conditionally, depending on run-time conditions. For this reason, PolyWorks offers
control commands in the form of the Macro Script Control Language that allows
adding basic control structures (e.g., IF, WHILE) to macro scripts. The Macro Script
Control Language is a simple but powerful programming language supported by the
Macro Script Editor.
2.2 Tools
Writing, testing and executing macro scripts requires using the Macro Script Editor
pane and its companion, the Command History pane.
The Macro Script Editor is the tool to use to write and save scripts, check their syntax,
and run them. It also offers useful display options, breakpoints to control macro script
execution, as well as command help and completion features to increase efficiency.
This subject is presented in Chapter 3 Macro Script Editor pane.
Figure 2.1 The Macro Script Editor pane and the Command History pane. The
FirstScript.pwmacro macro script has been run in the Macro Script Editor and
the output can be seen in the Command History pane.
Macro script
The Command History pane displays the commands given by the user in the
application using menu items, toolbars, and mouse clicks used to select objects and
control object visibility. These application commands can be directly copied to a macro
script and executed in the Macro Script Editor to repeat the same operations in the
application. The Command History pane can also be used to give individual commands
to see what they do and to see error messages if they are incorrectly written. This
subject is presented in Chapter 4 Command History Pane.
In Figure 2.1, both panes are shown using the PolyWorks|Inspector module. The macro
script open in the Macro Script Editor has been executed, sending a message to the
Command History pane. The Command History pane shows commands given in the
application by the user as well as information concerning the execution of the macro
script.
2.3 Commands
Three types of commands ca be used in a macro script:
Application commands
These commands carry out operations in the application. They are the commands to
use to import objects, extract measured components, generate report tables, and
more. Note that where a dialog box is used in the application to perform an
operation, for example to best-fit align Data objects to Reference objects in
PolyWorks|Inspector, several application commands may have to be given in a script
to perform the same operation.
Application commands can be given in the Command History pane to test command
behavior and syntax.
The MSCL is a simple but powerful programming language that adds control to script
execution in the form of loops or command execution based on conditions. In
addition, it offers mathematical, comparison, and logical operators and expressions.
MSCL commands, combined with utility commands (see next bullet) let you create
powerful and flexible scripts. For example, a script could query the user for a
tolerance value, loop through all circle objects in the project, and for unmeasured
circles apply the tolerance to a specific dimensional control. This subject is presented
in Chapter 6 Macro Script Control Language.
Utility commands
Utility commands let you get input from the user, send output to the Command
History pane, handle errors during macro script execution, run other macro scripts,
work with text files and strings, and more. Utility commands are available in all
modules that have a Macro Script Editor. Most utility commands can be given in the
Command History pane to test command behavior and syntax.
For demonstration purposes, a simple macro script that selects and deletes all circle
objects in the project is shown in Figure 2.2. It contains all three types of commands.
The user is queried to confirm doing the operation – the answer is stored in a variable.
Depending on the answer, the operation is carried out or not. A message is sent to the
Command History pane indicating the result of the operation and, if carried out, the
number of circles deleted. Note that comments have been added to the macro script to
describe the actions that commands perform.
The workflow for macro script creation is presented in Chapter 5 Creating a Basic Macro
Script.
Figure 2.2 A macro script that deletes all circles in the open project if the user presses the Yes
button. In (a), the dialog box displayed by the script to query the user to continue. In
(b), the macro script – MSCL commands are in blue and comments are in green. The
Command History pane contains the output of the MACRO ECHO utility commands.
(a)
(b)
2.4 Resources
Several resources are available to help users learn how to successfully write scripts in
PolyWorks. They are presented in the subsections that follow.
The present reference guide presents the entire scripting environment, explains how to
create macro scripts, presents in detail the Macro Script Control Language (MSCL), and
provides useful examples that users can paste into a macro script and try out in order to
understand the commands.
In addition, additional commands are presented to help users get started with
scripting, and then basic programming concepts are presented to users help create
more robust macro scripts more efficiently. These subjects are presented in Chapter 7
Application commands, Chapter 8 Utility Commands to Get Started, and Chapter 8
Basic Programming Concepts.
Finally complete sample macro scripts are provided that perform a described task for
the IMAlign, the PolyWorks|Modeler, and the PolyWorks|Inspector modules, as well as a
multiapplication macro script. For more information, see Chapter 9 Sample Macro
Scripts.
The Help > Commands menu item of the Macro Script Editor displays the user’s web
browser with HTML help on MSCL and utility commands as well as application
commands for the module. An example of the guide is shown in Figure 2.3.
2.4.2.1 Organization
Most top-level items are related to application commands that are specific to the
current application (e.g., PolyWorks|Inspector). Clicking an item opens the command
branch, displaying other subbranches or terminal items. Information is provided for
terminal items, as they form a complete command, such as a command description, the
description of command arguments, and special notes when required.
Figure 2.3 The Command Reference guide provides a description and the syntax of application
commands for the current module, utility commands, and the elements of the Macro
Script Control Language.
Other top-level items provide information on MSCL commands and utility commands.
The Language branch contains the elements of the MSCL and the DATA FILE and
MACRO branches contain the utility commands.
APPLICATION COMMANDS
MSCL COMMANDS
UTILITY COMMANDS
MSCL commands can only be given in the Macro Script Editor while application
commands and utility commands can be given in both the Macro Script Editor and the
Command History pane.
Note that the OBSOLETE branch contains commands that no longer exist in the current
version of the PolyWorks Metrology Suite but that are supported for compatibility
reasons. Those commands should no longer be used; for more information, see Section
2.4.3 Obsolete command update.
The Command Reference guide provides the complete syntax for each command, as
shown in the example below.
Figure 2.4 Command Reference branches that are not application specific.
The command shown in the figure can take four arguments – they are located after the
command, between parentheses and separated by commas. A short description of the
command is provided, and a note if required. In addition, the following information is
provided for each argument:
Arguments: The argument’s type (e.g., string, integer, double, array of strings).
Note that some commands do not have arguments. If a command in a macro script
does not have the correct syntax, it will fail and the macro script will stop. The Macro
Script Editor offers the Check Syntax functionality to make sure that commands have
the correct syntax before running a script.
The Upgrade command of the Macro Script Editor allows identifying and resolving
issues related to obsolete commands. This subject is presented in Section 7.2.5
Replacing obsolete application commands.
Macro scripts can be found on the InnovMetric Web site, in the Macro Zone area of
the Technical Support Zone. Certain scripts have been provided by PolyWorks users
while other scripts have been created by specialists at InnovMetric Software Inc.
Consulting and integration services are available to users who desire to have macro
scripts developed for them:
InnovMetric Software Inc. offers integration services that include the creation of
automated solutions through macro-script programming. For more information, go
to the InnovMetric website at www.innovmetric.com.
The PolyWorks user community includes users that have become very proficient in
scripting tasks and who make themselves available as consultants to other users.
3.1 Introduction
The Macro Script Editor is an integrated environment that allows creating, testing, and
running macro scripts that perform actions in your PolyWorks Metrology Suite
application (e.g., PolyWorks|Inspector). The Macro Script Editor resides within its own
dedicated pane.
Script window – An area where macro scripts can be written, saved, tested for syntax
errors, run, and edited. The window offers tools to help users create macro scripts
easily and quickly. Note that shortcut keys are offered to work efficiently within the
commands in the script.
The sections that follow describe the Macro Script Editor. First, the menus and the
options offered by the Macro Script Editor are explained. Then, an example of a macro
script is given to illustrate different options and functionalities that are built into the
script window to make it easier to work with, test, debug macro scripts. In addition,
tools that make it easier to write commands are presented. Finally, the shortcut keys to
be used in the script window are described.
Figure 3.1 The Macro Script Editor features (a) a main menu bar, (b) and (c) toolbars, (d) a text
window for each open script, and (e) a status bar.
3.3 Menus
This section provides presents each menu item offered on the Macro Script Editor’s
menu bar. For each menu item a description is provided as well its shortcut key and
toolbar button, if available. Note that most of the menu items are only available when a
script window is open.
Certain menu items are also offered on the shortcut menu that is available on right-
clicking a document tab or a command in a script window. Examples of these menus
are shown in Figure 3.2.
Figure 3.2 Right-clicking (a) a command or (b) a document tab displays two shortcut menus. In
(a), the right-click was performed on a selection of lines.
Main
menu
(a)
(b)
Shortcut menus
Close Closes the active macro script. If the script has been
modified, a message window opens asking to save
the changes. To save the changes, press the Yes
button, otherwise press the No button. To cancel
the file close operation, press the Cancel button.
To open a macro script file, choose the File > Open menu item. The macro script file
browser, shown in Figure 3.3, is displayed. It offers the items that follow:
File name
A text box that allows specifying the name of the file to open.
(file filter)
The file filter list box is located after File name. It allows specifying the file types to
find. Choose from PolyWorks Macro Script File (*.pwmacro) (only show files
with the .pwmacro file extension) and All Files (*.*). By default, the filter is set to
PolyWorks Macro Script File.
Favorite paths
A list box, located at the bottom left of the browser, that allows specifying a
preferred location for the file browser. Choose from the values presented in the
table:
Path Description
Path Description
Press the Open button to open the file in the Macro Script Editor, or the Cancel button
to cancel the operation.
It is also possible to open a script file by dragging it from an application, such as a file
browser, onto the Macro Script Editor pane. If multiple files are dragged, they are all
opened in individual cascading windows.
To save a macro script file, choose the File > Save menu item to save the script in the
active macro script window. This command displays a macro script file browser, similar
to the one shown in Figure 3.3, that offers the items that follow:
File name
A text box that allows specifying a file name. The name cannot contain the special
characters that must be excluded in file names (e.g., *, ?, /, \), and the name is not
case sensitive.
Save as type
A list box that allows specifying the type of file. Choose from PolyWorks Macro
Script Files (*.pwmacro) and All Files (*.*). The default value is PolyWorks Macro
Script Files. When All Files is specified, files may be saved with any or no file
extension.
Favorite paths
A list box, located at the bottom of the file browser, that allows specifying a
preferred location for saving macro script files. Choose from the values presented
in the table:
Path Description
Last User-Defined The path where the last macro script was opened from
or saved to.
Press the Save button to save the file, or the Cancel button to cancel the operation.
The Edit menu offers the following items that apply to the active script window:
Find Displays the dialog box show in Figure 3.4 (a) to find
the specified text.
Ctrl-F
Replace Displays the dialog box show in Figure 3.4 (b) to
find and replace the specified text.
Ctrl-H
Auto Indent All Automatically indents the contents of the active
macro script.
Ctrl-I
Comment out Transforms the block of text to comment format.
Ctrl-T
Uncomment out Removes the comment format from the block of
text.
Ctrl-U
Upgrade Automatically processes a script to resolve issues
related to obsolete application commands; the
Ctrl-G
original file is saved with a time stamp added to its
name. This operation is documented in Section
7.2.5 Replacing obsolete application commands.
Zooming the active script window can also be performed using the slider located on
the right of the status bar, or when the cursor is placed in a script window, by using the
mouse wheel (i.e., scroll forward to increase the zoom, and scroll backward to decrease
the zoom).
Figure 3.4 In (a), the Find dialog box, and in (b), the Replace dialog box.
(a)
(b)
The Debug menu offers items that allow testing and running, or executing, the active
macro script.
This section introduces the running of macro scripts, presents the Debug menu, and
presents other ways of executing macro scripts.
3.3.4.1 Introduction
When a command is chosen that launches the execution or the syntax checking of a
macro script, the contents of all modified macro scripts must be saved; the exact
behavior is determined by the Before debugging option (see Section 3.5.1 Macro
script display and functions).
Menu items on the Debug menu allow adding breakpoints to scripts and enabling/
disabling them. Breakpoints can be added to a script to stop the execution at that line.
Breakpoints allows running the script in a controlled manner (i.e., one group of
commands at a time), and allows verifying the current value of variables, if the
Information tooltips option is enabled. When a script being executed stops at a
breakpoint, that line is referred to as the current execution line; if the execution is
continued, it continues from the current execution line. If a breakpoint is disabled, it has
no effect on script execution.
Check Syntax Checks the contents of the active macro script for
syntax errors. Available when there is at least one
F7
script window.
Run to Cursor Executes the active macro script from the current
execution line up to the line containing the cursor,
Ctrl+F10
or until the end of the script is reached. If execution
stops at the cursor position, that line is not
executed, and it becomes the new current
execution line.
Available when there is at least one script window.
Skip to Cursor Skips all the commands from the current execution
line up to the line containing the cursor, or until the
Ctrl+Shift+F10
end of the script.
Available when there is at least one script window.
Step Into Very similar to the Step menu item. The only
difference is that if a MACRO EXEC command is
F11
encountered that calls another macro script, the
associated macro script is opened and executed
one line at a time, starting at the beginning of the
script.
When a macro is running, a continuous progress bar is displayed on the Macro Script
Editor’s status bar:
It is possible to run a macro script on disk from the Command History pane or from
within a macro script. These methods use the MACRO EXEC command and are
described in the chapters that follow.
A simple folder-based mechanism allows creating macro scripts with specific names
that are executed on performing specific actions in the application.
The actions are the following: opening and closing a workspace, and ending a scan
pass. Each macro is presented in the subsections that follow.
This may be useful to automatically launch certain PolyWorks Metrology Suite modules
or open specific PolyWorks projects. Make sure to load only one workspace at a time to
prevent conflicts.
The current visual layout of the instance of PolyWorks|Inspector where the scanning
is being performed.
If the macro is found, it is run. This enables additional, automatic processing of scan
pass data.
Note that the processing done by this macro is performed after other processing
specified in the plug-in dialog box (i.e., first scan line filtering and then other specified
processing, such as extracting point normals).
3.3.5.1 Options
To display the Macro Script Editor Options dialog box, choose the Tools > Options menu
item or press the toolbar button shown to the right. The dialog box shown in Figure 3.5
is displayed. Options are organized by pages. Once changes are made in a page, press
the Apply button to apply the changes, or the OK button to apply the changes and
dismiss the dialog box.
When changes are made using the Macro Script Editor of a specific module, the
changes must be saved explicitly using the Tools > Save User Configuration menu item
to be available next time an instance of the module is opened. All the Macro Script
Editors share the same configuration file. When options are saved in one module, using
the Save User Configuration menu item, the configuration file is updated with the
changed values for those options. When opening a Macro Script Editor in an instance of
the same or a different module, or the Workspace Manager, the editor uses the options
in the updated file. Note that changes made to the options of the Macro Script Editor of
the Workspace Manager cannot be saved explicitly; rather, they are automatically saved
when that application is closed.
The General page of the Macro Script Editor Options dialog box, shown in Figure 3.5,
offers the following general items:
Before debugging
A group label that allows specifying the behavior to apply to all unsaved macro
scripts when an operation that comprises debugging is launched, such as the
Check Syntax, Run, or Step menu items. Two options are offered:
Word wrap
A check box that enables the word wrap function, which is a visual effect. A line
that is longer than the width of the script window is continued by wrapping. Note
that it is still considered to be the same line (i.e., has the same line number, and is
all highlighted in yellow). By default, the check box is selected.
Smart Indent
A check box that enables the use of indenting logical blocks, such as IF-ENDIF,
when the ENTER key is pressed. By default, the check box is selected. The following
item is also offered to configure the feature:
Number of spaces
A list box that allows specifying the number of spaces to use for the smart
indent feature. Choose from: 2, 4, 6, and 8. The default value is 4.
The Display section offers several features that control the display in the script window.
Many items are illustrated in Figure 3.9, while other items are illustrated in the text that
follows, adjacent the item description. The following items are offered:
Document tabs
A check box that enables using document tabs which display the name of the
open macro scripts. When selected, it makes available an adjacent list box that
allows specifying where to position document tabs. Choose from: Top, Bottom,
Left, and Right. The default value is Bottom.
Line numbers
A check box that enables displaying line numbers in the left margin. By default, the
check box is selected.
White spaces
A check box that enables displaying spaces using a visual representation. By
default, the check box is cleared.
Indentation guides
A check box that enables displaying indentation guides. By default, the check box
is selected.
Block folding
A check box that enables displaying block
folding. Blocks are consecutive commands
delimited by two commands, one that begins
the block (e.g., IF), and one that ends the block
(e.g., ENDIF). By default, the check box is
selected. See the example to the right.
Information tooltips
A check box that enables displaying information tooltips for elements of a
command by hovering the pointer over the desired element:
When the pointer is hovered over a variable that has been assigned a value,
a window is displayed showing the value.
Automatic completion
A check box that enables an automatic completion feature. This feature proposes
valid commands based on the first characters typed by the user, or the names of
existing or reserved variables once the $ and first characters have been typed. By
default, the check box is selected.
The Regular Text, Keyword, Comment, and String pages of the Macro Script Editor
Options dialog box all offer the same items to configure the appearance of those
individual text elements. The Regular Text page is shown in Figure 3.6. See Figure 3.7
for an illustration of each text element.
The items are explained in the text that follows, and are found on each individual page.
Font
A list box that allows specifying a font for the text. The default value is Courrier
New.
Size
A list box that allows specifying a size for the text. The default value is 10.
Figure 3.6 The Regular Text page of the Macro Script Editor Options dialog box.
Font color
A color box that allows specifying the color of the font. To edit the color, click the
color box and click a new color in the list that is displayed. The default values are
black (for regular text), blue (for keywords), green (for comments), and magenta
(for string values).
Background color
A color box that allows specifying the color of the background. To edit the color,
click the color box and click a new color in the list that is displayed. By default, the
background color is white.
Bold
A check box that enables using the bold style component. By default, the check
box is cleared.
Italic
A check box that enables using the italic style component. By default, the check
box is cleared.
Figure 3.7 The four text elements for which the display can be configured using the
corresponding pages of the Macro Script Editor Options dialog box.
Comment
String
The Preview subsection offers a text area that displays sample text configured by the
specifications made on the page. The text is updated for each new specification.
The Window menu offers items that allow organizing multiple script windows:
The menu also lists the current script windows. The one preceded by a check mark is
the active script window. To make another script the active script, choose it in the list.
3.4 Toolbars
The Macro Script Editor features the Standard and Debug toolbars. The Standard
toolbar offers shortcuts for items located on the File, Edit, and Tools menus. The Debug
toolbar offers shortcuts for items located on the Debug menu. Both toolbars are shown
in Figure 3.8 with the tooltips of the toolbar buttons.
Figure 3.8 In (a), the Standard toolbar and in (b) the Debug toolbar. The tooltip associated with
each toolbar button is also presented.
(a)
A B C D E F G H I J K L M N O
(b)
A B C D E F G H I J K L
Several macro scripts can be open at a time. The name of each one can be displayed
in a document tab.
Numbered lines.
Block folding for logical structures which allows closing/opening IF-ENDIF and DO
WHILE-END WHILE blocks of commands.
Many of them are options and can be activated or deactivated. The editor‘s options are
described in Section 3.5.1 Macro script display and functions.
When working in a macro script window, two features are available to help users write
commands quickly and correctly: Command Completion and Command Help.
Command completion can be invoked at any time by pressing the TAB key, either in a
macro script window or in the command-line area of the Command History pane.
Whenever the TAB key is pressed, the Macro Script Editor will try to resolve the keyword
or sentence being typed. If a single solution is found, the keyword is completed
automatically; if several solutions are possible, they will be listed in a window and one
can be selected using the mouse or the arrow keys. Whenever an item is selected in the
list, the Macro Script Editor will display Intermediate command word if the proposed
Figure 3.9 The Macro Script Editor pane. Two macro scripts are open in separate script windows.
SetView is the active script. It demonstrates several of the editor’s features. SetView is
being executed in the step-by-step mode (line 13 will be executed next). Line 9 has an
enabled breakpoint, and line 11 has a disabled breakpoint. The cursor is placed on
the variable $Name on line 13, and the variable’s current content is displayed. The IF
block encompassing lines 14-16 is folded. The name of the macro script being
executed, and the current execution line number, are displayed on the editor’s status
bar.
solution does not complete a command, or it will display command help if its selection
completes a valid command, as shown in Figure 3.10.
When invoked, the Command Completion feature lists the available command
keywords.
To select a keyword and dismiss the window, double-click the desired item in the list, or
use the arrow keys to navigate in the list, and press ENTER. To dismiss the window
without choosing a keyword, press the ESC key or click anywhere outside the list.
If a command is complete, pressing the TAB key will display command help that
displays a general description of the command and its arguments.
The behavior described previously can be made automatic (i.e., no need to use the TAB
key) by selecting the Information tooltips and the Automatic completion options on
the General page of the Macro Script Editor Options dialog box. For more information,
see Section 3.3.5.1.1 General options.
Figure 3.10 Command completion and command help are available when writing macro scripts.
(a) The TAB key was pressed after typing the FEATURE command. A window is displayed that
contains all the other commands that can follow the FEATURE command. In the window, ANGLE is
highlighted – the text Intermediate command word is displayed to indicate that it does not form a
complete command. Since the command is not complete, help information cannot be displayed.
(b) When MAKE COAXIAL is selected, a valid command can be formed: FEATURE MAKE COAXIAL. As
a result, a help window is displayed for that command.
Figure 3.11 Clicking over a command and pressing the F1 key displays the Command Help
window. If information tooltips are enabled, the same information appears when the
pointer is placed over the command.
(a)
(b)
Command help can be obtained by clicking within a keyword and then pressing the F1
key, either in the macro script window or in the command-line area of the Command
History pane. If the keyword is an intermediate keyword, Intermediate command word is
displayed; if it completes a command along with the preceding keywords, the
command help is displayed instead. See Figure 3.11 for an example.
Shortcut key
Action
Modifier Key
Cancel Esc
Indent Tab
Shortcut key
Action
Modifier Key
Line up Up arrow
Shortcut key
Action
Modifier Key
4.1 Introduction
The Command History pane is an important companion tool for users who write scripts.
The Command History pane displays commands given by the user in the application,
which can be directly copied to a macro script window.
Application and utility commands can be given in the pane to try them out or to see if
they contain syntax errors, which are displayed in the pane.
The pane also displays information related to the execution of macro scripts in the
Macro Script Editor, such as error messages or the output of certain commands,
including MACRO ECHO.
The Command History pane is shown in Figure 4.1. It features a toolbar, a command
history area, and a command-line area. These elements are presented in the
subsections that follow.
4.2.1 Toolbar
The toolbar offers operations to configure the behavior and the layout of the Command
History pane:
Button Description
Figure 4.1 The Command History pane. It features (a) a toolbar, (b) a command history area,
shown here with content, and (c) a command-line area. The display of application
commands in the command history area can be toggled and the command-line area
can be hidden.
(a) Toolbar
The command history area can display application commands that correspond to
actions performed by the user in the application, as well as content related to
commands given explicitly by the user either on the command-line area or by
executing a macro script.
Application commands
The command history area can display application commands. All the commands given
by the user by way of the graphic user interface that are translated into application
commands, as shown in Figure 4.1. These commands include those chosen on main or
shortcut menus, selections in the tree view or in the 3D scene, and actions performed
by pressing toolbar buttons.
The command history area can also display application error messages that are
normally displayed if an action was not done correctly. For example, if a plane was not
selected for an action requiring a plane, an error message is displayed in the Command
History pane.
The command history area can display information related to commands given in the
command-line or by macro script execution:
The result of certain commands (e.g., MACRO ECHO), as shown in Figure 4.1.
Macro script syntax errors found while testing or running a macro script, as shown in
Figure 4.2.
When a macro script is executed it’s name is displayed. When the execution is over, a
corresponding message is displayed.
The command-line area supports the command completion and help features,
presented in Section 3.5.2 Help when writing commands. Previous commands can be
retrieved by navigating using the UP ARROW and the DOWN ARROW keys.
Some commands invoked in this way may differ from the same commands invoked
within a macro script. For example, the command
Displays a project file browser as if it were invoked by way of the application’s File menu,
whereas the same command invoked in a macro script must specify the location and
name of the project to open:
Figure 4.2 An error displayed in the Command History pane as a result of the Check Syntax
operation.
Error
message
The difference stems from the fact that commands in a macro script, as a general rule,
should not display windows that can block the execution of a script.
Finding the command may be as easy as giving the command manually and copying
the command that appears in the Command History pane to the active script. Or, the
command can be used to initiate a search in the Command Reference offered by the
Macro Script Editor’s Help menu. For an example of the Command History pane
containing given commands, see Figure 4.3.
Figure 4.3 The Command History pane echoes the commands given by the user in the
application. It is a useful learning tool for writers of macro scripts.
5.1 Introduction
This chapter introduces the steps required to create and run a macro script, and then
explains how to edit the macro script. Remember to always run new and untested or
undebugged scripts on test projects and not on real projects.
The approach taken here is to record commands while you work with the menus and
toolbars of your application. Then, the recording will be ended, and the recorded
commands pasted into a macro script in the Macro Script Editor pane. This may be a
first contact with application commands; their names usually clearly identify the action
they perform. Once the macro script is saved, it can be played to redo the same steps
automatically.
The chapters that follow explain how to use the Macro Script Command Language and
utility commands to go beyond the simple recording of user actions and make more
powerful macro scripts through the use of simple programming structures.
Generate a report.
The sections that follow will explain how to create a single script that will execute the
above tasks.
Open the desired inspection project and display both the Command History pane
and the Macro Script Editor pane.
2.2 Carry out the specific task in the application using menus and toolbar
buttons, and by manipulating objects in the tree view (e.g., selection,
visibility).
2.3 Stop the recording of application commands at the end of the task.
3.1 In the Macro Script Editor, create a new, empty macro script.
3.3 Save the macro script – file names do not require a file extension, but the
default extension, .pwmacro, is offered.
This step is important when commands have been modified or new commands
have been added to the script.
5. Run the macro script in either the normal mode or in the step-by-step mode.
Observe the effects on the inspection project.
The step-by-step mode is useful for command diagnostics as it executes only one
command at a time. For more information, see Section 3.3.4 Debug menu.
These steps in this general workflow are covered in detail in the sections that follow.
The script version number is automatically inserted at the beginning of the script (e.g.,
VERSION "5.0"). This line must always appear before any command in the script.
The procedures that follow use items on the menus offered by the Macro Script Editor.
1. Start the recording of a task by choosing the Tools > Record Commands > Start menu
item, or click the corresponding button on the Standard toolbar (shown to the
right).
A blinking red button appears to the right of the module’s status bar to indicate that
a macro script is being recorded.
Note that clicking the red button displays the Macro Script Editor pane if it is
currently hidden.
2. Perform the specific task until it is completed. In recording mode, every recordable
action that is performed in the PolyWorks Metrology Suite application is recorded in
the form of an application command.
3. Stop the recording by choosing the Tools > Record Commands > Stop menu item, or
clicking the corresponding button on the Standard toolbar (shown to the right). The
revolving PolyWorks Metrology Suite logo disappears from the status bar.
Figure 5.1 An example of recorded application commands that correspond to the simple task
defined earlier in the chapter. Application commands are loosely based on the
module’s top level menus (e.g., FILE SAVE PROJECT). Note that the commands on lines
10 and 11 could apply to specific, named objects, but by default they use the list of
objects selected by the command at line 8, which selects all feature objects.
To paste recorded command into the active macro script, proceed as follows:
1. Click at the desired location in the macro script open in the Macro Script Editor.
2. Choose the Tools > Paste Recorded Commands menu item to insert the recording, or
click the corresponding button on the Standard toolbar (shown to the right).
For an example of the application commands that correspond to the simple task that
was described in the introduction, see Figure 5.1. The actual commands follow:
To check the syntax of the contents of the active macro script window, choose the
Debug > Check Syntax menu item, or click the corresponding button on the Debug
toolbar (shown to the right).
If errors are found, the execution of the active macro script window is disabled, and a
red marker is displayed in the left margin of the line at which the first error was
encountered, as shown in Figure 5.2.
To run the contents of the active macro script window using the step-by-step mode
(i.e., execute one command at a time), choose the Debug > Step menu item for each
command to execute, or click the corresponding button on the Debug toolbar
(shown to the right). This is recommended for new or edited macro scripts.
To run the contents of the active macro script window in normal mode, choose the
Debug > Run menu item, or click the corresponding button on the Debug toolbar
(shown to the right). This is recommended for debugged and tested macro scripts.
A running macro script can be cancelled at any time by pressing the ESC key when the
Macro Script Editor has the input focus.
Figure 5.2 An error displayed in the Command History pane as a result of the Check Syntax
operation.
Error
message
Two important tools that help to edit and add commands are Command Completion
and Command Help; for more information, see Section 3.5.2 Help when writing
commands.
A few general notions pertaining to macro scripts are presented below; they are
presented in full in the chapter that follows. If you do not intend to add commands
unassisted at this time, you may skip this section and continue to Chapter 6 Macro
Script Control Language.
A macro script consists of a Unicode file containing statements. The following rules
apply to macro scripts:
Macro scripts are case insensitive. The use of capital letters is to make the commands
more readable.
To add comments to a macro script, begin a line with the # character. Only spaces can
be placed before the # character. All the characters that follow the # character are
ignored.
The following restriction applies to the first line of each macro script – it must begin
with the VERSION keyword, followed by the version number of that particular
macro script. For example:
VERSION "5.0"
To incorporate certain elements of version 5.0 in macro scripts created using versions
1.0, 2.0, 3.0, or 4.0, the first command must be replaced with the command Version
"5.0".
This chapter is the complete reference for the MSCL. It presents the general syntax of each language
element. The MSCL consists of keywords that can be combined with other language elements, such as
values and mathematical expressions, as well as commands, to form executable statements. The basic unit of
a macro script is the statement.
This chapter contains many examples. They are an important part of the explanations and contain pertinent
comments. Look at them carefully. Many can be copied and pasted directly into an empty macro script,
saved, and executed. Your ability to create macro scripts will grow with each new script that you realize.
6.1 Introduction
The Macro Script Control Language (MSCL) is a high-level macro (scripting) language
that permits you to add control commands to a macro script. They can be added with
any Unicode text editor. The resulting macro script must always be tested and executed
in the appropriate module’s Macro Script Editor tool. Note that IMAlign,
PolyWorks|Modeler, and PolyWorks|Inspector all have application commands specific
to their own module, and that are not used by the other modules. The Workspace
Manager also has a Macro Script Editor, which lets you execute scripts that can launch
processes in several modules.
The MSCL is explained mainly through its keywords. Each keyword is explained and
demonstrated using short macro script examples. Concepts associated with high-level
programming are touched on as a result. They include:
Variables are containers used to store and retrieve information. They can be used to
provide information to commands, such as an employee number (input variables), as
well as to receive information from commands, such as a result computed by a
command (output variables).
Mathematical expressions, functions (e.g., COS()), and operators (e.g., +,-, /).
Logical expressions and operators (e.g., AND, OR, NOT), which leads to the notion of
conditions.
The flow of loop execution, when explaining the BREAK and CONTINUE keywords
that belong to the WHILE-ENDWHILE structure.
The group of MACRO utility commands also offers functions that are associated with
high-level programming:
Modular programming, which consists in dividing a large task into many smaller
ones, and writing a main script that calls, or makes use of, the smaller scripts. The
smaller scripts are easier to test/debug, and often they are so specialized that they
can be reused by other macro scripts. This is discussed when explaining the MACRO
EXEC command (see Section 8.2 Modular programming).
Error handling, which involves actions to take when something has not been
performed properly (see Section 8.3 Error handling).
A macro script consists of a Unicode file containing statements. The following rules
apply to macro scripts:
Version number
The following restriction applies to the first line of each macro script – it must begin
with the VERSION keyword, followed by the version number of that particular
macro script. For example:
VERSION "5.0"
Note that the PolyWorks Metrology Suite 2020 can execute correctly macro scripts
that begin with the VERSION "5.0" command and that contain elements of MSCL
version 5.0 or earlier. It can also execute correctly macro scripts that begin with an
earlier version number command (e.g., VERSION "3.0") and that contain elements
of the MSCL pertaining to that version or to an earlier version.
Case insensitive
Macro scripts are case insensitive (e.g., MSCL commands, variable names, application
commands, comments). Small and capital letters are considered to be identical (e.g.,
WHILE and while, vMyVar and vmyvar). Capital letters are often used to make the
commands more readable.
Note that string variables may contain values with uppercase and lowercase letters.
Certain operating systems, such as Unix and Linux, differentiate between small and
capital letters with regards to file names.
Comments
To add comments to a macro script, begin a line with the # character. Only spaces can
be placed before the # character. All the characters that follow the # character are
ignored.
White spaces
There can only be one statement per line. Note that the editor offers the Word wrap
option which allows wrapping a long statement within a window’s current width.
This is a visual effect, and the statement is still considered to be on one line.
A statement can occupy more than one line by placing the \ character at the end of
each consecutive line, except the last one. The exception to this rule is a comment
line, as all the characters that follow the # character are ignored. To obtain
consecutive comment lines, begin each one with the # character. There are no start
of comment and end of comment characters that allow transforming to comments
all the text between the characters.
Most of the application commands included in the macro script examples in this
chapter belong to the PolyWorks|Inspector module. They are used to demonstrate
concepts that apply equally well to scripting in the IMAlign and the PolyWorks|Modeler
modules. A commented macro script for the IMAlign, the PolyWorks|Modeler, and the
PolyWorks|Inspector modules are offered in Chapter 9 Sample Macro Scripts, and one
for the Workspace Manager can be found in Section 9.5 A multiapplication script.
In most cases, you can copy a sample script directly into a macro script window, save it,
and then execute it to see how it works. Note that for the examples that include
PolyWorks|Inspector application commands, those scripts should be run in the Macro
Script Editor of the PolyWorks|Inspector module.
KEYWORDS <arguments>
where <arguments> are values that may be used by certain keywords to form a
statement. Arguments may be optional or required. If you omit required arguments, or
if too many arguments are entered for a command, an error message will be displayed
on running the macro script in the script window and the Command History pane.
The MSCL commands are described in the following sections. For each command, the
following information is provided:
The related syntax which explains how to write a statement using the keyword.
Helpful examples.
Type Definition
The type of a variable is determined by the content that is stored in the variable. Since
the content of the variable may change, the type of a variable may also change.
where <variable_name> represents the name of the variable being declared. A variable
name must respect the following conditions:
Not be a MSCL keyword (for a list of the keywords, see Section 6.3 MSCL commands).
As a convention in this document, user variable names will always start with a small
letter v (e.g., vNumberCircles). This makes it easy to identify variables. Note also that
variable names are case insensitive (e.g., vMyVar and vmyvar are the same variable).
<initial value> is an optional element that permits you to assign an initial value to the
variable on declaration:
DECLARE vMax_number
Use the SET keyword to assign values to declared variables. It has the following syntax:
To access the value stored in a variable, precede the variable name with the $ character.
The value can be used for different purposes, such as serving as a keyword argument,
assigning a value to another variable, or participating in a conditional expression.
In the following example, the value stored in the vGrayLevel variable is used to specify
values for the EDIT OBJECT COLOR command:
In the following example, the value stored in the vRed variable is used to assign a value
to other variables:
It is also possible to insert the content of a variable in a text string. For example:
For obvious reasons, the $ character by itself is not allowed in a text string. To obtain
that character, use the _DOLLAR reserved variable (see Section 6.4.7 Reserved
variables).
As no variable of that name has been declared, running the script results in an invalid
statement.
Variables declared at the beginning of a script are usually available throughout the
script, but variables declared within a logical structure are only available within the
structure. This is the notion of variable scope, explained in Section 6.8 Controlling the
scope of variables.
Consider the syntax of the MACRO INPUT STRING command, shown in Figure 6.1.
The Command Reference help indicates that the first argument is an output argument,
while the other two are input arguments:
The following example uses the MACRO INPUT STRING command. It queries the user
for a project name and assigns it to the output argument, the variable vProject_name.
The same variable is then used as an input argument for the FILE SAVE_AS command.
DECLARE vProject_name
DECLARE vTitle "Project Information"
MACRO INPUT STRING (vProject_name, $vTitle, "Please enter a project name")
# the variable vProject_name is used as an output argument and does not take
# a preceding $ character
# save the project using the value stored in the variable vProject_name
FILE SAVE_PROJECT_AS ($vProject_name)
# the variable vProject_name is used as an input argument, and requires a
# preceding $ character
Figure 6.1 An example of information provided by the Command Reference: The first argument
is an “output” argument (i.e., receives a value), and the other arguments are “input”
arguments (i.e., provide a value).
The MACRO INPUT DOUBLE, MACRO INPUT INTEGER, and MACRO INPUT
STRING commands also allow querying the user, and assign the value (of type double,
integer, and string) entered in the query window to an output argument variable; for
more information on these commands, see Section 7.3.2 Querying the user. Other
commands, which end typically with GET, can also be used to communicate a value to
an output argument variable.
DECLARE vAxis
DECLARE vColor
# gets the destination axis
# to perform a plane, axis, center point alignment
ALIGN PLANE_AXIS_CENTER_POINT DESTINATION_AXIS GET (vAxis)
# gets the color used to draw cross-sections in color map mode
MEASURE CROSS_SECTION OPTIONS DISPLAY VERTEX_COLOR GET \
(vColor)
The GET command is especially useful for storing specific configuration values and
parameter values in variables. New values can then be assigned to these items and
used temporarily. Finally, the items’ original values can be restored. In the example that
follows, the vMaxAngleBackup variable is first used as an output argument variable
and then as an input argument variable (with a preceding $).
DECLARE vMaxAngleBackup
# make a backup before changing the max angle value
FILE OPTIONS IMPORT PLANAR_GRID MAX_ANGLE GET (vMaxAngleBackup)
# changing the max angle value
FILE OPTIONS IMPORT PLANAR_GRID MAX_ANGLE (10)
# do something that is affected by this new value
#
# restoring the original value
FILE OPTIONS IMPORT PLANAR_GRID MAX_ANGLE ($vMaxAngleBackup)
Note that GET commands can also be entered in the command-line area of the
Command History pane without an output argument variable. The output information
appears in the echo of the command in the pane. This is true for all commands with
output argument variables. This information may be useful in the case of a macro script
under construction. For an example, see Figure 6.2.
An array is a variable that can contain several values. An index is used to access each
value. An array can then be conceived of as several variables, all having the same name,
but with a different index. Arrays are useful when automating tasks that have a number
of elements that varies, unknown to you at the time you write the macro script.
For an example of using an array in a macro script, see Section 9.4.2 Macro script with
an array variable.
A variable becomes an array when it is used as an array, for example when it is assigned
a second value. There is no explicit statement to identify a variable as an array. All
variables, including arrays, are declared the same way.
Like variables, array elements (same variable name but different index) do not have a
type. An element contains the last value that was assigned to it, so an array can contain
elements of different types. To assign values to an array, place them between brackets,
separated by commas:
To add/access an array element, for example the fourth one, square brackets [ ] are
used:
An integer, a double, and a string value are assigned to the first three elements of the
array.
When using the SET statement, the variable is not preceded by the $ symbol. This is
equally true for an array.
The elements can be displayed using the MACRO ECHO statement. In this case, the
$ is required in order to replace the elements by their value in the text string to be
displayed.
You can copy an entire array to another variable using the SET command:
Note that you can also provide an array of values to a command without using a
variable:
Note that if the same array of values are used elsewhere and could change, good
programming practices suggest using an array variable instead of providing an array of
values. You could then change the values assigned to the array variable and
everywhere the variable is used its contents are automatically updated.
Arrays are indexed using positive one-based (>= 1) integers. As for all variables,
elements that have not been assigned a value have the default value integer 0. This is
true even if the index used is invalid.
DECLARE vMyFirstArray
# display an element for which a value has not been explicitly assigned
MACRO ECHO ($vMyFirstArray[22])
# displays: 0
# use of an invalid index (indices are one based)
MACRO ECHO ($vMyFirstArray[0])
# displays: 0
DECLARE vMyFirstArray
# the following statements will not be compiled
MACRO ECHO ($vMyFirstArray[2.4])
MACRO ECHO ($vMyFirstArray["hello"])
MACRO ECHO ($vMyFirstArray[EXPR (4 + 2)])
However, if a variable is used as an index, and the variable is not an integer type, a
conversion of the variable output will be performed (see Section 6.9.3 Implicit data
type conversions). If the conversion does not result in a valid index, integer 0 is used.
DECLARE vMyFirstArray
DECLARE vIndex
SET vMyFirstArray[2] 28
# case where the conversion does not result in a valid index - integer 0 is used
SET vIndex "hello"
MACRO ECHO ($vMyFirstArray[$vIndex])
# displays: 0
An array cannot be assigned to an array element. In this case, the implicit index 1 is
used for the source array:
The SIZE keyword returns the number of elements in an array. It has the following
syntax:
SIZE <variable_name>
The size of an array increases as elements are added using the SET statement.
DECLARE vMyFirstArray
# add new elements
SET vMyFirstArray {1, 2, 3}
MACRO ECHO (SIZE(vMyFirstArray))
# displays: 3
Array elements do not have to be added in a sequential manner. As a result, the size of
an array is equal to the largest index used to assign a value to an element of an array.
DECLARE vMyFirstArray
# assign a value to the 100th element
SET vMyFirstArray[100] 1
MACRO ECHO (SIZE (vMyFirstArray))
# displays: 100
However, accessing an array element in read-only mode (using $) does not increase the
array size.
DECLARE vMyFirstArray
SET vMyFirstArray {22, 33}
MACRO ECHO (SIZE (vMyFirstArray))
# displays: 2
Reserved variables are reserved for use by the PolyWorks Metrology Suite. They do not
have to be declared and are always available. Reserved variables are those that begin
with the underscore character _ (e.g., _DOLLAR). Users cannot declare variables that
begin with an underscore.
To see the list of reserved variables available for an application, access the LANGUAGE >
RESERVED VARIABLES branch of the Command Reference (see Section 2.4.2 Command
Reference Guide). The list is also displayed in the last column of the table that follows.
One group of reserved variables, called escaped characters, are offered by all the
Note that while the TAB character is not excluded from being in a string, the _TAB
reserved variable was added to the list because it is found in other popular script
languages.
MACRO ECHO \
("300 M${_DOLLAR}!${_NEWLINE}${_TAB}${_QUOTES}Wow!${_QUOTES}")
# displays: 300 M$!
# "Wow!"
Note that braces are used in the example above to delimit variables names from the
characters that follow. For more information, see Section 6.4.4.1 Using braces to delimit
variable names.
Modifiers are expressions that modify the result of a substitution operation (i.e., when a
string value is substituted for the string variable name in a statement or a command).
Modifiers must be specified immediately after the variable name. If the variable name is
enclosed in braces, the modifiers must follow the variable name inside the braces.
Modifiers do not change the value stored in the variable. The list of modifiers, by
category, follows. Each category is followed by an example.
Figure 6.2 An example of giving a GET command in the Command History pane without an
output variable. The information obtained is displayed in the echo of the command.
The result
obtained.
# the :l modifier
MACRO ECHO ("vPlane_name in lowercase: $vPlane_name:l")
# displays: vPlane_name in lowercase: plane 4
# the :u modifier
MACRO ECHO ("vPlane_name in uppercase: $vPlane_name:u")
# displays: vPlane_name in uppercase: PLANE 4
Specific string variable modifiers, for string values that are file names:
:e Removes all but the suffix. Useful for extracting the extension from a file name.
:h Removes a trailing path name component, leaving the head. Useful for
extracting the parent folder from a path name.
:r Removes a trailing suffix of the form .xxx, leaving the base name. Useful for
removing the extension from a file name.
:t Removes all leading path name components, leaving the tail. Useful for
extracting the file name from a path name.
# the :h modifier - extracts only the path of the parent folder of the file name
MACRO ECHO ("Folder of the file name is: $vFilename:h")
# displays: Folder of the file name is: c:\temp\backup
# the :r modifier - extracts all but the extension of the file name
MACRO ECHO ("file name with new extension: ${vFilename:r}.doc")
# displays: file name with new extension: c:\temp\backup\readme.doc
# the :t modifier - extracts only the file name and extension of the
# complete file name
MACRO ECHO ("Tail of the file name is: ${vFilename:t}")
# displays: Tail of the file name is: readme.txt
Two statements allow incrementing and decrementing the value stored in a variable:
++ <variable_name>
-- <variable_name>
DECLARE vNumber 4
++ vNumber
MACRO ECHO ($vNumber)
# displays: 5.0
-- vNumber
MACRO ECHO ($vNumber)
# displays: 4.0
These two statements are especially useful for controlling the number of loops that will
be executed using the WHILE structure, described in Section 6.7.3 Repeating the
execution of statements using the WHILE statement.
Variables only exist and are available with a scope. In a simple script, the entire script
may be the scope and defined variables are available at all times. However, if the script
has logical structures (e.g., WHILE and IF), a variable that is defined within a logical
structure only exists within the scope of that logical structure. This subject is presented
in Section 6.8 Controlling the scope of variables.
In the previous section, the creation and use of variables was described. This section
describes the following groups of special variables:
Macro script variables are variables that are automatically declared and to which
values are automatically assigned; you can access their content (read), but cannot
edit it.
Global variables are shared variables, offered by the scripting language and not the
MSCL, that are useful in sharing information between module scripts.
Macro script variables are a special category of variables managed by the MSCL. When
a macro script is called by the MACRO EXEC command, macro script variables are
automatically declared and are automatically assigned values that the user can access
but cannot change.
The MACRO EXEC command and macro script variables are discussed in Section 8.2
Modular programming.
The scripting language, and not the MSCL, offers shared variables which are useful in
sharing information between module scripts, such as a user or company name.
Shared variables are totally different from the notion of MSCL variables. They are
created, accessed, and deleted using MACRO ... commands. For complete information,
see Section 7.3.6 Using shared variables.
The difference between these keywords is that EXPR_I returns only the integer
component of the result of the mathematical expression, without any rounding.
This subsection first presents the available mathematical operators and mathematical
functions and then explains how to use them within mathematical expressions.
+ (addition) / (division)
- (subtraction) % (modulo)
* (multiplication)
Here are some examples of mathematical expressions, which always require using the
EXPR keyword:
The EXPR keyword is presented in Section 6.5.3 Mathematical expressions along with
additional examples of mathematical expressions.
Order of
Operators (from left to right)
evaluation
Order of
Operators (from left to right)
evaluation
3 *, /, %
4 +, -
The mathematical functions described in the table that follows can only be used within
mathematical expressions.
Mathematical
Description
function
COS cosine of x
SIN sine of x
TAN tangent of x
DECLARE vNumber1 2
DECLARE vNumber2 4
DECLARE vMyResult
Set vMyResult EXPR (POW($vNumber1,$vNumber2))
MACRO ECHO ($vMyResult)
# displays: 16.0
The EXPR keyword is presented in Section 6.5.3 Mathematical expressions along with
additional examples of mathematical expressions.
The EXPR and EXPR_I keywords are used to construct mathematical expressions:
The difference between these keywords is that EXPR_I returns only the integer
component of the result of the mathematical expression, without any rounding.
The result type depends on the operands used in the mathematical expression. It is
integer if all operands are integer, and double if there is a double operand. The division
operation results in a double value, and the modulo operation, which requires integer
operands, always produces an integer result. The examples that follow illustrate the
evaluation, and the result type, of mathematical expressions.
Mathematical expressions can also be used as arguments. In the example that follows,
the MACRO INPUT INTEGER command is used to display a window that displays the
string Enter a value, read the value entered by the user at the keyboard, and assign it to
the vGraylevel variable. However, the next command, EDIT OBJECT COLOR, cannot
accept as arguments values larger than 255. In this case, the modulo operator provides
the required control for all three arguments. Note the use of the command
continuation character \.
DECLARE vGraylevel
MACRO INPUT INTEGER (vGraylevel, , "Enter a value")
EDIT OBJECT COLOR(EXPR($vGraylevel % 256), \
EXPR($vGraylevel % 256), \
EXPR($vGraylevel % 256))
The example that follows use the EXPR_I keyword to return only the integer
component of a mathematical expression as an argument.
The EXPR and EXPR_I keywords can also be included within a mathematical
expression. This is particularly useful, as EXPR_I can provide the integer component of
a value to an operator that requires integer operands, such as the modulo operator (%).
This subsection first presents the comparison and the logical operators used in logical
expressions and then presents logical expressions.
Logical expressions can be used as conditions within IF and WHILE structures; for more
information, see Section 6.7 Controlling the flow of execution.
Logical expressions can also be used to assign a resulting boolean value within
DECLARE and SET statements; for more information, see Section 6.4.3 Assigning values
to existing variables.
The logical expressions in the following examples all return TRUE (i.e., numerical 1):
DECLARE vVar1 10
DECLARE vVar2 20
DECLARE vVar3 30
DECLARE vMyResult
# Example 1
SET vMyResult $vVar1 < $vVar2
MACRO ECHO ($vMyResult)
# displays: 1
# Example 2
SET vMyResult ($vVar3 >= $vVar2)
MACRO ECHO ($vMyResult)
# displays: 1
# Example 3
SET vMyResult $vVar1 != $vVar2
MACRO ECHO ($vMyResult)
# displays: 1
Comparison operators in a logical expression are evaluated from left to right; for more
information, see Section 6.6.4 Evaluating logical expressions.
A logical expression can have one or more logical operators, each having two operands.
Operands of logical operators must be boolean values (i.e., True or False) or evaluate to
a boolean value.
Logical
Description
operator
NOT Reverses the result. Returns False if the result is true or True if
the result is false.
Example that returns True:
NOT (6 > 9)
The “AND” and “OR” logical operators allow constructing logical expressions with any
number of comparison operators, while the “NOT” logical operator reverses the result
of a logical expression.
Here are some simple examples of logical expressions using logical operators. In each
case, the expression returns True (i.e., numerical 1).
DECLARE MyResult
# Example 1: Age is greater than 2 AND less than 10
DECLARE vAge 5
SET MyResult $vAge > 2 AND $vAge < 10
MACRO ECHO ($MyResult)
# Displays 1
A logical expression returns one of two values on evaluation: True, or False. False is
considered as the numerical value 0, or as an empty string (""), and True is considered as
any nonzero value or any nonempty string.
# Example with a logical operator: AND (returns True if both operands are True)
DECLARE VMyResult
# Declaring 2 variables using logical expressions that evaluate to True values
DECLARE vResult1 6 > 4
DECLARE vResult2 2 > 1
SET VMyResult $vResult1 AND $vResult2
# The logical expression is evaluated to be True; True is assigned to vMyResult
MACRO ECHO ($VMyResult)
# Displays 1 (value for True)
Logical operators can be combined with comparison operators to allow for more than
one comparison:
Note that a logical expression can have just one variable and no operator:
DECLARE VMyResult
DECLARE vVar1 6 > 4
# Logical expression with just one operand containing the boolean value True
SET VMyResult $vVar1
MACRO ECHO ($VMyResult)
# Displays 1 (value for True)
The comparison and the logical operators are presented in the subsections that follow,
with additional examples of logical expressions.
The order in which operators are evaluated in a logical expression is presented in the
table that follows. The first line has the highest priority, and the priority diminishes from
one line to the next. If two or more operators have the same priority, i.e. are on the
same line, they are evaluated from left to right. Note that parentheses () allow changing
the order of evaluation in a logical expression.
Order of
Operators (from left to right)
evaluation
1 Expressions in parentheses
Mathematical operators
3 *, /, %
4 +, -
Comparison operators
Logical operators
6 NOT
7 AND
8 OR
A False value may be a boolean value (i.e., False) or the numerical value 0.
A True value may be a boolean value (i.e., True), a numerical value different than 0, or
a string value.
The IF statement permits the conditional execution of specific statements. It will also
be referred to as the IF structure, as it begins with the IF keyword and ends with the
ENDIF keyword.
A simple IF structure that processes one condition has the following syntax:
IF <condition>
< Statement1 >
< Statement2 >
ENDIF
If the <condition> is True, the statements are executed. If the <condition> is False, the
execution of the macro script continues with the line after the ENDIF keyword. For
more information on conditions, see Section 6.7.1 Constructing conditions.
DECLARE vNbHoles 3
DECLARE vMinNbHoles 4
IF $vNbHoles < $vMinNbHoles
# display a message to the effect that there are not enough holes
MACRO ECHO ("Not enough holes.")
ENDIF
The IF structure also permits the conditional execution of one of two sets of
statements. In this case, the IF structure has the following syntax:
IF <condition>
< Statement1.1 >
< Statement1.2 >
ELSE
< Statement2.1 >
< Statement2.2 >
ENDIF
If the <condition> is True, the first set of statements is executed. If the <condition> is
False, the second set of statements is executed. In both cases, the execution of the
macro script continues with the line after the ENDIF keyword.
The example that follows evaluates a mathematical expression that results in numeric
0, which is a False condition. Consequently, the second set of statements will be
executed.
IF EXPR (8 % 2)
# it would be awkward to read this
MACRO ECHO ("8 is an odd number")
ELSE
MACRO ECHO ("8 is an even number")
ENDIF
IF <condition1>
< Statement1.1 >
< Statement1.2 >
ELSEIF <condition2>
< Statement2.1 >
< Statement2.2 >
ELSEIF <condition3>
< Statement3.1 >
< Statement3.2 >
ENDIF
script continues with the line after the ENDIF keyword. The example that follows has
three conditions.
DECLARE vAge 25
IF $vAge < 10
MACRO ECHO ("Age is less than 10")
ELSEIF $vAge <= 40
MACRO ECHO ("Age is between 10 and 40 inclusively")
ELSEIF $vAge > 40
MACRO ECHO ("Age is greater than 40")
ENDIF
Note that the comparison operations shown in the example above can be combined
using logical operators. For example:
DECLARE vAge 25
IF $vAge =>10 AND $vAge <= 40
MACRO ECHO ("Age is between 10 and 40 inclusively")
ENDIF
WHILE <condition>
<Statements>
ENDWHILE
As long as the <condition> is True, the set of statements is repeated. When the
<condition> is False, the execution of the macro script continues with the line after the
ENDWHILE keyword. For more information on conditions, see Section 6.7.1
Constructing conditions.
DECLARE vLoopVar 4
WHILE $vLoopVar
MACRO ECHO ($vLoopVar)
# decrement vLoopVar within the WHILE structure to avoid infinite looping
-- vLoopVar
ENDWHILE
# end of example
4
3
2
1
The next example uses the BREAK keyword to exit the WHILE structure when the
value of the vLoopVar variable is less than 6.
DECLARE vLoopVar 8
# A WHILE structure that will continue repeating instructions until the value
# of the vLoopVar variable = 0
WHILE $vLoopVar
MACRO ECHO ($vLoopVar)
IF $vLoopVar < 6
# exiting the structure
BREAK
ENDIF
# Subtract one from the vLoopVar variable value
-- vLoopVar
ENDWHILE
Execution displays:
8
7
6
5
The next example uses the CONTINUE keyword to avoid executing the MACRO
ECHO ($vLoopVar) statement, as long as the value of the variable vLoopVar is greater
than 4.
DECLARE vLoopVar 8
WHILE $vLoopVar
# Subtract one from the vLoopVar variable value
-- vLoopVar
IF $vLoopVar > 4
# jump back to the WHILE statement
CONTINUE
ENDIF
4
3
2
1
0
The family of MACRO utility commands also offers ways of controlling script execution.
They are presented later in this document, in these sections:
Each logical structure (e.g., WHILE and IF) has its own scopes.
Example #1:
Example #2:
...
ENDIF end of False scope
# end of File scope
Example #3:
The largest scope is the File scope. It starts at the beginning of a macro script and ends
at the end of the macro script. Scopes can be nested within other scopes. In the
previous example, each scope is nested within the File scope. The following example
illustrates nested scoping.
A variable is said to be declared at File scope when its declaration is made outside of any
logical structure. In the following example, the variables vA and vE are declared at File
scope.
Variables declared at File scope exist from the moment of their declaration to the end of
the macro script. All other variables exist from the moment of their declaration to the
end of their scope. In the example in Figure 6.3, the scope, or life span, of each variable
is indicated by way of comments, as well as lines.
The notion of nested scopes authorizes the use of variables having the same name but
having different scopes. The variable that is the most nested is the one that is used.
100
100
200
100
In the next example, similar to the previous one, a variable vA is used to initialize a
second variable vA that is defined within a more nested scope.
VERSION "5.0"
# beginning of File scope
# available variables: none
DECLARE vA
# available variables: vA (is available and declared at File scope)
WHILE <condition-0> beginning of Loop scope
# available variables: vA
DECLARE vB
# available variables: vA, vB
DECLARE vD
# available variables: vA, vB, vD
vD
ENDIF end of False scope
# available variables: vA, vB
DECLARE vE
# available variables: vA, vE vE
# end of File scope
# variables: none
100
100
200.0
100
This section explains the data type conversions that can occur when using the Macro
Script Control Language. A conversion occurs when data of type A is converted to data
of type B with or without the loss of precision or information. When the conversion is
requested by the user through an element of the control language, it is said to be
explicit. Conversions that occur without being requested are referred to as implicit.
This section presents the standard conversion from one data type to another, and then
presents operations that result in explicit data type conversion as well as situations that
result in implicit data type conversion.
Data types may be converted from one data type to another data type, either explicitly
or implicitly. Certain conversions may result in a loss of precision. This section explains
how standard data type conversions are performed.
Possible conversions for the integer data type are explained in the table that follows.
Convert Loss of
Method
to precision
Possible conversions for the double data type are explained in the table that follows.
Convert Loss of
Method
to precision
Possible conversions for the string data type are explained in the table that follows.
Convert Loss of
Method
to precision
Conversions made by the EXPR, the EXPR_I, and the STRING_DECIMAL keywords
are explained in the table that follows.
Conversion done by
STRING_DECIMAL
expression EXPR (expression) EXPR_I (expression)
(expression)
string none
Command arguments
Conditions with only one operand undergo no conversion. However, if there are two
operands and a conditional operator, and the operands are not of the same type,
then there can be an implicit conversion of the type of one of the operands.
Comparisons between two numeric types are done without any difficulty. In the case
of numeric - string comparisons, the string operand is always converted to the
numeric type.
Mathematical operators require numeric operands. String types are first converted to
numeric types. If a mathematical operation is carried out on an integer and a double,
the result is a double type. However, there are two exceptions to this rule. A division
always results in a double type, and a modulo operation requires integer types, and
gives an integer type result.
The ++var1 operation is the equivalent of the SET var1 EXPR ($var1 + 1) statement,
and the --var1 operation is the equivalent of the SET var1 EXPR ($var1 - 1)
statement. The content of the variable is converted to a numeric type, if necessary.
Array index [ ]
Arrays require integer indices. The value used as an index is converted to an integer.
If the conversion fails, the default value of 0 is assigned, which is an invalid value for
an index.
7.1 Introduction
This chapter presents application commands and utility commands to get started
writing macro scripts. For each command, the content from the Command Help is
provided containing the command syntax and an example is given.
As the software evolves, so do the commands used for scripting. As new commands
appear, certain commands may be made obsolete. Obsolete commands are detected in
the Macro Script Editor and flagged appropriately to help the user identify them and
replace them with the updated commands. A subsection explains how to update a
macro script containing obsolete commands.
A macro script typically executes actions on objects. You can specify which objects to
use, and they must respect certain constraints (e.g., used, not locked, visible), similar to
doing a task manually.
There are several ways to specify objects to a command. Two ways are useful when the
objects are known ahead of time:
The name of the object. This lets you process specific objects.
The index number of the object. This is useful for cycling through consecutive
objects, such as all the objects under a specific branch. Note that index numbers for
objects under a branch in the tree view always start at 1 and are consecutive.
Two ways are useful when the selection must be determined at run time:
The current selection in the tree view is used. The selection can be made at run-time
by the user, or be performed by a command in a script that selects objects.
The default selection, when only one valid object exists in the tree view for the
command that will be executed.
The selection must correspond to the requirements of the command to execute in the
macro script. For example, certain commands only operate on specific objects, and
other commands require that only one object be selected.
Note that some commands do not require an explicit selection, but rather use all the
objects of a certain type that have specific properties. The section that follows deals
with specifying object properties.
When using the PolyWorks Metrology Suite, actions operate on objects that must have
certain properties, such as being unlocked or visible. See the following commands in
the Command Reference, available on choosing the Help > Commands item on the
menu of each Macro Script Editor tool, to specify certain properties for objects:
Scripting offers many TREEVIEW commands. The first command that follows is an
actual command. The second command is a general format – choose the category of
objects (e.g., planes, points), and write as many commands as there are object
categories.
This command selects or deselects an object in the tree view by its name.
Example:
Example:
Example:
Objective: Count all circle features, including those contained within pattern features
and cross-section feature groups.
When running a macro, you may want to temporarily change values in a dialog box,
execute commands using the temporary values, and then restore the original values at
the end of the macro. This is possible for values in text boxes and check boxes.
To read and store the original values, output variables are used. To read the stored
values, and reset them in the dialog box, input variables are used. For more
information, see Section 6.4.5 Using variables as input and output arguments for
commands.
The macro script that follows will make use of two items, found in the
PolyWorks|Inspector Options dialog box, and shown in Figure 7.1:
Text box: Max angle (on the Objects > Reference/Data > Point Clouds > Planar
Grids/Meshes page).
Two variables are needed to store the actual values for each item:
DECLARE vInitial_max_angle
DECLARE vInitial_view_grid
To read and store the value of each item, use the GET keyword, preceded by the
appropriate keywords. Note that pressing the TAB key for command completion in the
Macro Script Editor results in the display of the possible following keywords at any
position in a command (see Section 3.5.2.1 Command Completion feature for more
information on command completion). Note that the exact command to use can be
easily found by changing the value for each option in the options dialog box and
pressing the Apply button, and then consulting the Command History pane for the
resulting commands.
Figure 7.1 Pages of the PolyWorks|Inspector Options dialog box. In each case, the arrow
indicates the option that will be used in the example scripts.
# use MACRO ECHO commands to show the value stored in each variable:
MACRO ECHO ("The initial Max angle is $vInitial_max_angle")
# displays: The initial Max angle is 75.0
MACRO ECHO ("Initial View Grid is $vInitial_view_grid")
# displays: Initial View Grid is On
# where "On" means that the check box is selected
Next, to set temporary values for the same items, the commands are identical, except
for the GET keyword. In a sense, it is replaced by an implicit PUT keyword. Note that
the values to set are sometimes specified directly in the command, or obtained as
Values can be set for the two options using input variables (with $) or by specifying
values directly; examples of both follow:
Note also, in the case of the Grid check box, that three values are possible: "On", "Off",
and "Toggle". If the command is given without parentheses or argument, the default
action is to switch the current value of the check box to its other value (i.e., toggle).
At the end of the macro execution, reset the initial values, using input variables:
This command displays pages that guide the user as to how to scan a QR Code. This
information can then be used in the script, to open a PolyWorks|Inspector or an IMAlign
project of the scanned name for example.
This command allows the user to enter text that is encoded as QR Codes which can then
be printed.
Certain application commands (e.g., commands that are the equivalent of menu items
of the PolyWorks Metrology Suite modules) may become obsolete as the software
evolves. In the editor, obsolete commands in a script are flagged with an orange
background. Certain obsolete commands are still supported, while others are not and
may hinder the execution of the script. On placing the pointer over an obsolete
command, an information tooltip is displayed, stating what to do, as shown in Figure
7.2 (a). An obsolete command can be replaced by the following:
A renamed command.
The command has been renamed but it still has the same parameters, so technically
it can still be used. The new renamed command, and its parameters, are displayed. A
warning sign is displayed on the first line of the information tooltip. For an
example, see Figure 7.2 (a). In this case, the correct command name should be used.
A superseded command.
The command has been renamed and a change has been made to its parameters. A
warning sign is displayed on the first line of the information tooltip, and the
command name that supersedes it, and its parameters, are displayed. In this case, the
command should no longer be used – it must be rewritten using the new command
name and parameters.
Note that certain obsolete commands simply can no longer be used (e.g., the subject of
the command no longer exists). A danger sign is displayed on the first line of the
information tooltip. Such commands must be removed from the script. If their intent is
still important to the purpose of the script, other commands must be used to perform
their functions.
The Edit > Upgrade command attempts to resolve issues related to obsolete commands,
which produces the following results:
The current script is backed up by adding the current date and time to the script
name.
The first line displays a message starting with the term TODO, which allows
searching these cases easily in a long script.
The second line includes the name of the command that supersedes the
obsolete command, without any arguments.
Figure 7.2 In (a), obsolete application commands are displayed with a colored background. On
placing the cursor in a command, an information tooltip indicates that the
command is obsolete, and is replaced by a renamed command, given underneath
the message. In (b), the Edit > Upgrade operation has been performed. The first arrow
points an obsolete command that has been replaced by its renamed command, and
a second arrow points a command that is superseded by another command.
Information
tooltip
Replaced
command
Superceded
command
The utility commands that follow may also be useful in your macro scripts.
• WINDOW REFRESH
Disabling the screen refresh at the beginning of a long macro script, or when the project
contains large Reference and Data objects, may speed up macro script execution. The
screen refresh can then be re-enabled at the end of the macro script.
This command turns on/off the echoing of commands in the Command History pane.
The MACRO INPUT group of commands can be used to query information from a user
at macro script run time. The information is stored in output variables, which must
already be declared. If the command takes only one string argument, it represents the
text to appear in the window title; if there is a second string argument, it represents text
that will appear to prompt the user. For an example, see Figure 7.3.
The dialog box that is displayed offers two buttons, OK and Cancel; the Cancel button
generates an error code that can be detected using the MACRO
GET_ERROR_STATUS command.
For the purposes of the commands that follow, the following variables need to be
declared:
# integer variables
DECLARE vButtonpressed
DECLARE vNbrDigits
# a double variable
DECLARE vMaxAngle
# string variables
DECLARE vFolder_name
DECLARE vRef_file_name
# a string variable
DECLARE vUsername
This command displays a window with the prompt message. The user presses the Yes or
the No button, and the corresponding integer value, 1 or 0 respectively, is assigned to
an output variable.
Example:
Figure 7.3 An example of the two string arguments of a MACRO INPUT ... command.
Window title
User prompt text
Objective: Display a window showing the message “Do you want to continue?” and
store the user-pressed button in the vButtonpressed output variable.
Example:
Objective: Display a folder browser window titled “Workspace path” and store the
user-selected value in the vFolder_name output variable.
Example:
Example:
Objective: Display a file browser titled “Reference object path” and store the user-
selected value in the vRef_file_name output variable.
No prompt is necessary as a file browser is displayed, letting you choose the appropriate
file. On pressing the browser’s Open button, the file chosen is stored in the variable.
Example:
Objective: Display a window titled “Config info” with the prompt “Enter no. digits after
point”, and store the user-entered value in the vNbrDigits output variable.
Command: MACRO INPUT INTEGER (vNbrDigits, "Config info", "Enter no. digits after
point")
Example:
Objective: Display a window titled “User info” with the prompt “Enter your name”, and
store the user-entered value in the vUsername output variable.
Command: MACRO INPUT STRING (vUsername, "User info", "Enter your name")
This command queries the user by means of an input window for one or more values of
any type and assigns them to as many output variables.
Example:
Objective: Query the user for his/her age and height (meters).
DECLARE vHeight
# Query the user; the first argument is the optional window title
MACRO INPUT MULTIPLE_PARAMETERS ("About you", $vq1, $vA1, vAge,
vHeight)
The utility commands that follow allow you to pause or suspend the execution of the
macro script.
• MACRO PAUSE
Example:
Objective: Pause the macro script execution and display a window with the title Pause
window, and two messages, Consider the color map and Press the OK button
to continue.
Command: MACRO PAUSE ("Pause window", "Consider the color map", "Press the
OK button to continue")
• MACRO SLEEP
Example:
Objective: Make the macro sleep for one second (i.e., 1000 milliseconds).
Let’s assume a file c:\inspect_para.txt, with three lines of six fields per line, which each
contains three dataset names and three numeric values in the following format:
Note that the default field delimiters are the space or the TAB character. The delimiter
may also be user defined, but it then has to be specified in certain file-parsing
commands. In addition, empty fields are supported in certain commands. See the
second command that follows for examples.
The file-parsing commands that follow are located under the DATA_FILE branch of the
macro command tree of the Command Reference. The variables must already have
been declared.
# declaring variables
DECLARE vNbr_lines
DECLARE vNbr_fields
DECLARE vLine2
DECLARE vL2_F3
Example:
Example 1:
Objective: Read the number of fields in the first line in the file c:\inspect_Ex1.txt. A
default delimiter is used (i.e., the space or the TAB character), and empty
fields are not allowed. The first line contains: Me You Us. The value returned
to the output variable should be 3.
Example 2:
Objective: Read the number of fields in the first line in the file c:\inspect_Ex2.txt. The
delimiter symbol in the file is @. The first line contains: Me@You@Us. The
value returned to the output variable should be 3.
Example 3:
Objective: Read the number of fields in the first line in the file c:\inspect_Ex3.txt. The
delimiter symbol in the file is @. The first line contains: Me@@Us. If empty
fields are allowed (i.e., the last argument is set to “On”), the value returned
to the output variable is 3, otherwise it is 2.
",abc," 3
"," 2
Example:
Example:
Objective: In the file c:\inspect_para.txt, read the third field on the second line.
The scripting language, and not the Macro Script Control Language, offers shared
variables. A shared variable can be created, read, modified, and deleted in any macro
script (e.g., PolyWorks|Inspector, PolyWorks|Modeler, IMAlign, Workspace Manager). If a
shared variable is not deleted explicitly, it is available until the Workspace Manager is
closed.
Figure 7.4 An example of a macro script that uses the MACRO STRING group of commands. The
string being processed contains repeated terms, and it begins and ends with a space.
The macro script execution is shown in the Command History pane. The distinctive
part of each command has been highlighted.
Such variables are useful for sharing information between different scripts, such as the
company name. Note that shared variables are useful and dangerous at the same time,
as they are also available to any other script that may change its value.
The table that follows lists the related commands; for their syntax, see the Command
Reference of any Macro Script Editor tool.
Avoid simple variable names, such as name or number, that may be used by other
scripts. You can personalize your shared variables by adding a prefix to your shared
variable names (ex. ab_name, where ab is the project in question or even a number).
Check, at the time of creating a shared variable, if the command was successful – the
command fails if a shared variable of the same name already exists.
A shared variable is used in the macro script sample provided in Section 9.5 A
multiapplication script.
8.1 Introduction
This chapter presents basic programming practices that will make debugging easier,
save you time, and lead you to making smaller, specialized scripts that becomes tools
that are available from any other script.
The example that follows illustrates this divide and conquer approach, common to
programming in general. A first macro script is provided – within a project, it aligns a
Data and a Reference object, makes a comparison, and generates an inspection report.
Parts of the macro script are then used to make separate, short macro scripts. Finally, a
second macro script is proposed that makes calls to four smaller macro scripts, using
the MACRO EXEC command.
DECLARE vProject
DECLARE vReport
MACRO INPUT DIRECTORY_PATH (vProject, "Select a project to open")
MACRO INPUT DIRECTORY_PATH (vReport, "Select a report export folder")
# open the project
FILE OPEN_PROJECT_IN_PWK ( , $vProject)
# perform a rough alignment
TREEVIEW SELECT NONE
TREEVIEW DATA SELECT (1, "On")
ALIGN POINT_PAIRS
# perform a Best-Fit alignment
ALIGN BEST_FIT DATA_TO_REFERENCE CREATE \
FIT_TO_REFERENCE_OBJECT_SURFACES
# perform a comparison
TREEVIEW REFERENCE SELECT (1, "On")
MEASURE DATA_COLOR_MAP REFERENCE_SURFACE CREATE
# export the report
FILE EXPORT_REPORT HTML_FILE ($vReport)
A second, modular version of the first macro script follows. Its uses MACRO EXEC calls
to short, mono-task, macro scripts. As explained previously, the first argument of the
MACRO EXEC command is the name of the macro script to execute; arguments
required by the named macro script follow, separated by commas.
DECLARE vProject
DECLARE vReport
MACRO INPUT DIRECTORY_PATH (vProject, , "Select a project to open")
MACRO INPUT DIRECTORY_PATH (vReport, , "Select a report export folder")
MACRO EXEC ("OpenProject", $vProject)
MACRO EXEC ("RoughAlignment")
MACRO EXEC ("BestFitAlignment")
MACRO EXEC ("CompareDataToRef")
MACRO EXEC ("ExportReport", $vReport)
# end of example
# OpenProject
FILE OPEN_PROJECT_IN_PWK ( , $1)
# RoughAlignment
TREEVIEW SELECT NONE
TREEVIEW DATA SELECT (1, "On")
ALIGN POINT_PAIRS
# BestFitAlignment
ALIGN BEST_FIT DATA_TO_REFERENCE CREATE \
FIT_TO_REFERENCE_OBJECT_SURFACES
# CompareDataToRef
TREEVIEW REFERENCE SELECT (1, "On")
MEASURE DATA_COLOR_MAP REFERENCE_SURFACE CREATE
# ExportReport
FILE EXPORT_REPORT HTML_FILE ($1)
When a macro script is called by the MACRO EXEC command, macro script variables
are automatically declared and are automatically assigned values that the user can
access, but cannot change (except for output arguments). The table that follows
describes the macro script variables.
The examples that follow provide a complete review of using macro script variables.
The macro script Macro_1 contains a MACRO EXEC command that calls Macro_2.
Macro_2 contains two MACRO ECHO commands that display the content of the
variables $0 and $#, which are declared and initialized when the MACRO EXEC
command is executed. $0 is assigned the name of the macro script, Macro_2, and $# is
assigned the number of arguments passed to the MACRO EXEC command, 1.
# Macro_1
MACRO EXEC ("Macro_2")
# a reminder: $0
# Macro_2
MACRO ECHO ("$0 is running right now.")
MACRO ECHO ("$0 has received $# arguments.")
A string and an integer argument are added to the example as additional arguments of
the MACRO EXEC command.
# Macro_1
MACRO EXEC ("Macro_2", "Bobby", 33)
# a reminder: $0 $1 $2
# Macro_2
MACRO ECHO ("$0 is running right now.")
MACRO ECHO ("$0 has received $# arguments.")
MACRO ECHO ("$1 is $2 years old.")
The next example illustrates that the value integer 0 is assigned to a macro script
variable when the user does not enter a specific value as an argument, as is the case for
the variable $1. However, the user must always specify the name of the macro script to
be executed, hence the value of $0.
# Macro_1
# the only required argument is the name of the macro script
# to be executed.
MACRO EXEC ("Macro_2", , 33)
# a reminder: $0 $1 $2
# Macro_2
MACRO ECHO ("$0 is running right now.")
MACRO ECHO ("$0 has received $# arguments.")
MACRO ECHO ("$1 is $2 years old.")
Note that the last line displayed contains a 0 (0 is 33 years old). The $1 macro script
variable has been assigned the default value, integer 0.
A last example illustrates how the execution of the instructions in a macro script, in this
case the MACRO ECHO commands in Macro_2, can be preempted by testing if the
right number of arguments have been passed to the calling MACRO EXEC command,
in Macro_1, or not.
# Macro_1
MACRO ECHO ("First call:")
MACRO EXEC ("Macro_2")
# a reminder: $0
MACRO ECHO ("Second call:")
MACRO EXEC ("Macro_2", "Bobby", 33)
# a reminder $0 $1 $2
# Macro_2
IF $# < 3
MACRO ECHO ("Not enough arguments.")
MACRO END
ENDIF
MACRO ECHO ("$0 is running right now.")
MACRO ECHO ("$0 has received $# arguments.")
MACRO ECHO ("$1 is $2 years old.")
First call:
Not enough arguments.
Second call:
Macro_2 is running right now.
Macro_2 has received 3 arguments.
Bobby is 33 years old.
Output arguments, presented in Section 6.4.5 Using variables as input and output
arguments for commands, can be used when calling a macro script using the MACRO
EXEC command.
In this case, the MACRO OUTPUT_ARGUMENT command can be used in the macro
script that is called to assign a value to the output argument.
Here is a simple example. The following commands are contained in a first macro script:
# Macro1.pwmacro
# The MACRO EXEC command contains an output argument
DECLARE vAnyName
MACRO EXEC ("Macro2.pwmacro", vAnyName)
MACRO ECHO ($vAnyName)
# Macro2.pwmacro
# A value is assigned to the output argument, identified using its argument index
MACRO OUTPUT_ARGUMENT (1,"How about Ringo?")
The execution of a command can succeed or fail. This result is called the error status. It
can be obtained with the MACRO GET_ERROR_STATUS command. Once the error
status of a command is known, a decision can be made as to the actions to take in case
of failure. The exception to this rule is the MACRO EXEC command. The error status of
this command is that of the last command to be executed in the macro script.
This command gets the error status (i.e., No Error or Error) of the last statement that was
executed and assigns it to the specified out string variable. In earlier versions of the
scripting language, version 3 and below, this command returned the status of the last
executed command. As a result, a script written using an earlier version and containing
this command is not fully forward compatible with the version 4 or later of the scripting
language.
Statements include:
Note that the ++ and -- statements cannot fail. If the variable to increment or decrement
is not a number, an implicit conversion is carried out. If the conversion fails, integer 0 is
obtained and then incremented or decremented.
Stops the execution of the current macro script. It can be placed in a main macro script,
in which case the macro script execution terminates. If it is placed in a nested macro
script called from a main macro script by way of the MACRO EXEC command, the
nested macro script would terminate and the control would return to the main macro
script from which it was called.
The argument string is optional. You can specify "No Error" or "Error". The default value
is "No Error". The command MACRO END ends the execution of a macro script and the
argument specifies the error status of the macro script at that moment.
When the end on error mode is activated, the execution of a macro script is immediately
terminated when the error status of the most recently executed statement is Error. It is
as if the following commands were executed after each statement in the macro script
(let’s assume that the variable vStatus has already been declared):
The end on error mode is specific to each macro script. If you activate this mode in one
macro script, it has no influence on the mode in a parent or a child macro script.
Examples:
# set vStatus to "Error" to run the WHILE loop body at least once
DECLARE vStatus "Error"
DECLARE vProject
# as long as FILE OPEN_PROJECT_IN_PWK fails, retry the command
WHILE $vStatus == "Error"
MACRO INPUT DIRECTORY_PATH (vProject, "Specify the desired folder",)
FILE OPEN_PROJECT_IN_PWK ( , $vProject)
MACRO GET_ERROR_STATUS (vStatus)
ENDWHILE
#...proceed with the valid PolyWorks|Inspector project
The following example uses the MACRO END command to end a macro script that has
not received all the necessary arguments:
IF $# <= 2
MACRO PAUSE ("Error", "Too few arguments for this macro script.", \
"Expected 2 arguments; got $#.", "leaving macro script.")
MACRO END ("Error")
ENDIF
9.1 Introduction
This chapter presents a macro script that performs a described task for each of the
IMAlign, the PolyWorks|Modeler, and the PolyWorks|Inspector modules.
DECLARE vConv
# read the Convergence factor in the alignment dialog box
ALIGN OPTIONS CONVERGENCE GET (vConv)
# start the best-fit alignment using the Convergence factor
ALIGN START ($vConv,-1)
# lock the selected 3D images in the tree view
EDIT IMAGE LOCK ( )
The first IF-ENDIF determines the minimum number of triangles for a connected set of
triangles. This number of triangles may or may not be specified by the user. The IF $1
command is true only if an argument was passed to the macro. In this case, the first
argument’s value is copied to vNbTriMin. Otherwise, vNbTriMin keeps its value of 20
assigned at declaration.
DECLARE vNbLevels
DECLARE vNbCurLevel
DECLARE vNbTriForLevel
DECLARE vNbTriMin 20
IF $1
SET vNbTriMin $1
ENDIF
#
# Find all connected sets of triangles and select the triangles that belong to these
# objects. Each connected set, or object, occupies one selection stack level.
# Following this operation, the only objects that are still selected are those that
# contain less than vNbTriMin triangles. Now delete all selected triangles.
SELECT ELEMENTS LEVEL COUNT GET (vNbLevels)
IF $vNbLevels > 0
EDIT OBJECT DELETE_SELECTED_ELEMENTS
ENDIF
MACRO ECHO ("===== Completed =====")
# End of script
The following example automates the alignment of three point clouds, and then
generates a data color map using the Reference object in the project. The first point
cloud is called pointcloud1. Each point cloud must be imported in a different alignment
group.
This macro executes an automatic alignment of three different point clouds. The
original position of the three point clouds is approximately the same. The rough
alignment of the first point cloud (scan) is done by a manual operation, then the two
other scans are aligned automatically, using the first point cloud’s global alignment
matrix. Note that the three point clouds initially have the “ignored” status in the project.
One by one, the objects are assigned the “used” status, are aligned, and then are
reassigned the “ignored” status.
DECLARE vDatanb 1
WHILE $vDatanb <= 3
# rough alignment of the first point cloud
TREEVIEW OBJECT SELECT NONE
TREEVIEW DATA SELECT ($vDatanb, "On")
EDIT OBJECT USE
IF $vDatanb == 1
# rough alignment of the first scan
ALIGN POINT_PAIRS
ALIGN BEST_FIT DATA_TO_REFERENCE CREATE \
FIT_TO_REFERENCE_OBJECT_SURFACES
ELSE
# rough alignment of the second and third point cloud
TREEVIEW OBJECT SELECT NONE
TREEVIEW DATA SELECT ($vDatanb, "On")
ALIGN TRANSFORM_USING_MATRIX FROM_OBJECT \
("pointcloud1", "Global", "Off", )
ALIGN BEST_FIT DATA_TO_REFERENCE CREATE \
FIT_TO_REFERENCE_OBJECT_SURFACES
ENDIF
# generation of a color map of the deviations
VIEW POSE CENTER
VIEW POSE Z_POS
MEASURE DATA_COLOR_MAP REFERENCE_SURFACE CREATE
REPORT_ITEM SNAPSHOT CAPTURE
# set the vStatus of the selected point cloud to ignored
TREEVIEW OBJECT SELECT NONE
TREEVIEW DATA SELECT ($vDatanb, "On")
The following macro script displays the center of mass coordinate derived from the
measured point primitives in the open PolyWorks|Inspector project. A point named CM
will be created in the project to visualize more easily the center of mass coordinates.
DECLARE vNbpts
# check that there are points in the project; if not, end the macro
# get the number of points to process
TREEVIEW FEATURE POINT COUNT GET(vNbpts)
If $vNbpts == 0
MACRO ECHO ("No points found...leaving.")
MACRO END ("No Error")
ENDIF
TREEVIEW OBJECT SELECT NONE
# select all measured point primitives and make them visible
TREEVIEW PRIMITIVE SELECT MEASURED
TREEVIEW OBJECT VIEW KEEP
# define variables:
# vNbptsmeasured: holds the number of point features with a measured primitive
# vStatus: holds status of last point feature measured primitive selection
# vNbpts: holds the number of point features in the project
# vPtArray: is an array that will hold the current point’s X, Y, and Z values
# vCmArray: is an array that will hold the center of mass coordinates
# vNb: is a counter in a loop
DECLARE vNbptsmeasured 0
DECLARE vStatus
DECLARE vPtArray
DECLARE vCmArray
DECLARE vNb 1
# accumulates in vCmArray[1], vCmArray[2] and vCmArray[3] the sum
# of the X, Y, and Z coordinates
WHILE $vNb <= $vNbpts
# get the X, Y, and Z values of the point
TREEVIEW OBJECT SELECT NONE
# select measured primitive by feature index
TREEVIEW FEATURE POINT MEASURED SELECT($vNb, "On")
# validate selection - the feature may have no measured primitive
MACRO GET_ERROR_STATUS (vStatus)
IF $vStatus == "No Error"
# get the X, Y, Z coordinates of the selected point
TREEVIEW PRIMITIVE POINT PROPERTIES POINT \
GET(vPtArray[1], vPtArray[2], vPtArray[3])
Basic commands are available that let you perform tasks in the IMAlign, the
PolyWorks|Modeler, and the PolyWorks|Inspector modules:
Execute scripts written for those modules (does not apply to PolyWorks|Reviewer).
Concerning the IMMerge module, a command is available that runs the module using
the specified parameters.
As the example demonstrates how to process in one module and then use the output
in a downstream module, the actual tasks executed are purposefully simple. A more
complex task could be executed using a similar structure.
Step A. To do in IMAlign:
Step B. To do in IMMerge:
2. Specify the IMAlign project (IMBlock_Aligned, in the active workspace) and the
desired parameters for IMMerge.
3. Start the merging task. The output polygonal model, Model.pol, is written to the
associated workspace.
4. Close IMMerge.
Step C. To do in PolyWorks|Modeler:
WM_script – The main script that drives the entire process, written in the Macro Script
Editor tool of the Workspace Manager.
IMAlign_script – A script written in the Macro Script Editor tool of the IMAlign module.
Here are the three scripts in order. The WM_script content is as follows:
# HOUSEKEEPING
MACRO SHARED_VARIABLE DELETE ("svNb_images")
# End of WM_SCRIPT
Load the main macro script, WM_script, in the Macro Script Editor tool of the
Workspace Manager and execute it. It starts the other modules and executes scripts
written in their own Macro Script Editor tools. On completion, a simple multiapplication
task has been performed.
Workspace Manager The Workspace Manager allows managing your data by way
of workspaces, in addition to launching PolyWorks
Metrology Suite applications. It also allows configuring
PolyWorks options and entering license keys.
A E
abs() 85 exiting a macro 137
acos() 85 EXPR 83, 86
application commands EXPR_I 83, 86
help for 41
arguments, input and output 73
arrays
F
finding the size of 78 false, definition of 90
implicit indexes 77 file-parsing commands 122
in a sample macro script 144
indexes 76
asin() 85 G
assigning values to variables 71 GET 109
atan() 85
I
B
IF-ELSE-ENDIF structure 93
BREAK 96 INPUT 116
input arguments 73
C
calling other macro scripts 131 J-L
Command History pane log10() 85
Command Line area 53 logical expressions 89, 90
Command reference documentation 41 looping in a macro script 95
comments in a macro script 63, 66
CONTINUE 96
converting data types 101 M
cos() 85 MACRO END 137
creating variables 70 MACRO EXEC 131
MACRO GET_ERROR_STATUS 137
D MACRO PAUSE 121
Macro Script Control Language. See MSCL
DATA_FILE 122 Macro Script Editor
DECLARE 70 editing macro scripts 43
declaring variables 70 interface 23
menus 24 Q
recording macro scripts 58
running macro scripts 61 querying the user 116
macro scripts
accessing check and text boxes 109 S
adding comments to 67
and programming 64 to 65 SET 71
creating 59 sin() 85
data conversion in 101 SIZE 78
editing 61 sqrt() 85
general rules that apply to 62, 66 storing and reqading parameters in a text file 122
running 61
testing 61
writing commands over more than one line T
67
tan() 85
MACRO SLEEP 122
TREEVIEW 107
MACRO STRING 125
true, definition of 90
mathematical expressions 83, 86
mathematical functions 85
modular programming 131 V-Z
MSCL 67
variables
a programming language 65
assigning values to 71
DECLARE 70
declaring 70
EXPR 83, 86
decrementing 82
EXPR_I 83, 86
incrementing 82
general rules 62, 66
MSCL 69
IF-ENDIF structure 93
reserved 79
input and output arguments 73
scope of 97
keywords 68
types 69, 71
logical expressions 90
using value stored in 72
mathematical expressions 83, 86
VERSION 63, 66
SET 71
WHILE-ENDWHILE structure 95
SIZE 78
statement format 67 WINDOW REFRESH 115
variables 69 to 75
VERSION 63, 66
WHILE-ENDWHILE structure 95
O
object tree, commands that work with the 107
obtaining information from the user 116
output arguments 73
P
pow() 85