Table of Contents

Table of Contents

Category Command Reference

Commands by Category

AGV

Description
Deprecated, use AGV class.
Gets various information about an agv, based on the what parameter:
AGV_CURRENT_CP - Returns the agv's current control point
AGV_ORIGIN_CP - Returns the agv's origin control point
AGV_INTERMEDIATE_DEST_CP - Returns the agv's intermediate destination control point
AGV_DEST_CP - Same as AGV_INTERMEDIATE_DEST_CP
AGV_FINAL_DEST_CP - Returns the agv's final destination control point
AGV_DEST - Returns the agv's destination object
AGV_BATTERY_LEVEL - Returns the agv's current battery level as a percentage of battery capacity (0 - 100)
AGV_AMP_HOURS - Returns the agv's current battery level in amp hours
AGV_START_RECHARGE - Starts the agv recharging. Returns the time it will take to recharge to full capacity.
AGV_RECHARGE_TO_LEVEL - Explicitly set's the agv's battery level to p1 (0 - 100).
AGV_ADD_ALLOC_POINT - Should be called from the travel initialization trigger. Manually adds a control point/control area for allocation, i.e. a control point or control area that would not otherwise need to be allocated as part of the agv's current travel path. The control point/control area is passed as p1, and the distance at which it must be allocated is passed as p2. The command will return a reference to a node that represents that allocation. Use AGV_SET_ALLOC_POINT_DEALLOC_DIST and AGV_SET_CAN_STOP_AT_ALLOC_POINT to specify further data on that allocation point.
AGV_SET_ALLOC_POINT_DEALLOC_DIST - For a manual allocation point that's been added, this sets the travel distance at which the agv can deallocate the object. You should call this at some point after adding the allocation, so that the object will be properly deallocated. p1 is a reference to the allocation point node returned by AGV_ADD_ALLOC_POINT, and p2 is the deallocation distance.
AGV_SET_CAN_STOP_AT_ALLOC_POINT - Sets whether or not the agv can stop at a manually added allocation point. The default is no, i.e. the agv will not stop at the stop distance, but will continue to the next stoppable point before attempting to allocate the object. Setting this to 1 will allow the agv to stop at the manual allocation point to allocate ahead. p1 is a reference to the allocation point node returned by AGV_ADD_ALLOC_POINT, and p2 is 1 or 0.
AGV_ATTACH_TRAILER - Manually attaches a trailer to the AGV. p1: the object to attach. p2: the trailer gap to apply. p3: If 1, the trailer will be attached behind the AGV (attach to the AGV's tail), if 0, the trailer be attached ahead of the AGV (attach to the AGV's head). p4: If 1, the trailer will automatically be detached when the object exits the AGV, if 0, the trailer should be manually detached.
AGV_DETACH_TRAILER - Manually detaches a trailer from the AGV. p1: the object that is attached as a trailer.
AGV_SPEED - Returns the agv's current speed
AGV_PROXIMITY_STATE - Returns 1 if the agv is blocked by proximity on an accumulating path, 0 otherwise.
AGV_ACCUM_AHEAD_AGV - Returns the agv ahead of this agv on an accumulating path, if one exists.
Example
agvinfo(agv, AGV_DEST_CP);
Description
Returns a control point connection. Also, if connection is a string and controlpoint and rank are both 0, then this command will return the index of the given connection. This is for speed, so that you can subsequently use a number for the connection.
Example
cpconnection(cp, "ForwardTo", 1) Returns the first ForwardTo connection on cp
cpconnection(cp, "LookForWork>NextLookForWork", 1) Traverses two connections to find an object. This is the same as cpconnection(cpconnection(cp, "LookForWork", 1), "NextLookForWork", 1)
cpconnection(cp, "LookForWork:2>NextLookForWork", 1) Same as cpconnection(cpconnection(cp, "LookForWork", 2), "NextLookForWork", 1)
int connIndex = cpconnection(0, "LookForWork", 0);
treenode obj = cpconnection(cp, connRank, 1);
Gets the index of the connection, and then uses the index instead of the name.

Communication

Commands for communicating with external applications such as sockets, database communication, and links with Microsoft Excel.
Receives data sent to the socket
Description
This command receives data that has been sent to the socket specified as socket. The value of socket is the number that is returned by clientcreate(). This command operates differently in flexscript vs. c++. In c++, buffer must be a valid pointer to a char* destination into which the read bytes will be copied. The return value will be the total number of bytes received. Up to bufsize bytes from the clients message will be read and stored in the preallocated character array called buf. In flexscript, however, buffer should be passed as NULL, and the return value will be the actual string that is received. If noblocking = 1, then this command does not block FlexSim program execution, but if noblocking = 0, FlexSim program execution will block (freeze) until something is received from the client.
Example
c++: int bytes = clientreceive(1,Buf,15,0);
flexscript: string readstr = clientreceive(1, NULL, 15, 0);
Opens an ODBC database
Description
This command attempts to open an ODBC database. Returns a 1 for success, 0 otherwise. The database must have an ODBC alias (or Data Source Name DSN) defined before it is opened. This is done using the "Data Sources" option in the Windows Control Panel. The alias name is passed to the command as databasename, the database file name should not be passed. Databases can be opened in two different modes. These modes have slightly different behavior and available commands. The two modes are SQL mode and Table mode. If the parameter tablemode is 1, then the database will be opened in Table mode, and command should be the name of the table in the database to open. If the table is opened successfully, the entire table will be available to read. Individual cells can be edited in Table mode. No SQL commands should be called if the database is in Table mode. If tablemode is 0, then the database will be open in SQL mode and command should be the initial SQL query. If the query executes successfully, only the result of the query will available to read. Individual cells cannot be edited in SQL mode. However, SQL update queries can be called once the database is open. If showlogin is 1 then the standard login prompt (username/password) will be shown before the connection to the database is made.
Example
dbopen("itemdrive","timetable",1);

This opens a database with the alias "itemdrive" and opens the table called "timetable" in Table mode.

dbopen("warehouse","select * from inventory",0);

This opens a database with the alias "warehouse" and performs a SQL query on it. The database is open in SQL mode.
Perform an SQL query on the open ODBC database
Description
This command performs the SQL query specified by query on the currently open database. The result becomes the current table. If the database is in Table mode, this command does nothing. If the query returns a table, that table can be read using the dbgettablecell() command. If the query performed an update, the dbgettablecell() command will cause an exception to occur.
After performing UPDATE statements with this command, a SELECT should be called immediately following, as there is no table returned by an UPDATE. This command is only usable in SQL mode. If forwardOnlyCursor is 1, then it will assume the result is a forward-only-cursor result. For forward-only cursors you cannot use dbgetnumrows(). Instead, after the call to dbsqlquery(), you call dbnextrow(). This command will return the activated row. It will return -1 once it hits the end of the table.
Example
dbsqlquery("select processtime from timetable where type='1'");

This returns a new table based on the SQL query passed.

dbsqlquery("update timetable set processtime=type*2");

This updates the database based on the query passed.
Sets the username and password used to access an ODBC database with dbopen()
Description
This command sets the username and password that will be used to access a database when dbopen() is called next. This allows a model builder to use the login parameters required by a database, without having to use the username/password prompt that dbopen() provides. The username and password set by this command will be used every time dbopen() is called until they are changed by calling dbusername() again. It is acceptable to set either the username, password or both to an empty string.
Example
dbusername("user1","abc123XYZ");

This sets the username to "user1" and the password to "abc123XYZ". These values will be used to access a database the next time dbopen() is called.

dbusername("","");

This clears out the last set username and password. The next time dbopen() is called, the database will be accessed without a username or password.
Launch Microsoft Excel
Description
This command opens Microsoft Excel so that it can be accessed by FlexSim. If launchdir is not specified, the path defined in Tools|Excel...|Global Settings will be used. Otherwise, the launchdir must be an accurate path to the location on the hard drive where EXCEL.EXE is located. It is typically something like "C:/Program Files/Microsoft Office/Office10," but may be different depending on the version of Excel installed. It is generally not required to launch Excel before communicating with it. However, if FlexSim is set to communicate with Excel via DDE (by calling maintenance(1000,1), this is not the default behavior) Excel must be running before any communication can be performed. If excellaunch() is called at the beginning of communication, excelquit() must also be called before the user opens a new model, compiles the current model or closes FlexSim.
Example
excellaunch(" C:/Program Files/Microsoft Office/Office10");
excelopen("C:/mybook.xls");
excelsetsheet("Sheet1");
double thenum = excelreadnum(1,1);
excelclose(true);
excelquit();

This starts Excel, opens a workbook called "mybook," stores a value read from row 1, column 1 from that workbook, then closes the file and Excel.
Gets the server will attempt to accept a client connection
Description
The server will attempt to accept a client connection. If noblocking = 0, the command blocks until a connection is made. It returns an index used to reference the connection made.

The server will attempt to accept a connection from a waiting client. A number will be returned that is the index of the connection established. A return value of 0 indicates that no connection was created. This value will be used in all future server calls. If noblocking = 1, the server will not block FlexSim program execution, but will return a 0 if no client attempts to connect. If noblocking = 0, the server will block (freeze) FlexSim program execution until a client attempts to connect. Connections with clients are only made with this command.
Example
int client = serveraccept(0);
Receives a message from the connection
Description
Receives a message from the specified connection. This command operates differently in flexscript vs. c++. In c++, buffer must be a valid pointer to a char* destination into which the read bytes will be copied. The return value will be the total number of bytes received. Up to bufsize bytes from the clients message will be read and stored in the preallocated character array called buf. In flexscript, however, buffer should be passed as NULL, and the return value will be the actual string that is received. If noblocking = 1, then this command does not block FlexSim program execution, but if noblocking = 0, FlexSim program execution will block (freeze) until something is received from the client.
Example
c++: int bytes = serverreceive(1,Buf,15,0);
flexscript: string readstr = serverreceive(1, NULL, 15, 0);

Conversions

Commands for converting units, data types, and spatial coordinate.
Converts the given value (a time) from one time format to another
Description
Converts the given value (a time) from one format to another. The from and to arguments only accept the following values:

FS_DATETIME
XL_DATETIME
MODEL_TIME
DATE_STR
TIME_STR
DATETIME_STR

FS_DATETIME - the number of seconds since Jan 1, 1601. getmodelunit(START_TIME) returns a value in FS_DATETIME units.

XL_DATETIME - the serialized day number, where day 1 is Jan 1, 1900. Feb 10, 2025 1:30 PM is 45698.5625 in XL_DATETIME units. This format is used in Microsoft Excel for dates.

MODEL_TIME - the number of model units since the model start time

DATE_STR - a string representing the date portion of a datetime value. The resulting text will depend on the date format specified in the model settings. If converting from this format, the value must be formatted according to those settings.

TIME_STR - a string representing the time portion of a datetime value. The resulting text will depend on the time format specified in the model settings. If converting from this format, the value must be formatted according to those settings.

DATETIME_STR - a string representing the time and date of a datetime value. The resulting text will depend on the time and date formats specified in the model settings. If converting from this format, the value must be formatted according to those settings; the time portion must be first, separated from the date portion by a single space.

Note that year 3000 and beyond are not supported by this command.
Example
convert(42308, XL_DATETIME, MODEL_TIME) // converts an Excel date to a valid model time

Conveyor


Deprecated

Commands that are no longer supported, or for which alternative commands have been made. The documentation for these commands has been discontinued, and therefore may be incorrect. Many of the commands still work for backwards compatibility purposes, but we encourage you to use their alternatives instead.
Deprecated, use Math.atan2()
Description
This command is deprecated. Use Math.atan2() instead.

Returns the angle in degrees, rotated clockwise from the positive x axis, of the vector (dx, dy). Calling angle(dx, dy) is the same as calling -Math.degrees(Math.atan2(dy, dx)).
Example
double myangle = angle(distx, disty)
Deprecated, use Object.attrs.assert()
Description
This command is deprecated. Use Object.attrs.assert().

Gets a reference to attribute attributename of object, creates the attribute if it does not exist.
Example
Deprecated, use treenode.labels.assert()
Description
This command is deprecated. Use treenode.labels.assert() instead.

Gets a reference to label labelname, creating the label if it does not exist.
Example
Deprecated, legacy conveyors are no longer supported
Description
Deprecated, Legacy conveyors are no longer supported.

This command is used in conjunction with the BasicConveyor object.

The bcgetitemkinematics command is used to obtain a reference to one of the three kinematics associated with a flowitem traveling on a BasicConveyor:

0 = The main convey state kinematics. You may get kinematic information from this, but do not change the kinematic by adding kinematics or initializing it.

1 = A user-definable kinematics that is dependent on simulation time.

2 = A user-definable kinematics that is dependent on the convey position of the flowitem on the conveyor.

The two user-definable kinematics are available for the user to set up customized kinematic motion in addition to traveling down the length of the conveyor. Use bcgetitemkinematics to get a reference to the desired kinematics node, and then use standard initkinematics() and addkinematic() commands as normal. You will need to use the alternative initkinematics parameter list: initkinematics(node, x, y, z, rx, ry, rz, managerots, localcoords). Also, if you add kinematics to the type 2 convey depend kinematic node, bear in mind that all time units for that kinematic no longer apply to actual simulation time units. Instead, they are interpretted as "convey units". For example, a speed of 5 is no longer 5 units per time unit, but is instead 5 units per conveyed unit. Acceleration is not distance per time squared, but distance per conveyed unit squared. Start times are no longer a time to start the kinematic, but a position along the conveyor to start the kinematic at. As an example, let's say you add a kinematic to the convey dependent kinematic node to travel 1 unit in the y direction with "start time" 5 and "max speed" 0.5. What that translates to for the convey dependent kinematic is that the item will start traveling in the y direction once it reaches 5 units along the conveyor. Also, for every unit that it travels down the length of the conveyor, it will travel 0.5 units in the y direction (0.5 y units per convey unit). Thus it will finish the y kinematic once it has travelled 7 units down the conveyor. If the item is blocked in the middle because of accumulation, say at convey position 6, then its y kinematic will also stop, and not resume until the item resumes along the conveyor.

See bcsetitemconveystate command documentation for a general description of the BasicConveyor object.
Example
treenode kin = bcgetitemkinematics(current, item, 2);
treenode kin2 = bcgetitemkinematics(current, item, 1);

initkinematics(kin, 0,0,0, 0,0,0, 0,0);
addkinematic(kin, 0,1,1,0.5,1,1,0,0, 5, KINEMATIC_TRAVEL);
initkinematics(kin2, 0,0,0, 0,0,0, 0,0);
addkinematic(kin2, 0,0,720,360,0,0,0,0, time()+5.0, KINEMATIC_ROTATE);
Deprecated, legacy conveyors are no longer supported
Description
Deprecated, Legacy conveyors are no longer supported.

This command is used in conjunction with the BasicConveyor object.

The bcsetdirection command stops all flowitems on the conveyor and sets the direction of travel to 1=forward and 0=reverse. All flowitems will need to have their convey state reset with the bcsetitemconveystate() command before they will begin moving again. The example below shows how to stop the conveyor, and then have all the flowitems accelerate up to a speed of 1 in the reverse direction. Any additional item kinematics will still be active after a direction change.

See bcsetitemconveystate command documentation for a general description of the BasicConveyor object.
Example
bcsetdirection(so(),0);
for(int i = 1; i <= so().subnodes.length; i++)
{
     treenode item = so().subnodes[i];
     bcsetitemconveystate(so(), item, bcgetitemposition(so(), item), 0, 1, 0.2);
}
Deprecated, legacy conveyors are no longer supported
Description
Deprecated, Legacy conveyors are no longer supported.

This command is used in conjunction with the BasicConveyor object.

The BasicConveyor object allows flowitems to be moved in and out of the conveyor at any time and at any location. Each flowitem on the BasicConveyor can be assigned and re-assigned its own kinematic profile defining how the flowitem is to move along the conveyor. When one flowitem overtakes another flowitem on the conveyor which is either stopped or traveling at a slower speed, it will slow down immediately to match that flowitem's speed. Although flowitems may travel in either direction along the conveyor, all flowitems will travel in the same direction at any given time. The travel direction of the conveyor is set with the bcsetdirection() command. As flowitems are moved in and out of the conveyor, other flowitems on the conveyor are aware of the increase or decrease in available space along the conveyor, and will accumulate naturally. After a flowitem enters the conveyor, either indirectly with the receiveitem() command or directly with the moveobject() command; it is necessary to define the flowitem's initial kinematic profile. This profile is refered to as the flowitem's "convey state", and it is set with the bcsetitemconveystate() command. The convey state for a flowitem can be set multiple times if desired. The following are definitions for the parameters used to define the convey state of a flowitem:

basicconveyor = A reference to the conveyor.

item = A reference to the flowitem.

startpoint = The starting location for the flowitem as measured from the beginning of the conveyor, along the conveyor's length to the flowitem's edge furthest from the head of the conveyor (the leading edge if the conveyor's direction is forward, the trailing edge if the conveyor's direction is backward).

startspeed = The initial speed the flowitem will begin traveling at.

targetspeed = The target speed the flowitem will try to achieve. If the targetspeed is greater than the startspeed, then the flowitem will accelerate up to the target speed; otherwise it will decelerate down to the target speed. If both the startspeed and the targetspeed are set to 0, the flowitem will be positioned at the startpoint, and will not move.

accdec = The acceleration or deceleration used to achieve the target speed over time. A value of 0 indicates infinite acceleration/deceleration; or in other words the flowitem will reach it's targetspeed immediately.

No destination or termination speed is required, because the flowitems continue traveling along the conveyor until they either reach the end of the conveyor, run into another flowitem, or their convey state is changed again. The BasicConveyor allows multiple "Decision Points" to be defined along its length. These trigger points are convenient locations to update the convey state of a flowitem. In addition to the main convey state kinematic assigned to the flowitem with the bcsetitemconveystate() command, a flowitem has two other kinematic structures associated with it that may be used to apply custom kinematic motion (translation or rotation) in addition to the travel motion along the conveyor. One of the kinematic structures is based on simulated time units, and the other is based on distance units along the length of the conveyor. To access these kinematic structures, use the bcgetitemkinematics() command, then use the initkinematics() and addkinematic() commands to create the custom kinematic motion desired. See bcgetitemkinematics() command documentation for more information.
Example
bcsetitemconveystate(current, item, position, 0, 60, 0);
Deprecated, use Math.ceil()
Description
This command is deprecated. Use Math.ceil() instead.

Gets the smallest integral value not less than num.
Example
Deprecated, use Table.cell()
Description
This command is deprecated. Use Table.cell() instead.

Gets a reference to the table's cell.
Example
double val = getnodenum(cellrc(reftable("MyTable"),2,3));
Deprecated, use conveyor.targetSpeed
Example
changeconveyorspeed(current, 4);
This example changes the conveyor's speed to 4.
Deprecated, use Object.input.close()
Description
This command is deprecated. Use Use Object.input.close() instead.

This command blocks the input of the object. Only the input ports themselves, or the input in general needs to be closed to block entry. When port connections are displayed with sufficient size in the view window, you will see a small red bar drawn across all the input ports (squares) for the object, signifying the input ports are blocked. Individual ports may still be open and drawn in green, but entry to the object is still blocked because of the red bar. Compare this command with stopinput().
Example
if (current.subnodes.length == getvarnum(current,"maxcontent")
closeinput(current);

This blocks the input ports of current when it has too many objects inside it.
Deprecated, use Object.output.close()
Description
This command is deprecated. Use Object.output.close() instead.

This command blocks the output of the object. Only the output ports themselves, or the output in general needs to be closed to block the exit. When port connections are displayed with sufficient size in the view window, you will see a small red bar drawn across all the output ports (squares) for the object, signifying the output ports are blocked. Individual ports may still be open and drawn in green, but exit from the object is still blocked because of the red bar. Compare this command with stopoutput().
Example
if (current.subnodes.length == current.mincontent)
closeoutput(current);

This blocks the output ports of current, if current has too few objects inside it.
Deprecated, use Process Flow instead
Description
This command is deprecated. Use Process Flow instead.

This command creates a task sequence on the object specifies as dispatcher that causes it to send a message to the object specified as receiver. The OnMessage trigger of the receiving object will be executed when the message is sent. The values passed as param1, param2, and param3 will be available in the trigger function using the param() command. This task sequence will be given a priority of priority and a preempting value of preempting. The possible values for preempting are:

0 - PREEMPT_NOT
1 - PREEMPT_ONLY
2 - PREEMPT_AND_ABORT_ACTIVE
3 - PREEMPT_AND_ABORT_ALL
Example
createsendmessagetask(current, current.centerObjects[1],1,PREEMPT_NOT,5, 6, 7);
Deprecated, use Process Flow instead
Description
This command is deprecated. Use Process Flow instead.

This command creates a task sequence for the object specified by dispatcher that causes it to travel to the point specified by xlox, y, and z. Once the object reaches that point, it will wait in the state specified as state until an endwaittask() command is issued to it. For a list of legal states, see setstate(). If relativeloc is 1, the specified point is relative to the origin of dispatcher. If relativeloc is 0, the specified point is the exact point in

the model that dispatcher will try to travel to. It will travel until its front edge reaches the specified point. This task sequence will be given a priority of priority and a preempting value of preempting. The possible values for preempting are:

0 - PREEMPT_NOT
1 - PREEMPT_ONLY
2 - PREEMPT_AND_ABORT_ACTIVE
3 - PREEMPT_AND_ABORT_ALL
Example
createtraveltolocandwaittask(current.centerObjects[1], 1, 5.15, 2.5, 0, 0, STATE_IDLE, 1, PREEMPT_NOT);
Deprecated, use Process Flow instead
Description
This command is deprecated. Use Process Flow instead.

This command creates a task sequence for the object specified by dispatcher that causes it to travel to the point specified by xlox, y, and z. If relativeloc is 1, the specified point is relative to the origin of dispatcher. If relativeloc is 0, the specified point is the exact point in the model that dispatcher will try to travel to. It will travel until its front edge reaches the specified point. This task sequence will be given a priority of priority and a preempting value of preempting. The possible values for preempting are:

0 - PREEMPT_NOT
1 - PREEMPT_ONLY
2 - PREEMPT_AND_ABORT_ACTIVE
3 - PREEMPT_AND_ABORT_ALL
Example
createtraveltoloctask(current.centerObjects[1], 1, 5.15, 2.5, 0, 0, 1, PREEMPT_NOT);
Deprecated, use Process Flow instead
Description
This command is deprecated. Use Process Flow instead.

This command creates a task sequence on the object specified as dispatcher that causes the object to not perform new task sequences that it is given until it has been released. The object can be released with the endwaittask() command. The object will be in the state specified by state while it is waiting. For a list of possible states, see setstate() command. This task sequence will be given a priority of priority and a preempting value of preempting. The possible values for preempting are:

0 - PREEMPT_NOT
1 - PREEMPT_ONLY
2 - PREEMPT_AND_ABORT_ACTIVE
3 - PREEMPT_AND_ABORT_ALL
Example
createwaittask(current.centerObjects[1], STATE_IDLE, 1, PREEMPT_NOT);
Deprecated, use treenode.labels["LabelName"].destroy()
Description
This command is deprecated. Use treenode.labels["LableName"].destroy() instead.

Deletes the specified label from the node called "labels" on the specified object.
The specified label can either be the labelname as a string or the label's rank as a number.
If the label does not exist in that node, this command does nothing.
Example
dellabel(current,"MyLabel")
Deprecated, use Table.query()
Description
This command is deprecated. Use Table.query() instead.

Dumps the full result table for the last call to query() into a node. If asTable is 1, it will dump the result as table data. If asTable is 0, it will dump it as bundle data.
Example
Reads an Excel range and dumps it to a treenode
Description
This function is overloaded so that it has two functions depending on which arguments you pass in. The first (where you pass in a string) is deprecated. Use excelrangereadnum() and excelrangereadstr() instead.

The second (where you pass in a treenode) will read a range in Excel and assign all of the data in that range to the target treenode. If the treenode has bundle data, the excel data will be set on the bundle. Otherwise, subnodes will be inserted under the target treenode that will have the Excel data set on them as either string or number data, in the same format as Global Tables.

The origin of the range is specified by the row and col passed in, and the second pair of numbers will specify the size of the range. If 0 is passed in for any one of these, Flexsim will automatically choose the boundary in that direction of the Excel range that has data.

Flags can be passed in to change exactly what is read from Excel. Those flags are EXCEL_DATA_AUTOMATIC, EXCEL_DATA_NUMBER, EXCEL_DATA_STRING, EXCEL_DATE_AS_NUM, EXCEL_USE_COLUMNHEADERS and EXCEL_USE_ROWHEADERS.

EXCEL_DATA_AUTOMATIC will assign string or number data based on what the datatype of the Excel cell is. This is the default behavior.

EXCEL_DATA_NUMBER will force all Excel data to be read as a number.

EXCEL_DATA_STRING will force all Excel data to be read as a string.

EXCEL_DATE_AS_NUM will read any Excel dates as numbers readable by Flexsim as dates. Otherwise, the data will come in as a string.

EXCEL_USE_COLUMNHEADERS will take the first row of data and use it as names for the table columns instead of data.

EXCEL_USE_ROWHEADERS will take the first column of data and use it as names for the table rows instead of data.

Example
treenode myTable = node ("Tools/GlobalTables/GlobalTable1>variables/data", model());

excelrangeread(myTable, 1, 1, 5, 0, EXCEL_DATA_AUTOMATIC | EXCEL_USE_COLUMNHEADERS);

This will read data from the active sheet starting at cell A1. It will read the first five rows, and read as many columns as have data in them. The first row will be used as names for the columns of the Global Table we're writing to. Therefore, if the Excel sheet has 10 columns with data in them, a total of 40 nodes will be inserted under the data variable of the Global Table. Each of those nodes will have the datatype of their corresponding Excel cell.
Reads data under a treenode and writes it to the active Excel sheet
Description
This function is overloaded so that it has two functions depending on which arguments you pass in. The first(where you pass in a string) is deprecated. Use excelrangewritenum() and excelrangewritestr() instead.

The second (where you pass in a treenode) will write all the of the data under a treenode to the active Excel sheet. If the treenode has bundle data, this will read the bundle and write it to the sheet, otherwise it will look for child nodes with data on them, like a Global Table. The row and col passed in here specify where on the Excel sheet to begin writing the data. All of the data on the source node will always be written. Flags can be passed in to change the use of headers. Those flags are EXCEL_USE_COLUMNHEADERS and EXCEL_USE_ROWHEADERS.

EXCEL_USE_COLUMNHEADERS will write any existing column headers as a separate row in the Excel table.

EXCEL_USE_ROWHEADERS will write any existing row headers as a separate column in the Excel table.
Example
treenode myTable = node ("Tools/GlobalTables/GlobalTable1>variables/data", model());

excelrangewrite(myTable, 1, 1, EXCEL_USE_ROWHEADERS | EXCEL_USE_COLUMNHEADERS);

This will take all of the data in GlobalTable1 and write it to the active Excel sheet, starting at cell A1. Before it writes any of the actual data, there will be a row of column headers and column of row headers.
Description
This command is deprecated. Use the Group class instead.

Create a new family (a list of nodes used for organizing relational information).
Example
familycreate(item,"family1")
Description
This command is deprecated. Use the Group class instead.

Returns a pointer to a member of the specified family.
Example
familymember(item,"family1",2)
Description
This command is deprecated. Use the Group class instead.

Adds a new family member to the specified familycontainer.
Example
familymemberadd(item,"family1",item.subnodes[1])
Description
This command is deprecated. Use the Group class instead.

Removes a family member from the specified familycontainer.
Example
familymemberdel(item,"family1",item.subnodes[2])
Description
This command is deprecated. Use the Group class instead.

Returns the size of the specified family.
Example
familymemberqty(item,"family1")
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class to construct the array using an array literal: Array arr = [1, 2, 3];

Fill a local array with values.
Example
Description
Performs a matching test a defined number of times, and when a match is found, returns a user-definable value associated with that match. Within the match expression and return expression, "count" can be used to determine which iteration your are on in the check. This can be used to search in a list of things for a matching item or criterion. If returnexpression is not included in the call, then findmatch() will return the count associated with the matching expression. If no matches are found, findmatch() will return 0. If reverseorder is 1, then it will go backwards, assigning count to nr first, then nr - 1, etc. down to 1. If returnexpression is left out, then findmatch will return the count associated with the found match.
Example
int portNr = findmatch(current.outObjects.length, current.outObjects[count].subnodes.length < 5);
This example will return the output port number that corresponds to the first object it finds connected to current's output ports that has a content less than 5.

treenode object = findmatch(current.outObjects.length, current.outObjects[count].subnodes.length < 5, current.outObjects[count]);
This example is similar to the previous example except it will return the object itself instead of the associated port number.

int item2Rank = findmatch(current.subnodes.length, current.subnodes[count].type == 2);
This example will return the rank number of the first item found in current's queue that has an item type of 2.

Description
Iteratively evaluates an expression, and then returns the maximum value found, or a user-definable return value associated with that maximum value. Within the value expression, return expression and criterion, "count" can be used to determine which iteration you are on in the check. If the return expression is not defined, the maximum value found will be returned. Additionally, you can specify a criterion to filter out values as invalid. If criterion is defined and nothing meets the criterion, 0 will be returned.
Example
double latestCreation = findmax(current.subnodes.length, getcreationtime(current.subnodes[count]));
This example will return the maximum creation time of all items in current.

int largestQueuePortNr = findmax(current.inObjects.length, current.inObjects[count].subnodes.length;
This example will return the input port number associated with the object with the largest queue of items.

int largestQueuePortNr = findmax(current.inObjects.length, current.inObjects[count].subnodes.length, count, getitemstate(current.inObjects[count].first) == FR_STATE_READY);
This example is the same as the previous example, but additionally in includes a criterion that the first item in the upstream object must also have been released.

Deprecated, use Math.floor()
Description
This command is deprecated. Use Math.floor() instead.

Gets the largest integral value not greater than num.
Example
Deprecated, use Object.stats.input.value
Description
This command is deprecated. Use Object.stats.input.value instead.

Returns the input statistic of the involved object.
Example
double inval = getinput(current.centerObjects[1]);
Deprecated
Description
This command is deprecated. Returns one of the values from the movement record that is passed in as the first parameter to the function. This record is the return value from a call to getmoverecord(). The value passed to this function as the second parameter indicates which value from the movement record the user wishes to retrieve:
0 = The record ID. This is the record\'s row number in the movement table.
1 = The ItemID of the flowitem whose movement is recorded by the record.
2 = The time the flowitem moved.
3 = The object that the flowitem moved from. This is returned as an int and should be converted to a treenode using tonode().
4 = The object that the flowitem moved to. This is returned as an int and should be converted to a treenode using tonode();
5 = The itemtype of the flowitem at the time it moved.
Example
See the example for getnummoverecords().
Deprecated, use Table.query()
Description
This command is deprecated. Use Table.query() instead.

Returns the number of columns in the result table for the last call to query().
Example
Deprecated, use Table.query()
Description
This command is deprecated. Use Table.query() instead.

Returns the total number of rows in the result table for the last call to query()
Example
Deprecated, use Table.query()
Description
This command is deprecated. Use Table.query() instead.

Returns the source table's row number associated with a matched row in the last query() result.

table - If a string, it is the name of the table as defined in the FROM statement. If you used an alias, it should be the table's alias. If a number, it should be the 1-based index of the table in the FROM statement. If there is only one table in the query, this should be 1. For multiple tables, the first table in the FROM is 1, the second is 2, etc.
matchRow - The 1-based row of the result table of the query.

Note that this command will not work if you use aggregator functions such as MIN(), MAX(), AVG(), etc. in the SELECT clause. When aggregators are used, this command just returns the number of rows in the source table.
Example
Deprecated, use Table.query()
Description
This command is deprecated. Use Table.query() instead.

Returns a value in the result table for the last call to query()

row - The 1-based row number of the result table
col - The 1-based column number of the result table, or the name of the result column. If you have defined aliases in the select statement, the column name should be the alias.
Example
Deprecated, use treenode.rank
Description
This command is deprecated. Use treenode.rank instead.

Gets the rank of a child node in its parent's sub-tree.
Example
Deprecated, use Object.stats.state().value
Description
This command is deprecated. Use Object.stats.state().value instead.

Returns the state of an object in numeric form.
Example
getstatenum(current);
Deprecated, use Object.stats.state().valueString
Description
This command is deprecated. Use Object.stats.state().valueString instead.

Returns the state of an object as a text string.
Example
getstatestr(current);
Deprecated, use Object.inObjects[]
Description
This command is deprecated. Use Object.inObjects[] instead.

Reference the upstream object connected to a downstream object's input port.
Example
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Index of occurrence of value in list. The list, of length qty, is searched and the position in the list of the value val is returned by this function.
Example
listinlist(5,3,2,1,2,3,4)

This returns the index number 4 because 3 is the fourth number in the list of 5 numbers.
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Index of highest value. The list, of length qty, is searched and the position in the list of the highest value is returned by this function.
Example
listmax(5,2,1,2,3,4)

This returns a 5 because 4 is the largest value and it is fifth in the list of five numbers.
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Highest value. The list, of length qty, is searched and the value of the highest value is returned by this function.
Example
listmaximum(5,2,1,2,3,4)

This returns a 4 because it is the highest value in the list.
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Average of values. The mean of the values in the list, of length qty, is returned by this function.
Example
listmean(5,2,1,2,3,4)

This returns 2.5.
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Index of lowest value. The list, of length qty, is searched and the position in the list of the lowest value is returned by this function.
Example
listmin(5,2,1,2,3,4)

This returns 2 because 1 is the lowest value and it is second in the list.
Deprecated, use the Array class
Description
This command is deprecated. Use the Array class instead.

Lowest value. The list, of length qty, is searched and the value of the lowest value is returned by this function.
Example
listminimum(5,2,1,2,3,4)

This returns 1 because that is the lowest value in the list.
Deprecated, use Array class
Description
This command is deprecated. Use the Array class instead.

Allocate general purpose local array with the given quantity of local variables.
Type can be: 1 = num, 2 = str, 3 = coupling, 4 = obj. May only be used in flexscript.
Example
localarray(1,4)
Returns a random sample from a lognormal distribution
Description
lognormal() and lognormal2() are similar functions, but with different parameter definitions. lognormal() uses parameter definitions as defined on wikipedia and other sites. lognormal2() uses parameters as defined in the latest versions of Expertfit. Essentially, the parameters can be converted as follows:

lognormal( location, normalmean, normalstdev ) = lognormal2( location, Math.exp( normalmean ), normalstdev )
lognormal2( location, scale, shape ) = lognormal( location, Math.log( scale ), shape ) (Math.exp(x) is e raised to the x power, and Math.log(x) is the natural logarithm of x.)

Please make sure you use the right distribution. Using the wrong distribution could result in bad simulation results.

lognormal( location, normalmean, normalstdev, stream ) is a continuous probability distribution.

Inputs:
location : ( - , )
normalmean such that ( Math.exp( normalmean ) > 0 )
normalstdev such that ( normalstdev > 0 )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( location , )
mean = location + Math.exp( normalmean + normalstdev² 2)
variance = Math.exp( 2*normalmean + normalstdev² ) [ Math.exp( normalstdev² ) − 1 ]

Probability Density Functions:



Possible Applications:
Used to model the time to perform some task, and to model quantities that are the product of a large number of other quantities. It can also be used as a rough model in the absence of data.

Comments:
The probability density for the lognormal distribution takes on shapes similar to gamma( normalstdev, normalmean ) and weibull( normalstdev, normalmean ) densities for normalstdev > 1, but can have a large spike close to x=0 that is often useful.
Example
Returns a random sample from a lognormal distribution
Description
This command is an alternative to the lognormal2 command, used in the absence of data. You can specify the mean and standard deviation, and the command will calculate from those parameters the proper location, scale, and shape parameters for the lognormal2 command, and return a sample from that distribution. Note that the shape of the distribution is pre-defined to be a bell-shaped curve with a reasonably long right tail. Hence this command isn't as flexible as the lognormal2 command. This command, similar to the triangular distribution, should be used in the absence of data, where you know the mean and standard deviation of the distribution, and you assume that the distribution is right-skewed (it has a longer right tail), but you do not have a real data set to fit to a distribution. Refer to lognormal2 for more information. Relating to the diagram describing the lognormal2 distribution, the lognormalmeanstdev command uses a normalstdev/shape value of 0.75 to define its shape. Note that since the shape of the distribution is hard-set, depending on the mean and standard deviation values, this may return a negative value.
Example
double cycletime = lognormalmeanstdev(10, 2);
This example will return a random value that follows a right-skewed lognormal distribution with a mean of 10 and standard deviation of 2.
Deprecated, use the Array class
Description
This command is deprecated. Use Array(qty) instead. Array array = Array(4);

Initializes a local array.
Example
Deprecated, use Table.sort()
Description
This command is deprecated. Use Table.sort() instead.

Sorts the table by each column (ascending for positive columns, descending for negative columns).
Example
Deprecated, use kinematics instead
Description
This command is deprecated. Use kinematics instead.

Causes the object to travel to a given rz and return the simulation time that it will arrive. Similar to the travelto command, but includes a start and end speed definition. Used in the development of the TaskExecuter.
Example
ntravelto(current, 0, 5, 8, 0, 1, 1, 1, 0, 1)
Deprecated, use kinematics instead
Description
This command is deprecated. Use kinematics instead.

Updates the rz of an object after a ntravelto() command was called on it. Used in the OnPreDraw of the TaskExecuter to update it's position.
Example
ntraveltoupdate(current)
Deprecated, use Object.input.open()
Description
This command is deprecated. Use Object.input.open() instead.

This command unblocks the input of the object after it has been previously blocked with the closeinput() command. It is necessary that both the input ports themselves, and the input in general, are open before entry will be allowed. It is advised that modelers never use this command in any field other than the OnMessage field which has been triggered with the senddelayedmessage() command, because commands which open ports often spawn several other activities that shouldn't be performed during transitional events. Compare this command with resumeinput().
Example
if (current.subnodes.length < maxcontent)
openinput(current);
Deprecated, use Object.output.open()
Description
This command is deprecated. Use Object.output.open() instead.

This command unblocks the output of the object after it has been previously blocked with the closeoutput() command. It is necessary that both the output ports themselves, and the output in general, are open before exiting is allowed. It is advised that modelers never use this command in any field other than the OnMessage field which has been triggered with the senddelayedmessage() command, because commands which open ports often spawn several other activities that shouldn't be performed during transitional events. Compare this command with resumeoutput().
Example
if (current.subnodes.length > mincontent)
openoutput(current);
Deprecated, use Object.outObjects[]
Description
This command is deprecated. Use Object.outObjects[] instead.

Reference the downstream object connected to an upstream object's output port.
Example
Deprecated, use Object.attrs[]
Description
This command is deprecated. Use the treenode.attrs's [] operator instead.

Gets a reference to the ranked node in the object's attribute sub-tree at rank.
Example
Deprecated, use Table("GlobalTableName")
Description
This command is deprecated. Use the Table class instead.

Gets a reference to a global table.
Example
Table table = reftable("GlobalTable1")
Deprecated, use Vec3.project()
Description
This command is deprecated. Use Vec3.project() instead.

This command returns the x, y, or z location of an object relative to an object that contains it. The containerobj does not need to be the immediate container, but does need to eventually be a container of the object. Use a coordinate value of 1,2,3 for x,y,z respectively.
Example
double x = relloc(current,model(),1);
double y = relloc(current,model(),2);
double z = relloc(current,model(),3);

Sets x, y and z to the x,y,z positions of the current object relative to the model space.
Deprecated, use Object.input.resume()
Description
This command is deprecated. Use Object.input.resume() instead.

This command opens the input of an object just like openinput() does, but because it keeps track of previous stopinput() commands called on the object, it will only open input after all stops have been resumed. Refer to openinput() documentation for additional information.
Example
resumeinput(current.centerObjects[1]);
Deprecated, use Object.resume()
Description
This command is deprecated. Use Object.resume() instead.

Tells the object that it may resume whatever it was doing before stopobject() was called on it.
The id value is optional and is for matching stop requests with resume requests. Refer to the stopobject()
documentation for more information on this.
Example
resumeobject(current.centerObjects[1]);
Deprecated, use Object.output.resume()
Description
This command is deprecated. Use Object.output.resume() instead.

This command opens the output of an object just like openoutput() does, but because it keeps track of previous stopoutput() commands called on the object, it will only open output after all stops have been resumed. Refer to openoutput() documentation for additional information.
Example
resumeoutput(current.centerObjects[1]);
Deprecated, use user libraries
Description
This command is deprecated. Use user libraries instead.

This saves the node to disk as a service pack file (.fpk).
A save file dialog box will appear, allowing you to define the path and name of the file. A service pack is nothing more than a node with subnodes. The first subnode is assumed to be toggled flexscript and contain string data with code. When the service pack is loaded using File | Install Service Pack, the first subnode of you service pack will execute automatically. The code will usually copy the other subnodes into the MAIN and VIEW trees.
Example
savefpk(so());
Deprecated, use Object.setLocation()
Description
This command is deprecated. Use Object.setLocation() instead.

Sets the x, y, and z location of the object's rotational center, relative to its container.
Example
Deprecated, use treenode.rank
Description
This command. Use treenode.rank instead.

Sets the rank of a child node in its parent's sub-tree.
Example
Description
This command is deprecated. Use Object.stats.state().valueString = stateStr;

For development use. Set the state of an object using the actual name of one of the states. The state names must be as they appear in a state pie chart.
Example
setstate_s(current,"busy")
Deprecated, use the Model class
Description
This command is deprecated. Use Model.statisticalTime instead.

Returns the current simulation time with respect to when stats were last reset, such as since the warmup time has passed in an experiment or since resetstats() was executed.
Example
item.TimeIn = statisticaltime();

This sets the label called "TimeIn" on the object referenced by item to the current simulation clock time.
Deprecated, use Object.input.stop()
Description
This command is deprecated. Use Object.input.stop() instead.

This command closes the input of the object just like closeinput() does, but it also keeps track of consecutive stopinput() commands, and will only open input after all stops have been resumed. Refer to closeinput() documentation for additional information.
Example
stopinput(current.centerObjects[1]);
Deprecated, use Object.stop()
Description
This command is deprecated. Use Object.stop() instead.

Tells the object to stop whatever it is doing, go into the state specified (in the state profile if specified), and waits for resumeobject() to be called. Stopobject commands are accumulated, meaning if stopobject is called twice on the same object, the object will not resume its operations until resumeobject has been called twice as well. Stopping an object depends on the type of object that is being stopped.

For FixedResources, generally events are delayed indefinitely, input and output is stopped, and all operations going into and out of the object are stopped. This means that TaskExecuters trying to load/unload to or from the object will have to wait until the object has been resumed.

For TaskExecuters, events are not delayed, but rather a preempting task sequence with priority of 100,000 is created for the TaskExecuter, with one TE_STOP task in it.

Be aware that, if there are several stop requests for the same object, the state for each stop request is not remembered. If an object is requested to stop by entity A with state 12, and then is later requested to stop by entity B for state 14, it will go into state 14 and forget state 12. Even if entity B resumes the object before entity A, the object will remain in state 14 until all stop requests have resumed.

The last two parameters, id and priority, are optional and have recently been added to fix the problem in the previous paragraph. If you specify these parameters, then it will store a record of the stop request, instead of just incrementing a value for the number of stops requested. The id is like a key for that stop request. The priority allows the object to prioritize its stop requests. For example, if you have a stop request for the scheduled down state, and another for the breakdown state at the same time, technically the object should be in two states at once, but since a FlexSim object can only be in one state at a time, the priority value breaks the tie and goes into the state of the highest priority stop request.

The id value should match an id value that is added to a resumeobject() command later on. This is for matching stop requests with their appropriate resume requests. For example, if you stop an object for scheduled maintenance with and id of 1, once the scheduled maintenance is finished, you will need to resume the object with the same id of 1.
Example
stopobject(current.centerObjects[1], STATE_BLOCKED);
Deprecated, use Object.output.stop()
Description
This command is deprecated. Use Object.output.stop() instead.

This command closes the output of the object just like closeoutput() does, but it also keeps track of consecutive stopoutput() commands, and will only open output after all stops have been resumed. Refer to closeoutput() documentation for additional information.
Example
stopoutput(current.centerObjects[1]);
Deprecated, use string.substr()
Description
This command is deprecated. Use string.substr() instead.

Returns a substring of string defined by index start (base 1) and length.
Example
Deprecated, use string.substr()
Description
This command is deprecated. Use string.substr() instead.

This command will return a portion of a string. The new string is defined with a starting character number and a length. A start value of 0 refers to the first character in the original string.
Example
stringpart("Hello",2,3) returns the sub string "llo".
Deprecated, use string.replace()
Description
This command is deprecated. Use string.replace() instead.

Returns a copy of stringtosearch with all occurrences of searchfor replaced with replacewith.
Example
Deprecated, use the Model class
Description
This command is deprecated. Use Model.time instead.

Returns the current simulation time.
Example
item.TimeIn = time();

This sets the label called "TimeIn" on the object referenced by item to the current simulation clock time.
Deprecated, use treenode.up
Description
This command is deprecated. Use treenode.up to set the node's parent (container).

This command moves movenode into the container node. This is like the moveobject command, except no events (ie. OnSend, OnReceive) are executed.
Example
transfernode(current.labels["inactivequeue"].first, current.labels["activequeue"]);
Deprecated, use Object.getLocation()
Description
This command is deprecated. Use Object.getLocation().

Gets the x location of the rotational center of the object within its container.
Example
Deprecated, use Object.getLocation()
Description
This command is deprecated. Use Object.getLocation() instead.

Gets the y location of the rotational center of the object within its container.
Example
Deprecated, use Object.rotation
Description
This command is deprecated. Use Object.rotation instead.

Gets the y rotation of an object (rotation about the y-axis).
Example
Deprecated, use Object.getLocation()
Description
This command is deprecated. Use Object.getLocation() instead.

Gets the z location of the rotational center of the object within its container.
Example
Deprecated, use Object.rotation
Description
This command is deprecated. Use Object.rotation instead.

Gets the z rotation of an object (rotation about the z-axis).
Example

Development

High-level development commands not typically intended for end users.
Description
For developer use. Set a maintenance switch.

The first parameter designates the operation. The second parameter designates a state to set it to.

Maintenance switches:
0. print this list
1. deadlinks
2. atttrbute bind method (0=names, 1=indices, 2=bootstrap)
3. numberprecision
4. display binding report
5. usercollisions
6. post-onsend
7. loadsavemode
8. disablefscheck
9. disablefspreprocess
10. splinetension
11. streamalizer
12. immediately load extended docs
13. save reps at experiment end
14. suppress object library compile
15. suppress global compile
16. set runtime info
17. get runtime info
18. bind c++ functions
19. autorebind c++ functions onoff
20. get presentation mode
21. refresh main menu
22. is optquest enabled
23. flypaths in seconds units
24. chached ports on/off
25. bind on reset on/off
26. set category name (user command group is 22, other 23, 24+ is available)
27. object sizermode 0. default 1. 3-axis
28. show hidden nodes in tree
29. hide 3d cursor
30. supress simclock redraw
31. use parser two
32. grid draw settings: bitwise field: 0x1-auto expand grid, 0x2-show grid axes, 0x4-show grid origin
1000. DDE
Example
maintenance(0)
Description
For developer use. This gives direct access to the Windows API PostMessage() command, posting a message to a window. Use windowfromnode() or getviewhwnd() to get access to the window handle. Refer to Windows API documentation for more information. Not that you cannot use a message that uses lParam or wParam as an [out] parameter, or one that you pass in as a pointer to a struct. You should be able to pass strings into lParam or wParam, but again thay cannot be [out] parameters. FlexSim does not include all possible WM_ messages in its flexscript macros, so if you want to use one in flexscript, you will need to find the definition in the windows header files and add the definition to your flexscript code.
Example
postwindowmessage(windowfromnode(view), WM_COPY, 0,0);
Description
For developer use. This gives direct access to the Windows API SendMessage() command, sending a message to a window. Use windowfromnode() or getviewhwnd() to get access to the window handle. Refer to Windows API documentation for more information. Not that you cannot use a message that uses lParam or wParam as an [out] parameter, or one that you pass in as a pointer to a struct. You should be able to pass strings into lParam or wParam, but again thay cannot be [out] parameters. FlexSim does not include all possible WM_ messages in its flexscript macros, so if you want to use one in flexscript, you will need to find the definition in the windows header files and add the definition to your flexscript code.
Example
sendwindowmessage(windowfromnode(view), WM_COPY, 0,0);
Description
For developer use. This command queries the joystick or controller state or sets functionality for a joystick or controller.

stickno defines an id for the joystick or gamepad you want to query. This is a number between 0 and 32. Usually you will only have one joystick connected to your computer, so in this case you should use the value 1 as stickno. If you are using a gamepad, you might need to use stickno 2. For Xbox controllers, stickno will be a value between 0 and 3. For VR controllers, stickno will be either 0 or 1. For Oculus touch controllers, stickno 0 is the left hand and stickno 1 is the right hand. Use stickno -1 to get the status, position, or rotation of a connected VR headset.

command defines the operation that the command should perform. This should be one of the macros below:

STICK_JOY_STATUS - Queries the connectivity of the joystick. If the joystick is connected properly, then this command will return 0. If the return value is non-zero, then there is some error with the joystick's connectivity, and you can view the system console to see what the error is. The following errors apply:
    MMSYSERR_NODRIVER - The joystick driver is not present.
    MMSYSERR_INVALPARAM - Invalid joystick ID or hwnd is NULL.
    JOYERR_NOCANDO - Cannot capture joystick input because a required service (such as a Windows timer) is unavailable.
    JOYERR_UNPLUGGED - The specified joystick is not connected to the system.
    JOYERR_PARMS - Invalid joystick ID or hwnd is NULL.

STICK_JOY_XPOS - Current X-coordinate of the joystick. This is a number between 0 and 65535. 0 means the joystick is pushed all the way to the left, 65535 means it is pushed all the way to the right, and 32768 is exactly in the center. If you are using a gamepad, then this is the x position of the left side joystick.

STICK_JOY_YPOS - Current Y-coordinate of the joystick. Again this is a number between 0 and 65535. 0 is up, 65535 is down. If you are using a gamepad, this is the position of the gamepad's left joystick.

STICK_JOY_ZPOS - Current Z-coordinate of the joystick. If you are using a joystick, this will usually be the current setting of the joystick's throttle. Again it is a value between 0 and 65535. If you are using a gamepad, this represents the y position of the right side joystick.

STICK_JOY_BUTTONS - Current state of the 32 joystick buttons. This is bitwise integer with each bit representing the state of a given button. For a joystick, the main trigger button is usually represented by the 0x00000001 bit, other buttons on the stick are 0x00000002 and 0x00000004, and buttons on the base of the joystick are then higher order bits. You will need to test these out on your own as each joystick is a little different.

STICK_JOY_SET_CAPTURE - This command sets the joystick capture to a FlexSim window that you specify. This command requires the win and p parameters to be passed in. By executing this command, joystick messages will be sent to the OnStick attribute of the view. For example, if you have an ortho view that you would like to listen to joystick events, you would call this command, passing the ortho view's HWND handle (use windowfromnode()), and a polling period. The period specifies a time interval in milliseconds to repeatedly call the OnStick event. If p is 0, then the OnStick event will only be called when the joystick's state changes. If p is greater than 0, then the OnStick event will simply be called at the end of each sample period interval. Example: stick(1,5, windowfromnode(sv()), 200); This will cause the OnStick event to be called every 200 milliseconds. In order for this to work, you need to add an OnStick attribute to the view (you may also need to rebind the view's attributes after adding it: right-click->Edit|Rebind Object Attributes).

STICK_JOY_RELEASE_CAPTURE - This command releases the joystick capture for the window that was previously captured with the 5 command. You need to pass in the win parameter as with command 5.

STICK_JOY_RPOS - Current position of the rudder or fourth joystick axis of the joystick. For a joystick, this is usually the rotation of the joystick if your joystick can rotate around its z axis. Again it is a number between 0 and 65535. If you are using a gamepad, it is the x position of the right side joystick.

STICK_JOY_UPOS - Current fifth axis position of the joystick.

STICK_JOY_VPOS - Current sixth axis position of the joystick.

STICK_JOY_POV - Current position of the point-of-view control of the joystick. It is a number between 0 and 35900 and represents the number of degrees times 100. For a gamepad, this represents the directional pad on the left of the gamepad. Up is 0, right is 9000, down is 18000, left is 27000. If the directional pad is not pressed, the value will be 65535. If you are using a joystick, there may be a directional thumb controller on the stick itself that you can press up, down, right, or left, and this will get the setting of that controller.

STICK_JOY_CURRENT_BUTTON - Current button number that is pressed.

STICK_JOY_FLAGS - Flags indicating the valid information returned about the joystick.

STICK_XBOX_STATUS - Queries the connectivity of the Xbox controller. If the controller is connected properly, this returns 0.

STICK_XBOX_BUTTONS - Bitmask of the device digital buttons. A set bit indicates that the corresponding button is pressed.

STICK_XBOX_LEFT_THUMB_X - Left thumbstick x-axis value. Each of the thumbstick axis members is a signed value between -32768 and 32767 describing the position of the thumbstick. A value of 0 is centered. Negative values signify down or to the left. Positive values signify up or to the right.

STICK_XBOX_LEFT_THUMB_Y - Left thumbstick y-axis value. The value is between -32768 and 32767.

STICK_XBOX_RIGHT_THUMB_X - Right thumbstick x-axis value. The value is between -32768 and 32767.

STICK_XBOX_RIGHT_THUMB_Y - Right thumbstick y-axis value. The value is between -32768 and 32767.

STICK_XBOX_LEFT_TRIGGER - The current value of the left trigger analog control. The value is between 0 and 255.

STICK_XBOX_RIGHT_TRIGGER - The current value of the right trigger analog control. The value is between 0 and 255.

STICK_VR_STATUS - Returns 1 if an Oculus Rift controller is active. Returns 2 if an HTC Vive controller is active. Returns 0 if the controller is inactive. Returns nullvar if the controller is not attached.

STICK_VR_THUMB_X - Thumbstick or trackpad x-axis value between -1 and 1.

STICK_VR_THUMB_Y - Thumbstick or trackpad y-axis value between -1 and 1.

STICK_VR_INDEX_TRIGGER - Index trigger value between 0 and 1.

STICK_VR_GRIP_TRIGGER - Grip trigger value between 0 and 1. On HTC Vive, grip button is pressed.

STICK_VR_BUTTON_1 - The first button is pressed. A or X on Oculus Rift. Unused on HTC Vive.

STICK_VR_BUTTON_2 - The second button is pressed. B or Y on Oculus Rift. Unused on HTC Vive.

STICK_VR_BUTTON_3 - The third button is pressed. Enter or Home on Oculus Rift. Menu on HTC Vive.

STICK_VR_BUTTON_4 - The fourth button is pressed. Thumbstick on Oculus Rift. Trackpad on HTC Vive.

STICK_VR_TOUCH_BUTTON_1 - The first button is touched. Unused on HTC Vive.

STICK_VR_TOUCH_BUTTON_2 - The second button is touched. Unused on HTC Vive.

STICK_VR_TOUCH_BUTTON_3 - The third button is touched. Unused on Oculus Rift.

STICK_VR_TOUCH_BUTTON_4 - The fourth button is touched.

STICK_VR_TOUCH_THUMB_REST - The thumb rest sensor is touched on Oculus Rift. Unused on HTC Vive.

STICK_VR_TOUCH_INDEX_TRIGGER - The index trigger sensor is touched.

STICK_VR_TOUCH_POINTING - The hand gesture is pointing on Oculus Rift. Unused on HTC Vive.

STICK_VR_TOUCH_THUMB_UP - The hand gesture is thumbs-up on Oculus Rift. Unused on HTC Vive.

STICK_VR_HAND_POSITION - The controller position in VR space.

STICK_VR_HAND_ROTATION - The controller rotation in VR rotation coordinates.

STICK_VR_HAND_WORLD_POSITION - The controller position in FlexSim world space.

STICK_VR_HAND_WORLD_ROTATION - The controller rotation in FlexSim rotation coordinates.

STICK_VR_HAND_OFFSET_POSITION - The controller's position in FlexSim world space, but with an offset applied based on the controller's rotation. Pass an array as the offset vector in the p parameter. You can use this option to get a point relative to the controller, such as a finger position or where the controller is pointing.

STICK_VR_TARGET_FLOOR_POSITION - The target position on the floor that the controller is pointing towards. Pass a value in the p parameter for the maximum distance away from the controller.

STICK_VR_SET_VIBRATION - Causes the controller to vibrate. On Oculus Rift, pass an array for the p parameter where the first element is a value between 0 and 1 for the frequency and the second element is a value between 0 and 1 for the amplitude. On HTC Vive, pass a duration in microseconds for the p parameter.

STICK_VR_SUBMIT_VIBRATION - Causes the controller to subtly vibrate. On original Oculus Touch controllers, pass an array of amplitudes (0 - 255) for the p parameter to be queued up and executed. Unused on HTC Vive or Oculus Rift S controllers.
Example
stick(1, STICK_JOY_YPOS); This gets the y position of the joystick id 1

Drawing

Commands associated with drawing graphics in the planar, orthographic, or perspective views. Draw commands are designed for use in OnDraw events such as the "Custom Draw Code" field found in an object's Properties window.
Draws a 3D column
Description
A very versatile command that can draw anything with multiple sides and a height such as a square, a pentagon, a pyramid, and even a cylinder (if the total number of sides is large).

Draws a column with its origin (center of base) positioned at x, y, z. The column is then defined by the number of sides, a base radius, a top radius, and a height. The column can be rotated in degrees about each axis with rx, ry, rz. The color is defined by the red, green, blue color components ranging from 0 to 255.

An optional opacity parameter will change the column from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be repeated textureXrepeat and textureYrepeat times on each face of the column.

The location, size and rotation of the column are by default relative to the object it is drawn on. The parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawcolumn(0,0,0, 5 ,4,2, 6 ,0,0,0, 175,175,175, .6, 3, 5,1);
Draws a 3D cube
Description
Draws a cube with its origin (bottom left corner) positioned at x, y, z. Its length, width, and height is defined by sx, sy, and sz respectively. It can be rotated in degrees about the x, y, and z axis by rx, ry, and rz. The color is defined by the red, green, blue color components ranging from 0 to 255.

An optional opacity parameter will change the cube from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be repeated textureXrepeat and textureYrepeat times on each face of the cube.

The location, size and rotation of the cube are by default relative to the object it is drawn on. The optional parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawcube(0,0,0, 5,3,2, 0,0,0, 175,175,175, .6, 3, 1,1);
Draws a 3D clyinder
Description
This command draws a hollow cylinder with its origin (center of base) positioned at x, y, z. The cylinder's dimensions are defined by a base radius, a top radius and a height. Use the drawdisk() command to cap off the ends of the cylinder. The cylinder can be rotated in degrees about the x, y, and z axis by rx, ry, and rz. The color is defined by the red, green, blue color components ranging from 0 to 255.

An optional opacity parameter will change the cylinder from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be used as texturing around the outside circumference of the cylinder.

The location, size and rotation of the cylinder are by default relative to the object it is drawn on. The optional parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawcylinder(0,0,0, 1,1, 5, 0,0,0, 175,175,175, .6,3);
Draw a 3D disk
Description
Draws a flat planar disk with its origin (center of radius) positioned at x, y, z. The disk's dimensions are defined by an inner radius, an outer radius, a start angle, and a sweep angle. A sweep angle of 360 makes a complete circle. An innerradius greater than 0 will create a disk with a hole in the middle of it. The disk can be rotated in degrees about the x, y, and z axis by rx, ry, and rz. The color is defined by the red, green, blue color components ranging from 0 to 255.

An optional opacity parameter will change the disk from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be used as texturing across the face of the disk.

The location, size and rotation of the disk are by default relative to the object it is drawn on. The optional parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawdisk(0,0,0, .5,2, 90,270, 0,0,0, 175,175,175, 1,3);
Description
This command can only be used in a 3D view. It draws a texture-mapped text string. This uses the same functionality that draws the names and stats below objects. If scaled correctly, it draws a very crisp, readable text. Use this in conjunction with setdrawnamefunction() to customize the data that is shown in the box below objects. Unlike drawtext(), this command's parameter set is much more stripped down, so you should use gl commands (i.e. fglTranslate(), fglScale(), fglColor(), etc.) to set up the location, size, and render settings before drawing the text.
Example
Add the following code to an object's Custom Draw Code trigger:

if(!param(2)) {
	setdrawnamefunction(80, 15, c, param(1), 1);
} else {
	fglTranslate(-40, -15, 0);
	drawflattext("Hello World");
}
	
This will draw the text Hello World in the display box below the object
Draws a planar quadrilateral
Description
This command draws a planar quadrilateral with vertices defined by x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, and z4. The color is defined by the red, green, blue color components ranging from 0 to 1. The resultant shape and lighting is dependent on the order or sequence in which the vertices are defined. If vertices are all in one plane, consider using drawrectangle() command.
Example
drawquad(view, 0, 0, 1, 0, 0, 0, 2, 2, 2, 4, 5, 6, 1, 0, 0);

This example draws a quadrilateral with vertices defined by the following four points: (0,0,0), (1,0,0), (2,2,2), and (4,5,6). The quadrilateral will be red in color.
Draw a 3D rectangle
Description
Draws a flat planar rectangle with a user-defined location, length, width, rotation, and color. The drawquad() command must be used to draw a rectangle that is not parallel with the x, y or z plane.

An optional opacity parameter will change the rectangle from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be repeated textureXrepeat and textureYrepeat times across the face of the rectangular plane as texturing.

The location, size and rotation of the rectangle are by default relative to the object it is drawn on. The optional parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawrectangle(0,0,0, 2,3, 0,0,0, 175,175,175, .6, 1, 2,3);
Draw a 3D sphere
Description
Draws a hollow sphere with its origin (center of sphere) positioned at x, y, z. The sphere's dimensions are defined by a single radius. The color is defined by the red, green, blue color components ranging from 0 to 255.

An optional opacity parameter will change the sphere from clear (0) to opaque (1). If a valid textureindex number is entered, then the associated image will be wrapped over the surface of the sphere as a texture.

The location, size and rotation of the sphere are by default relative to the object it is drawn on. The optional parameters shown in brackets [ ] must ALL be used or ALL not used. The textureindex is a numeric value that can be learned using the gettextureindex() command or through the Tools | Media Files menu.
Example
drawsphere(0,0,0,5,175,175,175,1,3);
Draws text
Description
This command draws text at a location defined by x, y, and z. The width parameter is not used. The text width and height is determined by the height parameter. The rotation is defined by rx, ry, and rz. The color is defined by the red, green, blue color components ranging from 0 to 1. You can define the flags parameter as follows: 0x1 = bold, 0x2 = italic, 0x4 = underline. The flags parameter only applies to non-3d views The opacity if used should be a number ranging between 0 (full transparency) to 1 (opaque). Call drawfont() command to change font type before calling drawtext() if desired. This command can be used in a planar, 3D, graph or panel view.
Example
drawtext(view, "Hello", 0,0,0, 0,.3,.1, 90,0,0, 1,0,0, .8);

This example draws "Hello" at location (0,0,0) with size 0.3, thickness 0.1, rotation (90,0,0), an rgb color (1,0,0), and opacity of 0.8.
Enables an OpenGL draw setting
Description
Enables an OpenGL draw setting. Note that for optimization purposes, FlexSim's drawing engine does not automatically restore the enabled/disabled state of a given setting, so it is up to you, if you use this command, to restore the setting to its default after you have executed your drawing functionality. Failing to restore a setting to its default will result in weird rendering of other objects in the model.

Common OpenGL draw settings:
GL_LIGHTING
    Turns lighting on and off.
    Turn it on if polygons do not change color when they turn away from the viewer.
    Default: enabled.
GL_CULL_FACE
    Turns back-face culling on and off
    Turn it off if you want both sides (front and back) of all polygons drawn.
    Default: disabled.
GL_TEXTURE_2D
    Turns texturing on and off.
    Turn it off if a texture is being displayed and you don't want it there.
    Default: enabled.

You can refer to standard OpenGL documentation on glEnable() for more information if needed.
Example
fglEnable(GL_LIGHTING);
Sets the normal vector for shading subsequent vertices in OpenGL
Description
Sets the normal vector for shading subsequent vertices in OpenGL drawing. Polygons will be flat shaded unless normals are applied to them. A normal is a vector that is perpendicular to the polygon and points in the direction the polygon is facing. Remember polygons with vertices defined in a counter-clockwise winding points forward per the "right-hand rule". Polygon shading is based on the angle between the normals and the light source. Normals are applied to each vertex in the same way colors are, but is usually just defined at the start of each polygon definition. When a polygon's normals point directly at the light source, they are brightly shaded; and are darker shaded when the angles are skewed. You can refer to standard OpenGL documentation for more information if needed.
Example
fglNormal(1,0,0);
Gets the specified information from a mesh
Description
Gets the specified information from the mesh associated with meshnode. Index is the index of the requested vertex (base 0). Type is specified as one of the following for the mesh (index and param ignored):
MESH_PER_VERTEX_ATTRIBS
MESH_PER_MESH_ATTRIBS
MESH_FLAGS
MESH_NR_VERTS
MESH_GET_INDEX - Returns the vertex index for the given index (only valid with MESH_INDEXED flag)

The following are vertex specific types:
MESH_POSITION
MESH_TEX_COORD2
MESH_NORMAL
MESH_DIFFUSE
MESH_DIFFUSE4
MESH_AMBIENT_AND_DIFFUSE
MESH_AMBIENT_AND_DIFFUSE4

If specifying a vertex, the following are valid for param:
MESH_COLOR_RED
MESH_COLOR_GREEN
MESH_COLOR_BLUE
MESH_COLOR_ALPHA
MESH_POS_X
MESH_POS_Y
MESH_POS_Z
MESH_TEX_S
MESH_TEX_T
Example
double xposition = meshinfo(Model.find("mesh"), MESH_POSITION, 6, MESH_POS_X)
Description
This command gives direct access to the functionality that displays information in boxes below objects in the model. FlexSim's 3D display mechanism works by performing multiple drawing passes over the objects in the model. First, it gathers and caches data for what needs to be drawn. Then it goes through and draws the object shapes and calls the objects' custom draw functionality. Finally it draws any overlays such as connectors, information boxes, etc. The setdrawnamefunction() command, if called as part of an object's custom draw functionality, i.e. its OnDraw event or its Custom Draw Code trigger, will cause a callback to be fired when the drawing sequence gets to the information box step for that object. To do this, call the command and specify the size that you want the box to be drawn, and pass as the nodefunction parameter a reference to a node holding the code you want to fire to draw the box information, as well as up to 3 parameters that will be passed as param(1), param(2), and param(3) into that nodefunction. Then implement the nodefunction code to draw any information you want, using the drawflattext() command, or any other OpenGL drawing commands. Note that when the nodefunction is call, the OpenGL model view matrix will be set so that the (0,0,0) point is at the top-center of the display box, and one length unit represents one pixel on the screen.
Example
Add the following code to an object's Custom Draw Code trigger:

if(!param(2)) {
	setdrawnamefunction(80, 15, c, param(1), 1);
} else {
	fglTranslate(-40, -15, 0);
	drawflattext("Hello World");
}
	
This will draw the text Hello World in the display box below the object

Events

Commands for creating, searching and manipulating events.
Description
The eventtype legend allows you to associate a string with a given value for a given parameter in that eventtype. Passing a negative number for 'parameter' allows you to add a preceeding string to explain the parameter. If the 'parameter' is negative and the 'value' is -1, then it assumes the number is a pointer to a node and will display the node's path as a string.
Example
addtoeventtypelegend(index,-1,-1,"resource: "); // for p1, display the text "resource: " and display the path for the object
addtoeventtypelegend(index,-2,0,"covermode: "); // for p2, display the text "covermode: "
addtoeventtypelegend(index,2,1,"YellowToGreen"); // for p2, a value of 1 should display "YellowToGreen" instead of the number 1
addtoeventtypelegend(index,2,2,"RedToGreen"); // for p2, a value of 2 should display "RedToGreen" instead of the number 2
addtoeventtypelegend(index,3,0,""); // for p3, this makes zeroes blank
addtoeventtypelegend(index,4,0,""); // for p4, this makes zeroes blank
Description
For developer use. This command creates an event that will occur sometime in the future in the model's run. The event will be created for the object specified by object. It will occur time seconds from the time that this command is called. If an event needs to occur that the same simulation time that it was created at, time should be 0. When the event occurs, the OnTimerEvent event function of the class of object will be called. This function will be passed code, data, and involved. These values can be accessed in OnTimerEvent as eventcode, eventdata, and i. Generally, eventcode is used to determine what type of event is being created or executed. Eventdata is used as a description of the event for the user's benefit. It is generally not important to the execution of OnTimerEvent. Any objects that are involved in the event, such as a flowitem that is entering or exiting, are passed as involved and are referenced in OnTimerEvent as i. There are predefined values for code that the user should use listed below:

1 - EVENT_OPENINPUTS
2 - EVENT_OPENOUTPUTS
3 - EVENT_PROCESSFINISH
4 - EVENT_CREATEPART
5 - EVENT_DESTROYPRODUCT
6 - EVENT_CONVEYEND
7 - EVENT_BEGINLOADTIME
8 - EVENT_BEGINUNLOADTIME
9 - EVENT_ENDLOADTIME
10 - EVENT_ENDUNLOADTIME
11 - EVENT_ENDDELAYTIME
12 - EVENT_BEGINDOWNTIME
13 - EVENT_ENDDOWNTIME
14 - EVENT_ENDWAITTIME
15 - EVENT_MEETBATCHQTY
16 - EVENT_ENDTRAVELTIME
17 - EVENT_ENDSETUP

If a user wishes to create their own types of events, they should use values for code that are greater than 100. See also eventcode and eventdata.
Example
if (current.subnodes.length >= current.mincontent)
{
createevent(current,5,EVENT_OPENOUTPUTS,"openoutputs",involved);
}

This creates an event that will occur in 5 simulation seconds that will open the output ports of the object specified as current, for the flowitem specified by involved, if the content of current is less than the label called mincontent of the object referenced by current.
Destroys events associated with object
Description
Destroys events associated with the given object. The first parameter, object, is the only required parameter. Other parameters are optional and provide a filter for choosing which events to destroy, as follows:

time: If greater than or equal to the time that that the command is called, this parameter will filter events by their time. If the event's time is not equal to the time passed in, then the event will not be destroyed. Pass -1 if you don't want this as a filter.

code: If greater than 0, this parameter filters events by their event code. If the event's code is not equal to the code passed in, the event will not be destroyed.

data: If not NULL, this parameter filters events by the data string associated with the event. If the event's data string is not equal to the string passed in, the event will not be destroyed.

involved: If not NULL, this parameter filters events by their involved node or object. If the event's involved node is not equal to the node passed in, the event will not be destroyed.
Example
destroyeventsofobject(model().subnodes[2])
Description
For developer use. Returns a string value describing something related to the Event Log.

Operations:
ELI_GET_OBJECTPATH 1 - returns the path of the object at index n1 from the objectpaths array.
ELI_GET_INVOLVEDPATH 2 - returns the path of the object at index n1 from the involvedpaths array.
ELI_GET_OTHERPATH 3 - returns the path of the object at index n1 from the otherpaths array.
ELI_EVENTTYPE_NAME 4 - returns the name of the eventtype at index n1 from the eventtypes array.
ELI_LOGGEDEVENTTYPE_NAME 5 - returns the name of the logged eventtype at index n1 from the loggedeventtypes array.

Other operations relating to the Event Log that return number values can be accessed using the applicationcommand() function:
"seteventlogging" - enables or disables logging for eventtype n1.
"geteventlogging" - returns whether logging is enabled for eventtype n1.
"getobjectpathslistsize" - returns the size of the objectpaths array.
"getinvolvedpathslistsize" - returns the size of the involvedpaths array.
"getotherpathslistsize" - returns the size of the otherpaths array.
"geteventtypeslistsize" - returns the size of the eventtypes array.
"getloggedeventtypeslistsize" - returns the size of the loggedeventtypes array.
"geteventtypecode" - returns the index of the eventtype by name passed as n1.
Example
string objectpath = eventloginfo(ELI_GET_OBJECTPATH,1);
Description
For developer use. This command returns information for use within the OnListen and OnPreListen event functions.
The information returned is information that was passed to the event you are listening to.
Info 1 will return the engine event code. Engine event codes have macros such as SM_MESSAGE and SM_DRAW.
Info 2 and 3 return pointers to associated treenodes.

To set up listening, you add a "listeners" attribute to the object you want to listen to (Object A). The listeners attribute should have subnodes that are couplings to the object(s) that you want to listen from (Object B). Before an event fires on Object A, Object B's OnPreListen event function will fire. After an event first on Object A, Object B's OnListen event function will fire. You can also filter events by additing a subnode with number data below Object B's coupling node. The number data should be a bitwise sum of the bitshifted event codes you want to listen for. If the coupling has no subnode, the object will default to listening to every event.
Example

treenode current = c;
treenode involved = i;
int code = listenerinfo(1);
treenode associated = tonode(listenerinfo(2));
treenode coupling = tonode(listenerinfo(3));

print("OnListen");
print("current: ", current);
print("involved: ", involved);
print("code: ", code);
print("associated: ", associated);
print("coupling: ", coupling);

FixedResources

Commands associated with FixedResource objects. Most of these commands are used when developing custom behavior for the BasicConveyor or BasicFR object.
Gets the object reference stored in the FixedResource involved variable for the item
Description
This returns the object reference stored in the FixedResource involved variable for the item.
The FixedResource class allows sub-classes to store 1 involved variable on each flowitem. What these variables mean is dependent on the type of class.
For example, a Processor uses the involved variable to store a reference to the dispatcher called for a flowitem if the Processor is set to use operators for the process or setup time.
If you are using the explicit FixedResource class as an object in your model, you can use this command, along with the setitemvar, getitemvar, and setiteminvolved commands, to store variables on the items the object receives.
Example
getiteminvolved(current.first)
Description
Tells the fixedresource to evaluate its pull requirement for the passed item that is in the object through the input port portnr. If the pull evaluation is true, this command pulls the item immediately. This command returns 1 if the item was successfully pulled and 0 if not. If the item cannot be pulled for any of various reasons (such as closed ports or the item not being released), then this command returns 0. The bypassflags parameter is a bitwise combination of macros that start with BYPASS_ to specify certain criteria to ignore in determining item availability. You can specify BYPASS_ALL to immediately pull the item regardless of availability.
Example
pullitem(current, item, 1); // See also Pull Best Item picklist option
Tells the FixedResource to open inputs and receive a flowitem
Description
Tells the FixedResource station to open its inputs and receive a flowitem.
The port parameter is optional, and should only be used if you know exactly which port you want to receive from. If the port parameter is specified, this object will try to receive any item from the upstream object if its corresponding output port is open, ignoring any items' previous send-to return values (similarly to how pull logic works). This function should be executed only once to receive an item, and it should only executed again once you have received (or have confirmed reception of) that item.
See also releaseitem() command. This function should only be used from within a BasicFR's or BasicConveyor's code fields, as other objects implement receiveitem() on their own.
Example
receiveitem(current)
Description
This should only be executed from triggers of a BasicFR object, and usually will only be executed from the resume object field. This command looks up references to taskexecuters that have been saved using the savestoppedtransportin command, and notifies those taskexecuters that they can resume their unload operation. The saverank parameter refers to a rank in the tree of a specific saved reference. If the saverank parameter is not specified, all saved references will be resumed. If this parameter is specified, only the taskexecuter associated with the specific rank will be allowed to resume. Saved references are stored as sub-nodes in the BasicFR's nroftransportsin variable. References to specific saved taskexecuters can be referenced by: nroftransportsinnode.subnodes[saverank].value
Example
resumetransportsin(current);
Description
This should only be executed from triggers of a BasicFR object, and usually will only be executed from the resume object field. This command looks up references to taskexecuters that have been saved using the savestoppedtransportout command, and notifies those taskexecuters that they can resume their load operation.The saverank parameter refers to a rank in the tree of a specific saved reference. If the saverank parameter is not specified, all saved references will be resumed. If this parameter is specified, only the taskexecuter associated with the specific rank will be allowed to resume. Saved references are stored as sub-nodes in the BasicFR's nroftransportsout variable. References to specific saved taskexecuters can be referenced by: nroftransportsoutnode.subnodes[saverank].value
Example
resumetransportsout(current);
Description
This sets the value of a FixedResource variable for the item. The var parameter should be either 1, 2, or 3, and the value parameter should be whatever value you want to set it to. The FixedResource class allows sub-classes to keep up to 3 number variables on each flowitem. What these variables mean is dependent on the type of class.

For example, a Processor uses variable 1 to store the time the item started its processing time, and variable 2 to store the item's processing time. If you are using the explicit FixedResource class as an object in your model, you can use this command, along with the getitemvar, getiteminvolved, and setiteminvolved commands, to store variables on the items the object receives.
Example
setitemvar(current.first, 3, time())
Notifies the FixedResource object that item will now be moved into it
Description
This command notifies a downstream FixedResource object that the specified item will now be moved into it from an upstream object. This should only be used if the upstream object's Use Transport field is checked, but you are moving the item explicitly, instead of using an FRLOAD task. This allows the downstream FixedResource to manage data on how many items are slated to enter the object, but haven't arrived yet. Execute this command just before you move the item out with the moveobject command. For more information, refer to the FixedResource documentation. If this command returns 0, then the object has been stopped using the stopobject command, and you must wait until it has been resumed before moving the item into it.
Example
transportincomplete(current.outObjects[port], item, opipno(current, port));

This example should be executed from the Request Transport From field before a moveobject command if you decide that you don't want to use a transport, but rather want to immediately move the flowitem
Notifies the FixedResource object that item will now be moved out of it
Description
This command notifies the FixedResource object that the specified item will now be moved out of it. This should only be used if the object's Use Transport field is checked, but you are moving the item explicitly, instead of using an FRLOAD task. This allows the FixedResource to manage data on how many items are still in the object but are ready to leave. Execute this command just before you move the item out with the moveobject command. For more information, refer to the FixedResource documentation. If this command returns 0, then the object has been stopped using the stopobject command, and you must wait until it has been resumed before moving the item into it.
Example
transportoutcomplete(current, item, port);

This example should be executed from the Request Transport From field before a moveobject command if you decide that you don't want to use a transport, but rather want to immediately move the flowitem

Kinematics and Splines

Commands associated with kinematics and spline math.
Description
For developer use. Calculate spline mapping and set the current spline parameters using the spline object spline. This command will set the values to be returned by subsequent calls to the splinex(), spliney(), splinez(), splinerx(), splinery(), splinerz(), splinelength(), splineposobject() commands. It will not set the precalculated values for the spline object given in spline, as in fastspline().The parameter perc is the position along the spline of interest. This command does not lock precalculated values as when the fastsplineall() or fastsplineupdate() commands are used. A spline can be defined as any chain of objects that are connected from output ports to input ports. Pass the first object in the output port to input port chain as parameter 1.
Example
spline(splinestartobject,0.6)

Language

Flexscript or C++ keywords and constructs.

Media

Commands associated with presentation and media such as images, sounds, 3D shapes, video and flypaths.

Miscellaneous

Miscellaneous commands that have not been categorized.
Copies thenode into the specified container
Description
Copy thenode into the node specified as container. This command is different from createinstance() in that it does not attempt to establish any links between thenode and any class. If an instantiation is required, use createinstance() instead.

If samename is 1, the copy will have the same name as thenode.

If samename is 0, the newly created node's name will be thenode's name with a random number added to the end.

If inobject is 1, the copy will be created in the object data portion of the container. If the container does not have object data, the command does nothing.

If cached is 1, a pre-cached version of the node will be copied. This is generally faster.

If replace is 1, the copy will overwrite container, instead of being placed inside it.

If those parameters are not specified, they default to 0.
Example
createcopy(Model.find("Tools/FlowItemBin/7/1"), current)
Description
Returns information about the model's unit settings.
FlexSim's typical units are: time - 1 second, length - 1 meter, volume - 1 liter, mass - 1 kilogram. Also may return a name or abbreviation of the current model's units
querytype can be one of the following values:
TIME_MULTIPLE returns the number of seconds represented by each time unit in the current model
LENGTH_MULTIPLE returns the number of meters represented by each length unit in the current model
FLUID_MULTIPLE returns the number of liters represented by each fluid unit in the current model
FLUID_TYPE returns 0 if the fluid units represent volume, or returns 1 if the fluid units represent mass
DATE_TIME_NODE returns a reference to the date/time node in the model units tree
START_TIME returns the start time in seconds (since Jan 1, 1601)
START_TIME_NODE returns a reference to the start time node in the model units tree
CURRENT_TIME returns the current time in seconds (since Jan 1, 1601)
CURRENT_TIME_NODE returns a reference to the current time node in the model units tree
STOP_TIME returns the stop time in seconds (since Jan 1, 1601)
STOP_TIME_NODE returns a reference to the start time node in the model units tree
START_YEAR returns the year associated with the start time as a number
START_MONTH returns the month associated with the start time as a number betweeen 1 (Jan) and 12 (Dec)
START_DAY returns the day associated with the start time as a number, where 1 indicates the first day of the month
START_DAYOFWEEK returns the day associated with the start time as a number, where 0 indicates Sunday
START_HOUR returns the hour associated with the start time as a number between 0 and 23
START_MINUTE returns the minute associated with the start time as a number between 0 and 59
START_SECOND returns the second associated with the start time as a number between 0 and 59
START_MILLISECOND returns the millisecond associated with the start time as a number between 0 and 999
CURRENT_YEAR returns the number of years since the model start time
CURRENT_DAY returns the number of days since the model start time
CURRENT_HOUR returns the number of hours since the model start time
CURRENT_MINUTE returns the number of minutes since the model start time
CURRENT_SECOND returns the number of seconds since the model start time
CURRENT_MILLISECOND returns the number of milliseconds since the model start time
CURRENT_YEAR_OF_TIME returns the year associated with the current time as a number
CURRENT_MONTH_OF_YEAR returns the month associated with the current time as a number between 1 (Jan) and 12 (Dec)
CURRENT_DAY_OF_MONTH returns the day associated with the current time as a number, where 1 indicates the first day of the month
CURRENT_DAY_OF_WEEK returns the day associated with the current time as a number, where 0 indicates Sunday
CURRENT_HOUR_OF_DAY returns the hour associated with the current time as a number between 0 and 23
CURRENT_MINUTE_OF_HOUR returns the minute associated with the current time as a number between 0 and 59
CURRENT_SECOND_OF_MINUTE returns the second associated with the current time as a number between 0 and 59
CURRENT_MILLISECOND_OF_SECOND returns the millisecond associated with the current time as a number between 0 and 999
TIME_NAME returns the name of the model time units
TIME_PLURAL_NAME returns the plural name of the model time units
TIME_ABBREVIATION returns the abbreviation of the model time units
LENGTH_NAME returns the name of the model length units
LENGTH_PLURAL_NAME returns the plural name of the model length units
LENGTH_ABBREVIATION returns the abbreviation of the name of the model length units
FLUID_NAME returns the name of the model fluid units
FLUID_PLURAL_NAME returns the plural name of the model fluid units
FLUID_ABBREVIATION returns the abbreviation of the name of the model fluid units
START_TIME_STR returns the start time as a string, formatted by the date and time formats
CURRENT_TIME_STR returns the current time as a string, formmatted by the date and time formats
STOP_TIME_STR returns the stop time as a string, formatted by the date and time formats
TIME_FORMAT returns the time format used to format date/time strings
DATE_FORMAT returns the date format used to format date/time strings
Example
getmodelunit(LENGTH_MULTIPLE)
Moves object to the specified location
Description
This command moves the object to the specified location through the specified port. The specified port does not have to actually exist, this value is used by the receiving location to be able to reference the port the object came in through. When an object moves into location, the OnReceive event function of location is executed. This includes the OnEntry trigger function. Explicitly calling this on a flowitem with events queued up for it may cause problems. Only use when you know that no events are pending for the object being moved.
Example
moveobject(current.first,current.centerObjects[1]);

This moves the first object that is inside the object referenced by current to the object connected to current's first center port.
Deprecated, use treenode.getPath()
Description
This command is deprecated. Use treenode.getPath() instead.

Sets the name of a node to the path of the object relative to the model.
Example
nametomodelpath(curlistnode, current);

Model Execution

Commands for stopping, starting, and managing simulation runs.
Sets the simulation speed
Description
This command sets the speed at which the simulation will run. It is the same as clicking and dragging the slider bar on the Run Control window, but more precise. The speed that the model will attempt to run at is defined as the number of simulation time units per real second. The model may not actually achieve this speed if the computer cpu can not keep up. precisionMode defines the precision to use. If 0, the precision mode will remain what it was before the call. If you pass RUN_SPEED_LOW_PRECISION, it will set to a low precision run speed. If you pass RUN_SPEED_HIGH_PRECISION, it will run in high precision mode. This is used for emulation purposes. The precision mode will be reset to low precision on every reset, so you need to have something in your model set it back on reset or when the model starts to enable high precision mode.
Example
runspeed(10);
go();

This sets the speed to 10 simulation seconds per real second, then runs the model.

NetworkNodes

Commands associated with NetworkNode objects and network paths.
Gets information regarding the current state of a taskexecuter on a node network
Description
Returns information regarding the current state of a taskexecuter on a node network. Valid queries are as follows:

NETWORK_INFO_DEST_NET_NODE_RANK - returns the destination column/rank of the network node that the TE would travel to were he to be given a travel task to destobj. Usually this will simply be the network node attached to destobj, but if multiple network nodes are attached to destobj, the command will find the closest one.
NETWORK_INFO_ORIGIN_NET_NODE_RANK - returns the origin column/rank of the network node that the TE would start from were he to be given a travel task to destobj. Usually this will simply be the current network node where the TE is located, but if that network node has virtual exits, the command will find the virtual exit that renders the shortest travel distance.
NETWORK_INFO_DISTANCE - returns the shortest travel distance to the destination object through the network.
NETWORK_INFO_CUR_DIST_ALONG_EDGE - Only valid when the TE is actively doing a travel task. This returns the current distance that the TE has traveled along its current network edge. For this query, destobj should be NULL.
NETWORK_INFO_CUR_TRAVEL_ORIGIN_RANK - Only valid when the TE is actively doing a travel task. This returns the rank of the origin node at which the TE starts its current travel operation. For this query, destobj should be NULL.
NETWORK_INFO_CUR_TRAVEL_DEST_RANK - Only valid when the TE is actively doing a travel task. This returns the rank of the destination node to which the TE is traveling for its current travel operation. For this query, destobj should be NULL.
Example
int destrank = gettenetworkinfo(current, NULL, NETWORK_INFO_CUR_TRAVEL_DEST_RANK);
Gets information on a traffic controller
Description
This command gives you access to various information on a traffic control, as well as lets you direct the traffic control to perform logic. Logic/data that is performed/returned is based on the info parameter, as follows:

trafficcontrolinfo(tc, TCI_NR_ACTIVE_TRAVELERS) - returns the total number of active travelers in the traffic control.

trafficcontrolinfo(tc, TCI_ACTIVE_TRAVELER, num travelnr) - returns a reference to the nth active traveler in the traffic control.

trafficcontrolinfo(tc, TCI_ACTIVE_TRAVELER_COUPLING, num travelernr) - returns a reference to a coupling node, stored in the Traffic Control's variables tree, that is associated with the nth active traveler. This coupling can be used to stored custom user information regarding that active traveler. To do this, add sub-nodes to the coupling node with nodeinsertinto(), add data, etc. Note that once the active traveler leaves the traffic control area, the coupling, and its sub-nodes, will automatically be destroyed.

trafficcontrolinfo(tc, TCI_ACTIVE_TRAVELER_RANK_FROM_TRAVELER, obj traveler) - This command takes a reference to a traveler object and returns which index in the traffic control's active travelers is associated with that traveler. If zero is returned then the object is not an active traveler in the traffic control.

trafficcontrolinfo(tc, TCI_NR_MEMBERS) - Returns the total number of network nodes that are members of the traffic control area

trafficcontrolinfo(tc, TCI_MEMBER, num membernr) - Returns a reference the nth network node member of the traffic control

trafficcontrolinfo(tc, TCI_MEMBER_COUPLING, num membernr) - Returns a reference to a coupling node, stored in the traffic control's variables, that is associated with the nth network node member of the traffic control. Like TCI_ACTIVE_TRAVELER_COUPLING, this node may be used to store data associated with that network node.

trafficcontrolinfo(tc, TCI_MEMBER_RANK_FROM_NETWORK_NODE, obj netnode) - Takes a network node reference and returns the member index of that network node in the traffic control. If zero is returned then the network node is not a member of the traffic control.

trafficcontrolinfo(tc, TCI_NR_ENTRY_REQUESTS) - Returns the number of entry requests currently in queue waiting to enter the traffic control area.

trafficcontrolinfo(tc, TCI_ENTRY_REQUEST_TRAVELER, num requestnr) - Returns a reference to the traveler associated with the nth entry request, who is waiting get into the traffic control area.

trafficcontrolinfo(tc, TCI_ENTRY_REQUEST_NETWORK_NODE, num requestnr) - Returns a reference to the network node where the traveler is waiting, associated with the nth entry request

trafficcontrolinfo(tc, TCI_ENTRY_REQUEST_NODE, num requestnr) - Returns a reference to a node associated with the nth entry request. Like TCI_ACTIVE_TRAVELER_COUPLING, you may add sub-nodes to store data associated with the request. Do not, however, change the data on this node, as this is used by the traffic control logic.
trafficcontrolinfo(tc, TCI_ALLOW_ENTRY, num requestnr) - Calling this command will instruct the traffic control to allow the traveler associated with the nth entry request to enter the traffic control area.

trafficcontrolinfo(tc, TCI_SET_ENTRY_REQUEST_RANK, num requestnr, num settorank) - Calling this command will cause the traffic control to rerank its nth entry request to the specified rank.

Also, a note regarding using the traffic control triggers to override the traffic control's default logic. The traffic control's OnEntryRequest trigger, which fires when a traveler first requests entry into the traffic control area, can take 3 different return values:

TC_ON_ENTRY_REQUEST_DEFAULT - If this value is returned from the trigger, the traffic control will perform its normal filtering logic.

TC_ON_ENTRY_REQUEST_ALLOW - If this value is returned, the traffic control will ignore its default logic and simply allow the traveler into the area. Note that if this is used, the traffic control will ignore its maximum capacity variable, so depending on the logic you define, the number of travelers in the area may exceed the maximum capacity variable you specify on the traffic control.

TC_ON_ENTRY_REQUEST_QUEUE - If this value is returned, the traffic control will ignore its default logic and add the request to its request queue, disallowing the traveler from entering the area at that time.
The traffic control's OnExit trigger may take one of two return values:

0 - If this value is returned, the traffic control will perform its default logic, allow other travelers to enter, etc.

1 - If this value is returned, the traffic control will do nothing. In this case the user should use the trigger to explicitly tell the traffic control which traveler(s) to receive using TCI_ALLOW_ENTRY.

If you plan on implementing your own custom logic for allowing travelers into the area, then it is recommended that you use the traffic control's default "Mutual Exclusion" mode.
Example
treenode netnode = trafficcontrolinfo(tc, TCI_MEMBER, 2);

Object Data

Commands for accessing and assigning data on objects.
Deprecated, use Object.stats.output.value
Description
This command is deprecated. Use Object.stats.output.value instead.

Returns the output statistic of the involved object.
Example
double outval = getoutput(current.centerObjects[1]);
Sets the value of an animation variable on an object
Description
Sets the value of an animation variable on an object. Animation variables are attributes of an animation that may need to dynamically change for different runs of the animation, such as surrogates, time between keyframes, or position/rotation/size values of a given keyframe. For example, you may use surrogates in building your animation. You do this by choosing a default visual from the flowitem bin to use as you create the animation. Then when the simulation runs, you substitute real flowitems in for those surrogates when you run the simulation. You do this substitution by setting the value of an animation variable that you've associated with that surrogate to the actual reference to the flowitem. Another example is you may use an animation variable to dynamically define the z position of a keyframe at run-time.
Example
setanimationvar(current, "Animation1", "Item1", current.first);
Sets the shape frame of an object
Description
Sets the frame attribute of the object to the framenumber. The frame defines which 3D image to display. This is a nice way of changing the 3D shape of an object on the fly. There are two ways to define frames on an object. First, you can do it through the naming of various 3D files. For example, if the object was assigned Operator.3ds as its default shape, and there are additional files in the same directory as Operator.3ds named OperatorFRAME1.3ds, OperatorFRAME2.3ds and OperatorFRAME3.3ds, then the frame attribute could be set to 0,1,2, or 3 which would change the displayed shape to each of the 3ds files respectively. Secondly, you can add sub-nodes to an obejct's shape attribute, each with a path to the 3D file associated with that frame. Subsequently, frame 1 would be associated with the shape attribute's first sub-node, etc. This is the method used within FlexSim's environment to define shape frames. If toframe is a string, then the latter method is assumed, and it will find the shape attribute sub-node with the corresponding name. One use of this command would be to change the 3d shape in the OnDown trigger to show a "broken" shape.
Example
if(getframe(current) == 3)) setframe(current, 5);

Object Functions

Commands associated with calling functions on objects and nodes; including nodefunctions, events, messages and their related access variables.
Description
This command will create a listening mechanism where whenever the defined event is called on object, relayNode will also be executed. flags is a bitwise mask of one of the following values:
EVENT_PRE_LISTEN: The listening function will be called before theNode is called.
EVENT_LISTEN: (default) The listening function will be called after theNode is called.
EVENT_PERSIST: The listener will persist across model resets.
EVENT_PASS_THROUGH_PARAMS: When theNode is called, the parameters passed into the event will also be "passed through" into the listening node. In this case, par1, par2, etc. are not used.
EVENT_LISTEN_ONCE: The listening mechanism will automatically be removed after the first event firing.
When the listening node is called, if it returns EVENT_STOP_LISTENING, the listener mechanism will be removed and the listening node will no longer be called. The return value is a reference to a node associated with the listening. If this node is later deleted, the listening mechanism will stop.

To get a list of the events that can be listened to on an object, call function_s(object, "enumerateEvents", destNode). The object will dump a table onto destNode that contains information on all the events that can be listened to on the object.

Some events may have "requirements". This means that in order to properly bind to the event, you have to pass additional parameters in. The enumeration table will give information on the number of requirements and their names. When requirements are needed they displace and shift par1, par2, etc. For example, if an event has 2 requirements, these requirements will take up par1 and par2 of the eventlisten() call, and par3 will then become param(1) in relayNode's code.
Example
eventlisten(current, "OnEntry", current.entrylistener);
Description
For developer use. This command will create a listening mechanism where whenever nodefunction() is called on theNode, relayNode will also be executed. flags is a bitwise mask of one of the following values:
NFL_PRE_LISTEN: The listening function will be called before theNode is called.
NFL_LISTEN: (default) The listening function will be called after theNode is called.
NFL_PERSIST: The listener will persist across model resets.
NFL_PASS_THROUGH_PARAMS: When theNode is called, the parameters passed into that function will also be "passed through" into the listening node. In this case, par1, par2, etc. are not used.
When the listening node is called, if it returns NFL_STOP_LISTENING, the listener mechanism will be removed and the listening node will no longer be called. The return value is a reference to a node associated with the listening. If this node is later deleted, the listening mechanism will stop.
Example
nodefunctionlisten(getvarnode(current, "entrytrigger"), current.entrylistener);
Send a delayed message to an object, firing its OnMessage trigger after the delay time has transpired
Description
Causes a message to be sent to the toobject from the fromobject after the delaytime has transpired. When the toobject receives the message, its OnMessage trigger will fire.
In the code of the OnMessage trigger, you may refer to the fromobject as msgsendingobject, and the three numeric par values passed in as msgparam(1), msgparam(2) and msgparam(3).
This is a very usefuly command for creating your own time events during a model run.
Example
senddelayedmessage(current.outObjects[1], 25, current, 0, 0, 0);

Sends a message from the current object to the object connecte to output port 1 of the current object 25 time units after this command is executed. Zeros are passed for all three of the user-defined parameters.
Send a message to an object, firing its OnMessage trigger
Description
Causes a message to be sent immediately to the toobject from the fromobject as in a direct function call. When the toobject receives the message, its OnMessage trigger will fire.
In the code of the OnMessage trigger, you may refer to the fromobject as msgsendingobject, and the three par values passed in as msgparam(1), msgparam(2) and msgparam(3). These message parameters are Variants, meaning they can be numbers, strings, treenode references or arrays.
Example
sendmessage(current.centerObjects[1], current, item, 10);

This sends a message to the object connected to current's first center port. A reference to item is passed as par1 and the number 10 as par2.

Object Ports

Commands associated with the port connections of an objects.
Open all input ports of object
Description
Open all input ports of object. If an input port has a pass-through state as a result (both connected ports are open), both objects will be sent a notification message that the port has become "ready". The object with the input port will receive an OnInOpen message and the object with an output port will receive an OnOutOpen message. During traversal of the ports, any given port will only allow pass-through evaluation once. Modelers should only use this command when working with fluid objects because the internal behavior of discrete objects controls the opening and closing of their ports, and therefore this command may be overridden. For discrete objects the modeler is referred to openinput() and resumeinput().
Example
openallip(current)
Open all output ports of object
Description
Open all output ports of object. If an output port has a pass-through state as a result (both connected ports are open), both objects will be sent a notification message that the port has become "ready". The object with the input port will receive an OnInOpen message and the object with an output port will receive an OnOutOpen message. During traversal of the ports, any given port will only allow pass-through evaluation once. Modelers should only use this command when working with fluid objects because the internal behavior of discrete objects controls the opening and closing of their ports, and therefore this command may be overridden. For discrete objects the modeler is referred to openoutput() and resumeoutput().
Example
openallop(current)

Output

Commands for giving feedback to the modeler for debugging or reporting purposes.
Opens the FlexSim file interface
Description
Opens the FlexSim file interface. Returns 1 if successful. Returns 0 if an error is encountered.

Parameter 2 can be "w" for writing, "r" for reading, or "a" for appending. Default is "w". Use the commands fpt(), fpr(), fpf(), etc. to write to the opened text file. Use filereadline() to read a line from the file. Using this command, you can only have one file open at a time. To write to multiple files simultaneously, use the C standard fopen/fclose commands or C++ standard fstream classes in C++ or through a dll.

If in write mode, the contents of the file will be cleared, and the file pointer will be set to the top of the file. The file must be closed to save any data written to the file.
Example
fileopen("C:/myfile.txt", "w");

People


Process Flow

Example
treenode token = createtoken(node("Operator1", model()), "Start", 0);
setlabel(token, "type", 1);
releasetoken(token);
Description
Creates a token in a Process Flow Sub Flow which starts that sub flow. Once the created token hits a Finish activity it will return the value evaluted from the Return Value field.
instanceObject: If the instanceObject is specified then current may be used by the activities in the Sub Flow to get access to the instanceObject. This can be useful when multiple objects execute the same Sub Flow but require object specific data.
If no Start activity is specified, the activities in the Sub Flow will be searched and the first Start activity will be used.
If multiple Finish activities are contained in the Sub Flow, the return value will be evaluated from whichever Finish activity the token enters. However, if internal sub flows cause other tokens to enter a Finish activity, it may be necessary to specify the Finish activity name so the correct return value is evaluated.

NOTE: It is important that the activities used in the Sub Flow do not create delays or wait. If the token is interrupted by a delay or wait, the token will not arrive at the Finish activity when the executesubflow function finishes.
Example
return executesubflow("SubFlow1", processor);
Example
treenode childToken = getchildtoken(token, 3);
int numChildren = getchildtoken(token);
Example
treenode parentToken = getparenttoken(token);
Example
treenode token = gettokenbyid(54);
treenode token = gettokenbyid(23, "ProcessFlow2");
Description
Gets all the tokens "inside" an activity or shared asset. For activities, this is the current set of tokens in the activity. For resources, it is the set of tokens who have acquired the resource. For zones, it is the set of tokens that have entered the zone. For a list, it is the set of tokens who have been pushed to the list. Returns an Array containing the result.

instanceObject - The object associated with the desired process flow instance. For general process flow's this is the same as the process flow itself. For task executer and fixed resource process flows, it is the 3D object, i.e. task executer or fixed resource, associated with the process flow instance. If executed from within process flow activity logic, this will usually just be "current". If you pass NULL here, it will get tokens for all instances.

activityOrAsset - The target activity or shared asset. If NULL, the command will return all active tokens in the entire process flow instance.

flags - Defines optional flags. If GET_TOKENS_REQUESTS is passed for a shared asset, it will return the set of tokens requesting the shared asset (i.e. tokens waiting to enter a zone, tokens back ordering on a list, etc.).
Example
Array tokensInActivity = gettokens(current, getactivity(processFlow, "Wait For Exit")); Array resourceOwners = gettokens(current, getactivity(processFlow, "Resource1"));
Example
releasetoken(token);
releasetoken(token, 3);
releasetoken(token, "To Start");
releasetoken(token, getactivity(processFlow, "Start"));

Rack Object

Commands for accessing and assigning data on Rack objects.
Draws a box in the rack's given bay and level
Description
Draws a box in the rack's given bay and level. x,y, and z are numbers between 0 and 1 representing the percentage into the cell to start drawing the box. sx, sy, and sz are numbers between 0 and 1 representing the size percentage of the box. Red, green and blue specify the color of the box.

To ensure that the boxes are drawn correctly, you should disabled OpenGL textures with fglDisable(GL_TEXTURE_2D) before calling this command in a draw trigger.
Example
fglDisable(GL_TEXTURE_2D);
for (int bay = 1; bay <= 5; bay++) {
    for (int level = 1; level <= 3; level++) {
        rackdrawfilledcell(current, bay, level, 0,0,0, 0.5,1,1, 255,0,0);
    }
}
fglEnable(GL_TEXTURE_2D);

This example draws red boxes in bays 1-5, levels 1-3, that fill half of each cell's volume (sx = 0.5, sy =1, sz = 1).
Draw the rack's virtual content
Description
Draws the rack's "virtual" content. This command will usually only be used if you are recycling flowitems using the rackrecycleitem command. When this command is executed, the rack goes through its content table, and draws a box for every flowitem in the rack, at its appropriate bay and level. If virtualonly is 1, then it will only draw a box in spots where a slot is filled, but no flowitem is present (the flowitem has been recycled). Bayfillperc and levelfillperc are values between 0 and 1, and specify the percent of the cell to fill with the drawn box. Item depth is the size each item takes up in the rack. For a floor storage rack, this the z size of the items. For a regular rack, it is the y size of the items.
Example
rackdrawvirtualcontent(current, 0.9,0.9,3, 256,0, 0, 1);
Recycles the flowitem into the flowitem bin
Description
Recycles the flowitem into the flowitem bin specified.
This command is for advanced users, and should not be used unless you are prepared to do some debugging.
Bin rank should be the rank of the flowitem in the flowitem bin (textured colored box = 5, etc.).
When this command is called, the flowitem is recycled, but the spot where it is located is designated as taken,
and further flowitems will be put into the rack as if this spot is already filled.
This can significantly increase the speed of a model.
Subsequent commands to rackgetbaycontent(), rackgetcellcontent(), etc. will return values as if the item were still there.
However, rackgetitembybaylevel() will return NULL for an item that has been recycled and has yet to be restored.
Make sure the item is not released or waiting for a transport before calling this command.
Note that max content of the rack will not work properly if this command is used. Also you will need to eventually restore the item using the
rackrestoreitem() command.
Example
rackrecycleitem(current, item, 5);

This recycles the flowitem into the 5th ranked flowitem of the flowitem bin (usually the textured colored box).

Statistics

Commands for creating, manipulating, and accessing statistical data; including probability distributions.
Adds a field to the bundle
Description
Adds a field to the bundle with the given field name. Returns the field rank (base 0) of the added field. All fields for a bundle must be added before any entries are added. The type is a bitwise flag that must be one of the following values:

BUNDLE_FIELD_TYPE_DOUBLE : stores a 64-bit double
BUNDLE_FIELD_TYPE_FLOAT : stores a 32-bit float
BUNDLE_FIELD_TYPE_INT : stores a 32-bit integer
BUNDLE_FIELD_TYPE_STR : stores a string. If used, you should also define the maximum string size, which will be the space allocated for each string entry. If maxstrsize is unspecified, the default will be 32 bytes. The field will be able to store strings at least as long as the specified length, and any longer strings will be truncated.
BUNDLE_FIELD_TYPE_VARCHAR: stores a string. This field type does not impose a limit on string length. This field type is recommended if you need variable string lengths, or if strings are frequently repeated.
BUNDLE_FIELD_TYPE_NODEREF : stores a reference to a node
BUNDLE_FIELD_TYPE_BINARY : stores a 1 or 0 as a single bit. Bits are allocated in blocks of 32, so that one binary field requires 32 bits. However, 32 binary fields can share a single block.

You can optionally bitwise combine any of the above values (except BUNDLE_FIELD_TYPE_BINARY) with BUNDLE_FIELD_INDEX_MAP. All values in this type of field will be indexed for quick lookup (O(log n)) using getbundleindexentries().

You can optionally combine BUNDLE_FIELD_TYPE_INT, BUNDLE_FIELD_TYPE_STR, BUNDLE_FIELD_TYPE_VARCHAR, or BUNDLE_FIELD_TYPE_NODEREF with BUNDLE_FIELD_INDEX_HASH. All values in this type of field will be indexed for quick lookup (O(1)) using getbundleindexentries(). This type of field is only recommended for use with bundles that rarely, if ever, change size while the model is running.

You can optionally combine any of the above values (except BUNDLE_FIELD_TYPE_BINARY) with BUNDLE_FIELD_NULLABLE, to allow those fields to contain null values. If a field is nullable, you can pass a null Variant in to setbundlevalue(), and it is possible to get a null Variant from getbundlevalue().
Example
addbundlefield(x, "Object Name", BUNDLE_FIELD_TYPE_STR | BUNDLE_FIELD_NULLABLE, 64);
Returns one of two possible values, based on the given probability
Description
bernoulli( p, a, b, stream ) is a discrete probability distribution.

Inputs:
p is the probability that a will be returned;  where p∈ ( 0, 100 )
100 −p is the probability that b will be returned.
a∈ ( - , )
b∈ ( - , )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = { a , b }
mean = ( ap + b(100−p) ) 100
variance = (p100)(1 −p100) when a=1 and b=0

Possible Applications:
Used to model a random occurrence that has two possible outcomes such as a pass/fail test. It is possible to generate more than two values by nesting bernoulli commands; however, it is better to use empirical distributions in these cases.

Comments:
The bernoulli(p, 1, 0) and binomial(1, p) distributions are the same.
Example
treenode curoperator = current.centerObjects[bernoulli(90,1,2,1)];

The bernoulli command in this example has a 90 percent probability of returning 1 otherwise it will return 2, using random number stream 1. It is used within a centerObject reference such that 90 percent of the time curoperator references the object connected to center port 1 of the current object, otherwise curoperator references the object connected to center port 2.
Returns a random sample from a beta distribution
Description
beta( a, b, α1, α2, stream ) is a bounded continuous probability distribution.

Inputs:
a is the lower-endpoint parameter ∈ ( - , )
b is the upper-endpoint parameter( b > a )
α1 is the 1st  shape parameter ( 0, )
α2 is the 2nd shape parameter ( 0, )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( a , b )
mean = a + α1(ba) (α1 + α2)
variance = α1α2(ba (α1 + α2)²(α1 + α2 + 1)

Probability Density Functions:



Possible Applications:
The beta distribution is often used to model task durations in the absence of real data because it can be definitively bounded between a minimum and maximum value, and it can take on a number of different probability density shapes depending on the two shape parameters used. For most real world task durations, the density shape will have a longer right tail than a left, so if you know the mean μ and the mode (most likely value) m, you can back calculate suitable shape parameters with the following equations:

α1 ≅ ( μa)(2mab) (mμ)(ba)

α2α1(bμ) (μa)

Comments:
The beta( a, b, 1, 1) and uniform( a, b) distributions are the same.
The density is symmetric about (a + b) 2 when α1 = α2.
The density will have a hump and longer right tail when α2 > α1 > 1.
The mean and mode are equal when α1 = α2 > 1.
Example
double ptime = beta(8, 12, 1.3, 3, 5);

The ptime variable is set equal to a beta distribution having a minimum value of 8, a maximum value of 12, and shape factors of 1.3 and 3 for α1 and α2 respectively. FlexSim's random stream number 5 will be used to generate variates from the distribution. The distribution density will have a nice humped curve with a long right tail.
Returns a random sample from a binomial distribution
Description
binomial( t, p, stream ) is a discrete probability distribution used to represent the number of successes in t independent Bernoulli trials with probability p of sucess on each trial.

Inputs:
t is the number of independent trials { 1, 2, ..., }.
p is the probability of success for any given trial (0, 100)
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = { 0, 1, 2, ..., t }
mean = tp 100
variance = t ( p 100 )( 1 −p 100 )

Possible Applications:
The binomial distribution is useful for modeling the number of defective parts in a batch of size t, or the actual number of people in random size groups, or maybe the number of items ordered from inventory.

Comments:
The binomial(1, p ) and bernoulli( p, 1, 0 ) distributions are the same.
The binomial( t, p ) distribution is symmetric when p = 50 percent.
Example
int fparts = binomial(item.batchsize, 10, 5);

The number of failed parts will be written to the fparts variable based on a 10% probability that any given part will fail within a batch quantity defined by a label on the flowitem named "batchsize". FlexSim's random stream number 5 will be used to generate variates from the distribution.
Returns a random sample from a continuous empirical distribution
Description
A continuous empirical distribution with percentages and values defined in the table specified.

Empirical distributions reference tables created by the user that contain a list of values and probability percentages associated with each value. Probability percentages must be entered in column 1 starting with row 1 of the table, and the associated values are entered in column 2. The table may have as many rows as needed to define as many values as desired. The percents are entered as numbers between 0 and 100, and should add up to a total of 100 percent; otherwise any values defined after a cumulative percentage of 100 is reached will never be returned.

There are three commands in FlexSim that can be used to generate random variates from the empirical distributions defined in tables. The three commands are dempirical(), empirical() and cempirical(). The first one is a discrete distribution and will return the explicit values listed in the table. The next two are bounded continuous distributions, meaning they return a continous number within a range. The values in column 2 for the continuous distributions must be in ascending order because they will interpolate values between two adjacent values in the table.

Let's assume we have a table with 4 rows and 2 columns. In column one are the percentages 10, 20, 30 and 40 adding up to 100 percent. In column two are the values 0.1, 0.2, 0.3 and 0.4. Now let's see the differences between the discrete empirical command and the two continuous empirical commands. The discrete command will only generate random variates that match exactly the values that were entered into column two of the table. The continuous commands will generate random variates that are real numbers uniformly distributed between two adjacent numbers in column two of the table. The difference between the two continuous commands is in how the bounds of the uniform ranges are defined.

The command dempirical("mytable") will return the number 0.1 for ten percent of the samples, the number 0.2 for twenty percent of the samples, the number 0.3 for thirty percent of the samples, and the number 0.4 for forty percent of the samples assuming a very large sample set.

The command empirical("mytable") will return a number uniformly distributed between 0.1 and 0.2 for ten percent of the samples, a number uniformly distributed between 0.2 and 0.3 for twenty percent of the samples, a number uniformly distributed between 0.3 and 0.4 for thirty percent of the samples and a number uniformly distributed between 0.4 and 0.4 for forty percent of the samples. If you want the last forty percent to be between 0.4 and 0.5 instead of 0.4, add a 5th row with column one being a value of 0 and column two being 0.5 or the desired upper bound.

The command cempirical("mytable") will return a number uniformly distributed between 0.0 and 0.1 for ten percent of the samples, a number uniformly distributed between 0.1 and 0.2 for twenty percent of the samples, a number uniformly distributed between 0.2 and 0.3 for thirty percent of the samples and a number uniformly distributed between 0.3 and 0.4 for forty percent of the samples. You can define a lower bound for the first ten percent to be a value different than 0.0 by adding a row to the beginning of the table (row 1) where column one is a value of 0 and column two is 0.05 or the desired lower bound.

Here is a summary in tabular form showing the possible return values ("x") for each of the three distribution functions:



Here is an example of adding a "dummy" first row so that cempirical() starts at 0.05 instead of 0.0 (notice that row 1 has a probability of 0 percent):



Here is an example of adding a "dummy" last row so that empirical() has a range between each value including the last (any number can be entered for the percent of the last row because the percents already add up to 100% with the previous row, so it doesn't matter what it is):



When using ExpertFit to determine an empirical distribution that matches your data, you need to be aware that if your data has been defined as integers, then ExpertFit will fit it for use with dempirical(), and if your data has been defined as real numbers, ExpertFit will fit it for use with empirical(). When your data set is composed of real numbers, ExpertFit will show the same percentage for the last value as for the previous to last value, but you'll notice that the percents add up to 100% with the second to last entry.
Example
cempirical("mytable", 5);

Returns a random variate from a continuous empirical distribution defined in a global table named "mytable" using random number stream 5.

cempirical(current.labels["ptime"] 5);

Returns a random variate from a continuous empirical distribution defined in a node table defined on a label named "ptime" of the current object, and using random number stream 5.
Description
For developer use. This command lets you create, reset or add data to a histogram, x/y chart, or a data series. The first three parameters define the associated node in the tree as well as the operation to do. The last three parameters, x,y and z, define the appropriate data for the operation. The first parameter should be the main node in the tree that holds the graph/histo data. The second parameter should be either 1, 2, or 3, and defines the type of data that the node holds. 1 means graphx data. For this data type the node contains a list of sub-nodes, and each sub-node contains a number that is a unique point in a data series. 2 means graphxy. For this data type, the node again contains a list of sub-nodes but this time the sub-nodes are paired together as x/y pairs. Nodes ranked 1 and 2 hold the x and y values for one data point, nodes 3 and 4 hold x and values for the next data point, etc. A type parameter of 3 means histo data. Here the node holds data associated with a histogram. The action parameter should be either 1, 2, or 3, and defines the action that you want to do. 1 means a create operation. This is only needed for histogram type data, as it needs to set up the node's sub-tree structure. To create a histogram plot, pass the minimum value for the histogram as the x parameter, the maximum value of the histogram as the y value, and the number of divisions, or buckets, as the z parameter. An action parameter value of 2 means you want to reset the data. This will clear the content of the node for graphx or graphxy data, and will reset the histogram values for histogram data. An action parameter value of 3 means you want to add a data point. For graphx and histo data, pass the data point as the x parameter. For graphxy data, pass the as the x and y paramters. In summary: Type: 1-graphx/2-graphxy/3-histo.
Action: 1-create (only needed for histo data)/2-reset/3-add point.
Data: x,y are data points [histo create: x=start, y=end, z=nr of divisions].
Example
dataplot(stats_contentgraph(model.find("Processor2")),2,3,8.6,5,0); This adds a point to Processor2's content graph for time 8.6 and content 5. This example is only for demonstration purposes. You should never need to do this since the Processor automatically maintains its content graph.
Returns a random sample from a discrete empirical distribution
Description
A discrete empirical distribution.

The table referenced must contain a list of values and probability percentages associated with each of the values. Probability percentages must be entered in column 1 starting with row 1 of the table, and their associated values are entered in column 2. The table may have as many rows as needed to define as many values as desired. The percents are entered as numbers between 0 and 100, and should add up to a total of 100 percent; otherwise any values defined after a cumulative percentage of 100 is reached will never be returned.

A detailed description of the three empirical distributions used in FlexSim and their differences is included with the cempirical() command.
Example
int ptype = dempirical("prodtypes", 5);

Assigns a value to the ptype variable using a discrete empirical distribution defined in a global table named "prodtypes" using random number stream 5.

dempirical(current.labels["route"], 5);

Returns a random variate from a discrete empirical distribution defined in a node table defined on the label named "route" of the current object, and using random number stream 5.
Returns random integer between the min and max
Description
duniform( a, b, stream ) is a bounded discrete probability distribution.

Inputs:
a is the lower-endpoint parameter
b is the upper-endpoint parameter
a and b are integer numbers where a < b
ba is the scale parameter
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = { a, a+1, ..., b }
mean = ( a + b ) 2
variance = ( (ba + 1)²− 1 ) 12

Possible Applications:
Used to approximate a quantity that is felt to be randomly varying between a and b, but hardly anything else is known.

Comments:
There is an equal probability that an a, or b, or any discrete (integer) number inbetween will be returned.
Example
duniform(1, 6, 3);

Random number stream 3 will be used to generate a random variate from a discrete uniform distribution having a minimum value of 1 and a maximum value of 6. This simulates the roll of a dice.
Description
A continuous empirical distribution.

The table referenced must contain a list of values and probability percentages associated with each of the values. Probability percentages must be entered in column 1 starting with row 1 of the table, and their associated values are entered in column 2. The table may have as many rows as needed to define as many values as desired. The percents are entered as numbers between 0 and 100, and should add up to a total of 100 percent; otherwise any values defined after a cumulative percentage of 100 is reached will never be returned.

A detailed description of the three empirical distributions used in FlexSim and their differences is included with the cempirical() command.
Example
empirical("mytable", 5);

Returns a random variate from a continuous empirical distribution defined in a global table named "mytable" using random number stream 5.

empirical(current.labels["ptime"], 5);

Returns a random variate from a continuous empirical distribution defined in a table defined on a label named "ptime" on the current object using random number stream 5.
Returns a random sample from an erlang distribution
Description
erlang( γ, β, m, stream ) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( β > 0 )
m is the shape parameter ∈ {1, 2, ... }
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ , )
mean = γ + mβ
variance = mβ²

Possible Applications:
Used to model the time to complete some task such as assembly, customer service and machine repair.

Comments:
When γ = 0, this distribution is known as the m-Erlang(β) distribution.
The exponential( γ, β ) and erlang( γ, β, 1 ) distributions are the same.
For a positive integer m, the gamma( γ, β, m ) and erlang( γ, β, m ) distributions are the same.
Example
double servicetime = erlang(60, 2, 4, 5);

The servicetime variable is set equal to a erlang distribution with a location parameter of 60, a scale parameter of 2, a shape parameter of 4, using random stream number 5. The mean is 100 + (2*4) = 108.
Returns a random sample from an exponential distribution
Description
exponential( γ, β, stream) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( 0, )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ, )
mean = γ + β
variance = β²

Possible Applications:
Often used to model the interarrival times of a continous stream of customers and/or customer orders into a system. It is also a popular distribution for modeling the time between failure of mechanical equipment.

Comments:
Variates less than the mean occur much more frequently than variates greater than the mean.
The exponential distribution is the only continuous distribution with the memoryless property of producing totally independent variates.
If the location parameter (γ) is set to zero, then β becomes the mean, and the distribution's variates will range between zero and infinity.
The exponential( γ, β ) and gamma( γ, β, 1 ) distributions are the same.
Example
exponential(0, 10, 5);

An exponential distribution with a location of 0 and a scale of 10 (mean = 10). FlexSim's random stream number 5 will be used to generate variates from the distribution.
Returns a random sample from a gamma distribution
Description
gamma( γ, β, α, stream ) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( β > 0 )
α is the shape parameter ( α > 0 )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ , )
mean = γ + αβ
variance = αβ²

Probability Density Functions:



Possible Applications:
Used to model the time to complete some task such as assembly, customer service or machine repair.

Comments:
The exponential( γ, β ) and gamma( γ, β, 1 ) distributions are the same.
For a positive integer m, the gamma( γ, β, m ) and erlang( γ, β, m ) distributions are the same.
Shape values less than 1 are rarely used.
Example
double repairtime = gamma(60, 2, 3.4, 5);

The repairtime variable is set equal to a gamma distribution with a location parameter of 60, a scale parameter of 2, a shape parameter of 4, and using random stream number 5. The mean is 100 + (2*3.4) = 106.8.
Description
Calculates and returns a certain statistic of a data set.
stat - Can be one of the following values
STAT_MEAN - calculates the sample mean of the set
STAT_MIN - calculates the minimum value in a defined range of values. p1 is the first element in the range (default is the first element in the set), p2 is the last element in the range (default is the last element in the set), and p3 defines a stride, allowing you to look at every nth value (default 1). If either of p1, p2, or p3 is 0, then it will revert to that value's respective default.
STAT_MAX - calculates the maximum element in a defined range of values. p1, p2 and p3 are the same as for STAT_MIN
STAT_VARIANCE - calculates the unbiased variance of the data set
STAT_STD_DEV - calculates the unbiased standard deviation of the set
STAT_SUM - calculates the sum of the set
STAT_CONF_INTERVAL_HALF_WIDTH - calculates the confidence interval half-width of the set. Pass in p1 to define the desired confidence percentage. FlexSim will return precise values for percentages at 80%, 90%, 95%, 98%, 99%, and 99.8% and for sample sizes at or below 100 degrees of freedom. For percentages not in this set, FlexSim will "clamp" it to the nearest percentage ABOVE the percentage passed in. So if you pass in a 75%, it will return an 80% confidence interval. Since an 80% confidence interval will be a "wider" interval, we clamp up to be "safer" with the wider interval. Confidence intervals above 99.8 will simply return 0 (i.e. not valid). For degrees of freedom above above 100, it will assume 100 degrees of freedom.
nrSamples - defines the number of samples in the set.
Note: parameter 2 as a parentNode is deprecated and you should use the parameter 2 as nrSamples option because it encompasses the other and is more flexible. The following deprecated functionality: getdatastat(STAT_MEAN, myNode, 0, 0, 0, 0) can be represented using the newer option with: getdatastat(STAT_MEAN, myNode.subnodes.length, myNode.subnodes[count].value, 0, 0, 0)
sampler - an expression that gets the nth value in the sample.
Use count for determining which value is to be retrieved. Below are several examples:
For calculating the mean of all values in column 5 of global table GT1:
getdatastat(STAT_MEAN, Table("GT1").numRows, Table("GT1")[count][5])
For calculating the sum of all values in field "Time" of a bundle:
getdatastat(STAT_SUM, Table("MyBundle").numRows, Table("MyBundle")[count]["Time"])
Example
Returns the statistic value for the given object
Description
It is preferred to use Object.stats instead. Gets the specified statistic from the given object.
name - The name of the statistic. Valid names can be enumerated using function_s(object, "enumerateStatistics", targetNode). Documentation for the meaning of the various statistics that an object provides should be found in each object's documentation. The documentation may include spaces in the names of the statistics, for readability. In passing these as the name parameter to getstat(), you should remove all spaces.
flag - Can be one of the following values
STAT_CURRENT - returns the current value of this statistic
STAT_MIN - returns the minimum value of this statistic
STAT_MAX - returns the maximum value of this statistic
STAT_AVERAGE - returns the average value of this statistic
STAT_TIME_AT_VALUE - returns the total simulation time the stat spent at a given value (requires an additional p1/p2/p3 parameter designating the desired value). This is only valid if the stat is tracking its history or profile data, such as in objects' standard "State" statistics. See below for more information on this.

p1, p2, and p3 are for providing "requirements" to resolve the correct statistic. For example, a list has several per-partition statistics. In order to get a partition's statistic, you need to pass the desired partition ID as p1. Requirements depend on the statistic that is being retrieved.

There are also several special stat names that you can use. They are: "State", "Output", "Input", "Content", "Staytime". If you use one of these names, the command will return the corresponding standard statistic of the object. Examples:
getstat(object, "Output", STAT_CURRENT) - returns the current (total) output of the object (same as object.stats.output)
getstat(object, "Content", STAT_AVERAGE) - returns the average content of the object
getstat(object, "State", STAT_CURRENT, 0) - returns the current state of the object (same as object.stats.state().value)
getstat(object, "State", STAT_TIME_AT_VALUE, 0, STATE_IDLE) - returns the total idle time of the object (0 designates the state profile, i.e. the default state profile)
getstat(object, "Staytime", STAT_MAX) - returns the maximum recorded stay time of the object
Note that some stats that do not make sense will not return valid data, such as average state, or average output.

STAT_TIME_AT_VALUE
If you want to get the STAT_TIME_AT_VALUE access, the statistic needs to track either historical or profile data. If it is an object's standard "State" statistic, FlexSim will automatically make it track its profile data, so you don't need to do any extra work for that. For other statistics, however, you will need to explicitly "subscribe" to the statistic to make it track its profile or history data. Historical data records each change of value and the corresponding simulation time of that value change. Profile data records the total time the variable was at each value. Only non-negative integer values are valid for profile data.

To subscribe to a tracked variable, first find where the tracked variable statistic is in the tree. For example if it's the "Content" statistic, you'll likely find it at object>stats/stats_content. Then call the following command on the node: function_s(statNode, "addSubscriber", needsHistory, needsProfile, persist). The needsHistory and needsProfile parameters are booleans telling which data you want to track. The persist is a boolean that tells if you want it to track these statistics indefinitely going forward. The tracked variable tries not to continue tracking extra data if it is not needed. If nobody subscribes to its data "persistently", then it will discontinue recording the data if it doesn't get subscribers for a while (I think after 5 or so model resets with no subscribers).

Recording historical data will allow you to get the STAT_TIME_AT_VALUE access. However, using historical data for getting STAT_TIME_AT_VALUE is slower than if you track profile data. With historical data, it must traverse the entire history to calculate STAT_TIME_AT_VALUE, whereas if you track profile data, it stores the total time at the value directly in the profile data.
Example
Description
Import tree dataset from a Comma Separated Value (CSV) file. datatree should be the node to import the data into. There are 3 possible formats to import. If format is 1, then the data is imported as a table, meaning each sub-node of datatree is a row in the table, and each sub-node of each row is a cell in the table. This is the same as using the importtable() command. If format is 2, then the data is imported as a simple data series. The csv file is assumed to have one column, and each row's value is imported into a sub-node of datatree. If format is 3, then the data is imported as a series of x,y pairs. The csv file is assumed to have 2 columns. Row 1 column 1 of the csv file is imported as sub-node 1 of datatree, row 1 column 2 is imported as sub-node 2 of datatree, row 2 column 1 is imported as sub-node 3 of datatree, and so forth.
Example
importdataset(so(),"C:\\mydataset.csv",1)
Returns a random sample from an inversegaussian distribution
Description
inversegaussian( γ, β, α, stream ) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( β > 0 )
α is the shape parameter ( α > 0 )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ , )
mean = γ + β
variance = β³α

Probability Density Functions:



Possible Applications:
Used to model the time to complete some tasks.

Comments:
The inversegaussian( γ, 1, α ) and wald( γ, α ) distributions are the same.
As γ approaches infinity, the distribution becomes more like the normal (Gaussian) distribution.
The β parameter has elements of a shape parameter since it affects the skewness and kurtosis (width).
Example
double repairtime = inversegaussian(60, 2, 4, 5);

The repairtime variable is set equal to a inversegaussian distribution with a location parameter of 60, a scale parameter of 2, a shape parameter of 4, and using random stream number 5.
Returns a random sample from a log laplace distribution
Description
loglaplace( γ, β, α, stream ) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( β > 0 )
α is the shape parameter ( α > 0 )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ , )
mean = γ + βα² ( α²− 1) for α > 1
variance = β²α² ( 2α² + 1 ) ( α² - 1 )² ( α² - 4 ) for α > 2

Probability Density Functions:



Possible Applications:
Rarely used in defining processing times.

Comments:
This distribution is also known as the double-exponential distribution because its density curve is essentially two exponential curves back-to-back.
Example
loglaplace(0, 2, 8, 5);

A loglaplace distribution with a location parameter of 0, a scale parameter of 2, a shape parameter of 8, and random stream number 5.
Returns a random sample from a log logistic distribution
Description
loglogistic(γ, β, α, stream) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( 0, )
α is the shape parameter ( 0, )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ, )
mean = γ + β(πα)csc(πα) for α > 1
variance = β²(πα){2csc(2πα) − (πα)[csc(πα)]²} for α > 2

Possible Applications:
Used to model the time to perform some task.
Example
loglogistic(0, 1, 2, 5);

A loglogistic distribution with a location (shift) of 0, a scale of 1, a shape factor of 2 and random stream number 5.
Returns a random sample from a lognormal distribution
Description
lognormal() and lognormal2() are similar functions, but with different parameter definitions. lognormal() uses parameter definitions as defined on wikipedia and other sites. lognormal2() uses parameters as defined in the latest versions of Expertfit. Essentially, the parameters can be converted as follows:

lognormal( location, normalmean, normalstdev ) = lognormal2( location, Math.exp( normalmean ), normalstdev )
lognormal2( location, scale, shape ) = lognormal( location, Math.log( scale ), shape ) (Math.exp(x) is e raised to the x power, and Math.log(x) is the natural logarithm of x.)

Please make sure you use the right distribution. Using the wrong distribution could result in bad simulation results.

Example
double cycletime = lognormal2(0, 29.8, 0.31, 5);

Set the cycletime variable to a lognormal2 distribution with location parameter 0, scale parameter 29.8, shape parameter 0.31, and random stream number 5.
Returns a random sample from a normal distribution
Description
normal(μ, σ, stream) is an unbounded continuous probability distribution.

Inputs:
μ is the location parameter ∈ ( - , )
σ is the scale parameter ( 0, )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( - , )
mean = μ
variance = σ²

Probability Density Functions:



Possible Applications:
Used to model various types of error such as machined hole diameters for large quantities of parts. This distribution is not used much in simulation because variance found in real processes do not typically follow a symmetric distribution such as this.

Comments:
The normal distribution is completely symmetric meaning values below the mean have the same probability for occurance as values above the mean. The mode and mean are equal for the normal distribution. When using this distribution, be aware that negative values can be returned, and therefore truncating the distribution at 0 may be necessary as shown in the example below.
Example
double thickness = Math.max(0.001, normal(5, 1.2));

The thickness is set a normal distribution having a mean of 5 and a standard deviation of 1.2 that is truncated for values less than 0.001. No random stream has been declared, so the default stream number 0 will be used to generate variates from the distribution.
Description
Makes number streams antithetic. Using this command, users can switch random streams to generate numbers between 1 and 0; rather than the default of 0 to 1. This is helpful for determining if random numbers are having a big affect on the results of the model. It's also useful when experimenting with massive models and there isn't sufficient time to run the model for multiple iterations as required for good statistical sampling. The user can then choose to do just one regular run and one antithetic run of the model to obtain two diametrically apposed results. These two results can be averaged for an approximation that is somewhat better than if each run of the model used random stream generators without antithetic sampling.
Example
randantithetic(1);
Initializes a random stream
Description
Initializes the random number stream by setting its first value to seedvalue. Although there are an unlimited number of random number streams available to the user, only the first one hundred streams numbered 0 through 99 have been initialized when the FlexSim application is opened. To create a new stream, simply execute the randinit() command for the new stream. For instance, executing randinit(105, 7628912) will create a new stream number 105 if it does not currently exist, and set its initial seed value to 7628912.

If "Repeat Random Streams" has been selected in the Statistics menu, then streams 0 through 99 will be automatically initialized with a default seed value for that stream whenever the model is reset. For streams 100 and above, you must use the randinit() command to set their initial seed values if you wish to repeat their random streams. Any positive integer may be passed in as the seedvalue for a random number stream. If you pass in a seedvalue of 0 for random streams 0 through 99, it is a special case that will initialize them to their default seed values.

seedvalues 2 through 6 are only used if you are using FlexSim's Combined MRG random number generator. To enable this generator, call maintenance(49,1) when your model opens.
Example
Example 1:

randinit(5, 73241);

Initialize FlexSim's random stream number 5 with a sead value of 73241.

Example 2:

randinit(2,0);
for(int i = 100; i <= 199; i++)
{
    randinit(i, realtime(1) * uniform(0, 1, 2));
}

First initialize standard stream number 2 to its default seed value, then execute a loop for 100 iterations to create (if necessary) streams 100 through 199 and set their initial seed value to the product of a random number pulled from stream 2 and the current number of real clock seconds.
Returns a random number between the min and max values
Description
uniform( a, b, stream ) is a bounded continuous probability distribution.

Inputs:
a and b are real numbers with a < b
a is the location parameter defining the minimum variate
b defines the maximum variate
ba is the scale parameter
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = [ a, b ]
mean = ( a + b ) 2
variance = ( ba 12

Possible Applications:
Used to approximate a value that is felt to be randomly varying between a and b but hardly anything else is known.

Comments:
There is an equal probability that an a, or b, or any real number inbetween will be returned.
The uniform(0, 1) distribution is essential in generating random variates from all the other distributions and will return a continuous set of random values between and inclusive of 0 and 1.
Example
uniform(12.3, 27.5, 3);

Random number stream 3 will be used to generate a random variate from a uniform distribution having a minimum of 12.3 and a maximum of 27.5.
Returns a random sample from a weibull distribution
Description
weibull( γ, β, α, stream ) is a non-negative continuous probability distribution.

Inputs:
γ is the location parameter ∈ ( - , )
β is the scale parameter ( β > 0 )
α is the shape parameter ( α > 0 )
stream is a reference to one of FlexSim's random number streams {0,1,2,...}

Outputs:
range = ( γ , )
mean = γ + ( βα ) Γ(1 α) where Γ() is the Gamma function.
variance = ( β²α ) { 2Γ(2 α) − 1 α [ Γ(1 α) ] ² }

Probability Density Functions:



Possible Applications:
The weibull distribution is commonly used when there is not sufficient data available because it can take on so many different shapes depending on the shape factor. It is a very common distribution used for representing the time between equipment failures, as well as the time to complete a manual task.

Comments:
The weibull( γ, β, 1 ) and exponential( γ, β ) distributions are the same.
The weibull( γ, β, 2 ) and rayleigh( γ, β ) distributions are the same.
The weibull distribution is skewed to the left if α > 3.6
Example
weibull(0, 2, 3, 5);

A weibull distribution with a location parameter of 0, a scale parameter of 2, a shape parameter of 3, and random stream number 5.

Strings

Commands associated with strings, string manipulation and string comparisons.

Tables

Commands for accessing, assigning and managing data in tables.

TaskExecuter Object

Commands associated with TaskExecuter objects and a tasksequence.
Dynamically change a task in tasksequence
Description
This command is deprecated. Use the TaskSequence and TaskSequence.Task class methods and properties instead. This command lets you change a task dynamically. For example, if you want an operator to travel to object B instead of traveling to object A, but a task has already been created for him to travel to object A, you can use this command to change the task.

The first parameter (tasksequence) specifies the tasksequence containing the task. The second parameter (taskrank) specifies the rank of the task in the tasksequence. All other parameters are the same as for the inserttask command.

This command should only be executed if the task is not the currently active task in the task sequence!
Example
changetask(gettasksequence(current, 0), 4, TASKTYPE_TRAVEL, current.centerObjects[5]);

This example changes the fourth task in the current object's active task sequence to a travel task to travel to the object connected to the 5th center port of the current object.
Release all operators connected to taskexecuter that are working on involved
Description
Release all operators connected to the specified dispatcher that are currently working on the involved object. This command should be executed from a trigger when you want to release operator(s) that you have called to a process using the requestoperators command or using a utilize task. The first parameter can be either a dispatcher connected to operator(s) that you want to free, or it can be the operator itself. The second parameter is a key for releasing the appropriate operator(s). If you have called the operator(s) using the requestoperators command, then the second parameter of the freeoperators command should match the third parameter of the requestoperators command. If you have given an operator a utilize task, then the second parameter of the freeoperators command should match the involved1 parameter of the utilize task. You would probably execute this command from a trigger like OnProcessFinish or OnSetupFinish. For more information, refer to the task sequence section of the user manual.
Example
freeoperators(current.centerObjects[1], item);
Gets a reference to the first or second involved object of the task of the tasksequence
Description
This command is deprecated. Use the TaskSequence and TaskSequence.Task classes instead. Returns a reference to either the first or second involved object for the nth ranked task of the specified task sequence.
The ranking is based on the initial ranking of the task, when the task sequence was initially created and tasks were
added. It is not based on the ranking at a given time in the simulation, as tasks may have already been completed
and subsequently destroyed. The third parameter defines which involved object it is (1 or 2)


You can also pass a reference to the TaskExecuter as the first parameter, and the value 0 as the second parameter
to get the involved of the object's currently active task.
Example
treenode loaditem = getinvolved(gettasksequence(current.centerObjects[1], 0), 2, 1);
Gets the task type of the task at rank taskrank of tasksequence
Description
This command is deprecated. Use the TaskSequence and TaskSequence.Task class methods and properties instead. Returns the task type for the nth ranked task of the specified task sequence.
The ranking is based on the initial ranking of the task, when the task sequence was initially created
and tasks were added. It is not based on the ranking at a given time in the simulation, as tasks
may have already been completed and subsequently destroyed.

You can also pass a reference to the TaskExecuter as the first parameter, and the value 0 as the second parameter
to get the task type of the object's currently active task.
Example
if(gettasktype(gettasksequence(current.centerObjects[1], 0), 2) == TASKTYPE_LOAD)...
Gets the tasksequence variable for the task at rank taskrank of tasksequence
Description
This command is deprecated. Use the TaskSequence and TaskSequence.Task class methods and properties instead. Returns a reference to one of the four task variables for the nth ranked task of the specified task sequence.
The ranking is based on the initial ranking of the task, when the task sequence was initially created and tasks were
added. It is not based on the ranking at a given time in the simulation, as tasks may have already been completed
and subsequently destroyed. The third parameter defines which task variable it is (1 - 4)


You can also pass a reference to the TaskExecuter as the first parameter, and the value 0 as the second parameter
to get the task variable of the object's currently active task.
Example
double myvar = gettaskvariable(gettasksequence(current.centerObjects[1], 0), 2, 1);
Description
Request a specified number of operators to come to the station object and work on the involved object until released. The involved object will later need to be passed into the freeoperators() command when releasing the operators. The operator(s) being called must either be the object referenced by dispatcher, or be connected to its output ports.

The tasksequence which is sent to the operator(s) will be given a priority and preempting value. The possible values for preempting are as follows:

    0 = PREEMPT_NOT
    1 = PREEMPT_ONLY
    2 = PREEMPT_AND_ABORT_ACTIVE
    3 = PREEMPT_AND_ABORT_ALL

For each operater that needs to be called, stopobject() will be called on the station, and a tasksequence that looks like the following will be sent to the dispatcher (or operator) object.

    1. put a preempt "bookmark" in the task sequence (TASKTYPE_MILESTONE)
    2. travel to the station (TASKTYPE_TRAVEL)
    3. resume the station (TASKTYPE_STOPREQUESTFINISH)
    4. be utilized at the station (TASKTYPE_UTILIZE)
Example
requestoperators(current.centerObjects[1], current, item, 2, 0, PREEMPT_NOT);

This calls 2 operators connected to the object that is connected to the first center port of the current object to come to the current object, and work on the item.

Tree Access

Commands for referencing nodes or objects through FlexSim's tree structure.

Tree Node Data

Commands for accessing and assigning data to nodes in the tree. Many of these commands can be used on objects as well, because objects are also nodes in the tree.
Gets the object that "owns" the executing node, usually the current object
Description
This command returns the node with object data attached to it that is the start of the sub-tree that thenode is in. In other words, it returns the object node that contains thenode. The result of this command is cached on thenode, so that subsequent calls to ownerobject(thenode) do not search in the tree, but return the cached result. If thenode subsequently changes parent, ownerobject(thenode) will return the cached result.

This command is used in most code fields and trigger fields to set the access variable current. In these fields, c references the node that contains the code, and ownerobject(c) references the object that "owns" that node.

Example
string objname = ownerobject(c).name;

This sets objname to the name of the object that contains the node referenced by c. The c usually refers to the node where the code is being written.

treenode current = ownerobject(c);

This example is present in most code fields in FlexSim, and retrieves access to the "current" object.