(normative)
This annex describes the use of JavaScript with the Script node. "Concepts - Scripting" contains a general overview of scripting in VRML while "Nodes Reference - Script" describes the Script node.
Netscape JavaScript was created by Netscape Communications Corporation (http://home.netscape.com). JavaScript is a programmable API that allows cross-platform scripting of events, objects, and actions. The JavaScript Specification, Version 1.1, can be found at: http://home.netscape.com/eng/javascript/. It is expected that JavaScript, Version 1.2, will be the scripting language of a Script node when JavaScript becomes a standard. The difference for VRML is that objects in numeric expression will have valueOf() called and if that fails, then toString() will be called.
JavaScript is currently undergoing standardization through ECMA.
The Math object is required to be supported by the JavaScript implementation. This includes the constants: E, LN10, LN2, PI, SQRT1_2, SQRT2 and the methods: abs(), acos(), asin(), atan(), atan2(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), sqrt(), tan().
The url field of the Script node may contain a URL that references JavaScript code:
Script { url "http://foo.com/myScript.js" }
The javascript: protocol allows the script to be placed inline as follows:
Script { url "javascript: function foo() { ... }" }
The url field may contain multiple URL's and thus reference a remote file or in-line code:
Script { url [ "http://foo.com/myScript.js", "javascript: function foo() { ... }" ] }
The file extension for JavaScript source code is .js.
The MIME type for JavaScript source code is defined as follows:
application/x-javascript
Events sent to the Script node are passed to the corresponding JavaScript function in the script. The script is specified in the url field of the Script node. The function's name is the same as the eventIn and is passed two arguments, the event value and its timestamp (See "Parameter passing and the EventIn function"). If there is no corresponding JavaScript function in the script, the browser's behavior is undefined.
For example, the following Script node has one eventIn field whose name is start:
Script { eventIn SFBool start url "javascript: function start(value, timestamp) { ... }" }
In the above example, when the start eventIn is sent, the start() function is executed.
When a Script node receives an eventIn, a corresponding method in the file specified in the url field of the Script node is called. This method has two arguments. The value of the eventIn is passed as the first argument and the timestamp of the eventIn is passed as the second argument. The type of the value is the same as the type of the eventIn and the type of the timestamp is SFTime. "Mapping between JavaScript types and VRML types" provides a description of how VRML types appear in JavaScript.
Authors may define a function named eventsProcessed which is to be called after some set of events has been received. Some implementations call this function after the return from each EventIn function, while others call it only after processing a number of EventIn functions. In the latter case, an author can improve performance by placing lengthy processing algorithms which do not need to execute for every event received into the eventsProcessed function.
The eventsProcessed function takes no parameters. Events generated from it are given the timestamp of the last event processed.
Authors may define a function named initialize which is invoked at some time after the VRML file containing the corresponding Script node has been loaded and before any events are processed. This allows initialization tasks to be performed prior to events being received. These might include such actions as constructing geometry or initializing external mechanisms.
The initialize function takes no parameters. Events generated from it are given the timestamp of when the Script node was loaded.
Authors may define a function named shutdown which is invoked when the corresponding Script node is deleted or when the world containing the Script node is unloaded or replaced by another world. This function can be used to send events informing external mechanisms that the Script node is being deleted so they can clean up allocated resources.
The shutdown function has no parameters. Events generated from it are given the timestamp of when the Script node was deleted.
The fields and eventOuts of a Script node are accessible from its JavaScript functions. As in all other nodes, the fields are accessible only within the Script. The eventIns are not accessible. The Script's eventIns can be routed to and its eventOuts can be routed from. Another Script node with a pointer to this node can access its eventIns and eventOuts as for any other node.
Fields defined in the Script node are available to the script by using its name. Its value can be read or written. This value is persistent across function calls. EventOuts defined in the script node can also be read. The value is the last value assigned.
The script can access any exposedField, eventIn or eventOut of any node to which it has a pointer:
DEF SomeNode Transform { } Script { field SFNode node USE SomeNode eventIn SFVec3f pos directOutput TRUE url "javascript:... function pos(value) { node.set_translation = value; }" }
This example sends a set_translation eventIn to the Transform node. An eventIn on a passed node can appear only on the left side of the assignment. An eventOut in the passed node can appear only on the right side, which reads the last value sent out. Fields in the passed node cannot be accessed. However, exposedFields can either send an event to the "set_..." eventIn or read the current value of the "..._changed" eventOut. This follows the routing model of the rest of VRML.
Events generated by setting an eventIn on a node are sent at the completion of the currently executing function. The eventIn must be assigned a value of the same datatype; no partial assignments are allowed. For example, one cannot assign the red value of an SFColor eventIn. Since eventIns are strictly write-only, the remainder of the partial assignment would have invalid fileds. Assigning to the eventIn field multiple times during one execution of the function still only sends one event and that event is the last value assigned.
Assigning to an eventOut sends that event at the completion of the currently executing function. Assigning to the eventOut multiple times during one execution of the function still only sends one event and that event is the value of the eventOut at the completion of script execution.
JavaScript native datatypes consist of boolean, numeric and string. The language is not typed, so datatypes are implicit upon assignment. The VRML 2.0 SFBool is mapped to the JavaScript boolean. In addition to the JavaScript true and false constants, the VRML 2.0 TRUE and FALSE values may be used. The VRML 2.0 SFInt32, SFFloat and SFTime fields are mapped to the numeric datatype. It will maintain double precision accuracy. The will be passed by value in function calls. All other VRML 2.0 fields are mapped to JavaScript objects. JavaScript objects are passed by reference.
The JavaScript boolean, numeric and string are automatically converted to other datatypes when needed. See section 3.1.2 in the JavaScript Reference Specification for more details.
In JavaScript, assigning a new value to a variable gives the variable the datatype of the new value, in addition to the value. Scalar values (boolean and numeric) are assigned by copying the value. Other objects are assigned by reference.
When assignments are made to eventOuts and fields, the values are converted to the VRML field type. Scalar values (boolean and numeric) are assigned by copying the value. Other objects are assigned by reference. There is an example on assigning to illustrate the differences.
The SF objects will be assigned as references, except for assigning to or from eventOut, fields, and MF objects. The exceptions for eventOut, field and MF objects are at the interface between VRML field values and JavaScript variables. The VRML fields are maintained in the correct datatype must be copied at assignment.
For eventOut objects, assignment copies the value to the eventOut, which will be sent upon completion of the current function. Assigning an eventOut to an internal variable creates a new object of the same type as the eventOut with the current value of the eventOut. Field objects behave identically to eventOut objects, except that no event is sent upon completion of the function.
Assigning an element of an MF object to an SF object creates a new object of the corresponding SF object type with the current value of the specified MF element. Assigning an SF object to an element of an MF object (which must be of the corresponding type) copies the value of the SF object into the dereferenced element of the MF object.
This subclause lists the class static methods available in the Browser object which allow scripts to get and set browser information. Descriptions of the methods are provided under the Browser Interface topic of the Scripting clause of ISO/IEC 14772. The syntax for a call would be:
mymfnode = Browser.createVrmlFromString('Sphere {}');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The SFColor object corresponds to a VRML SFColor field. All properties are accessed using the syntax sfColorObjectName.<property>, where sfColorObjectName is an instance of an SFColor object. The properties may also be accessed by the indices [0] for red, [1] for green and [2] blue. All methods are invoked using the syntax sfColorObjectName.method(<argument-list>), where sfColorObjectName is an instance of an SFColor object.
sfColorObjectName = new SFColor(r, g, b)
where
r, g, and b are scalar values with the red, green, and blue values of the colour. Missing values will be filled by 0.0.
The properties of the SFColor object are:
|
|
|
|
|
|
|
|
The methods of the SFColor object are:
|
|
|
|
|
|
|
|
The SFImage object corresponds to a VRML SFImage field.
sfImageObjectName = new SFImage(x, y, comp, array)
where
x is the x-dimension of the image. y is the y-dimension of the image. comp is the number of components of the image (1 for greyscale, 2 for greyscale+alpha, 3 for rgb, 4 for rgb+alpha). All these values are scalar. Array is an MFInt32 field containing the x x y values for the pixels of the image. Format of each pixel is the same as the PixelTexture file format.
The properties of the SFImage object are:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The SFNode object corresponds to a VRML SFNode field.
sfNodeObjectName = new SFNode(vrmlstring)
where
vrmlstring is an ISO 646 string containing the definition of a VRML node
Each node may assign values to its eventIns and obtain the last output values of its eventOuts using the sfNodeObjectName.eventName syntax.
|
|
|
|
The SFRotation object corresponds to a VRML SFRotation field. It has four numeric properties: x, y, z (the axis of rotation) and angle. These may also be addressed by indices [0] through [3].
sfRotationObjectName = new SFRotation(x, y, z, angle)
where
x, y, and z are the axis of the rotation. angle is the angle of the rotation (in radians). All values are scalar. Missing values default to 0.0, except y, which defaults to 1.0.
sfRotationObjectName = new SFRotation(axis, angle)
where
axis is a SFVec3f object whose value is the axis of rotation. angle is the scalar angle of the rotation (in radians)
sfRotationObjectName = new SFRotation(fromVector, toVector)
where
fromVector and toVector are SFVec3f valued objects. These vectors are normalized and the rotation value that would rotate from the fromVector to the toVector is stored in the object.
The properties of the SFRotation object are:
|
|
|
|
|
|
|
|
|
|
The methods of the SFRotation object are:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The SFVec2f object corresponds to a VRML SFVec2f field. Each component of the vector can be accessed using the x and y properties or using C-style array dereferencing (i. e., sfVec2fObjectName[0] or sfVec2fObjectName[1]).
sfVec2fObjectName = new SFVec2f(number1, number2)
where
number1 and number2 are scalar expressions. Missing values default to 0.0.
The properties of the SFVec2f object are:
|
|
|
|
|
|
The methods of the SFVec2f object are:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The SFVec3f object corresponds to a VRML SFVec3f field. Each component of the vector can be accessed using the x, y, and z properties or using C-style array dereferencing (i. e., sfVec3fObjectName[0], sfVec3fObjectName[1] or sfVec3fObjectName[2]).
sfVec3fObjectName = new SFVec3f(number1, number2, number3)
where
number1, number2, and number3 are scalar expressions. Missing values default to 0.0.
The properties of the SFVec3f object are:
|
|
|
|
|
|
|
|
The methods of the SFVec3f object are:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The MFColor object corresponds to a VRML MFColor field. It is used to store a one-dimensional array of SFColor objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfColorObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to SFColor (0, 0, 0).
mfColorObjectName = new MFColor([SFColor, SFColor, ...])
where
The creation method shall initialize the array using 0 or more SFColor-valued expressions passed as parameters.
The property of the MFColor object is:
|
|
|
|
The method of the MFColor object is:
|
|
|
|
The MFFloat object corresponds to a VRML MFFloat field. It is used to store a one-dimensional array of SFFloat values. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfFloatObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to 0.0.
mfFloatObjectName = new MFFloat([number, number...])
where
The creation method shall initialize the array using 0 or more numeric-valued expressions passed as parameters.
The property of the MFFloat object is:
|
|
|
|
The method of the MFFloat object is:
|
|
|
|
The MFInt32 object corresponds to a VRML MFInt32 field. It is used to store a one-dimensional array of SFInt32 values. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfInt32ObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to 0.
mfInt32ObjectName = new MFInt32([number, number, ...])
where
The creation method shall initialize the array using 0 or more integer-valued expressions passed as parameters.
The property of the MFInt32 object is:
|
|
|
|
The method of the MFInt32 object is:
|
|
|
|
The MFNode object corresponds to a VRML MFNode field. It is used to store a one-dimensional array of SFNode objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfNodeObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to NULL.
mfNodeObjectName = new MFNode([SFNode, SFNode, ...])
where
The creation method shall initialize the array using 0 or more SFNode-valued expressions passed as parameters.
The property of the MFNode object is:
|
|
|
|
The method of the MFNode object is:
|
|
|
|
The MFRotation object corresponds to a VRML MFRotation field. It is used to store a one-dimensional array of SFRotation objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfRotationObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to SFRotation (0, 0, 1, 0).
mfRotationObjectName = new MFRotation([MFRotation, MFRotation, ...])
where
The creation method shall initialize the array using 0 or more SFRotaion-valued expressions passed as parameters.
The property of the MFRotation object is:
|
|
|
|
The method of the MFRotation object is:
|
|
|
|
The MFString object corresponds to a VRML 2.0 MFString field. It is used to store a one-dimensional array of SFString objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfStringObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to the empty string.
mfStringObjectName = new MFString([SFString, SFString, ...])
where
The creation method shall initialize the array using 0 or more SFString-valued expressions passed as parameters.
The property of the MFString object is:
|
|
|
|
The method of the MFString object is:
|
|
|
|
The MFTime object corresponds to a VRML MFTime field. It is used to store a one-dimensional array of SFTime values. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfTimeObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to 0.0.
mfTimeObjectName = new MFTime([numeric, numeric, ...])
The creation method shall initialize the array using 0 or more numeric-valued expressions passed as parameters.
The property of the MFTime object is:
|
|
|
|
The method of the MFTime object is:
|
|
|
|
The MFVec2f object corresponds to a VRML MFVec2f field. It is used to store a one-dimensional array of SFVec2f objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfVec2fObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to SFVec2f (0, 0).
mfVec2fObjectName = new MFVec2f([SFVec2f, SFVec2f, ...])
The creation method shall initialize the array using 0 or more SFVec2f-valued expressions passed as parameters.
The property of the MFVec2f object is:
|
|
|
|
The method of the MFVec2f object is:
|
|
|
|
The MFVec3f object corresponds to a VRML MFVec3f field. It is used to store a one-dimensional array of SFVec3f objects. Individual elements of the array can be referenced using the standard C-style dereferencing operator (e. g., mfVec3fObjectName[index], where index is an integer-valued expression with 0 <= index < length and length is the number of elements in the array). Assigning to an element with index > length results in the array being dynamically expanded to contain length elements. All elements not explicitly initialized are set to SFVec3f (0, 0, 0).
mfVec3fObjectName = new MFVec3f([SFVec3f, SFVec3f,...])
where
The creation method shall initialize the array using 0 or more SFVec3f-valued expressions passed as parameters.
The property of the MFVec3f object is:
|
|
|
|
The method of the MFVec3f object is:
|
|
|
|
The VrmlMatrix object provides many useful methods for performing manipulations on 4x4 matrices. Each of element of the matrix can be accessed using C-style array dereferencing (i.e., vrmlMatrixObjectName[0][1] is the element in row 0, column 1). The results of dereferencing a VrmlMatrix object using a single index (i.e. vrmlMatrixObjectName[0]) are undefined. The translation elements will be in the fourth row. For example, vrmlMatrixObjectName[3][0] is the X offset.
VrmlMatrixObjectName = new VrmlMatrix(f11, f12, f13, f14, f21, f22, f23, f24, f31, f32, f33, f34, f41, f42, f43, f44)
where
A new matrix initialized with the values in f11 through f44 is created and returned. The translation values will be f41, f41, and f42.
VrmlMatrixObjectName = new VrmlMatrix()
where
A new matrix initialized with the identity matrix is created and returned.
The VRMLMatrix object has no properties.
The methods of the VRMLMatrix object are:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following is an example of a Script node which determines whether a given colour contains a lot of red. The Script node exposes a Color field, an eventIn, and an eventOut:
DEF Example_1 Script { field SFColor currentColor 0 0 0 eventIn SFColor colorIn eventOut SFBool isRed url "javascript: function colorIn(newColor, ts) { // This method is called when a colorIn event is received currentColor = newColor; } function eventsProcessed() { if (currentColor[0] >= 0.5) // if red is at or above 50% isRed = true; }" }
Details on when the methods defined in Example_2 Script are called are provided in "Concepts - Execution Model".
The following two examples illustrate the use of browser access:
createVrmlFromURL methodDEF Example_2 Script { field SFNode myself USE Example_2 field SFNode root USE ROOT_TRANSFORM field MFString url "foo.wrl" eventIn MFNode nodesLoaded eventIn SFBool trigger_event url "javascript: function trigger_event(value, ts){ // do something and then fetch values Browser.createVRMLFromURL(url, myself, 'nodesLoaded'); } function nodesLoaded(value, timestamp){ if (value.length > 5) { // do something more than 5 nodes in this MFNode... } root.addChildren = value; }" }addRoute method
DEF Sensor TouchSensor {} DEF Baa Script { field SFNode myself USE Baa field SFNode fromNode USE Sensor eventIn SFBool clicked eventIn SFBool trigger_event url "javascript: function trigger_event(eventIn_value){ // do something and then add routing Browser.addRoute(fromNode, 'isActive', myself, 'clicked'); } function clicked(value){ // do something }" }
The following example illustrates assigning with references and assigning by copying.
Script { eventIn SFBool eI eventOut SFVec3f eO field MFVec3f f [ ] url "javascript: function eI() { eO = new SFVec3f(0,1,2); // 'eO' contains the value // (0,1,2) which will be sent // out when the function // is complete. a = eO; // 'a' contains a SFVec3f // object with the value (0,1,2) b = a; // 'b' references the same // object as 'a'. a.x = 3; // 'a' and 'b' both contain // (3,1,2). 'eO' is unchanged. f[1] = a; // 'f[1]' contains the value // (3,1,2). c = f[1]; // 'b' contains a SFVec3f // object with the value (3,1,2) f[1].y = 4; // 'f[1]' contains the value // (3,4,2). 'c' is unchanged. }" }
The following example illustrates uses the fields and methods of SFVec3f and MFVec3f.
DEF SCR-VEC3F Script { eventIn SFTime touched1 eventIn SFTime touched2 eventIn SFTime touched3 eventIn SFTime touched4 eventOut SFVec3f new_translation field SFInt32 count 1 field MFVec3f verts [ ] url "javascript: function initialize() { verts[0] = new SFVec3f(0, 0, 0); verts[1] = new SFVec3f(1, 1.732, 0); verts[2] = new SFVec3f(2, 0, 0); verts[3] = new SFVec3f(1, 0.577, 1.732); } function touched1 (value) { new_translation = verts[count]; // move sphere around tetra count++; if (count >= verts.length) count = 1; } function touched2 (value) { var tVec; tVec = new_translation.divide(2); // Zeno's paradox to origin new_translation = new_translation.subtract(tVec); } function touched4 (value) { new_translation = new_translation.negate(); } function touched3 (value) { var a; a = verts[1].length(); a = verts[3].dot(verts[2].cross(verts[1])); a = verts[1].x; new_translation = verts[2].normalize(); new_translation = new_translation.add(new_translation); }" }