Misc. Classes

class libavg.avg.Bitmap

Bases: Boost.Python.instance

Class representing a rectangular set of pixels in CPU memory. Bitmaps can be obtained from any RasterNode or loaded from disk. For nodes of type ImageNode, the current bitmap can be set as well. In general, huge Bitmaps (e.g. width>65536) are supported as long as they fit into memory.

The layout of the pixels in the bitmap is described by its pixel format. You can receive a complete list of all supported pixel formats by calling avg.getSupportedPixelFormats(). The pixel formats are:

  • B5G6R5: 16 bits per pixel blue, green, red components.
  • B8G8R8: 24 bits per pixel blue, green, red components.
  • B8G8R8A8: 32 bits per pixel: blue, green, red and an alpha (opacity) component.
  • B8G8R8X8: 32 bits per pixel, with the last byte unused.
  • A8B8G8R8
  • X8B8G8R8
  • R5G6B5
  • R8G8B8
  • R8G8B8A8
  • R8G8B8X8
  • A8R8G8B8
  • X8R8G8B8
  • I8: 8 bits of greyscale intensity.
  • I16: 16 bits of greyscale intensity.
  • A8: 8 bits of transparency information.
  • YCbCr411: Interleaved YCbCr: Y Y Cb Y Y Cr. Effectively 12 bits per pixel. Output format of some cameras.
  • YCbCr422: Interleaved YCbCr: Cb Y Cr Y. Effectively 16 bits per pixel. Output format of some cameras.
  • YUYV422: Like YCbCr422, but grey values come first, so the order is Y Cb Y Cr.
  • YCbCr420p: Not a valid pixel format for a single bitmap, but still a description of planar bitmap coding. Signifies separate bitmaps for Y, Cb and Cr components, with Cb and Cr half as big in both x and y dimensions. This is mpeg YCbCr, where the color components have values from 16...235. Used by many video formats, including mpeg.
  • YCbCrJ420p: Same as YCbCr420p, but this is the jpeg version with component values in the range 0...255. Used in video as well, for instance in motion jpeg encoding.
  • YCbCrA420p: YCbCr420p with an additional alpha (transparency) bitmap at full resolution. Used in flash video with transparency.
  • BAYER8: Bayer pattern. This is raw camera sensor data with an unspecified pixel order. The other BAYER_XXX constants specify differing camera sensor arrangements.
  • BAYER8_RGGB
  • BAYER8_GBRG
  • BAYER8_GRBG
  • BAYER8_BGGR
  • R32G32B32A32F: 32 bits per channel float RGBA.
  • I32F: 32 bits per channel greyscale intensity.
__init__(size, pixelFormat, name)

Creates an uninitialized bitmap of the given size and pixel format. name is a name to be used in debug output.

__init__(bitmap)

Creates a copy of an already existing bitmap.

__init__(bitmap, tlPos, brPos)

Returns a rectangle inside an existing bitmap as a new bitmap. Note that the pixels are not copied and write operations will therefore effect the original bitmap as well.

__init__(fileName)

Loads an image file from disk and returns it as bitmap object.

blt(srcBmp, pos)

Copies the pixels of srcBmp into the current bitmap at pos.

getAvg() → float

Returns the average of all bitmap pixels.

getChannelAvg(channel) → float

Returns the average of one of the bitmap color channels (red, green or blue). Used for automatic tests.

getFormat()

Returns the bitmap’s pixel format.

getName() → string
getPixel(pos) -> (r, g, b, a)

Returns one image pixel as a color tuple. This should only be used for single pixels, as it is very slow.

getPixels(copyData = True) → string

Returns the raw pixel data in the bitmap as a python buffer. This method can be used to interface to external libraries such as the python imaging library PIL (http://www.pythonware.com/products/pil/).

Parameters:copyData (bool) – Whether to copy the bitmap data into the returned python buffer or return a view to the memory in the bitmap. Note that the second variant (copyData = False) is dangerous, since referencing the buffer after the bitmap is deleted will cause a crash.
getResized(newSize) → Bitmap

Returns a new bitmap that is a resized version of the original.

getSize() → Point2D

Returns the size of the image in pixels.

getStdDev() → float

Returns the standard deviation of all bitmap pixels.

save(filename)

Writes the image to a file. File format is determined using the extension. Supported file types are those supported by gdk-pixbuf. This includes at least png, jpeg, gif, tiff and xpixmaps.

setPixels(pixels)

Changes the raw pixel data in the bitmap. Doesn’t change dimensions or pixel format. Can be used to interface to the python imaging library PIL (http://www.pythonware.com/products/pil/).

Parameters:pixels (string) – Image data.
subtract(otherbitmap) → bmp

Subtracts two bitmaps and returns the result. Used mainly to compare test images with the intended results (along with getAvg() and getStdDev()).

class libavg.avg.BitmapManager

Bases: Boost.Python.instance

(EXPERIMENTAL) Singleton class that allow an asynchronous load of bitmaps. The instance is accessed by get().

loadBitmap(fileName, callback, pixelformat=NO_PIXELFORMAT)

Asynchronously loads a file into a Bitmap. The provided callback is invoked with a Bitmap instance as argument in case of a successful load or with an avg.Exception instance in case of failure. The optional parameter pixelformat can be used to convert the bitmap to a specific format asynchronously as well.

classmethod get() → BitmapManager

This method gives access to the BitmapManager instance.

setNumThreads(numThreads)

Sets the number of threads used to load bitmaps. The default is a single thread. This should generally be less than the number of logical cores available.

class libavg.avg.Color

Bases: Boost.Python.instance

A color in the rgb colorspace. libavg Colors can be constructed either from tuples or using html-like string syntax. Colors can be animated, and any interpolation between two colors is performed in the CIE-Lch color space for best results (See http://www.stuartdenman.com/improved-color-blending/).

__init__(string)

Constructs a color from a three- or six-character hex code (F80 and FF8800 are equivalent colors).

__init__(r, g, b)

Constructs a color from three channel values in the range 0..255.

__init__((r, g, b))

Constructs a color from an rgb tuple.

r

Red component of the color (ro).

g

Green component of the color (ro).

b

Blue component of the color (ro).

classmethod mix(color1, color2, ratio) → color

Creates a color that is a mix of the two colors passed as parameters.

classmethod fromLch(l, c, h) → color

Creates a color from values in Lch color space.

class libavg.avg.CubicSpline(controlpoints)

Bases: Boost.Python.instance

Class that generates a smooth curve between control points using cubic spline-based interpolation. For an introduction on spline interpolation, see http://en.wikipedia.org/wiki/Spline_interpolation.

Parameters:controlpoints – A list of 2D coordinates. The x coordinates must be in increasing order.
interpolate(x) → y

Takes an x coordinate and delivers a corresponding y coordinate.

class libavg.avg.FontStyle(font="sans", variant="", color="FFFFFF", fontsize=15, indent=0, linespacing=-1, alignment="left", wrapmode="word", justify=False, letterspacing=0, aagamma=1, hint=True)

Bases: libavg.avg.ExportedObject

A FontStyle object encapsulates all configurable font attributes in a WordsNode. It provides a way to set all relevant attributes (font, fontsize, etc.) in one line of code. The attributes correspond to the WordsNode attributes; refer to the WordsNode reference for descriptions.

class libavg.avg.ImageCache

Bases: Boost.Python.instance

libavg’s global two-level cache of images in CPU (general system) and GPU (graphics card) memory. Access this class using the player.cache property. The cache is used for all images loaded from files in textures, including ImageNode images, VectorNode textures and fill textures, and all RasterNode mask textures. Bitmap objects are not cached.

capacity

The capacity of the cache as a tuple (cpu, gpu) in bytes. The capacity can also be set using avgrc. Default CPU capacity is one-quarter of physical RAM, default GPU capacity is 16 megabytes.

getNumImages -> (cpu, gpu)

Returns the number of images loaded.

getMemUsed -> (cpu, gpu)

Returns the number of bytes used by images.

class libavg.avg.Logger

Bases: Boost.Python.instance

An python interface to libavg’s logger. It can be accessed as follows:

import libavg
libavg.logger

Logging

log(message, category, severity)

Logs a message if category is active or severity is at least ERROR.

Parameters:
  • category – One of the categories listed or a custom category. Defaults to Logger.Category.APP.
  • severity – One of the severities listed. Defaults to Logger.Severity.INFO.
  • message – The log message string.
critical(msg, category)

Shortcut to log() with severity= Logger.Severity.CRIT.

error(msg, category)

Shortcut to log() with severity= Logger.Severity.ERR.

warning(msg, category)

Shortcut to log() with severity= Logger.Severity.WARN.

info(msg, category)

Shortcut to log() with severity= Logger.Severity.INFO.

debug(msg, category)

Shortcut to log() with severity= Logger.Severity.DBG.

Configuration

addSink(logger)

Add a python logger object to libavg’s logging handlers. The python logger gets the key category as an “extra” kwarg, useful for formatting the output.

removeSink(logger)

Remove a previously added logger. It will not receive any messages dispatched by the logger annymore. It’s safe to call the function even if the logger is not present.

removeStdLogSink()

Remove libavg console printing sink.

Setting AVG_LOG_OMIT_STDERR as EnvironmentVar has the same effect.

configureCategory(category, severity)

Assign a severity to a given category. category is either a custom string or a Logger.Category severity has to be one of Logger.Severity, or it will default to Logger.Severity.None

getCategories()

Returns a dict with category as key and severity as value

The Logger can also be configured using AVG_LOG_CATEGORIES with the format:

CATEGORY[:SEVERITY] [CATEGORY[:SEVERITY]]...

Thus it is possible to set a severity level for every category. If no severity is given, the default severity is used. (refer to: setDefaultSeverity()) If the category does not exist, it will be created.

export AVG_LOG_CATEGORIES="CONFIG:INFO APP:DBG PROFILE:DBG MEMORY"

Default categories are NONE, APP and DEPREC. They are set to the defaultSeverity.

Categories:

APP
Reserved for application-level messages issued by python code.
CONFIG
Outputs configuration data.
DEPREC
Deprecation Messages that warn of functionality that will be removed from libavg in the future.
EVENTS
Outputs basic event data.
MEMORY
Outputs open/close information whenever a media file is accessed.
NONE
Outputs everything that has not been categorized.
PROFILE
Outputs performance statistics on player termination.
PROFILE_V
Outputs performance statistics for video decoding.
PLUGIN
Messages generated by loading plugins.
PLAYER
General libavg playback messages.
SHADER
Shader compiler messages.
VIDEO
Audio/Video related messages.

Severities

CRIT Critical

ERR Error

WARN Warning

INFO Info

DBG Debug

NONE None

class libavg.avg.Point2D([x, y=(0, 0)])

Bases: Boost.Python.instance

A point in 2D space. Supports most arithmetic operations on vectors. The operators +, -, == and != are defined for two Point2D parameters. Unary - (negation) is defined as well. Point2D objects can also be multiplied and divided by a scalar.

Point2D implicitly converts from and to 2-element float tuples and lists, so in most cases you can use one of these types whenever a point is needed.

x
y
classmethod angle(p1, p2) → float

Returns the angle between the two vectors p1 and p2 in the range 0 and 2*pi, with 0 being the positive x axis. Angles run clockwise.

getAngle() → float

Returns the direction of the vector as an angle between pi and -pi, with 0 being the positive x axis. Angles run clockwise.

getNorm() → float

Returns the euclidian norm of the point, that is sqrt(x*x+y*y).

getNormalized() → Point2D

Returns a normalized version of the point with the same angle but a norm of one. Throws an exception if called on Point2D(0,0).

getRotated(angle) → Point2D

Return the position of point rotated around the origin.

getRotated(angle, pivot) → Point2D

Return the position of point rotated around pivot.

classmethod fromPolar(angle, radius) → Point2D

Converts polar to cartesian coordinates. angle is in radians with 0 being the positive x axis. Angle is clockwise (assuming that y points downward).

isInPolygon(poly) → bool

Checks if the point is inside a polygon.

Parameters:poly – List of points which constitute a polygon to check against.
Returns:True if point is inside, False otherwise.
class libavg.avg.SVG(filename[, unescapeIllustratorIDs=False])

Bases: Boost.Python.instance

SVG objects load and parse an svg file and render images from it. svg (Scalable Vector Graphics, see http://en.wikipedia.org/wiki/Svg) files are xml-based and contain two-dimensional vector graphics. They can be created with editors such as Adobe Illustrator and Inkscape. SVG objects can render elements in the file to bitmaps and create image nodes from elements in the file. Since the files contain vector graphics, the elements can be scaled to any size when rendering without loss of resolution.

Parameters:
  • filename – The name of the file to load.
  • unescapeIllustratorIDs – If this is True, the file is assumed to be generated by Adobe Illustrator. Illustrator mangles element names to create IDs in the svg file. Setting this parameter to True allows these element names to be passed as IDs.
renderElement(elementID[, size | scale=1]) → Bitmap

Renders an element to a Bitmap. Either scale or size may be given. size is the size of the bitmap. scale is a factor to scale the native bitmap size with.

createImageNode(elementID, nodeAttrs[, size | scale=1]) → Node

Convenience method that calls renderElement() to render a bitmap and then creates an image node that displays that bitmap. nodeAttrs is a dictionary containing constructor parameters for the node.

getElementPos(elementID) → Point2D

Returns the position of an element.

getElementSize(elementID) → Point2D

Returns the original size of an element.

class libavg.avg.TestHelper

Bases: Boost.Python.instance

Miscellaneous routines used by tests. Not intended for normal application usage.

class libavg.avg.VersionInfo

Bases: Boost.Python.instance

Exposes version data, including the specs of the builder.

full

Full string containing a compact form of branch and revision number (if the build doesn’t come from an exported tree)

release

String representation in the form major.minor.micro

major

Integer component of the release version (major)

minor

Integer component of the release version (minor)

micro

Integer component of the release version (micro)

revision

Revision number, if applicable, or 0

branchurl

Full URL path that represents the branch root, if applicable, or empty string

builder

String representation in the form of user@hostname machinespecs

buildtime

ISO timestamp representation of the build

class libavg.avg.VideoWriter(canvas, filename[, framerate=30, qmin=3, qmax=5, synctoplayback=True])

Bases: Boost.Python.instance

Class that writes the contents of a canvas to disk as a video file. The videos are written as motion jpeg-encoded mov files. Writing commences immediately upon object construction and continues until stop() is called. pause() and play() can be used to pause and resume writing.

The VideoWriter is built for high performance: Opening, writing and closing the video file is asynchronous to normal playback. Writing full HD videos of offscreen canvasses to disk should cost virtually no time on the main thread of execution for an Intel Core-class processor with a graphics card that supports shaders.

Parameters:canvas – A libavg canvas used as source of the video.
filename

The name of the file to write to. Read-only.

framerate

The speed of the encoded video in frames per second. This is used for two purposes. First, it determines the nominal playback speed of the video that is encoded in the file. Second, if synctoplayback is False, the VideoWriter will also use the framerate value as the actual number of frames per second to write. Read-only.

qmin
qmax

qmin and qmax specify the minimum and maximum encoding quality to use. qmin = qmax = 1 give maximum quality at maximum file size. qmin=3 and qmax=5 (the default) give a good quality and a smaller file. Read-only.

synctoplayback

If synctoplayback is True (the default), each frame played back in the canvas will be written to disk. This makes a lot of sense in combination with Canvas.registerCameraNode(). If not, framerate is used to determine which frames to write to disk. For instance, if synctoplayback is False, framerate is 25 and the player is running at 60 fps, one movie frame will be written for each 2.5 frames of playback. The actual, not the nominal playback speed is used in this case. Read-only.

pause()

Temporarily stops recording.

play()

Resumes recording after a call to pause(). play() doesn’t need to be called after construction of the VideoWriter - writing commences immediately.

stop()

Ends the recording and writes the rest of the file to disk. Note that this is asynchronous to normal playback. If you need to immediately re-open the video file (e.g. for playback in a video node), destroy the python object first. This waits for sync.

libavg.avg.validateXml(xmlString, schemaString, xmlName, schemaName)

Validates an xml string using a schema. Throws an exception if the xml doesn’t conform to the schema.

class libavg.statemachine.StateMachine(name, startState)

Bases: object

A generic state machine, useful for user interface and other states. Consists of a set of states (represented by strings) and possible transitions between the states. The StateMachine can be configured to invoke callbacks at specific transitions and when entering or leaving a state. All callbacks are optional. State changes can be logged for debugging purposes.

State machines are initialized by calling addState() for each possible state after constructing it.

Parameters:
  • name (String) – A name for the state machine to be used in debugging output.
  • startState (String) –
state

The current state the StateMachine is in. States are strings.

addState(state, transitions[, enterFunc=None, leaveFunc=None])

Adds a state to the StateMachine. Must be called before the first changeState.

Parameters:
  • state (String) – The name of the state to add.
  • transitions – This parameter can be either a list of destination states or a dict of destinationState: callable pairs. The callables are invoked whenever the corresponding state change happens. If transitions() is a list, no state change callbacks are registered.
  • enterFunc – A callable to invoke whenever the state is entered.
  • leaveFunc – A callable to invoke whenever the state is left.
changeState(newState)

Changes the state. This includes calling the leave callback for the current state, actually changing the state, calling the transition callback and calling the enter callback for the new state.

Raises a avg.Exception if newState is not a valid state or if there is no transition defined from the current state to newState.

dump()

Prints all states and transitions to the console.

makeDiagram(imageFName[, showMethods=False])

Dumps a graph of the state machine to an image file using dot. graphviz must be installed and in the path for this to work. Very useful for debugging. If showMethods is true, names of enter, leave and transition methods are included in the diagram.

traceChanges(trace)

If trace is set to True, all state changes are dumped to the console.

class libavg.persist.Persist(storeFile, initialData[, validator=lambda v: True, autoCommit=False])

Bases: object

A general purpose persistent object. Its state is defined in the data attribute and pickled from/to a store file.

Parameters:
  • storeFile (string) – Full path of the store file that is used to store and retrieve a serialized version of the data.
  • initialData – A pickle-able object that is assigned to the data attribute when no file store exists or when the store file is corrupted.
  • validator (callable) – An optional callable that receives the object state as soon it’s de-pickled from the store file. If the validator call doesn’t return True, the object state is restored to the provided initialData.
  • autoCommit (bool) – If True, the commit method is registered as an atexit function.
data

State of the persistent object.

storeFile

Returns the full path of the store file.

commit()

Dumps the contents of the data attribute to the store file.

class libavg.persist.UserPersistentData(appName, fileName, initialData[, validator=lambda v: True, autoCommit=False])

Bases: libavg.persist.Persist

A Persist subclass that sets up an OS-independent path for the store file. Under posix-compliant OSes is $HOME/.avg/<appName>/<fileName>.pkl Under Windows is %APPDATA%Avg<appName>/<fileName>.pkl

Parameters:
  • appName (string) – Name of the application. This string is used to compose the full path to the file store and it creates a namespace (directory) for multiple files for the same application.
  • fileName (string) – Name of the file store file. .pkl will be added as extension.
class libavg.sprites.Spritesheet(dataFName)

Bases: object

A sprite sheet is a collection of (possibly animated) images all loaded from one large image file (the ‘atlas’). A sample can be found at src/samples/sprite.py.

Parameters:dataFName (string) – Name of an xml file that stores sprite information such as the name of the aggregate image and the locations of the individual sprites in the atlas. libavg expects files in Starling format.
class libavg.sprites.Sprite(spritesheet, spriteName)

Bases: libavg.avg.DivNode

A single-image sprite generated from a sprite sheet.

Parameters:spriteName (string) – Name of the entry in the data file that specifies where in the atlas the sprite is located.
class libavg.sprites.AnimatedSprite(spritesheet, spriteName[, loop=False, fps=30])

Bases: libavg.sprites.Sprite

A multi-frame sprite generated from a sprite sheet. An AnimatedSprite can be used like a small high-performance video, with playback, pause and seek functionality.

Parameters:spriteName (string) – Prefix string for the data file entries that correspond to the individual sprite frames. Any entries that consist of this prefix followed by numbers digits are added to this sprite.
curFrameNum

Number of the frame currently shown. To display a different frane, set this attribute.

fps

Speed in frames per second that the sprite should use for playback.

loop

True if the sprite should loop endlessly, False otherwise.

numFrames

Number of frames in the sprite. Read-only.

play()

Starts playback.

pause()

Stops playback.