Appendix A. Storyboard Lua API

Table of Contents

Storyboard Lua API
gre.SCRIPT_ROOT
gre.set_data
gre.get_data
gre.set_value
gre.get_value
gre.resolve_data_key
gre.get_control_attrs
gre.set_control_attrs
gre.get_table_attrs
gre.set_table_attrs
gre.get_table_cell_attrs
gre.get_group_attrs
gre.set_group_attrs
gre.get_layer_attrs
gre.set_layer_attrs
gre.set_layer_attrs_global
gre.move_control
gre.move_layer
gre.send_event
gre.send_event_target
gre.send_event_data
gre.greio_disconnect
gre.clone_object
gre.delete_object
gre.clone_control
gre.delete_control
gre.poly_string
gre.get_string_size
gre.load_resource
gre.dump_resource
gre.walk_pool
gre.load_image
gre.timer_set_timeout
gre.timer_set_interval
gre.timer_clear_timeout
gre.timer_clear_interval
gre.animation_create
gre.animation_add_step
gre.animation_destroy
gre.animation_trigger
gre.animation_stop
gre.animation_pause
gre.animation_resume
gre.animation_create_tween
gre.touch
gre.key_up
gre.key_down
gre.key_repeat
gre.redraw
gre.quit
gre.thread_create
gre.receive_event
gre.vfs_open
gre.mstime
gre.env
Storyboard Lua Canvas API
gre.get_canvas
CANVAS:get_dimensions
CANVAS:fill
CANVAS:fill_rect
CANVAS:fill_poly
CANVAS:stroke_line
CANVAS:stroke_rect
CANVAS:stroke_poly
CANVAS:clear_rect
CANVAS:set_pixel
CANVAS:set_alpha
CANVAS:set_line_width
CANVAS:draw_image
CANVAS:draw_text
Storyboard Lua DOM Module
gredom.get_application
gredom.get_object
DOMOBJECT:get_name
DOMOBJECT:get_type
DOMOBJECT:get_parents
DOMOBJECT:get_children
DOMOBJECT:get_variables
Lua DOM Samples

Storyboard Lua API

gre.SCRIPT_ROOT

gre.SCRIPT_ROOT
                    

This is a variable that is filled in by the Storyboard Engine to contain the value of the project's scripts directory.

The gre.SCRIPT_ROOT variable provides a convenient way to reference the file resources in a location independent, project relative, fashion. When used in conjunction with the gre.env() function, the gre.SCRIPT_ROOT can provide an effective way to configure the search path for extra Lua modules.


Example:
                    

 local data_file = gre.SCRIPT_ROOT .. "/input_data.csv"
                    

gre.set_data

 gre.set_data(
    table
 )
            

Sets one or more items in the Storyboard application's data manager.  Each index and value in the table passed in will be set in the data manager using the index name as the key.


Parameters:

        table A table containing the variable to change as the key and the value to change it to as that key's value.

Example:
            

function lua_func( mapargs )
  local data_table  = {}
  data_table["variable_name"] = "variable data"
  gre.set_data( data_table )
end
            

gre.get_data

gre.get_data(
    key
    [, key2, ...]
)
            

Gets one or more values from the data manager. Each argument to the function is interpreted as a data manager key whose value should be extracted from the data manager. This function returns a table using all the values as indexes and the corresponding value is the data returned from the data manager. A nil is returned for any values that do not match a key in the data manager.


Parameters:

        key The key whose value should be extracted from the data manager.

Returns:

        A table containing the passed in arguments as keys and the resulting data manager values as
        the values associated with those keys.

Example - Accessing Control Variables:
            

function get_data_fuc( mapargs )
  --When accessing control variables, use the following qualified
  --model path Layer.Control.Variable
  local data_table = gre.get_data("my_layer.my_control.variable_name")
  local value = data_table["my_layer.my_control.variable_name"]
  print("control_variable_name = " .. tostring(value))
end
            


Example - Accessing Control Width (Internal Variable):
                    

function get_control_width( mapargs )
	--This will extract the width (grd_width) of the contro
    --'my_control' on the layer 'my_layer'
	local data = gre.get_data("my_layer.my_control.grd_width")
	local value = data["my_layer.my_control.grd_width"]
	print("The width of the control is " .. tostring(value))
end
            

gre.set_value

gre.set_value(
	key,
	value
	[, key2, value2, ...]
)
            

Set a variable in the data manager to a particular value. This function is a convenience function on top of gre.set_data that allows the key and value to be passed as a set of arguments to the function instead of having to create a table containing the key/value pairs.


Parameters:

        key  A string value containing the key to be set with the next following value
value  The value to be assigned to the preceding argument (key)

Example:
            

function lua_func( mapargs )
  -- Assign the string 'variable_data' to the application variable
  -- 'variable_name'
  -- This example is the same as gre.set_data()
  gre.set_value("variable_name", "variable_data")
end
            

gre.get_value

gre.get_value(
	key
	[, key2, ...]
)
            

Get the value of a variable from the data manager. This function is a convenience function on top of gre.get_data that allows the value to be returned directly to the caller instead of a single table return value. A nil is returned for any values that do not match a key in the data manager.


Parameters:

        key The key whose value should be extracted from the data manager.

Returns:

        The value associated with the data manager entry for the key, or nil if no entry exists.  If multiple
keys are specified, then multiple return values will be generated matching the argument order.

Example - Accessing Control Width:
            

function get_control_width( mapargs )
	-- This will extract the width of the control 'my_control'
    -- on the layer 'my_layer'
	-- This is the same example as gre.get_data()
	local value = gre.get_value("my_layer.my_control.grd_width")
	print("The width of the control is " .. tostring(value))
end
            

gre.resolve_data_key

gre.resolve_data_key(
    key1
    [, key2, ...]
)
		    

This function allows Lua scripts to resolve Storyboard context variables to a fully qualified name based on the current execution context.


Parameters:

            key1 ...    One or more string arguments containing the variable to resolve.

Returns:

            A table containing the arguments provided on input as keys with the values being the
            resolved data value.

Example:
    

-- Resolve the application my_var to a fully qualified name
local varname = "${app:my_var}"
local dv = gre.resolve_data_key(varname)
print("Full path for ${app:my_var} is " .. dv[varname])
		    

gre.get_control_attrs

gre.get_control_attrs(
    control_name
    tags ...
)
            

Get properties for a control.  Key name is the name of the control or a variable.  Tags can be a list of the following values:

        x, y, width, height, hidden, active, zindex, findex

A table with the results is returned.


Parameters:

        control_name    The model full path of the control to get information about
        tags            One or more tags as strings

Returns:

        A table containing the tags as keys with the associated table value being the Storyboard
        value associated with that tag.

Example:
            

function check_if_hidden()
  local dk_data = {}
  -- check if my_control is currently hidden
  dk_data = gre.get_control_attrs("my_layer.my_control", "hidden")
  if dk_data["hidden"] == 1 then
    print("my_control is currently hidden")
  else
    print("my_control is currently visible")
  end
end
            

gre.set_control_attrs

gre.set_control_attrs(
    control_name,
    tag_table
)
            

Set properties for a control.  The control_name is the name of the control or a variable. The tag_table contains the tags and values for the properties to set.

        x,  y, width, height, hidden, active, zindex, findex, effect

In the case of the focus index (findex), the initial value set in Storyboard Designer must be non-zero in order for it to be changed dynamically at runtime

The effect tag is a special attribute that can be used with OpenGL rendering platforms to apply a custom shader directly as an effect on the control object


Parameters:

        control_name    The model full path of the control to change properties on
        tag_table       A table with tags as the keys and the new values stored as the table's key values

Examples:
            

function set_control_hidden()
  local dk_data = {}
  dk_data["hidden"] = 1
  gre.set_control_attrs("my_control", dk_data)       
end
            
function set_control_blur_effect()
  local dk_data = {}
  local effect = {}

  effect["name"] = "blur"
  effect["passes"] = 3
  effect["radius"] = 1
  effect["composite"] = true

  dk_data["effect"] = effect
  gre.set_control_attrs("my_control", dk_data)
end
                    

gre.get_table_attrs

gre.get_table_attrs(
    table_name,
    tags
)
            

Get properties for a table.  Key name is the name of the control or a variable.  Tags can be any of the control tags mentioned in section 6.1.12 and any of the following values:

rows

The number of rows in the table

cols

The number of columns in the table

visible_rows

The number of visible rows in the table

visible_cols

The number of visible columns in the table

active_row

The active cell row

active_col

The active cell column

row

The row index of the upper left row

col

The column index of the upper left column

xoffset

The current scroll offset in the x direction

yoffset

The current scroll offset in the y direction


Parameters:

        table_name      The model full path of the table to get information about
        tags            One or more tags as strings

Returns:

        A table containing the tags as keys with the associated table value being the Storyboard
        value associated with that tag.

Example:
            

function check_if_hidden()
  local dk_data = {}
  -- Get the active row/column
  dk_data = gre.get_table_attrs("my_table", "active_row", "active_col")
  print("Active Cell: " .. tostring(dk_data["active_row"] .. ","
  .. tostring(dk_data["active_col"]))
end
            

gre.set_table_attrs

gre.set_table_attrs(
    table_name,
    tag_table
)
            

Set properties for a table.  The table_name is the name of the control or a variable. The tag_table contains the tags and values for the properties to set.

        x,  y, width, height, hidden, active, rows, cols, xoffset, yoffset


Parameters:

        table_name    The model full path of the table to change properties on
        tag_table     A table with tags as the keys and the new values stored as the table's key values

Example:
            

function resize_table()
  local dk_data = {}
  dk_data["rows"] = 5
  dk_data["cols"] = 10
  gre.set_table_attrs("my_table", dk_data)       
end
            

gre.get_table_cell_attrs

gre.get_table_cell_attrs(
    table_name,
    row,
    col,
    tags ...
)
            

Get properties for a table cell.  table_name is the name of the table.  Tags can be a list of the following values:

        x, y, width, height, hidden

A table with the results is returned.


Parameters:

        table_name    The model full path of the table to get information about
        row   The row of the table to get information on
        col   The column of the table to get information on
        tags          One or more tags as strings

Returns:

        A table containing the tags as keys with the associated table value being the Storyboard
        value associated with that tag.

Example:
            

function check_if_hidden()
  local dk_data = {}
  -- check if my_control is currently hidden
  dk_data = gre.get_table_cell_attrs("my_table", 1, 1, "hidden")
  if dk_data["hidden"] == 1 then
    print("cell 1.1 of my_table is currently hidden")
  else
    print("cell 1.1 of my_table is currently visible")
  end
end
            

gre.get_group_attrs

gre.get_group_attrs(
    group_name
    tags ...
)
            

Get properties for a group.  Key name is the name of the group or a variable.  Tags can be a list of the following values:

        x, y, hidden

A table with the results is returned.


Parameters:

        group_name    The model full path of the control to get information about
        tags          One or more tags as strings

Returns:

        A table containing the tags as keys with the associated table value being the Storyboard
        value associated with that tag.

Example:
            

function check_if_hidden()
  local dk_data = {}
  -- check if my_group is currently hidden
  dk_data = gre.get_group_attrs("my_layer.my_group", "hidden")
  if dk_data["hidden"] == 1 then
    print("my_control is currently hidden")
  else
    print("my_control is currently visible")
  end
end
            

gre.set_group_attrs

gre.set_group_attrs(
    group_name,
    tag_table
)
            

Set properties for a group.  The group_name is the name of the group or a variable. The tag_table contains the tags and values for the properties to set.

        x,  y, hidden


Parameters:

        group_n ame    The model full path of the group to change properties on
        tag_table       A table with tags as the keys and the new values stored as the table's key values

Examples:
            

function set_control_hidden()
  local dk_data = {}
  dk_data["hidden"] = 1
  gre.set_control_attrs("my_layer.my_group", dk_data)       
end
            
function set_control_blur_effect()
  local dk_data = {}
  local effect = {}

  effect["name"] = "blur"
  effect["passes"] = 3
  effect["radius"] = 1
  effect["composite"] = true

  dk_data["effect"] = effect
  gre.set_control_attrs("my_control", dk_data)
end

                    

gre.get_layer_attrs

 gre.get_layer_attrs(
    layer_name
    tags...
 )
            

Get properties for a layer instance associated with a particular screen.   The layer_name specifies either the fully qualified name of a layer instance using the ScreenName.LayerName naming convention or, if only the layer name is specified, the name will refer to a layer instance associated with the current screen

The tags are a list of string properties associated with the layer instance and can include one or more of the following values:

        x, y, alpha, hidden, active, zindex, xoffset, yoffset

A table containing the keys and their respective values is returned or nil if the layer can not be found.


Parameters:

        layer_name      The model full path of the layer to get information about
        tags            One or more tags as strings

Returns:

        A table containing the tags as keys with the associated table value being the Storyboard
        value associated with that tag.

Example:
            

function check_if_hidden()
  -- check if my_layer is currently hidden
  local data = gre.get_layer_attrs("my_layer", "hidden")
  if data.hidden == 1 then
    print("my_layer is currently hidden")
  else
    print("my_layer is currently visible")
  end
end
            

gre.set_layer_attrs

gre.set_layer_attrs(
    layer_name,
    tag_table
)
            

Set properties for a layer instance associated with a particular screen.   The layer_name specifies either the fully qualified name of a layer instance using the ScreenName.LayerName naming convention or, if only the layer name is specified, the name will refer to a layer instance associated with the current screen

alpha, hidden, active, x, y, zindex, width, height, xoffset, yoffset, effect

Note

Any change to the width and height values affect all layers.

The “effect” attribute requires the libgre-plugin-effects-3d.so plugin. This plugin is only available for OpenGL ES 2.0.


Parameters:

        layer_name    The model full path of the layer to change properties on
        tag_table     A table with tags as the keys and the new values stored as the table's key values

Example:
            

function set_layer_hidden()
  local data = {}
  data.hidden = 1
  gre.set_layer_attrs("my_layer", data)       
end
            

Render Effects:

The attribute contains a table with the name and attributes for the specific render effect being applied. Currently the following effects are defined:

blur, geometry

blur

This effect will add a blur to the contents of the layer. The following blur attributes are defined:


Parameters:

        passes        This is a number value which is the number of blur passes
        composite     This is a boolean value.  When true the blur will be applied to the final composition
                      of this layer with the framebuffer content.  If false the blur is only applied to the
                      layer content.
        radius        This is a number value which defined the radius of the blur effect in pixels

Example:
                                

function cbBlurEffect(mapargs)
  local attrs = {}
  local effect = {}

  effect["name"] = "blur"
  effect["passes"] = 2
  effect["radius"] = 1
  effect["composite"] = false
  attrs["effect"] = effect
  gre.set_layer_attrs("background.control1",attrs)
end
                            
geometry

This effect will allow custom OpenGL ES geometry to be applied to the rendering of the control or layer. This includes custom vertices and UV coordinates. The following attributes are defined:


Parameters:

        width    The viewport width for the content
        height    The viewport height for the content
        type    The type of primitive to render:  fan | triangles
        nvert    The number of vertex coordinates.  Options are 2 (x,y) and 3 (x, y, z)
        nuv        The number of UV coordinates.  Options are 2 or 0
        data    The table containing the vertex data

Example:

                            

function cbSetGeometry(mapargs)
  local gdata = {}
  local dz = 0.0
  local offset = mapargs.offset
  local dz2 = -offset
  local w
  local h = 240

  dz2 = -offset
  w = 320 - offset
  gdata = {
    {x=w/2, y=h/2, z=dz2, u=0.5, v=0.5},

    {x=w, y=0, z=dz, u=1.0, v=0},
    {x=w/2, y=0, z=dz2, u=0.5, v=0},
    {x=0, y=0, z=dz, u=0, v=0},

    {x=0, y=h, z=dz, u=0, v=1.0},
    {x=w/2, y=h, z=dz2, u=0.5, v=1.0},
    {x=w, y=h, z=dz, u=1.0, v=1.0},

    {x=w, y=0, z=dz, u=1.0, v=0},
  }

  local attrs = {}
  attrs["geometry"] = {
      width = w,
      height = h,
      type = "fan",
      nvert = 3,
      nuv = 2,
      data = gdata
  }
  gre.set_layer_attrs("geometry.layer3",attrs)
end
                            

gre.set_layer_attrs_global

gre.set_layer_attrs_global(
    layer_name,
    table
)
            

Set properties for a layer globally on all instances of the layer on all screens.  The layer_name is the name of the layer.  Table contains the tags and values for the properties to set.

        alpha, hidden, active, x, y, width, height


Parameters:

        layer_name    The model full path of the layer to change properties on
        tag_table     A table with tags as the keys and the new values stored as the table's key values

            

gre.move_control

gre.move_control(
    control_name,
    dx,
    dy,
    x,
    y
)
            

Move a controls to a new position.  The control_name is the name of the control or a variable.  Setting dx and or dy will move the layer by the specified delta from its current position.  The  dx and dy values can be 0 to set an absolute position using the x and y values only.


Parameters:

        control_name    The model full path of the control to move
        dx              A delta from the current x position or 0 to move using x
        dy              A delta from the current y position or 0 to move using y
        x               The x position to move to in absolute co-ordinates
        y               The y position to move to in absolute co-ordinates

Example:
            

gre.move_layer

gre.move_layer(
    layer_name,
    dx,
    dy,
    x,
    y
)
            

Move a layer to a new position.  The layer_name is the name of the layer or a variable that is associated with the layer name. Setting dx or dy will move the layer by the specified delta from its current position. The  dx and dy values can be 0 to set an absolute position using the x and y values only.


Parameters:

        layer_name  The model full path of the layer to move
        dx          A delta from the current x position or 0 to move using x
        dy          A delta from the current y position or 0 to move using y
        x           The x position to move to in absolute co-ordinates
        y           The y position to move to in absolute co-ordinates

Example:
            

gre.send_event

gre.send_event(
    event_name,
    [channel]
)
            

Send an event to the application or to a Storyboard IO channel.  channel is an optional parameter and if channel is not passed then the channel will be chosen as follows:

If the environment variable GREIONAME is set then it will be used otherwise the default channel is used.


Parameters:

        event_name    A string containing the event to send
        channel       An optional Storyboard IO channel to send the event on, if not specified the
                      event is added directly into the current Storyboard application event queue
                      if neither the environment variable or global GREIONAME variable are set.

Example:
            

-- Send to the event  to the application :
gre.send_event("my_event")

--To send the event to a Storyboard IO channel via parameters:
gre.send_event("my_event", “io_channel_name”)
            

gre.send_event_target

gre.send_event_target(
    event_name,
    target,
    [channel]
)
            

Send an event to a targeted model element (control, layer instance or screen) using the model's fully qualified path. The channel is an optional parameter.


Parameters:

        event_name    A string containing the event to send
        target        A string containing the object to target the event to (see Storyboard IO)
        channel       An optional Storyboard IO channel to send the event on, if not specified the
                      event is added directly into the current Storyboard application event queue
                      if neither the environment variable or global GREIONAME variable are set.

Example:
            

-- Send to the event directed at a particular control target:
gre.send_event("my_event", "my_layer.my_control")
            

gre.send_event_data

gre.send_event_data (  
    event_name,
    format_string,
    data,
    [channel]
)
            

Send an event with custom data to the application or to a Storyboard IO channel. The data parameter is a Lua table where the indexes match the values from the format string. channel is an optional parameter.

Special consideration is required for sending data that is to be formatted as an array (i.e., N[suf]M where M is greater than 0). In this case the data entry should be provided as a Lua table and not as a raw value parameter.

Data parameters must be sent in order of descending alignment requirements. Example: 4u1 4u1 2u1 1s0 is good, 2u1 4u1 4u1 1s0 is not


Parameters:

        event_name    A string containing the event to send
        format_string A string format of the event data payload
        data          A table whose keys match up with the keys specified in the format_string
        channel       An optional Storyboard IO channel to send the event on, if not specified the
                      event is added directly into the current Storyboard application event queue
                      if neither the environment variable or global GREIONAME variable are set.
Example:
            

-- Send a 'int32_update' event with a 32bit signed integer (int32_t)
-- payload to the 'controller' channel
function send_integer(value)
	loca  format = "4s1 value"
	local data = {}
	data["value"] = value
	gre.send_event_data("int32_update", format, data, "controller")
end

-- Send a 'int16_update' event with two 16bit signed integers (int16_t)
-- payload to the 'controller' channel
function send_two_integers(value1, value2)
	loca  format = "2s1 first 2s1 second"
	local data = {}
	data["first"] = value1
	data["second"] = value2
	gre.send_event_data("int16_update", format, data, "controller")
end

-- Send an 'array_update' event with an array of int32_t numbers (provided
-- as a table) to the client
function send_integer_array(values)
	-- Generate the format string dynamically based on the number of entries
	local count = #values
	local format = string.format("4s%d values", count)
	local data = {}
	data["values"] = values
	gre.send_event_data("array_update", format, data, "controller")
end

send_integer(12)
send_two_integers(10, 20)
send_integer_array({10, 20, 30, 40})

gre.greio_disconnect

gre.greio_disconnect(
    channel,
    [is_receive_channel]
)
		    

This function forces any cached Storyboard IO channel connections to the specified channel to be closed. Subsequent calls using the same channel name will re-establish the connection to the channel if required.


Parameters:

            channel    The channel that is to be disconnected.
            is_receiving    An optional boolean parameter.
                                            -True if closing a receiving channel.
                                            -False or no argument if closing a sending channel.

Example:
    

-- Send an event to a custom channel
gre.send_event("StoryboardRocks", "my_channel")
-- Close the cached connection to that channel
gre.greio_disconnect("my_channel")
            

gre.clone_object

gre.clone_object(
    reference_object_name,
    new_object_name,
    parent_name,
    data
)
            

Create a new control or group (new_object_name) within an existing parent (layer_name) by copying all of the properties of an existing object (reference_object_name). This new object will have all of the same actions, variables and it's current state will match the state of the reference object that is being copied. In the case of cloning groups, all of the reference group's controls will be cloned into the new group.

Currently only controls and groups are supported as source reference objects.

  • Controls can be cloned into either layer or group parents as long as no name conflict exists.

  • Groups can be cloned into layer parents as long as no name conflict exists.

The data argument is a table of properties that match the properties for that type of object as described in the gre.set_control_attrs or gre.set_group_attrs functions as applicable. For example, most objects support x, y,hidden properties


Parameters:

        reference_object_name    The name of the object that will be cloned.  This may be a fully qualified name
                                 of a group or control
        new_object_name          The name for the new object, this must be a unique name in the parents namespace
        parent_name              The name of the layer or group to place this object within, this object must exist
        data                     Optional: A table containing control attribute tags as the keys with new values to be applied.

Example:
            

function create_new_control()
  local data = {}
  data["x"] = 10
  data["y"] = 10
  gre.clone_object("my_control", "my_new_control", "my_layer", data)       
end
            

gre.delete_object

gre.delete_object(
    object_name,
)
            

Delete an object that has been cloned using gre.clone_object from the model. The object must be a control or a group.


Parameters:

        object_name     The fully qualified name of the object to delete

Example:
            

function delete_object()
  gre.delete_object("my_layer.my_object")       
end
            

gre.clone_control

gre.clone_control(
    reference_control_name,
    new_control_name,
    layer_name,
    data
)
            

This is a function to clone a control. This function has been deprecated and has been replaced with the gre.clone_object Lua API function. See the gre.clone_object for usage and examples.

gre.delete_control

gre.delete_control(
    control_name,
)
            

This is a function to delete a cloned control. This function has been deprecated and has been replaced with the gre.delete_object Lua API function. See the gre.delete_object for usage and examples.

gre.poly_string

gre.poly_string(
    x_values,
    y_values
)
  or
gre.poly_string(
    {{x=, y=}, ...}
)
            

This is a higher performance function for generating a polygon string based on a set of numeric data points maintained in Lua table arrays.

In the two argument form, the function receives as inputs two Lua tables whose content represents the numeric x and y data points to be converted to a string. The tables are 1 based arrays and must be of the same length.

In the single argument form, the function receives as input a single Lua table whose array content are tables with an "x" and "y" member value.

The string returned is designed to be compatible with the Storyboard polygon plugin and is in the form of X1:Y1 X1:Y2 ...


Parameters:

        x_values,
        y_values    An table containing numeric data for the x and y points respectively.

        {{x=, y=}}  A table containing tables with x and y members specifying the x and y points.

Example:
            

-- Create a triangle polygon in a 100x100 square
local x_points = { 0, 50, 100 }         -- Left, Middle, Right
local y_points = { 100, 0, 100 }        -- Bottom, Top, Bottom
local x_y_string = gre.poly_string(x_points, y_points)
print("X Y String: " .. x_y_string)

-- Create the same triangle, but with x,y member variables
local xy_points = { {x=0,y=100}, {x=50,y=0}, {x=100,y=100} }
local xy_string = gre.poly_string(xy_points)
print("XY String: " .. xy_string)
                

gre.get_string_size

gre.get_string_size(
    font,
    font_size,
    string,
    length,
    width
)
            

Calculate the area in pixels which the given string will occupy on the screen. Optionally calculate how many characters can fit into a predefined screen area.

Parameters:

        string          The string to render
        font            The name of the font to render in
        font_size       The size of the font to render in  
        string_length   The length of the string to render or 0 for all (optional)
        width           A clipping width (in pixels) for the string, used to calculate how many characters fit
        (optional, by default there is no clip)

Returns:

        A table containing the following entries:
        "num_bytes" number of bytes that will fit in the clip
  "width" string width in pixels as clipped by clip width
  "height" string height in pixels
        "line_height" height in pixels of the specified font

gre.load_resource

gre.load_resource(
    pool_name,
    resource_name,
    [pool parameters]
)
		    

This function will force the loading of a resource, such as an image or font, into the Storyboard application. This can be used in order to avoid load time delays that may be incurred as resources are lazy loaded into the application.


Parameters:

            pool_name       The name of the resource pool: image or font
            resource_name   The name of the resource that is to be loaded

The optional parameters vary depending on the pool being specified may not be required:
            image pool:
                w, h, background The width and height to cache the image at, and whether or not to load the
                image asynchronously the 'background'
            font pool:
                size (Required) The point size of the font to load
antialias A flag indicating if anti aliasing is to be used

These options should be passed as a table as the third parameter to ensure that the loader receives the
appropriate values.

On completion of a 'background' loaded resource, the following event is sent:
gre.resource_loaded 1s0 resource
Example:
    

-- Call this to pre-load the image and font into the cache
function on_app_init(mapargs)
-- Call this to pre-load a font at a 24pt size
	local opt = {}
	opt.size = 24
    gre.load_resource("font", "fonts/DejaVu.ttf", opt)

-- Call this to pre-load the image unscaled
    gre.load_resource("image", "images/tree.jpg")

-- Call this to pre-load the image and scale it to 100x100
    local opt = {}
	opt.w = 100
	opt.h = 100
    gre.load_resource("image", "images/scaledtree.jpg", opt)

-- Call this to pre-load the image and scale it to 100x100 asynchronously
    local opt = {}
    opt.w = 100
    opt.h = 100
    opt.background = 1
    gre.load_resource("image", "images/scaledtreebg.jpg", opt)
end
            

gre.dump_resource

gre.dump_resource(
    pool_name,
    resource_name
)
		    

This function performs the opposite of the gre.load_resource call and removes a resource from the specified resource pool cache.


Parameters:

            pool_name       The name of the resource pool: image or font
            resource_name   The name of the resource that is to be removed

Example:
    

-- Force the tree.jpg image out of the cache, image will reload as required
function flush_tree_image()
    gre.dump_resource("image", "images/tree.jpg")
    gre.dump_resource("font", "fonts/DejaVu.ttf")
end
            

gre.walk_pool

gre.walk_pool(
    pool_name,
)
		    

This function reports on the memory used by all of the resources loaded into a particular resource pool.


Parameters:

            pool_name       The resource pool whose content should be reported

Returns:

            A table is returned with keys as the resources that are contained in the pool and values
            indicating the number of bytes that a particular resource is using within the system.

Example:
    

-- Display the content of the current image cache
function show_image_cache(mapargs)
    print("Images")
    local data = gre.walk_pool("image")
    for k,v in pairs(data) do
        print("  ".. tostring(k) .. "=" .. tostring(v))
    end
end
            

gre.load_image

gre.load_image(
    image_name,
    [optional table of parameters]
)
		    

This function will force the loading of an image into the Storyboard application. This can be used in order to avoid load time delays that may be incurred as resources are lazy loaded into the application.

This is a convenience function for calling the more generic gre.load_resource


Parameters:
            resource_name    The name of the resource that is to be loaded

The optional parameters are as follows:
                w The width to cache the image at
                h The height to cache the image at
                background Whether or not to load the image asynchronously the 'background'

On completion of a 'background' loaded resource, the following event is sent:
gre.resource_loaded 1s0 resource
    

gre.timer_set_timeout

gre.timer_set_timeout(
    function,
    timeout
)
		    

This function creates a one-shot timer which fires after "timeout" milliseconds and then executes "function"


Parameters:

            function       The function to be called when the timer fires
            timeout        The time in milliseconds before the timer should fire

Returns:

            A piece of lightuserdata which serves as an identifier for the timer

Example:
    

local idval = {}
function cb_func()
	print("CB FUNC HAS BEEN CALLED")
end

--Call cb_func after 1 second
function cb_set_timeout()
	idval = gre.timer_set_timeout(cb_func, 1000)
end
            

gre.timer_set_interval

gre.timer_set_interval(
    function,
    interval
)
		    

This function creates a repeating timer which fires every "interval" milliseconds and then executes "function"


Parameters:

            function       The function to be called when the timer fires
            interval       The time in milliseconds of how often the timer should fire

Returns:

            A piece of lightuserdata which serves as an identifier for the timer

Example:
    

local idval = {}
function cb_func()
	print("CB FUNC HAS BEEN CALLED")
end

--Call cb_func every 2 seconds
function cb_set_interval()
	idval = gre.timer_set_interval(cb_func, 2000)
end
            

gre.timer_clear_timeout

gre.timer_clear_timeout(
    id
)
		    

This function stops an existing timer from firing


Parameters:

            id             The lightuserdata representing the timer

Returns:

            Nothing

Example:
    

local idval = {}
function cb_func()
	print("CB FUNC HAS BEEN CALLED")
end

--Call cb_func after 5 seconds
function cb_set_timeout()
	idval = gre.timer_set_timeout(cb_func, 2000)
end

function cb_clear_timeout()
	local data

	data = gre.timer_clear_timeout(idval)
end
            

gre.timer_clear_interval

gre.timer_clear_interval(
    id
)
		    

This function stops an existing timer from firing


Parameters:

            id             The lightuserdata representing the timer

Returns:

            Nothing

Example:
    

local idval = {}
function cb_func()
	print("CB FUNC HAS BEEN CALLED")
end

--Call cb_func every 5 seconds
function cb_set_interval()
	idval = gre.timer_set_interval(cb_func, 2000)
end

function cb_clear_interval()
	local data

	data = gre.timer_clear_interval(idval)
end
            

gre.animation_create

gre.animation_create(fps, [auto_destroy], [end_callback])
                    

Create a new animation at the desired frame rate (fps). The second parameter (optional), auto_destroy, tells if the animation should be released once completed. If you specify a value of 1 the animation will be released and the returned id is not valid once the animation has completed. The third parameter (optional) indicates a callback function to be invoked when the animation is complete.


Parameters:
        fps    The animation frame rate
        auto_destroy    Pass 1 in to release the animation once completed
        end_callback    Provide a Lua function to be called in the animation
Returns
        An animation id to be used on future animation calls, nil on failure.

Example:        

function animation_create(mapargs, fps)
	local id
	id = gre.animation_create(fps)
end

--Example of an creating an animation with an animation complete callback
local animation_state = "STOPPED"
function animation_create(mapargs, fps)
	local id
	id = gre.animation_create(fps, 0, animation_complete)

	gre.animation_trigger(id, {context="my_layer.my_control",
	id="my_control_animation"})
	animation_state = "RUNNING"
end

--The callback's first argument will be the completed animation's id.
--When triggered with an animation instance id (e.g., "my_control_animation"),
--otherwise it will be the id returned from calling animation_create.
function animation_complete(id)
	animation_state = "COMPLETED"
end

        

gre.animation_add_step

gre.animation_add_step(id, data)

Add a step to a created animation. The id must be from a call to gre.animation_create. The data parameter defines the animation step values.

Parameters:
        id    The animation id

        data    A table of animation step values which can include:

            key: The data key for the animation step to act upon
            rate:  The animation rate string: [linear|easein|easeout|easeinout|bounce]
            duration: The length of the step (msec)
            offset:  The offset from animation start where this step begins (msec)
            from: The value to start the animation at, if not specified the value is the current value of "key"
            to: The end point for the animation
            delta: The delta for the end of the animation from the start point.  If both "to" and "delta" are  given
            then the "to" value is used.

Example:

function create_animation(mapargs)
	local data = {}

	-- slide the x position 400 pixels over 2000 msec and auto-destroy
	-- it on completion
	id  = gre.animation_create(60, 1)
	data["rate"] = "linear"
	data["duration"] = 2000
	data["offset"] = 0
	data["delta"] = 400
	data["key"] = "mylayer.mycontrol.grd_x"
	gre.animation_add_step(id, data)
end
                    

gre.animation_destroy

gre.animation_destroy(id)


Destroy the animation associated with id.

Parameters:
        id    The animation to destroy

Example:
                    

function create_animation(mapargs)
	local data = {}

	-- slide the x position 400 pixels over 2000 msec
	id = gre.animation_create(60)
	data["rate"] = "linear"
	data["duration"] = 2000
	data["offset"] = 0
	data["delta"] = 400
	data["key"] = "mylayer.mycontrol.grd_x"
	gre.animation_add_step(id, data)

	-- destroy it
	gre.animation_destroy(id)
end
                    

gre.animation_trigger

gre.animation_trigger(animation_id, data)
gre.animation_trigger("animation_name")

Trigger an animation to run. If an animation_id is used to trigger the animation, then it must be the return value from gre.animation_create(). If a name is used to trigger an animation, then that name must be the name of the animation specified in Designer. This function can take an optional parameter, data_table. The data_table contains the tags and values for the extra arguments to set.


Parameters:
        animation_id    The animation to trigger
        data     A table containing the tags and values for the extra arguments to set
        id              The animation id used in the case of multiple animations with the same name
        context         The fully qualified name of an object in the model which will be used as the context for the animation

Example:
                    

function create_animation(mapargs)
	local data = {}

	-- slide the x position 400 pixels over 2000 msec and auto-destroy
	-- it on completion
	id = gre.animation_create(60, 1)
	data["rate"] = "linear"
	data["duration"] = 2000
	data["offset"] = 0
	data["delta"] = 400
	data["key"] = "mylayer.mycontrol.grd_x"
	gre.animation_add_step(id, data)

	gre.animation_trigger(id)
end

--Example of using gre.animation_trigger passing animation names.
function cb_toggle_cur_5day()
  if cur_5day_toggle == false then
      gre.animation_trigger("show_5day")
  else
      gre.animation_trigger("hide_mon_to_fri")
  end
end

--Example of using gre.animation_trigger with context.
function cb_toggle_cur_5day()
	local data = {}

	data["context"] = "Layer1.mycontrol"
    gre.animation_trigger("show_5day", data)
end
                    

gre.animation_stop

gre.animation_stop(animation_id, data)
gre.animation_stop("animation_name")

Stop an animation. If an animation_id is used to stop the animation, then it must be the return value from gre.animation_create(). If a name is used to stop an animation, then that name must be the name of the animation specified in Designer. This function can take an optional parameter, data_table. The data_table contains the tags and values for the extra arguments to set.


Parameters:
        animation_id    The animation to stop
        data     A table containing the tags and values for the extra arguments to set
        id              The animation id used in the case of multiple animations with the same name
        context         The fully qualified name of an object in the model which will be used as the context for the animation

Example:
                    

function create_animation(mapargs)
	local data = {}

	-- slide the x position 400 pixels over 2000 msec and auto-destroy
	-- it on completion
	id = gre.animation_create(60, 1)
	data["rate"] = "linear"
	data["duration"] = 2000
	data["offset"] = 0
	data["delta"] = 400
	data["key"] = "mylayer.mycontrol.grd_x"
	gre.animation_add_step(id, data)

	gre.animation_trigger(id)

	--do stuff

	--Stop the animation
	gre.animation_stop(id)
end

--Example of using gre.animation_stop passing animation names.
function cb_stop_cur_5day()
  if cur_5day_toggle == false then
      gre.animation_stop("show_5day")
  else
      gre.animation_stop("hide_mon_to_fri")
  end
end

--Example of using gre.animation_stop with context.
function cb_toggle_cur_5day()
	local data = {}

	data["context"] = "Layer1.mycontrol"
    gre.animation_stop("show_5day", data)
end
                    

gre.animation_pause

gre.animation_pause(animation_id, data)
gre.animation_pause("animation_name")

Pause a running animation. If an animation_id is used to pause the animation, then it must be the return value from gre.animation_create(). If a name is used to pause an animation, then that name must be the name of the animation specified in Designer. This function can take an optional parameter, data_table. The data_table contains the tags and values for the extra arguments to set.


Parameters:
        animation_id    The running animation to pause
        data     A table containing the tags and values for the extra arguments to set
        id              The animation id used in the case of multiple animations with the same name
        context         The fully qualified name of an object in the model which will be used as the context for the animation

Example:
                    

function pause_animation(id)
	--Pause the animation
	gre.animation_pause(id)
end

--Example of using gre.animation_pause passing animation names.
function cb_pause_cur_5day()
  if cur_5day_toggle == false then
      gre.animation_pause("show_5day")
  else
      gre.animation_pause("hide_mon_to_fri")
  end
end

--Example of using gre.animation_pause with context.
function cb_pause_cur_5day()
	local data = {}

	data["context"] = "Layer1.mycontrol"
    gre.animation_pause("show_5day", data)
end
                    

gre.animation_resume

gre.animation_resume(animation_id, data)
gre.animation_resume("animation_name")

Pause a running animation. If an animation_id is used to pause the animation, then it must be the return value from gre.animation_create(). If a name is used to pause an animation, then that name must be the name of the animation specified in Designer. This function can take an optional parameter, data_table. The data_table contains the tags and values for the extra arguments to set.


Parameters:
        animation_id    The running animation to pause
        data     A table containing the tags and values for the extra arguments to set
        id              The animation id used in the case of multiple animations with the same name
        context         The fully qualified name of an object in the model which will be used as the context for the animation

Example:
                    

function resume_animation(id)
	--Resume the animation
	gre.animation_resume(id)
end

--Example of using gre.animation_resume passing animation names.
function cb_resume_cur_5day()
  if cur_5day_toggle == false then
      gre.animation_resume("show_5day")
  else
      gre.animation_resume("hide_mon_to_fri")
  end
end

--Example of using gre.animation_resume with context.
function cb_resume_cur_5day()
	local data = {}

	data["context"] = "Layer1.mycontrol"
    gre.animation_resume("show_5day", data)
end
                    

gre.animation_create_tween

gre.animation_create_tween(name, tween_callback)
                    

Create a new animation tweening (interpolation) function that can be used by both Lua and Animation Timeline animations. The name of the tweening function cannot collide with any existing animation tweening names. The callback function is a generic tween function that will be provided with specific parameters outlining the desired range of the values being tweend and the frame at which the values should be interpolated.

The tweening function is called with four parameters elapsed, base, change, duration. The elapsed value indicates the interpolation location and is in the range from [0,duration] so if one wanted to derive the percentage that the animation has completed, it would be elapsed/duration. The base value represents the numeric starting point of interpolation and the end point of the animation will be base+change. These four values can be applied to various transforms to return a single floating point value that represents the desired outcome of the interpolation function at that point in time. The output of the interpolation is clamped to the range [base,base+change] though this restriction may be lifted in future releases of Storyboard.


Parameters:
        name     The name to use for the tween operation, it is case sensitive and must not collide with other tween names
        tween_callback  The callback function to be invoked when an animation using the named tween function is invoked
Returns
        true on successful registration

Example:        

-- Re-implementated linear tween
local function CustomTweenCB(elapsed, base, change, duration)
  return base + ((change * elapsed) / duration)
end

-- This is called at application initialization to register the custo
-- tween function
function CBRegisterTween(mapargs)
  gre.animation_create_tween("MyTween", CustomTweenCB)
end

-- Create an animation that fades out a layer and uses the custom
-- tween function
function CBAnimation(mapargs)
  local id = gre.animation_create(60)

  local data = {}
  data["rate"] = "MyTween"
  data["duration"] = 2000
  data["offset"] = 0
  data["from"] = 255
  data["to"] = 0
  data["key"] = "MyScreen.MyLayer.grd_alpha"
  gre.animation_add_step(id, data)

  gre.animation_trigger(id)
end
        

gre.touch

gre.touch(
    x ,
    y,
    [channel]
)
            

Send a touch event to the application at the co-ordinates passed in through the parameters.  channel is an optional parameter


Parameters:

        x           The x position to simulate the touch event at
        y           The y position to simulate the touch event at
        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.
Example:
            

gre.key_up

gre.key_up(
    code,
    [channel]
)
            

Send a key_up event to the application with the scancode passed in the parameters. channel is an optional parameter


Parameters:

        code        The utf-8 character code to inject
        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.
Example:
            

gre.key_down

gre.key_down(
    code,
    [channel]
)
            

Send a key_down event to the application with the scancode passed in the parameters. channel is an optional parameter


Parameters:

        code        The utf-8 character code to inject
        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.
Example:
            

gre.key_repeat

gre.key_repeat(
    code,
    [channel]
)
            

Send a key_repeat event to the application with the scancode passed in the parameters. channel is an optional parameter


Parameters:

        code        The utf-8 character code to inject
        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.
Example:
            

gre.redraw

gre.redraw(
    x,
    y,
    width,
    height,
    [channel]
)
            

Force a screen redraw.  channel is an optional parameter. Specifying a x,y,width,height of 0 will result in a full screen refresh occurring.


Parameters:

        x           The x position of the redraw bounding box event
        y           The y position of the redraw bounding box event
        width       The width position of the redraw bounding box event
        height      The height position of the redraw bounding box event
        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.
Example:
            

gre.quit

gre.quit(
    [channel]
)
            

Send QUIT event to application to force shutdown.  channel is an optional parameter.


Parameters:

        channel     An optional Storyboard IO channel to send the event on, if not specified the
                    event is added directly into the current Storyboard application event queue
                    if neither the environment variable or global GREIONAME variable are set.

Example:
            

-- Send a quit message to the application
gre.quit()
            

gre.thread_create

gre.thread_create(func)
		    

This function starts a new operating system thread of execution that is independent from Storyboard's main thread. The function provided as an argument indicates the starting context for this new thread of execution.

The Storyboard data and event (get_data/set_data/send_event) API are thread safe. However the execution of data changes outside of the main thread of execution can have a significant impact on performance of the application and the preferred way of synchronizing data obtained in a thread with the Storyboard UI thread is by using a Storyboard IO event and sending the data via gre.send_event or gre.send_event_data. There are no thread specific synchronization primitives, such as mutexes, for synchronizing Lua data access, serialize to the main thread using an event if this is a requirement.

In scenarios where a controlled shutdown and restart of a Storyboard application is required, separate threads of execution pose a synchronization challenge. In these situations all created thread(s) must have their execution interrupted and terminate in order for a clean shutdown to be observed. This can be accomplished nominally by intercepting the gre.quit event and then taking appropriate action to flag a shutdown variable or send an unblocking event.

This function is not available on all systems and is not available if gre.thread_create is set to nil.


Parameters:
func The Lua function to run in a separate thread of execution from the main UI thread.
Returns:
Nothing

Example:
    

-- Flag to indicate that we want our threads to quit executing
local quit_threads = false

-- Run a poll loop waiting for a file (a_file) to appear and
-- then send an event
function async_function()
	while(not quit_threads) do
		local fp = io.open("a_file")
		if(fp ~= nil) then
			fp:close()
			gre.send_event("file_created")
			return
		end
	end
end

-- Create the monitoring thread of execution
gre.thread_create(async_function)
		    

gre.receive_event

gre.receive_event(
    channel
)
            

Receive an event from a Storyboard IO channel.  This is a blocking call and works best when used on a separate Lua thread.


Parameters:

        channel    A Storyboard IO channel to receive the event on.

Returns:

        event       A table containing the name, target, format and a data table from a received event.

Example:
            

-- Receive a Storyboard IO event with data payload x, y, z:
ev = gre.receive_event("my_channel")

if ev ~= nil then
    print(ev.name)

    for k,v in pairs(ev.data) do
        print(tostring(k).." "..tostring(v))
    end
end

--To disconnect from my_channel:
gre.greio_disconnect("my_channel", true)
            

gre.vfs_open

gre.vfs_open(filename)
		    

This function provides read-only file access to resources packaged in the Storyboard virtual filesystem for embedded targets with no filesystem support. The function works similarly to the Lua io.open() and returns a FILE type object based on a project relative path. The returned object provides the file:read(), file:lines(), file:seek() and file:close() operations as described in the standard Lua documentation.

The use of this function can incur significant memory overhead if large files are read entirely into memory.

This function is not available on all systems and is not available if gre.vfs_open is set as nil.


Parameters:
filename The name of the resource to open as a project relative path (ie translations/french.csv)
Returns:
A file handle that contains readseeklinesclose operations.

Example:
    

-- Use a simple CSV parser that assumes a single delimiter between
-- variable and value
function load_translation()
	local fp = gre.vfs_open("translations/french.csv")
	if(fp ~= nil) then
		local comma, var, value
		for l in fp:lines()
		do
			comma = string.find(l, ',', 0, true)
			if(comma ~= nil)
			then
				var = string.sub(l, 1, comma - 1)
				value = string.sub(l, comma + 1)
				gre.set_data({ [var] = value })
			end
		end
		fp:close()
	end
end
		    

gre.mstime

gre.mstime()
gre.mstime(app_relative)
		    

Retrieve the current time in milliseconds in the default, no argument flavour. This call provides a higher resolution than the standard Lua os.clock()or os.date() functions.

When true is passed in as an argument, then the time returned will be relative to the application start time and aligned with the timestamps that are generated by the Storyboard logging API.


Returns:

        The current time in milliseconds in a system specific manner (gre.mstime()) or the time in milliseconds
        since the start of the application (gre.mstime(true))

Example:
    

-- Time an operation
local s = gre.mstime()
my_function()
local e = gre.mstime()
print("my_function took " .. tostring(e - s) .. "ms")

-- Determine how long from app start to this point
local delta = gre.mstime(true)
print(string.format("Application start to now: %d ms", delta)
		    

gre.env

gre.env(
    string_key
)
or
gre.env(
    table
)
		    

Return information about the Storyboard runtime environment. The input can be either a single string containing the key to look up or a table of keys for variables to match. The following table describes the available keys:

version

The version of this engine as a string value. The format of the string is four version numbers separated by dots: major.minor.service.build.

target_os

The target operating system

target_cpu

The target processor

renderer

The name of the graphics rendering technology being used.

screen_width

The dimensions of the screen width

screen_height

The dimensions of the screen height

active_screen

The name of the currently active screen

render_caps

The rendering capabilities. Currently the only defined capability is "3d" if 3d rendering is supported

mem_stats

Platform memory statistics for the engine. The results are returned as a table of key value pairs with two current keys defined. The key 'process_used' indicates the memory used by the sbengine process. The key 'heap_used' indicates only the heap (malloc) memory used by the sbengine process. Not all rendering engine platforms support all metrics, in which case the value will be set to 0 indicating no information.


Parameters:

Returns:

        If a single string is provided as an input argument, just a single data value for that argument is returned

        If a table is provided as an input argument, then a table with key/value pairs corresponding to the keys
        of the input argument and the results they provide.

Example:
    

-- Get the target OS for dynamic module loading
local os = gre.env("target_os")
print("Running on target OS: " .. tostring(os))

-- Report on the storyboard version and rendering technology
local info = gre.env({"version", "renderer"})
local msg = string.format("Storyboard version %s (%s renderer)",\
            info.version, info.renderer)
print(msg)