High Level Python API

The terragen_rpc module provides a Python API for making remote procedure calls to Terragen. It is intended to be a high level wrapper that lets you code stuff without thinking about TCP sockets or the JSON-RPC protocol.

Example usage:

import terragen_rpc as tg

# Print the nodes at the top level of the project

project = tg.root()
children = project.children()
for c in children:
    print(c.path())

# Print the parameters of a node whose path is "/Render Camera"

camera = tg.node_by_path('/Render Camera')
if camera:
    print(camera.param_names())
else:
    print("Node not found")

# Note: Exception handling was omitted from this example for brevity.
# See other examples for exception handling.

Note

For more detailed information about exception handling, jump to Exceptions/Errors.

Module: terragen_rpc

Changes

  • 0.9.0:

    • class Node replaces str for node IDs.

    • added member functions to Node: name, path, parent_path, parent, children, children_filtered_by_class, param_names, get_param_as_string, get_param_as_int, get_param_as_float, get_param_as_tuple, get_param_as_list, set_param, set_param_from_string.

    • removed free functions: get_param_as_int, get_param_as_float, get_param_as_tuple, get_param_as_list, set_param.

    • deprecated free functions: name, path, parent_path, parent, children, children_filtered_by_class, param_names, get_param_as_string, set_param_as_string, toggle_enable_node.

  • 0.8.0:

    • renamed name_and_path to path

    • implemented parent_path

    • implemented insert_clip_file

    • implemented insert_clip_file_after

    • implemented insert_clip_file_before

    • implemented get_param_as_int

    • implemented get_param_as_float

    • implemented get_param_as_tuple

    • implemented get_param_as_list

    • implemented set_param

    • delete accepts a node ID or a list of node IDs

    • The server-side methods ‘name_and_path’, ‘select_one_more’ and ‘select_more_as_array’ are deprecated, superseded by ‘path’ and ‘select_more’. This Python module’s methods continue to use the deprecated server-side methods for compatibility with servers 0.7.x and 0.8.x.

  • 0.7.0:

    • Implemented current_selection

    • Implemented select_just

    • Implemented select_more

    • Implemented select_none

    • create_child returns a node ID or None

    • open_project returns True or False

    • save_project returns True or False

  • 0.6.0:

    • We recommend that you catch TimeoutError.

    • TimeoutError is raised by impl.send_string() if a socket timeout occurs. It does this in case the version of Python being used doesn’t make socket.timeout an alias for TimeoutError.

Todo

  • Make operations safe on invalid and deleted node ids.

  • Perhaps(?) accept nodepaths anywhere a node id is accepted.

  • More functions that take lists as parameters, avoiding loops of RPC calls.

  • Functions that return more info about node parameters, such as type, or compound data including name, type and value.

terragen_rpc.high.project_filepath()

Get the file path and filename of the current project.

Returns

A string which is a file path.

Return type

str

terragen_rpc.high.root()

Get the root node of the current project.

Return type

Node | None

terragen_rpc.high.node_by_path(path)

Find a node by its path in the hierarchy.

Parameters

path (str) – Should begin with a forward slash.

Returns

A node ID if it was found, or None if it was not found.

Return type

Node | None

terragen_rpc.high.create_child(of_node, class_name)

Attempt to create a node as a child of an existing node.

Warning

If the class is an object file reader (e.g. ‘obj_reader’ or ‘tgo_reader’) a file dialog will appear and execution will be blocked until the dialog is closed. This will be fixed in the final version.

When loading a file into a newly created obj_reader, the only way to automatically set up shaders is respond to the file dialog at creation time. Setting the filename after the node is created will not set up shaders. This problem will be fixed in the final version.

Parameters
  • of_node (Node) – The ID of an existing node that will contain (be the parent of) the new node. To add to the top level of the project, use root().

  • class_name (str) – A node class. For example ‘group’, ‘camera’, ‘sunlight’, ‘render’, ‘obj_reader’, ‘image_map_shader’ etc. You can discover the class of a node by looking at the XML used to represent the node on the clipboard or in a TGC or TGD file. The class is the same as the XML element name.

Returns

The ID of the new node if it was successfully created, otherwise None.

Return type

Node | None

terragen_rpc.high.delete(node_or_nodes)

Delete node(s).

Parameters

node_or_nodes (Node | list of Node) –

terragen_rpc.high.current_selection()

Get a list of the nodes that are currently selected in the UI.

Returns

A list of node IDs. The order of the list is undefined. Do not expect the order to correspond to the order in which the nodes were selected.

Return type

list of Node

terragen_rpc.high.select_just(node_or_nodes)

Select node(s) in the UI by path, replacing the initial selection state.

Parameters

node_or_nodes (Node | list of Node) – A node ID or a list of node IDs

terragen_rpc.high.select_more(node_or_nodes)

Select additional node(s) in the UI by path, adding to the current selection state.

Parameters

node_or_nodes (Node | list of Node) – A node ID or a list of node IDs

terragen_rpc.high.select_none()

Clear the node selection state in the UI.

terragen_rpc.high.new_project()

Close the current project without saving, and start a new project.

terragen_rpc.high.open_project(filename)

Close the current project without saving, and open a project file.

Parameters

filename (str) –

Returns

True if the method succeeds, otherwise False.

Return type

bool

Note

Failure to open the project does not raise an exception, because success can be determined from the return value. Should we raise an exception instead of returning False?

terragen_rpc.high.save_project(filename)

Save the project as ‘filename’.

Parameters

filename (str) –

Returns

True if the method succeeds, otherwise False.

Return type

bool

Note

Failure to save the project does not raise an exception, because success can be determined from the return value. Should we raise an exception instead of returning False?

terragen_rpc.high.insert_clip_file(filename)

Load a clip file into the project. This is similar to choosing “Insert Clip File…” from the File menu and clicking “Add”, not “Insert”.

Inserting nodes from a clip file may cause the node selection state to change. Typically the new nodes are selected and everything else is deselected, but this is at the discretion of the server.

Parameters

filename (str) –

Returns

True if the method succeeds, otherwise False.

Return type

bool

Note

Failure to open the file does not raise an exception, because success can be determined from the return value. Should we raise an exception instead of returning False?

Todo

Implement auto_connect, the option of trying to auto-connect it into the node graph using metadata in the file and/or other heuristics on the server.

See also

insert_clip_file_after, insert_clip_file_before

terragen_rpc.high.insert_clip_file_after(filename, input_node)

Load a clip file into the project, and connect it into the node graph so that input_node will become its main input and the inserted nodes will output to whatever downstream connection(s) input_node was previously outputting to.

  • Pre-state: input_node =>> downstream(s)

  • Post-state: input_node -> INSERTED_NODES =>> downstream(s)

This is similar to what happens when the user context-clicks on the body of a node and chooses “Insert Clip File…” from the node context menu.

Inserting nodes from a clip file may cause the node selection state to change. Typically the new nodes are selected and everything else is deselected, but this is at the discretion of the server.

Parameters
  • filename (str) –

  • input_node (Node) – The ID of an existing node.

Returns

True if the method succeeds, otherwise False. The method will do nothing but return False if input_node is not valid.

Return type

bool

Note

Failure to open the file does not raise an exception, because success can be determined from the return value. Should we raise an exception instead of returning False?

See also

insert_clip_file, insert_clip_file_before

terragen_rpc.high.insert_clip_file_before(filename, output_node, output_param='input_node')

Load a clip file into the project, and connect it into the node graph so that the inserted nodes will output to output_param @ output_node, and whatever node was the previous input to output_param @ output_node will become the main input to the inserted nodes.

  • Pre-state: upstream -> output_node

  • Post-state: upstream -> INSERTED_NODES -> output_node

This is similar to what happens when the user context-clicks on an input port of a node and chooses “Insert Clip File…” from the connection context menu.

Inserting nodes from a clip file may cause the node selection state to change. Typically the new nodes are selected and everything else is deselected, but this is at the discretion of the server.

Parameters
  • filename (str) –

  • output_node (Node) – The ID of an existing node.

  • output_param (str) – The parameter name for an input port on output_node. Defaults to ‘input_node’ (the node’s main input port), but can be any parameter of output_node that is a node link parameter.

Returns

True if the method succeeds, otherwise False. The method will do nothing but return False if output_node is not valid or does not have a port named output_param.

Return type

bool

Note

Failure to open the file does not raise an exception, because success can be determined from the return value. Should we raise an exception instead of returning False?

See also

insert_clip_file, insert_clip_file_after

class terragen_rpc.high.Node(id)

A node ID.

name()

Get the name of the node.

Returns

The name of the node.

Return type

str

path()

Get the full path in the hierarchy if the node has a parent, or just the name of the node if is parentless (e.g. the project root node or an out-of-hierarchy node).

Returns

A string which is the full path of the node. If the node has a parent, the path starts with a forward slash and ends with the name of the node. If the node is has no parent (e.g. it’s the root node or an out-of-hierarchy node), the path is just the name of the node.

Return type

str

parent_path()

Get the path of the node’s parent in the hierarchy.

Returns

A string which is the path of the node’s parent

Return type

str

parent()

Get the parent node.

Return type

Node | None

children()

Get the children as a list of node IDs.

Returns

A list of IDs of the node’s children.

Return type

list of Node

children_filtered_by_class(class_name)

Get a list of nodes of a particular class.

Parameters

class_name (str) – A node class to match. For example ‘group’, ‘camera’, ‘sunlight’, ‘render’, ‘obj_reader’, ‘image_map_shader’ etc. You can discover the class of a node by looking at the XML used to represent the node on the clipboard or in a TGC or TGD file. The class is the same as the XML element name.

Returns

A list of IDs of the node’s children that match the class_name.

Return type

list of Node

param_names()

Get a list of the node’s parameters.

Returns

A list of names of the node’s parameters.

Return type

list of str

get_param(param_name)

Get a parameter’s value, which may be a string, number or list of numbers.

Todo

To be implemented. Currently returns the same as get_param_as_string.

get_param_as_string(param_name)

Get a string representation of a parameter’s current value.

Parameters

param_name (str) – A parameter name

Returns

A string representation of the parameter value. For 2D vectors, 3D vectors and colours, the string contains numbers separated by spaces without any leading or trailing whitespace.

Return type

str

Todo

What if the param_name is invalid?

get_param_as_int(param_name)

Get a parameter’s value as an integer.

Parameters

param_name (str) – A parameter name

Return type

int

Todo

What if the param_name is invalid?

get_param_as_float(param_name)

Get a parameter’s value as a float.

Parameters

param_name (str) – A parameter name

Return type

float

Todo

What if the param_name is invalid?

get_param_as_tuple(param_name)

Get a parameter’s value as a tuple of 1, 2, or 3 floats.

Parameters

param_name (str) – A parameter name

Returns

A tuple of the parameter’s component values.

Return type

tuple of float

Todo

What if the param_name is invalid?

get_param_as_list(param_name)

Get a parameter’s value as a list of 1, 2, or 3 floats.

Parameters

param_name (str) – A parameter name

Returns

A list of the parameter’s component values.

Return type

list of float

Todo

What if the param_name is invalid?

set_param(param_name, values)

Set a parameter’s value using a string, number, tuple of numbers or list of numbers.

Parameters
  • param_name (str) – A parameter name

  • values (str | number | tuple of numbers | list of numbers) – If the type is tuple or list, it is converted to a string representation of the value and set_param_from_string is called. Other types are cast to str using str() and set_param_from_string is called.

Todo

What if the param_name is invalid?

set_param_from_string(param_name, value_string)

Set a parameter’s value using a string representation which follows the same rules used by Terragen XML files.

Parameters
  • param_name (str) – A parameter name

  • value_string (str) – A string representation of the parameter value. For 2D vectors, 3D vectors and colours, the string must contain numbers separated by spaces.

Todo

What if the param_name is invalid?

terragen_rpc.high.parent(of_node)

DEPRECATED. Get the parent node of a node.

Returns

A string which is the path of the node’s parent

Return type

str

See also

Node.parent

terragen_rpc.high.children(of_node)

DEPRECATED. Get the children of a node as a list of node IDs.

Returns

A list of IDs of the node’s children.

Return type

list of Node

See also

Node.children

terragen_rpc.high.children_filtered_by_class(of_node, class_name)

DEPRECATED. Get a list of nodes of a particular class.

Returns

A list of IDs of the node’s children that match the class_name.

Return type

list of Node

See also

Node.children_filtered_by_class

terragen_rpc.high.name(of_node)

DEPRECATED. Get the name of a node.

Returns

The name of the node.

Return type

str

See also

Node.name

terragen_rpc.high.path(of_node)

DEPRECATED. Get the full path in the hierarchy for a node that has a parent, or just the name of a node if is parentless (e.g. the project root node or an out-of-hierarchy node).

Returns

A string which is the full path of the node. If the node has a parent, the path starts with a forward slash and ends with the name of the node. If the node is has no parent (e.g. it’s the root node or an out-of-hierarchy node), the path is just the name of the node.

Return type

str

See also

Node.path

terragen_rpc.high.parent_path(of_node)

DEPRECATED. Get the path of the node’s parent in the hierarchy.

Returns

A string which is the path of the node’s parent.

Return type

str

See also

Node.parent_path

terragen_rpc.high.param_names(of_node)

DEPRECATED. Get a list of the node’s parameters.

Returns

A list of names of the node’s parameters.

Return type

list of str

See also

Node.param_names

terragen_rpc.high.get_param_as_string(node, param_name)

DEPRECATED. Get a string representation of a parameter’s current value.

Returns

A string representation of the parameter value. For 2D vectors, 3D vectors and colours, the string contains numbers separated by spaces without any leading or trailing whitespace.

Return type

str

See also

Node.get_param_as_string

terragen_rpc.high.set_param_from_string(node, param_name, value_string)

DEPRECATED. Set a parameter’s value using a string representation which follows the same rules used by Terragen XML files.

Parameters
  • node (Node) – A node ID

  • param_name (str) – A parameter name

  • value_string (str) – A string representation of the parameter value. For 2D vectors, 3D vectors and colours, the string must contain numbers separated by spaces.

See also

Node.set_param_from_string

terragen_rpc.high.toggle_enable_node(node)

DEPRECATED. Toggle the enabled/disabled parameter of a node if it has one.

Parameters

node (Node) – A node ID

Note

To enable or disable a node whose status you do not know, instead of this function use: node.set_param_from_string(‘enable’, ‘1’) or node.set_param_from_string(‘enable’, ‘0’)

Exceptions/Errors

We think that in production it’s appropriate to handle at least ConnectionError and TimeoutError (the built-in Python exceptions) and terragen_rpc.ReplyError. These indicate issues that might be resolvable by the user at runtime, for example by restarting the server (Terragen) or resolving a network issue. A handler for these exceptions should give the user the opportunity to resolve them.

These and other exceptions are documented below.

Example:

import terragen_rpc as tg
import traceback

try:
    project = tg.root()
    # etc...

except ConnectionError as e:
    # A built-in Python exception raised by the socket.
    # This probably means that Terragen isn't running or
    # there is a misconfiguration in Terragen or this client.
    print("Terragen RPC connection error: " + str(e))
    # Extra handling here...
    # ...
except TimeoutError as e:
    # A built-in Python exception raised either by the socket
    # or by this module when a socket timeout occurs.
    # This could mean that the current instance of Terragen failed
    # to respond or that a previous instance has crashed without
    # properly closing the socket.
    print("Terragen RPC timeout error: " + str(e))
    # Extra handling here...
    # ...
except tg.ReplyError as e:
    # The server responded, but the data it returned could not be parsed.
    print("Terragen RPC server reply error: " + str(e))
    # Extra handling here...
    # ...
except tg.ApiError:
    # The server responded indicating that there was an API misuse. If
    # using the High Level API this probably means the server is running
    # a version of the API that is incompatible with this particular call.
    # Exception subclasses include ApiMethodNotFound and ApiInvalidParams.
    print("Terragen RPC API error")
    # Extra handling here...
    # Let's print something useful for debugging.
    print(traceback.format_exc()) # requires import traceback
    # The program continues running after this.

Base Class

exception terragen_rpc.Error(reply, msg='')

Base class for exceptions raised when an RPC call fails after making a successful connection.

Has subclasses including ReplyError, ApiError and LowLevelError.

reply

The Reply object being created when the exception was raised.

Type

Reply

Main Exceptions

exception terragen_rpc.ReplyError(reply, msg='Terragen RPC server responded with data that cannot be parsed.')

An exception raised when the server responds with data that could not be parsed. We recommend that you catch and handle this exception.

A subclass of Error.

reply

The Reply object being created when the exception was raised.

Type

Reply

exception terragen_rpc.ApiError(reply)

An exception raised when the reply from the server contains an error code that suggests an API mismatch between client and server or an incorrect use of the API. We recommend that you catch and handle this exception.

A subclass of Error.

Has subclasses including ApiInvalidParams and ApiMethodNotFound.

reply

The Reply object being created when the exception was raised.

Type

Reply

exception terragen_rpc.LowLevelError(reply)

An exception raised when the reply from the server contains an error code that suggests a problem with its implementation, or when this module encounters an internal error.

A subclass of Error.

Has subclasses including LowLevelParseError, LowLevelInvalidRequest, LowLevelInternalError and LowLevelServerError.

reply

The Reply object being created when the exception was raised.

Type

Reply

More Detailed Error Handling

More exception subclasses and the Reply class are documented in Low Level API Exceptions.