Table of Contents

Main screen functions

mglOpen: Opens the screen

usage: mglOpen(whichScreen, <screenWidth>, <screenHeight>, <frameRate>, <bitDepth>)
purpose: Opens an openGL window

argument value
whichScreen 0=Window, 1=primary screen, 2=secondary screen, etc
<screenWidth> [width] in pixels
<screenHeight> [height] in pixels
<frameRate> [frameRate] in hertz
<bitDepth> [bitDepth] this is usually 32 bits

Open last monitor in list with current window settings

mglOpen

Open with resolution 800×600 60Hz 32bit fullscreen

mglOpen(1,800,600,60,32);

Open in a window

mglOpen(0);


Note that mglOpen hides the mouse cursor as a default. If you want to show the mouse cursor, you should call mglDisplayCursor after opening the screen.

mglFlush: Flips front and back buffer

purpose: swap front and back buffer (waits for one frame tick)
usage: mglFlush
N.B. mglFlush has to be called after each operation that involves drawing or erasing from the currently open window

mglClose: Closes the screen

purpose: close OpenGL screen
usage: mglClose

Other screen functions

mglSwitchDisplay: Switch between multiple monitors

usage: mglSwitchDisplay(<displayID>)
purpose: If you are using multiple monitors to display stimuli (like for a dichoptic presentation), you can open up multiple displays using this function.

argument value
<displayID> which display to switch to

You can use this to open up two separate screens and control them independently. For example, say you have two monitors 1 and 2. You open the first in the usual way:

mglOpen(1)

Then you switch monitors so that you can open up the other one

mglSwitchDisplay
mglOpen(2)

Now if you want draw to the first display, you can do

mglSwitchDisplay(1)
mglClearScreen(0.5);
mglFlush;

Similarly, to draw to the second display

mglSwitchDisplay(2);
mglClearScreen(1);
mglFlush;

You can check the status of all open displays with:

mglSwitchDisplay(-2);

If you want to close all displays at once, you can do:

mglSwitchDisplay(-1);

mglMoveWindow: Moves windows created by mglOpen(0)

usage: mglMoveWindow(leftPos,topPos)
purpose: Moves a window created by mglOpen(0)

argument value
leftPos Left position of where the window will be moved to
topPos Top position of where the window will be moved to
mglOpen(0);
mglMoveWindow(100,100);


mglDescribeDisplays: Get information about your monitor and computer system

usage: [displayInfo computerInfo] = mglDescribeDisplays()
purpose: Gets information about your displays (as an array of structs with values for each monitor). As well as a single struct with info about your computer.

mglFrameGrab: Frame grab to a matlab matrix

usage: mglFrameGrab(<frameRect>)
purpose: Does a frame grab of the current mgl screen and returns it as a matrix of dimensions widthxheightx3

argument value
frameRect Optional argument that is a 1×4 array specifying a rectangular part of the frame to grab in the format [x y width height]
mglOpen();
mglScreenCoordinates;
mglClearScreen([0 0 0]);
global MGL;
mglPoints2(MGL.screenWidth*rand(5000,1),MGL.screenHeight*rand(5000,1));
mglPolygon([0 0 MGL.screenWidth MGL.screenWidth],[MGL.screenHeight/3 MGL.screenHeight*2/3 MGL.screenHeight*2/3 MGL.screenHeight/3],0);
 mglTextSet('Helvetica',32,[1 1 1]);
mglTextDraw('Frame Grab',[MGL.screenWidth/2 MGL.screenHeight/2]);
frame = mglFrameGrab;
mglFlush
imagesc(mean(frame,3)');colormap('gray')

Functions to adjust the coordinate frame

mglVisualAngleCoordinates: Visual angle coordinates

purpose: Sets view transformation to correspond to visual angles (in degrees) given size and distance of display. Display must be open and have valid width and height (defined in MGL variable)
usage: mglVisualAngleCoordinates(physicalDistance,physicalSize);

argument value
physicalDistance [distance] in cm
physicalSize [width height] in cm
mglOpen
mglVisualAngleCoordinates(57,[16 12]);

mglScreenCoordinates: Pixel coordinate frame

purpose: Set coordinate frame so that it is in pixels with 0,0 in the top left hand corrner
usage: mglScreenCoordinates()

mglTransform: Low-level function to adjust transforms

purpose: applies view transformations
usage: mglTransform(whichMatrix, whichTransform, [whichParameters])

argument value
whichMatrix 'GL_MODELVIEW', 'GL_PROJECTION', or 'GL_TEXTURE'
whichTransform 'glRotate', 'glTranslate', 'glScale','glMultMatrix', 'glFrustum', 'glOrtho','glLoadMatrix', 'glLoadIdentity', 'glPushMatrix','glPopMatrix', 'glDepthRange', or 'glViewport'
whichParameters function-specific; see OpenGL documentation

You can also specifiy one of GL_MODELVIEW, GL_PROJECTION, or GL_TEXTURE and a return variable current matrix values. If two outputs are specified, the result of the computation will be returned.

This function is usually not called directly, but called by mglVisualAngleCoordinates or mglScreenCoordinates to set the transforms

mglHFlip: Horizontally flip coordinates

purpose: flips coordinate frame horizontally, useful for when the display is viewed through a mirror
usage: mglHFlip()

mglOpen
mglVisualAngleCoordinates(57,[16 12]);
mglHFlip
mglTextSet('Helvetica',32,1,0,0,0,0,0,0,0);
mglTextDraw('Mirror reversed',[0 0]);
mglFlush;

mglVFlip: Vertically flip coordinates

purpose: flips coordinate frame vertically
usage: mglVFlip

mglOpen
mglVisualAngleCoordinates(57,[16 12]);
mglVFlip
mglTextSet('Helvetica',32,[1 1 1],0,0,0,0,0,0,0);
mglTextDraw('Vertically flipped',[0 0]);
mglFlush;

Texture functions used for displaying images

mglCreateTexture: Create a texture from a matrix

purpose: Create a texture for display on the screen with mglBltTexture image can either be grayscale nxm, color nxmx3 or color+alpha nxmx4
usage: texture = mglCreateTexture(image,axis)

argument value
image nxm matrix of grayscale values from 0 to 255, or nxmx3 matrix of RGB values or nxmx4 of RGBA values
axis 'xy' rows are x and columns are y dimension (default–matlab oriented matrix, i.e. will give you the same results as using imagesc), 'yx' rows are y and columns are x dimension
OUTPUT: texture a texture structure that can be drawn to the screen using mglBltTexture
mglOpen;
mglClearScreen
mglScreenCoordinates
texture = mglCreateTexture(round(rand(100,100)*255));
mglBltTexture(texture,[0 0]);
mglFlush;

mglBltTexture: Draw the texture to the screen

purpose: Draw a texture to the screen in desired position.
usage: mglBltTexture(texture,position,<hAlignment>,<vAlignment>,<rotation>)

argument value
texture A texture structure created by mglCreateTexture or mglText.
position Either a 2-vector [xpos ypos] or 4-vector [xpos ypos width height]. units are degrees.
hAlignment -1 = left, 0 = center, 1 = right (defaults to center)
vAlignment -1 = top, 0 = center, 1 = bottom (defaults to center)
rotation rotation in degrees, defaults to 0

To display several textures at once, texture can be an array of n textures, position is nx2, or nx4 and hAlignment, vAlignment and rotation are either a single value or an array of n.

multiple textures:

 mglOpen;
 mglVisualAngleCoordinates(57,[16 12]);
 image = rand(200,200)*255;
 imageTex = mglCreateTexture(image);
 mglBltTexture([imageTex imageTex],[-3 0;3 0],0,0,[-15 15]);
 mglFlush;

single textures

 mglOpen;
 mglVisualAngleCoordinates(57,[16 12]);
 image = rand(200,200)*255;
 imageTex = mglCreateTexture(image);
 mglBltTexture(imageTex,[0 0]);
 mglFlush;

mglDeleteTexture: Delete a texture

purpose: Deletes a texture. This will free up memory for textures that will not be drawn again. Note that when you call mglClose texture memory is freed up. You only need to call this if you are running out of memory and have textures that you do not need to use anymore.
usage: mglDeleteTexture(tex)

argument value
tex The texture created by mglCreateTexture that you want to delete
 mglOpen;
 mglClearScreen
 mglScreenCoordinates
 texture = mglCreateTexture(round(rand(100,100)*255));
 mglBltTexture(texture,[0 0]);
 mglFlush;
 mglDeleteTexture(texture);

Drawing text

mglTextSet: Set parameters for drawing text

purpose: Set text properties for mglText
usage: mglTextSet(fontName,<fontSize>,<fontColor>,<fontVFlip>,<fontHFlip>,<fontRotation>,<fontBold>,<fontItalic>,<fontUnderline>,<fontStrikeThrough>)

argument value
fontName 'fontName' (defaults to 'Times Roman')
fontSize font point size (defaults to 36)
fontColor [r g b] where r, g and b are values between 0 and 1 (defaults to [1 1 1])
fontVFlip 0 = no vertical flip, 1 = vertical flip (defaults to 0)
fontHFlip 0 = no horizontal flip, 1 = horizontal flip (defaults to 0)
fontRotation rotation in degrees (defaults to 0)
fontBold 0 for normal, 1 for bold (defaults to 0)
fontItalic 0 for normal, 1 for italic (defaults to 0)
fontUnderline 0 for normal, 1 for underline (defaults to 0)
fontStrikethrough 0 for normal, 1 for strikethrough (defaults to 0)
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglTextSet('Helvetica',32,[0 0.5 1 1],0,0,0,0,0,0,0);
mglTextDraw('Hello There',[0 0]);
mglFlush;

mglText: Create a texture from a string

purpose: Creates a texture from a string.
usage: tex = mglText('string')

argument value
string The string you want to draw
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglTextSet('Helvetica',32,[0 0.5 1 1],0,0,0,0,0,0,0);
thisText = mglText('hello')
mglBltTexture(thisText,[0 0],'left','top');
mglFlush;

Normally you will only set one output argument which is a texture usable by mglBltTexture. But if you have two output arguments

[tex texMatrix] = mglText('hello');

texMatrix will contain a 2D matlab array that has a rendering of the text (i.e. it will have values from 0-255 that represent the string). You can modify this matrix as you want and then use mglCreateTexture to create it into a texture that can be displayed by mglBltTexture

mglTextDraw: Draws text to screen (simple but slow)

purpose: wrapper around mglText and mglBltTexture to draw some text on the screen. If you need to draw text more quickly, you will have to pre-make the text textures with mglText and then use mglBltTexture when you want it. Otherwise, for non time-critical things this functions should be used.
usage: mglTextDraw(str,pos,<hAlignment>,<vAlignment>)

argument value
str desired string
pos [x y] position on screen
hAlignment -1 = left, 0 = center, 1 = right (defaults to center)
vAlignment -1 = top, 0 = center, 1 = bottom (defaults to center)
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglTextSet('Helvetica',32,[0 0.5 1 1],0,0,0,0,0,0,0);
mglTextDraw('Hello There',[0 0]);
mglFlush;

mglStrokeText: Fast no-frills line-based text drawing (does not use texture memory)

purpose: Draws a stroked fixed-width character or string on MGL display. Default width is 1, default height 1.8 (in current screen coordinates)
usage: [x,y]=mglStrokeText( string, x, y, scalex, scaley, linewidth, color, rotation );

argument value
string text string. Unsupported characters are printed as #
x,y center coordinates of first character (current screen coordinates)
scalex scale factor in x dimension (relative to character) (current screen coordinates). Note that text can be mirrored by setting this factor to a negative value.
scaley scale factor in y dimension (relative to character) (current screen coordinates). Optional, defaults to scalex.
linewidth width of line used to draw text. Default 1.
color text color. Default [1 1 1]
rotation in radians. Default 0.
OUTPUT x,y position after last letter (for subsequent calls) [optional]
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglStrokeText('Hello',0,0);
mglFlush;

Gamma tables

mglSetGammaTable: Sets the display card gamma table

purpose: Set the gamma table
usage: There are a number of ways of calling this function explained below.

Setting a redMin, redMax, redGamma, greenMin, etc.

mglSetGammaTable(0,1,0.8,0,1,0.9,0,1,0.75);

or with a vector of length 9:

mglSetGammaTable([0 1 0.8 0 1 0.9 0 1 0.75]);

or set with a single table for all there colors. Note that the table values go from 0 to 1 (i.e. 0 is the darkest value and 1 is the brightest value). If you have a 10 bit gamma table (most cards do–see section on monitor calibration for a list), then the intermediate values will be interpreted with 10 bits of resolution.

gammaTable = ((0:1/255:1).^0.8)';
mglSetGammaTable(gammaTable);

or set all three colors with differnet tables

redGammaTable = (0:1/255:1).^0.8;
greenGammaTable = (0:1/255:1).^0.9;
blueGammaTable = (0:1/255:1).^0.75;
mglSetGammaTable(redGammaTable,greenGammaTable,blueGammaTable);

can also be called with an nx3 table

gammaTable(:,1) = (0:1/255:1).^0.8;
gammaTable(:,2) = (0:1/255:1).^0.9;
gammaTable(:,3) = (0:1/255:1).^0.75;
mglSetGammaTable(gammaTable);

can also be called with the structure returned by mglGetGammaTable

mglSetGammaTable(mglGetGammaTable);

Note that the gamma table will be restored to the original after mglClose.

Timing. The setting of the gamma table is done by the OS in a way that seems to be asynchronous with mglFlush. For instance, the following code gives unexpected results:

mglOpen(1);
mglClearScreen(1); % set back buffer to white
mglWaitSecs(2);
mglSetGammaTable(zeros(1,256)); % now set the gamma table to all black, this should insure that nothing will be displayed
mglFlush; % now the flush will bring the value 255, set by the mglClearScreen above, to the front buffer, but because the gamma table is set to black, nothing should be displayed
mglWaitSecs(2);
mglClose;

This should keep the screen black, but on my machine, the screen temporarily flashes white. Presumably this is because the mglSetGammaTable happens after the mglFlush. It is recommended that you change the gamma while there is nothing displayed on the screen and wait for at least one screen refresh before assuming that the gamma table has actually changed.

mglGetGammaTable: Gets the current gamma table

purpose: returns what the gamma table is set to usage: table = mglGetGammaTable()

mglOpen;
gammaTable = mglGetGammaTable

Drawing functions

mglClearScreen

purpose: sets the background color
usage: mglClearScreen(<color>)

argument value
color color to set background to, can be a grayscale value or an [r g b] value

set to the level of gray (0-1)

mglClearScreen(gray)

set to the given [r g b]

mglClearScreen([r g b])

full example

mglOpen;
mglClearScreen([0.7 0.2 0.5]);
mglFlush();

mglPoints2: 2D points

purpose: plot 2D points on an OpenGL screen opened with mglOpen
usage: mglPoints2(x,y,size,color)

argument value
x,y position of dots on screen
size size of dots (in pixels)
color color of dots
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglPoints2(16*rand(500,1)-8,12*rand(500,1)-6,2,1);
mglFlush

mglPoints3: 3D points

purpose: plot 2D points on an OpenGL screen opened with mglOpen
usage: mglPoints2(x,y,z,size,color)

argument value
x,y,z position of dots on screen
size size of dots (in pixels)
color color of dots
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglPoints3(16*rand(500,1)-8,12*rand(500,1)-6,zeros(500,1),2,1);
mglFlush


mglLines2: 2D lines

purpose: mex function to plot lines on an OpenGL screen opened with glopen
usage: mglLines(x0, y0, x1, y1,size,color,<bgcolor>)

argument value
x0,y0 initial position of line
x0,y0 end position of line
size size of line (in pixels)
color color of line
bgcolor background color of line
mglOpen
mglVisualAngleCoordinates(57,[16 12]);
mglLines2(-4, -4, 4, 4, 2, [1 0.6 1]);
mglFlush

mglFillOval: Ovals

purpose: draw filled oval(s) centered at x,y with size [xsize ysize] and color [rgb]. the function is vectorized, so if you provide many x/y coordinates (identical) ovals will be plotted at all those locations.
usage: mglFillOval(x,y, size, color)

argument value
x,y center position of oval
size [width height] of oval
color color of oval
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
x = [-1 -4 -3 0 3 4 1];
y = [-1 -4 -3 0 3 4 1];
sz = [1 1];
mglFillOval(x, y, sz,  [1 0 0]);
mglFlush();

mglFillRect: Rectangles

purpose: draw filled rectangles(s) centered at x,y with size [xsize ysize] and color [rgb]. the function is vectorized, so if you provide many x/y coordinates (identical) ovals will be plotted at all those locations.
usage: [ ] = mglFillRect(x,y, size, color)

argument value
x,y center position of rectangle
size [width height] of rectangle
color color of rectangle
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
x = [-1 -4 -3 0 3 4 1];
y = [-1 -4 -3 0 3 4 1];
sz = [1 1];
mglFillRect(x, y, sz,  [1 1 0]);
mglFlush();


mglFixationCross: Cross

purpose: draws a fixation cross with no arguments, draws a fixation cross at origin (default width 0.2 with linewidth 1 in white at [0,0])
usage: mglFixationCross([width], [linewidth], [color], [origin]);
alternate usage: mglFixationCross( params )

argument value
params [width linewidth r g b x y]
width width in degrees of fixation cross
linewidth width in pixels on line
color color of fixation cross
origin center position of fixation (defaults to [0 0])
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
mglFixationCross;
mglFlush;

mglGluAnnulus: Annuli, rings

purpose: for annuli and rings, e.g. for retinotopic stimuli. The function is vectorized, such that multiple annuli can be rendered in one call. In this case, x,y, isize, and osize need to have the same number of elements. Color is also vectorized.
usage: [ ] = mglGluAnnulus( x, y, isize, osize, color, [nslices], [nloops] )

argument value
x,y position of circle from which annulus/annuli is/are derived
isize inner radius/radii
osize outer radius/radii
color color of annuli, either [], 3-vector, or 3-row by n-column matrix
nslices number of wedges used in polygon→circle approximation [default 8]
nloops number of annuli used in polygon→circle approximation [default 1]
mglOpen(0);
mglVisualAngleCoordinates(57,[16 12]);
x = zeros(10, 1);
y = zeros(10, 1);
isize = ones(10,1)
osize = 3*ones(10,1);
startAngles = linspace(0,180, 10)
sweepAngles = ones(1,10).*10;
colors = jet(10)'; % nb! transpose
mglGluPartialDisk(x, y, isize, osize, startAngles, sweepAngles, colors, 60, 2);
mglFlush();

mglGluDisk: Circular dots

purpose: for plotting circular (rather than square dots), use this function. on slower machines, large number of dots may lead to dropped frames. there may be a way to speed this up a bit in future.
usage: [ ] = mglGluDisk( x, y, size, color, [nslices], [nloops] )

argument value
x,y position of dots
size size of dots
color color of dots
nslices number of wedges used in polygon→circle approximation [default 8]
nloops number of annuli used in polygon→circle approximation [default 1]
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
x = 16*rand(100,1)-8;
y = 12*rand(100,1)-6;
mglGluDisk(x, y, 0.1,  [0.1 0.6 1], 24, 2);
mglFlush();


mglGluPartialDisk: Segments, wedges

purpose: for segments and wedges, e.g. for retinotopic stimuli. The function is vectorized, such that multiple segments can be rendered in one call. In this case, x,y, isize, osize, startAngles, and sweepAngles need to have the same number of elements. Color is also vectorized (see mglGluAnnulus and the example below).
usage: [ ] = mglGluPartialDisk( x, y, isize, osize, startAngles, sweepAngles, color, [nslices], [nloops] )

argument value
x,y center position of circle from which segment is derived
isize innter radius of segment
osize outer radius of segment
startAngles angle at which segment(s) start
sweepAngles angle each segment(s) sweep(s) out
color color of segment
nslices number of wedges used in polygon→circle approximation [default 8]
nloops number of annuli used in polygon→circle approximation [default 2]
mglOpen(0);
mglVisualAngleCoordinates(57,[16 12]);
x = zeros(10, 1);
y = zeros(10, 1);
isize = linspace(1, 5, 10);
osize = 3+isize;
startAngles = linspace(0,180, 10)
sweepAngles = ones(1,10).*10;
colors = jet(10)';
mglGluPartialDisk(x, y, isize, osize, startAngles, sweepAngles, colors, 60, 2);
mglFlush();

mglPolygon: Polygons

purpose: mex function to draw a polygon in an OpenGL screen opened with mglOpen. x and y can be vectors (the polygon will be closed)
usage: mglPolygon(x, y, [color])

argument value
x,y position of vertices
color color of polygon
mglOpen;
mglVisualAngleCoordinates(57,[16 12]);
x = [-5 -6 -3  4 5];
y = [ 5  1 -4 -2 3];
mglPolygon(x, y, [1 0 0]);
mglFlush();

mglQuads: Quads

usage: mglQuad( vX, vY, rgbColor, [antiAliasFlag] );
purpose: mex function to draw a quad in an OpenGL screen opened with mglOpen

argument value
vX 4 row by N column matrix of 'X' coordinates
vY 4 row by N column matrix of 'Y' coordinates
rgbColors 3 row by N column of r-g-b specifing the color of each quad
antiAliasFlag turns on antialiasing to smooth the edges


mglOpen;
mglScreenCoordinates
mglQuad([100; 600; 600; 100], [100; 200; 600; 100], [1; 1; 1], 1);
mglFlush();

Stencils to control drawing only to specific parts of screen

Here is a demonstration of how to use stencils using these these functions:

mglOpen;
mglScreenCoordinates;
%Draw an oval stencil
mglStencilCreateBegin(1);
mglFillOval(300,400,[100 100]);
mglStencilCreateEnd;
mglClearScreen;
% now draw some dots, masked by the oval stencil
mglStencilSelect(1);
mglPoints2(rand(1,5000)*500,rand(1,5000)*500);
mglFlush;
mglStencilSelect(0);

mglStencilCreateBegin: Start drawing a stencil

purpose: Begin drawing to stencil. Until mglStencilCreateEnd is called, all drawing operations will also draw to the stencil. Check MGL.stencilBits to see how many stencil planes there are. If invert is set to one, then the inverse stencil is made
usage: mglStencilCreateBegin(stencilNumber,invert)

argument value
stencilNumber stencil number, usualy 1-8 but look at the global variable MGL.stencilBits to see how many stencil planes there are.
invert 1 or 0 to invert the stencil that is made

see example above.

mglStencilCreateEnd: End drawing a stencil

purpose: Ends drawing to stencil usage: mglStencilCreateEnd

see example above.

mglStencilSelect: Select a stencil

purpose: Sets which stencil to use, 0 for no stencil usage: mglStencilSelect(stencilNumber)

argument value
stencilNumber number of stencil to use

See example above.

Keyboard and mouse functions

mglDisplayCursor: Hide or display the mouse cursor

purpose: Hide or display the mouse cursor
usage: mglDisplayCursor(<display>)

argument value
display 1 or 0 to display or hide the cursor

When you call mglOpen the mouse cursor is hidden by default. You can get it to come back by doing:

mglOpen
mglDisplayCursor

mglGetKeys: Get keyboard state

purpose: returns the status of the keyboard (regardless of whether the focus is on the mgl window)
usage: mglGetKeys(<keys>)

argument value
keys array of keycodes. In this case mglGetKeys will only return thestatus of those keys, for example: mglGetKeys([61 46]) will return the values of key 61 and 46.

mglGetMouse: Get mouse state

usage: mglGetMouse()
purpose: returns the status of the mouse buttons (regardless of whether the focuse is on the mgl window

mglGetKeyEvent: Get a key down event off of queue

purpose: returns a key down event waitTicks specifies how long to wait for a key press event in seconds. Note that the timing precision is system-dependent:

  • Mac OS X: about 1/60 s
  • Linux: 1/HZ s where HZ is the system kernel tick frequency (HZ=100 on older systems, HZ=250 or 500 on more modern systems)

The default wait time is 0, which will return immediately and if no keypress event is found, will return an empty array []. The return structure contains the character (ASCII) code of the pressed key, the system-specific keycode, a keyboard identifier (on Linux, this is the keyboard state, or modifier field), and and the time (in secs) of the key press event. NOTE that to get a key event the focus *MUST* be on the mgl window. For faster timing, try mglGetKeys
usage: mglGetKeyEvent(waitTicks)

argument value
waitTicks Ticks to wait for before giving up and returning empty event
mglOpen
mglGetKeyEvent(0.5)

mglGetMouseEvent: Get a mouse button down event off of queue

usage: mglGetMouseEvent(waitTicks)
purpose: returns a mouse down event waitTicks specifies how long to wait for a mouse event in seconds. Note that the timing precision is system-dependent:

  • Mac OS X: about 1/60 s
  • Linux: 1/HZ s where HZ is the system kernel tick frequency (HZ=100 on older systems, HZ=250 or 500 on more modern systems)

The default wait time is 0, which will return immediately with the mouse position regardless of button state. The return structure contains the x,y coordinates of the mouse, the button identifier if pressed (on the button-challenged Mac this is always 1) and 0 otherwise, and the time (in secs) of the mouse event. NOTE that the mouse down event has to be *ON* the mgl window for this to work with waitTicks not equal to 0

argument value
waitTicks Ticks to wait for before giving up and returning empty event
mglOpen
mglGetMouseEvent(0.5)

mglCharToKeycode: Returns keycode of char

Purpose: Returns the keycodes of a (list of) keynames
Usage: keycode=mglCharToKeycode(keyname)

Note on special keys: On Linux (X), special keys and function keys have unique names, e.g., 'Escape', 'F1', etc., so obtaining the keycodes for these is done by mglCharToKeycode({'Escape','F1'}) etc. On Macs, this is not possible; instead, test for the keycode and name of a key using the mglShowKey function.

The keycodes match those used by mglGetKeys and mglGetKeyEvent

argument value
keyname cell array where each entry is a key name string e.g. keyname = {'h','g' '1'}
OUTPUT:keycode vector of integer keycodes for each keyname entry e.g. for the above example, keyname=[44 43 11] (on Linux)

Example: testing for specific keypresses:

keycodes=mglCharToKeycode({'1','2' '3'}) % keys 1-3 on main keyboard
while (1); k=mglGetKeys(keycodes); if (any(k)),break;end;end

Technical note: the returned keycodes are identical to system keycodes+1

mglKeycodeToChar: Returns char of keycode

Purpose: Returns the keynames of a (list of) keycodes
Usage: keyname=mglKeycodeToChar(keycode)

Note on special keys: This repeats the above entry, deleted.

argument value
keycode vector of integer keycodes for each keyname entry for example, keyname=[44 43 11]
OUTPUT:keyname cell array where each entry is a key name string for the above example on linux keyname = {'h','g' '1'}

Example: testing which keys were pressed:

while (1); k=mglGetKeys; if (any(k)),break;end;end
keycodes=find(k);
keynames=mglKeycodeToChar(keycodes)

Technical note: keycodes are identical to system keycodes+1

Timing functions

mglGetSecs: Get time in seconds

purpose: Get current or elapsed time
usage: mglGetSecs(<t0>)

argument value
t0 start time from which to compute elapsed time

To get current time

t=mglGetSecs

Get elapsed time since t0

t0 = mglGetSecs;
elapsedTime=mglGetSecs(t0)

mglWaitSecs: Wait for a time in seconds

purpose: Wait for some time
usage: mglWaitSecs(waitTime)

argument value
waitTime time to wait for in seconds

Wait 3.3 seconds:

mglWaitSecs(3.3);

Sound functions

mglInstallSound: Install an .aiff file for playing with mglPlaySound

purpose: Install an .aiff file for playing with mglPlaySound
usage: mglInstallSound(soundName)

argument value
soundName aiff filename

This will install sounds to be played using mglPlaySound. Note that if you just want to use systems sounds then you do not need to call this function directly, it will be called by mglOpen to install all your system sounds. Once the sound is installed you can play it with mglPlaySound

soundNum = mglInstallSound('/System/Library/Sounds/Submarine.aiff');
mglPlaySound(soundNum);

With no arguments, mglInstallSound uninstalls all sounds

mglInstallSound

mglPlaySound: Play a system sound

purpose: Play a sound
usage: mglPlaySound(soundNum)

argument value
soundNum number of sound

Plays a system sound. After calling mglOpen, all of the system sounds will be installed and you can play a specific one as follows:

mglOpen;
global MGL;
mglPlaySound(find(strcmp(MGL.soundNames,'Submarine')));

With no arguments mglPlaySound plays the system alert sound

mglPlaySound

Note that this function returns right after it starts playing the sound (it does not wait until the sound finishes playing).

Test/Demo programs

Run these test programs without any parameters and they should display on your second monitor. With an optional single argument you can pass the number of the display you want to display on.

  • mglTestAlignment: Alignment of textures
  • mglTestDots: Draws dots
  • mglTestGamma: GUI controlled gamma
  • mglTestLUTAnimation: Gamma LUT animation
  • mglTestStencil: Demonstrates stencil functions
  • mglTestTex: Draws a gabor
  • mglTestTexMulti: Draws many small images to screen
  • mglTestText: Draws text
  • mglTestKeys: Returns keyboard codes