Embedding resources in scripts

This article describes how to embed certain texture and model resources within your script. Using this technique allows you to distribute or move your script to different locations without needing to worry about copying any resources along with it.

Embedding a resource involves using the built-in base64 Python module to encode binary data from a file into an ASCII string. During runtime you can decode this string back into the original binary data and create a texture or model from memory.

NOTE: The size of the encoded string will usually be larger than the size of the binary data. So it is only recommended to use this technique to embed small textures and models.

The following code will encode the specified file using the base64 module and output the filename and string:

import viz
import base64

# Name of the file to encode
FILENAME = 'ball.jpg'

print 'Copy the following line into your script:'
print ( FILENAME , base64.b64encode( open(viz.res.getFullPath(FILENAME),'rb').read() ) )

After you run the above code, copy the line it outputs into your script and assign it to a variable. It should look something like this:

image_data = ('ball.jpg', '/9j/4AAQSkZJR...irhTAr//Z\n')

NOTE: The sample code above shows the truncated version of the encoded string. The actual encoded string is much longer and cannot be displayed on this page.

Now when your script runs, you can load the data into a texture by decoding it using the base64 module and passing the decoded binary data to the viz.addTextureFromBuffer command. Here is the code you would use to create a texture object from the encoded data:

import base64

def addEmbeddedTexture(data,**kw):
    """Return texture object from base64 encoded data"""
    return viz.addTextureFromBuffer(data[0],base64.b64decode(data[1]),**kw)

# The encoded binary data
image_data = ('ball.jpg', '/9j/4AAQSkZJR...irhTAr//Z\n')

# Create texture from embedded data
texture = addEmbeddedTexture(image_data)

You can use this same technique to embed models within your script. The only difference is that you would use the viz.addChildFromBuffer command to create a node3d object from the decoded data.

NOTE: Currently only .ive and .osg files can be loaded from a memory buffer

For example, if you encoded the file logo.ive into your script, you would use the following code to create a node3d object from the embedded data:

import base64

def addEmbeddedNode(data,**kw):
    """Return node3d object from base64 encoded data"""
    return viz.addChildFromBuffer(data[0],base64.b64decode(data[1]),**kw)

# The encoded binary data
model_data = ('logo.ive', 'BAMCAREAA...AAAA=\n')

# Create model from embedded data
model = addEmbeddedNode(model_data)