Table Of Contents

Previous topic


Next topic


This Page

Quick links



Rift([fovType, trackingOriginType, …]) Class provides a display and peripheral interface for the Oculus Rift (see: head-mounted display.
Rift.productName Get the HMD’s product name.
Rift.manufacturer Get the connected HMD’s manufacturer.
Rift.serialNumber Get the connected HMD’s unique serial number.
Rift.firmwareVersion Get the firmware version of the active HMD.
Rift.resolution Get the HMD’s raster display size.
Rift.displayRefreshRate Get the HMD’s display refresh rate.


class psychopy.visual.Rift(fovType='recommended', trackingOriginType='eye', texelsPerPixel=1.0, headLocked=False, highQuality=True, nearClip=0.1, farClip=100.0, monoscopic=False, samples=1, mirrorRes=None, legacyOpenGL=True, warnAppFrameDropped=True, *args, **kwargs)

Class provides a display and peripheral interface for the Oculus Rift (see: head-mounted display.

fovType : str
Field-of-view (FOV) configuration type. Using ‘recommended’ auto-configures the FOV using the recommended parameters computed by the runtime. Using ‘symmetric’ forces a symmetric FOV using optimal parameters from the SDK.
trackingOriginType : str
Specify the HMD origin type. If ‘floor’, the height of the user is added to the head tracker by LibOVR.
texelsPerPixel : float
Texture pixels per display pixel at FOV center. A value of 1.0 results in 1:1 mapping. A fractional value results in a lower resolution draw buffer which may increase performance.
headLocked : bool
Lock the head position to the world origin. This cancels out any translation and rotation from the headset. Note, hand poses are NOT transformed accordingly (this will be addressed eventually).
highQuality : bool
Configure the compositor to use anisotropic texture sampling (4x). This reduces aliasing artifacts resulting from high frequency details particularly in the periphery.
nearClip : float
Location of the near clipping plane in GL units (meters by default) from the viewer.
farClip : float
Location of the far clipping plane in GL units (meters by default) from the viewer.
monoscopic : bool
Enable monoscopic rendering mode which presents the same image to both eyes. Eye poses used will be both centered at the HMD origin. Monoscopic mode uses a separate rendering pipeline which reduces VRAM usage. When in monoscopic mode, you do not need to call ‘setBuffer’ prior to rendering (doing so will do have no effect).
samples : int
Specify the number of samples for anti-aliasing. When >1, multi-sampling logic is enabled in the rendering pipeline. If ‘max’ is specified, the largest number of samples supported by the platform is used. If floating point textures are used, MSAA sampling is disabled. Must be power of two value.
legacyOpenGL : bool
Disable ‘immediate mode’ OpenGL calls in the rendering pipeline. Specifying False maintains compatibility with existing PsychoPy stimuli drawing routines. Use True when computing transformations using some other method and supplying shaders matrices directly.
mirrorRes: list of int
Resolution of the mirror texture. If None, the resolution will match the window size.
warnAppFrameDropped : bool
Log a warning if the application drops a frame. This occurs when the application fails to submit a frame to the compositor on-time. Application frame drops can have many causes, such as running routines in your application loop that take too long to complete. However, frame drops can happen sporadically due to driver bugs and running background processes (such as Windows Update). Use the performance HUD to help diagnose the causes of frame drops.

Get the absolute time for this frame.

callOnFlip(function, *args, **kwargs)

Call a function immediately after the next .flip() command.

The first argument should be the function to call, the following args should be used exactly as you would for your normal call to the function (can use ordered arguments or keyword arguments as normal).

e.g. If you have a function that you would normally call like this:

pingMyDevice(portToPing, channel=2, level=0)

then you could call callOnFlip() to have the function call synchronized with the frame flip like this:

win.callOnFlip(pingMyDevice, portToPing, channel=2, level=0)

Clear the back buffer (to which you are currently drawing) without flipping the window. Useful if you want to generate movie sequences from the back buffer without actually taking the time to flip the window.


Close the window (and reset the Bits++ if necess).


Set the color of the window.

NB This command sets the color that the blank screen will have on the next clear operation. As a result it effectively takes TWO flip() operations to become visible (the first uses the color to create the new screen, the second presents that screen to the viewer). For this reason, if you want to changed background color of the window “on the fly”, it might be a better idea to draw a visual.Rect that fills the whole window with the desired Rect.fillColor attribute. That’ll show up on first flip.

See other stimuli (e.g. GratingStim.color) for more info on the color attribute which essentially works the same on all PsychoPy stimuli.

See Color spaces for further information about the ways to specify colors and their various implications.


string. (Documentation for colorSpace is in the stimuli.)

e.g. GratingStim.colorSpace.

Usually used in conjunction with color like this:

win.colorSpace = 'rgb255'  # changes colorSpace but not
                           # the value of win.color
win.color = [0, 0, 255]    # clear blue in rgb255

See Color spaces for further information about the ways to specify colors and their various implications.


Check if a given device is connected to the Haptics engine.

controller : str
Name of the controller to check if connected.
True if specified controller connected, else False.
classmethod dispatchAllWindowEvents()

Dispatches events for all pyglet windows. Used by iohub 2.0 psychopy kb event integration.


Get the HMD’s display refresh rate. This rate is independent of the monitor display rate.

Refresh rate in Hz.

Get the firmware version of the active HMD. Returns a tuple containing the major and minor version.

tuple (int, int)
Firmware major and minor version.

Flip the front and back buffers after drawing everything for your frame. (This replaces the win.update() method, better reflecting what is happening underneath).

win.flip(clearBuffer=True) # results in a clear screen after flipping win.flip(clearBuffer=False) # the screen is not cleared (so represent

# the previous screen)
clearBuffer : boolean
Clear the frame after flipping.



Report the frames per second since the last call to this function (or since the window was created if this is first call)


Set whether fullscreen mode is True or False (not all backends can toggle an open window)


Set the monitor gamma for linearization

(don’t use this if using a Bits++ or Bits#) Overrides monitor settings.

getActualFrameRate(nIdentical=10, nMaxFrames=100, nWarmUpFrames=10, threshold=1)

Measures the actual fps for the screen.

This is done by waiting (for a max of nMaxFrames) until [nIdentical] frames in a row have identical frame times (std dev below [threshold] ms).

If there is no such sequence of identical frames a warning is logged and None will be returned.


the number of consecutive frames that will be evaluated. Higher –> greater precision. Lower –> faster.


the maximum number of frames to wait for a matching set of nIdentical


the number of frames to display before starting the test (this is in place to allow the system to settle after opening the Window for the first time.


the threshold for the std deviation (in ms) before the set are considered a match

getButtons(button_names, controller='xbox', edge_trigger='continuous')

Returns True if any of the buttons in button_list are held down. All buttons are ORed together and tested. Edge triggering can be enabled by specifying either ‘rising’ or ‘falling’ to edge_trigger. When enabled, True is returned only when a button’s state changes. If button_list is empty, will return True when no buttons are pressed.



Get a list of connected input devices (controllers) managed by the LibOVR runtime.

List of connected controller names.
getHandTriggerValues(controller='xbox', deadzone=False)

Get the values of the hand triggers representing the amount they are being displaced.

controller : str
Name of the controller to get hand trigger values.
deadzone : bool
Apply the deadzone to hand trigger values.
Left and right index trigger values.
getIndexTriggerValues(controller='xbox', deadzone=False)

Get the values of the index triggers representing the amount they are being displaced.

controller : str
Name of the controller to get index trigger values.
deadzone : bool
Apply the deadzone to index trigger values.
Left and right index trigger values.

Capture the current Window as an image.

Saves to stack for saveMovieFrames(). As of v1.81.00 this also returns the frame as a PIL image

This can be done at any time (usually after a .flip() command).

Frames are stored in memory until a .saveMovieFrames(filename) command is issued. You can issue getMovieFrame() as often as you like and then save them all in one go when finished.

The back buffer will return the frame that hasn’t yet been ‘flipped’ to be visible on screen but has the advantage that the mouse and any other overlapping windows won’t get in the way.

The default front buffer is to be called immediately after a win.flip() and gives a complete copy of the screen at the window’s coordinates.

getMsPerFrame(nFrames=60, showVisual=False, msg='', msDelay=0.0)

Assesses the monitor refresh rate (average, median, SD) under current conditions, over at least 60 frames.

Records time for each refresh (frame) for n frames (at least 60), while displaying an optional visual. The visual is just eye-candy to show that something is happening when assessing many frames. You can also give it text to display instead of a visual, e.g., msg=’(testing refresh rate…)’; setting msg implies showVisual == False.

To simulate refresh rate under cpu load, you can specify a time to wait within the loop prior to doing the win.flip(). If 0 < msDelay < 100, wait for that long in ms.

Returns timing stats (in ms) of:

  • average time per frame, for all frames
  • standard deviation of all frames
  • median, as the average of 12 frame times around the median (~monitor refresh rate)
  • 2010 written by Jeremy Gray
getThumbstickValues(controller='xbox', deadzone=False)

Get a list of tuples containing the displacement values (with deadzone) for each thumbstick on a specified controller.

Axis displacements are represented in each tuple by a floats ranging from -1.0 (full left/down) to 1.0 (full right/up). The SDK library pre-filters stick input to apply a dead-zone where 0.0 will be returned if the sticks return a displacement within -0.2746 to 0.2746. Index 0 of the returned tuple contains the X,Y displacement values of the left thumbstick, and the right thumbstick values at index 1.

Possible values for ‘controller’ are ‘xbox’ and ‘touch’; the only devices with thumbsticks the SDK manages.

controller : str
Name of the controller to get thumbstick values.
deadzone : bool
Apply the deadzone to thumbstick values.
Left and right, X and Y thumbstick values.
getTouches(touch_names, edge_trigger='continuous')

Returns True if any buttons are touched using sensors. This feature is used to estimate finger poses and can be used to read gestures. An example of a possible use case is a pointing task, where responses are only valid if the user’s index finger is extended away from the index trigger button.

Currently, this feature is only available with the Oculus Touch controllers.



Get the current tracking origin type.



Check if the HMD is mounted on the user’s head.

True if the HMD is being worn, otherwise False.

Check if the HMD is present.

True if the HMD is present, otherwise False.

Check if the user is doing a pointing gesture with the given hand, or if the index finger is not touching the controller. Only applicable when using Oculus Touch controllers.



Check if the user’s thumb is pointing upwards with a given hand, or if not touching the controller. Only applicable when using Oculus Touch controllers.



Check if the app has focus in the HMD and is visible to the viewer.

True if app has focus and is visible in the HMD, otherwise False.
logOnFlip(msg, level, obj=None)

Send a log message that should be time-stamped at the next .flip() command.

  • msg: the message to be logged
  • level: the level of importance for the message
  • obj (optional): the python object that might be associated with this message if desired

Get the connected HMD’s manufacturer.

UTF-8 encoded string containing the manufacturer name.

Sets the visibility of the mouse cursor.

If Window was initialized with noGUI=True then the mouse is initially set to invisible, otherwise it will initially be visible.


``win.mouseVisible = False``
``win.mouseVisible = True``
multiFlip(flips=1, clearBuffer=True)

Flip multiple times while maintaining the display constant. Use this method for precise timing.

WARNING: This function should not be used. See the Notes section for details.

flips: int, optional
The number of monitor frames to flip. Floats will be rounded to integers, and a warning will be emitted. Window.multiFlip(flips=1) is equivalent to Window.flip(). Defaults to 1.
clearBuffer: bool, optional
Whether to clear the screen after the last flip. Defaults to True.


# Draws myStim1 to buffer
# Show stimulus for 4 frames (90 ms at 60Hz)
myWin.multiFlip(clearBuffer=False, flips=6)
# Draw myStim2 "on top of" myStim1
# (because buffer was not cleared above)
# Show this for 2 frames (30 ms at 60Hz)
# Show blank screen for 3 frames (buffer was cleared above)

This function can behave unpredictably, and the PsychoPy authors recommend against using it. See for more information.


Multiply the current projection matrix obtained from the SDK using glMultMatrixf(). The matrix used depends on the current eye buffer set by ‘setBuffer()’.



Multiply the local eye pose transformation matrix obtained from the SDK using glMultMatrixf(). The matrix used depends on the current eye buffer set by ‘setBuffer()’.


onResize(width, height)

A default resize event handler.

This default handler updates the GL viewport to cover the entire window and sets the GL_PROJECTION matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the Window in pixels.

Override this event handler with your own to create another projection, for example in perspective.


Update all connected controller states. This should be called at least once per frame.



Get the HMD’s product name.

UTF-8 encoded string containing the product name.

Get the projection matrix for the current buffer.

raycastSphere(originPose, targetPose, targetRadius=0.5, rayDirection=None, maxRange=None)

Project an invisible ray of finite or infinite length from the originPose in rayDirection and check if it intersects with the targetPose bounding sphere.

Specifying maxRange as >0.0 casts a ray of finite length in world units. The distance between the target and ray origin position are checked prior to casting the ray; automatically failing if the ray can never reach the edge of the bounding sphere centered about targetPose. This avoids having to do the costly transformations required for picking.

This raycast implementation can only determine if contact is being made with the object’s bounding sphere, not where on the object the ray intersects. This method might not work for irregular or elongated objects since bounding spheres may not approximate those shapes well. In such cases, one may use multiple spheres at different locations and radii to pick the same object.

originPose ovrPosef
Origin pose of the ray.
targetPose ovrPosef or :obj:`ovrVector3f’
Pose of the target.
targetRadius float
The radius of the target.
rayDirection ovrVector3f
Vector indicating the direction for the ray. If None is specified, then -Z is used.
The maximum range of the ray. Ray testing will fail automatically if the target is out of range. The ray has infinite length if None is specified.
True if the ray intersects anywhere on the bounding sphere, False in every other condition.

# raycast from the head pose to a target headPose = hmd.headPose targetPos = rift.math.ovrVector3f(0.0, 0.0, -5.0) # 5 meters front isLooking = hmd.raycast(headPose, targetPos)

# now with touch controller positions rightHandPose = hmd.getHandPose(1) # 1 = right hand fingerLength = 0.10 # 10 cm pointing = hmd.raycast(rightHandPose, targetPos, maxRange=fingerLength)


Recenter the tracking origin.



To provide accurate measures of frame intervals, to determine whether frames are being dropped. The intervals are the times between calls to .flip(). Set to True only during the time-critical parts of the script. Set this to False while the screen is not being updated, i.e., during any slow, non-frame-time-critical sections of your code, including inter-trial-intervals, event.waitkeys(), core.wait(), or image.setImage().

see also:

Get the HMD’s raster display size.

tuple (int, int)
Width and height in pixels.
saveFrameIntervals(fileName=None, clear=True)

Save recorded screen frame intervals to disk, as comma-separated values.

fileName : None or the filename (including path if necessary) in
which to store the data. If None then ‘lastFrameIntervals.log’ will be used.
saveMovieFrames(fileName, codec='libx264', fps=30, clearFrames=True)

Writes any captured frames to disk.

Will write any format that is understood by PIL (tif, jpg, png, …)

filename: name of file, including path (required)

The extension at the end of the file determines the type of file(s) created. If an image type (e.g. .png) is given, then multiple static frames are created. If it is .gif then an animated GIF image is created (although you will get higher quality GIF by saving PNG files and then combining them in dedicated image manipulation software, such as GIMP). On Windows and Linux .mpeg files can be created if pymedia is installed. On macOS .mov files can be created if the pyobjc-frameworks-QTKit is installed.

Unfortunately the libs used for movie generation can be flaky and poor quality. As for animated GIFs, better results can be achieved by saving as individual .png frames and then combining them into a movie using software like ffmpeg.

codec: the codec to be used by moviepy for mp4/mpg/mov files.

If None then the default will depend on file extension. Can be one of ‘libx264’,’mpeg4’ for mp4/mov files. Can be ‘rawvideo’,’png’ for avi files (not recommended). Can be ‘libvorbis’ for ogv files.

fps: the frame rate to be used throughout the movie

only for quicktime (.mov) movies

clearFrames: set this to False if you want the frames to be kept

for additional calls to saveMovieFrames


# writes a series of static frames as frame001.tif,
# frame002.tif etc...

#as of PsychoPy 1.84.1 the following are written with moviepy
myWin.saveMovieFrames('stimuli.mp4') # codec = 'libx264' or 'mpeg4'

Get the connected HMD’s unique serial number. Use this to identify a particular unit if you own many.

UTF-8 encoded string containing the devices serial number.
setBlendMode(blendMode, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setBuffer(buffer, clear=True)

Set the active view and use the appropriate frustum settings. For stereoscopic displays, this demuxes drawing commands to the appropriate view buffer. Set clear=False to prevent clearing the buffer prior to use.

Warning! The window.Window.size property will return the buffer’s dimensions in pixels instead of the window’s when setBuffer is set to ‘left’ or ‘right’.

buffer : str
View buffer to divert successive drawing operations to, can be either ‘left’ or ‘right’.
clear : boolean
Clear the color, stencil and depth buffer.


setColor(color, colorSpace=None, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you want to set color and colorSpace simultaneously. See Window.color for documentation on colors.


Return to default projection. Call this before drawing PsychoPy’s 2D stimuli after a stereo projection change.

Note: This only has an effect if using Rift in legacy immediate mode OpenGL mode by setting ~Rift.legacy_opengl=True.

clearDepth : boolean
Clear the depth buffer prior after configuring the view parameters.


setGamma(gamma, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.


Change the appearance of the cursor for this window. Cursor types provide contextual hints about how to interact with on-screen objects.

The graphics used ‘standard cursors’ provided by the operating system. They may vary in appearance and hot spot location across platforms. The following names are valid on most platforms:

‘arrow’ : Default pointer ‘ibeam’ : Indicates text can be edited
‘crosshair’ : Crosshair with hot-spot at center
‘hand’ : A pointing hand

‘hresize’ : Double arrows pointing horizontally ‘vresize’ : Double arrows pointing vertically

Requires the GLFW backend, otherwise this function does nothing! Note, on Windows the ‘crosshair’ option is XORed with the background color. It will not be visible when placed over 50% grey fields.

Parameters:name – str, type of standard cursor to use
setMouseVisible(visibility, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.


Deprecated: As of v1.61.00 please use setColor() instead

setRecordFrameIntervals(value=True, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.


Set head-mounted display view. Gets the projection and view matrices from the HMD and applies them.

Note: This only has an effect if using Rift in legacy immediate mode OpenGL mode by setting ~Rift.legacy_opengl=True.

clearDepth : boolean
Clear the depth buffer prior after configuring the view parameters.


setScale(units, font='dummyFont', prevScale=(1.0, 1.0))

DEPRECATED: this method used to be used to switch between units for stimulus drawing but this is now handled by the stimuli themselves and the window should aways be left in units of ‘pix’

setSize(value, log=True)
setTrackinOrigin(origin_type='floor', recenter=False)

Set the tracking origin type. Can either be ‘floor’ or ‘eye’. The effect of changing types is immediate.

origin_type : str
Tracking origin type to use, can be either ‘floor’ or ‘eye’.
recenter : boolean
If True, the tracking origin is applied immediately.


setUnits(value, log=True)
setViewPos(value, log=True)

Check if the user requested the application should quit through the headset’s interface.

True if user requested the application quit via some menu in the HMD, otherwise False.

Check if the user requested the origin be recentered through the headset’s interface.

True if user requested the application recenter itself to reposition the origin, else False.

Size property to get the dimensions of the view buffer instead of the window. If there are no view buffers, always return the dims of the window.


None, ‘height’ (of the window), ‘norm’, ‘deg’, ‘cm’, ‘pix’ Defines the default units of stimuli initialized in the window. I.e. if you change units, already initialized stimuli won’t change their units.

Can be overridden by each stimulus, if units is specified on initialization. See Units for the window and stimuli for explanation of options.


Deprecated: use Window.flip() instead


Get the view matrix for the current buffer.


The origin of the window onto which stimulus-objects are drawn.

The value should be given in the units defined for the window. NB: Never change a single component (x or y) of the origin, instead replace the viewPos-attribute in one shot, e.g.:

win.viewPos = [new_xval, new_yval] # This is the way to do it win.viewPos[0] = new_xval # DO NOT DO THIS! Errors will result.

None, True or False. After a call to flip() should we wait for the blank before the script continues