88. opengl.canvas — This implements an OpenGL drawing widget for painting 3D scenes.

88.1. Classes defined in module opengl.canvas

class opengl.canvas.Light(ambient=0.0, diffuse=0.0, specular=0.0, position=[0.0, 0.0, 1.0], enabled=True)[source]

A class representing an OpenGL light.

The light can emit 3 types of light: ambient, diffuse and specular, which can have different color and are all off by default.

class opengl.canvas.LightProfile(ambient, lights)[source]

A lightprofile contains all the lighting parameters.

Currently this consists off: - ambient: the global ambient lighting (currently a float) - lights: a list of 1 to 4 Lights

class opengl.canvas.CanvasSettings(**kargs)[source]

A collection of settings for an OpenGL Canvas.

The canvas settings are a collection of settings and default values affecting the rendering in an individual viewport. There are two type of settings:

  • mode settings are set during the initialization of the canvas and can/should not be changed during the drawing of actors and decorations;
  • default settings can be used as default values but may be changed during the drawing of actors/decorations: they are reset before each individual draw instruction.

Currently the following mode settings are defined:

  • bgmode: the viewport background color mode
  • bgcolor: the viewport background color: a single color or a list of colors (max. 4 are used).
  • bgimage: background image filename
  • slcolor: the highlight color
  • alphablend: boolean (transparency on/off)

The list of default settings includes:

  • fgcolor: the default drawing color
  • bkcolor: the default backface color
  • colormap: the default color map to be used if color is an index
  • bklormap: the default color map to be used if bkcolor is an index
  • smooth: boolean (smooth/flat shading)
  • lighting: boolean (lights on/off)
  • culling: boolean
  • transparency: float (0.0..1.0)
  • avgnormals: boolean
  • wiremode: integer -3..3
  • pointsize: the default size for drawing points
  • marksize: the default size for drawing markers
  • linewidth: the default width for drawing lines

Any of these values can be set in the constructor using a keyword argument. All items that are not set, will get their value from the configuration file(s).


Reset the CanvasSettings to its defaults.

The default values are taken from the configuration files. An optional dictionary may be specified to override (some of) these defaults.

update(d, strict=True)[source]

Update current values with the specified settings

Returns the sanitized update values.

classmethod checkDict(dict, strict=True)[source]

Transform a dict to acceptable settings.


Activate the default canvas settings in the GL machine.

class opengl.canvas.Canvas(settings={})[source]

A canvas for OpenGL rendering.

The Canvas is a class holding all global data of an OpenGL scene rendering. It always contains a Scene with the actors and decorations that are drawn on the canvas. The canvas has a Camera holding the viewing parameters needed to project the scene on the canvas. Settings like colors, line types, rendering mode and the lighting information are gathered in a CanvasSettings object. There are attributes for some special purpose decorations (Triade, Grid) that can not be handled by the standard drawing and Scene changing functions.

The Canvas class does not however contain the viewport size and position. The class is intended as a mixin to be used by some OpenGL widget class that will hold this information (such as the QtCanvas class).

Important note: the Camera object is not initalized by the class initialization. The derived class initialization should therefore explicitely call the initCamera method before trying to draw anything to the canvas. This is because initializing the camera requires a working OpenGL format, which is only established by the derived OpenGL widget.


Return the bbox of all actors in the scene


Return all the settings to their default values.


Set the global ambient lighting for the canvas


Set the default material light properties for the canvas


Change the light parameters


Reset the Drawing options to default values


Set the Drawing options to some values

setRenderMode(mode, lighting=None)[source]

Set the rendering mode.

This sets or changes the rendermode and lighting attributes. If lighting is not specified, it is set depending on the rendermode.

If the canvas has not been initialized, this merely sets the attributes self.rendermode and self.settings.lighting. If the canvas was already initialized (it has a camera), and one of the specified settings is different from the existing, the new mode is set, the canvas is re-initialized according to the newly set mode, and everything is redrawn with the new mode.

setWireMode(state, mode=None)[source]

Set the wire mode.

This toggles the drawing of edges on top of 2D and 3D geometry. State is either True or False, mode is 1, 2 or 3 to switch:

1: all edges 2: feature edges 3: border edges

If no mode is specified, the current wiremode is used. A negative value inverses the state.

setToggle(attr, state)[source]

Set or toggle a boolean settings attribute

Furthermore, if a Canvas method do_ATTR is defined, it will be called with the old and new toggle state as a parameter.

do_wiremode(state, oldstate)[source]

Change the wiremode

do_alphablend(state, oldstate)[source]

Toggle alphablend on/off.

do_lighting(state, oldstate)[source]

Toggle lights on/off.


Set the linewidth for line rendering.

setLineStipple(repeat, pattern)[source]

Set the linestipple for line rendering.


Set the size for point drawing.

setBackground(color=None, image=None)[source]

Set the color(s) and image.

Change the background settings according to the specified parameters and set the canvas background accordingly. Only (and all) the specified parameters get a new value.


  • color: either a single color, a list of two colors or a list of four colors.
  • image: an image to be set.

Create the background object.


Set the default foreground color.


Set the highlight color.

setTriade(pos='lb', siz=100, triade=None)[source]

Set the Triade for this canvas.

Display the Triade on the current viewport. The Triade is a reserved Actor displaying the orientation of the global axes. It has special methods to show/hide it. See also: removeTriade(), hasTriade()


  • pos: string of two characters. The characters define the horizontal (one of ‘l’, ‘c’, or ‘r’) and vertical (one of ‘t’, ‘c’, ‘b’) position on the camera’s viewport. Default is left-bottom.

  • siz: float: intended size (in pixels) of the triade.

  • triade: None or Geometry: defines the Geometry to be used for representing the global axes.

    If None, use the previously set triade, or set a default if no previous.

    If Geometry, use this to represent the axes. To be useful and properly displayed, the Geometry’s bbox should be around [(-1,-1,-1),(1,1,1)]. Drawing attributes may be set on the Geometry to influence the appearance. This allows to fully customize the Triade.


Remove the Triade from the canvas.

Remove the Triade from the current viewport. The Triade is a reserved Actor displaying the orientation of the global axes. It has special methods to draw/undraw it. See also: setTriade(), hasTriade()


Check if the canvas has a Triade displayed.

Return True if the Triade is currently displayed. The Triade is a reserved Actor displaying the orientation of the global axes. See also: setTriade(), removeTriade()


Set the canvas Grid for this canvas.

Display the Grid on the current viewport. The Grid is a 2D grid fixed to the canvas. See also: removeGrid(), hasGrid()


  • grid: None or Actor: The Actor to be displayed as grid. This will normall be a Grid2D Actor.

Remove the Grid from the canvas.

Remove the Grid from the current viewport. The Grid is a 2D grid fixed to the canvas. See also: setGrid(), hasGrid()


Check if the canvas has a Grid displayed.

Return True if the Grid is currently displayed. The Grid is a 2D grid fixed to the canvas. See also: setGrid(), removeGrid()


Clear the canvas to the background color.


_Perform the drawing of a single item


Activate the canvas settings in the GL machine.


Override some settings


Reset the rendering engine.

The rendering machine is initialized according to self.settings: - self.rendermode: one of - self.lighting


Initialize the rendering engine.


Flush all OpenGL commands, making sure the display is updated.

draw_sorted_objects(objects, alphablend)[source]

Draw a list of sorted objects through the fixed pipeline.

If alphablend is True, objects are separated in opaque and transparent ones, and the opaque are drawn first. Inside each group, ordering is preserved. Else, the objects are drawn in the order submitted.


(Re)display all the actors in the scene.

This should e.g. be used when actors are added to the scene, or after changing camera position/orientation or lens.


Set up the canvas for 2D drawing on top of 3D canvas.

The 2D drawing operation should be ended by calling end_2D_drawing. It is assumed that you will not try to change/refresh the normal 3D drawing cycle during this operation.


Cancel the 2D drawing mode initiated by begin_2D_drawing.

setCamera(bbox=None, angles=None, orient='xy')[source]

Sets the camera looking under angles at bbox.

This function sets the camera parameters to view the specified bbox volume from the specified viewing direction.


  • bbox: the bbox of the volume looked at
  • angles: the camera angles specifying the viewing direction. It can also be a string, the key of one of the predefined camera directions

If no angles are specified, the viewing direction remains constant. The scene center (camera focus point), camera distance, fovy and clipping planes are adjusted to make the whole bbox viewed from the specified direction fit into the screen.

If no bbox is specified, the following remain constant: the center of the scene, the camera distance, the lens opening and aspect ratio, the clipping planes. In other words the camera is moving on a spherical surface and keeps focusing on the same point.

If both are specified, then first the scene center is set, then the camera angles, and finally the camera distance.

In the current implementation, the lens fovy and aspect are not changed by this function. Zoom adjusting is performed solely by changing the camera distance.

project(x, y, z, locked=False)[source]

Map the object coordinates (x,y,z) to window coordinates.

unproject(x, y, z, locked=False)[source]

Map the window coordinates (x,y,z) to object coordinates.

zoom(f, dolly=True)[source]

Dolly zooming.

Zooms in with a factor f by moving the camera closer to the scene. This does noet change the camera’s FOV setting. It will change the perspective view though.

zoomRectangle(x0, y0, x1, y1)[source]

Rectangle zooming.

Zooms in/out by changing the area and position of the visible part of the lens. Unlike zoom(), this does not change the perspective view.

x0,y0,x1,y1 are pixel coordinates of the lower left and upper right corners of the area of the lens that will be mapped on the canvas viewport. Specifying values that lead to smaller width/height will zoom in.

zoomCentered(w, h, x=None, y=None)[source]

Rectangle zooming with specified center.

This is like zoomRectangle, but the zoom rectangle is specified by its center and size, which may be more appropriate when using off-center zooming.


Rectangle zoom to make full scene visible.


Save the current OpenGL buffer


Show the saved buffer

add_focus_rectangle(color=(1.0, 0.2, 0.4))[source]

Draw the focus rectangle.

draw_cursor(x, y)[source]

draw the cursor


Set the list of actors inside the pick_window.

pick_parts(obj_type, store_closest=False)[source]

Set the list of actor parts inside the pick_window.

obj_type can be ‘element’, ‘face’, ‘edge’ or ‘point’. ‘face’ and ‘edge’ are only available for Mesh type geometry.

The picked object numbers are stored in self.picked. If store_closest==True, the closest picked object is stored in as a tuple ( [actor,object] ,distance) in self.picked_closest

A list of actors from which can be picked may be given. If so, the resulting keys are indices in this list. By default, the full actor list is used.


Set the list of actor elements inside the pick_window.


Set the list of actor points inside the pick_window.


Set the list of actor edges inside the pick_window.


Set the list of actor faces inside the pick_window.


Return the numbers inside the pick_window.


Highlight a selection of actors on the canvas.

K is Collection of actors as returned by the pick() method. colormap is a list of two colors, for the actors not in, resp. in the Collection K.


Remove a highlight or a list thereof from the 3D scene.

Without argument, removes all highlights from the scene.

88.2. Functions defined in module opengl.canvas


Return a list of the 2nd numbers in the openGL pick buffer.

opengl.canvas.glLineStipple(factor, pattern)[source]

Set the line stipple pattern.

When drawing lines, OpenGl can use a stipple pattern. The stipple is defined by two values: a pattern (on/off) of maximum 16 bits, used on the pixel level, and a multiplier factor for each bit.

If factor <= 0, the stippling is disabled.


Enable smooth shading


Disable smooth shading


Convert On/Off strings to a boolean

opengl.canvas.glEnable(facility, onoff)[source]

Enable/Disable an OpenGL facility, depending on onoff value

facility is an OpenGL facility. onoff can be True or False to enable, resp. disable the facility, or None to leave it unchanged.


Return the current OpenGL Viewport

Returns a tuple x,y,w,h spcifying the position and size of the current OpenGL viewport (in pixels).


Split a dict in canvas settings and other items.

Returns a tuple of two dicts: the first one contains the items that are canvas settings, the second one the rest.