18.1Class SDL

SDL wrapper class

Class SDL

This class acts as a module wrapper for SDL functions. The vast majority of the "SDL_" C namespace is provided by this module through access to SDL class.

In example, to initialize the system through SDL_Init(), Falcon users should do the following:


      load sdl

      SDL.Init( /* parameters *\/ )

Note: When using functions repeatedly, it is advisable to cache them to a local variable.

Methods
CreateCursorGets currently active cursor.
CreateRGBSurfaceCreates a paintable surface
CreateRGBSurfaceFromCreates a paintable surface using existing data.
EnableKeyRepeatEnable or disable key repeat and set key rate.
EnableUNICODEEnable or disable translation from keys to Unicode characters.
EventStateQuery or change processing ability.
GetAppStateGets current application state.
GetCursorGets currently active cursor.
GetGammaRampGet Gamma ramps for this hardware.
GetKeyNameGets a SDL specific name for a ceratin key
GetKeyStateGets a memory buffer which reflects current keyboard scancodes status.
GetModStateGets current keyboard modifier state.
GetMouseStateRetreive mouse state
GetVideoInfoReturns details about underlying video system.
GetVideoSurfaceRetreives the current video surface.
InitInitialize SDL system.
InitAutoInitialize SDL system and provide automatic cleanup.
IsBigEndianReturns true if the host system is big endian.
JoystickEventStateChanges joystick event propagation settings.
JoystickUpdateUpdates the state(position, buttons, etc.) of all open joysticks.
ListModesReturns a list of possible modes.
LoadBMPLoads an image from a BMP file.
MakeCursorBuilds an SDL cursor taking an array of strings as input.
PollEventPolls for event and calls handlers if events are incoming.
PumpEventsUpdate event listing and queueing during long operations.
QuitTurns off SDL system.
QuitSubSystemShuts down a subset of SDL.
SetGammaSets the gamma function values for the active SDL output.
SetGammaRampSet Gamma ramps for this hardware.
SetModStateSets current keyboard modifier state.
SetVideoModeChanges the video mode and/or starts SDL context window.
ShowCursorChanges or query the visibility of the mouse cursor.
StartEventsStats dispatching of SDL events to this VM.
StopEventsStops dispatching of SDL events.
VideoDriverNameReturns the name of the used video driver.
VideoModeOKVerifies if a given video mode is ok
WaitEventWaits forever until an event is received.
WasInitDetects if some SDL subsystem was initialized.

Methods

CreateCursor

Gets currently active cursor.

SDL.CreateCursor( mbData, mbMask, width, height, Xspot, Yspot )
mbData MemBuf containing visual bit data.
mbMask Membuf containing visibility mask data.
width Width of the cursor.
height Height of the cursor.
Xspot X position of the cursor hotspot.
Yspot Y position of the cursor hotspot.
Raise
SDLError if the cursor couldn't be created.

See SDL_CreateCursor documentation. Method SDL.MakeCursor is probably simpler to use.

CreateRGBSurface

Creates a paintable surface

SDL.CreateRGBSurface( flags, width, height, depth, [rMask],[gMask],[bMask],[aMask] )
flags Creation flags.
width Width of the created buffer.
height Height of the created buffer.
depth Bit per pixel depth of the image - can be 8, 16, 24 or 32.
rMask Red bitmask - defaults to low address bits.
gMask Green bitmask - defaults to second low address bits.
bMask Blue bitmask - defaults to third low address bits.
aMask Alpha bitmask - defaults to hihest address bits.
ReturnThe newly created surface.
Raise
SDLError on creation error.

The function can be called either with 4 or 8 parameters. 8 bits per pixel modes don't require bit masks, and they are ignored if provided; other modes require a bitmask. If the values are not provided, this function calculates them using a R,G,B,A evenly spaced bitmap, which will place the bits stored in the lowest address in the red space. On big endian machines, red will be placed in the most signficant bits, on little endian it will be place on the least significant bits.

You should provide your own bitmap values if you don't want alpha surfaces.

The flags can be a combination of the following:

- SDL.SWSURFACE - SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.

CreateRGBSurfaceFrom

Creates a paintable surface using existing data.

SDL.CreateRGBSurfaceFrom( pixels, width, height, depth, [rMask],[gMask],[bMask],[aMask] )
pixels Original pixels in a membuf.
width Width of the created buffer
height Height of the created buffer.
depth Bit per pixel depth of the image -- must match pixel membuf word length.
rMask Red bitmask - defaults to low address bits.
gMask Green bitmask - defaults to second low address bits.
bMask Blue bitmask - defaults to third low address bits.
aMask Alpha bitmask - defaults to hihest address bits.
ReturnThe newly created surface.
Raise
SDLError on creation error.

See also: SDL.

EnableKeyRepeat

Enable or disable key repeat and set key rate.

SDL.EnableKeyRepeat( delay, interval )
delay Delay before starting producing repeated keystores.
interval Interval between keystores.
Raise
SDLError if requested parameters cannot be set.

Enables or disables the keyboard repeat rate. delay specifies how long the key must be pressed before it begins repeating, it then repeats at the speed specified by interval. Both delay and interval are expressed in milliseconds.

Setting delay to 0 disables key repeating completely. Good default values are SDL.DEFAULT_REPEAT_DELAY and SDL.DEFAULT_REPEAT_INTERVAL.

EnableUNICODE

Enable or disable translation from keys to Unicode characters.

SDL.EnableUNICODE( mode )
mode Wether to enable, disable or query Unicode translation.
Returncurrent status of unicode translation.

The parameter can be:

Falcon tunrs unicode translation ON at initialization, as characters in Falcon as treated as Unicode values, but it is possible to turn this off for better performance if character values are not needed.

EventState

Query or change processing ability.

SDL.EventState( type, state )
type Event type to be filtered.
state Wether to enable, disable or query the event state.
Returntrue on success, false if the event queue is full

This method queries and/or changes the current processing status of an event. Disabling an event means that it won't be notified to event handlers anymore, and it will be silently discarded.

It will still be possible to see the effect of that event by querying directly the event interface.

State can be set to one of the following:

- SDL.IGNORE: indicated event type will be automatically dropped from the event queue and will not be filtered.

GetAppState

Gets current application state.

SDL.GetAppState()
ReturnCurrent application state

This function may return one of the following values:

- SDL_APPMOUSEFOCUS: The application has mouse focus.

GetCursor

Gets currently active cursor.

SDL.GetCursor()
Returnan instance of SDLCursor class or nil.

This method returns the currently active cursor. It can be used to store this away and set it later.

GetGammaRamp

Get Gamma ramps for this hardware.

SDL.GetGammaRamp( [aRet] )
aRet An array that will contain the gamma memory buffers on exit.
ReturnAn array containing the three MemBufs
Raise
SDLError if the hardware doesn't support gamma.

This functions returns three membuf that maps directly the gamma correction table for the red, green and blue value.

Each membuf is a 2 bytes memory vector of 256 binary values.

GetKeyName

Gets a SDL specific name for a ceratin key

SDL.GetKeyName( key )
key An SDLK value.
Returna string containing the key name.

GetKeyState

Gets a memory buffer which reflects current keyboard scancodes status.

SDL.GetKeyState()
ReturnA 1 byte memory buffer.

This method returns a memory buffer in which each element represents the status of a key scan code. The index of the code is provided by the SDLK enumeration; if a given item in the membuf is 1, then the key is currently pressed, else it it is released.

This memory buffer is automaitcally updated when SDL.WaitEvent or SDL.PollEvent are called. If the program doesn't call those function, the SDL.PumpEvents method can be used to update current keyboard status.

Note: Calling this method more than once per program will cause cause useless duplication of the memory buffer.

GetModState

Gets current keyboard modifier state.

SDL.GetModState()
ReturnAn integer containing or'd modifier state.

The returned integer is a bitfield where active modifiers bits are turned on. The values are those listed by the SDLKMOD enumeration.

GetMouseState

Retreive mouse state

SDL.GetMouseState( MouseBuf, interval )
MouseBuf
interval Interval between keystores.
Raise
SDLError if requested parameters cannot be set.

Enables or disables the keyboard repeat rate. delay specifies how long the key must be pressed before it begins repeating, it then repeats at the speed specified by interval. Both delay and interval are expressed in milliseconds.

Setting delay to 0 disables key repeating completely. Good default values are SDL.DEFAULT_REPEAT_DELAY and SDL.DEFAULT_REPEAT_INTERVAL.

GetVideoInfo

Returns details about underlying video system.

SDL.GetVideoInfo()
ReturnAn instance of a SDLVideoInfo
Raise
SDLError on error.

This function returns a read-only SDLVideoInfo instance containing informations about the video hardware.

If this is called before SDL_SetVideoMode, the vfmt member of the returned structure will contain the pixel format of the "best" video mode.

GetVideoSurface

Retreives the current video surface.

SDL.GetVideoSurface()
Returna SDLScreen instance representing the current video device.
Raise
SDLError on failure

See also: SDLScreen.

Init

Initialize SDL system.

SDL.Init( flags )
flags SDL initialziation flags
Raise
SDLError on initialization failure

This method initializes SDL. After initialization, it is necessary to call SDL.Quit() to clear the application state on exit; to avoid this need, it is possible to use the SDL.InitAuto Falcon extension.

Note: This "Init" method is not to be confused with Falcon language init statement.

The following initialization flags can be provided; to specify more than one flag, use bitwise or (pipe "|" operator):

- SDL.INIT_VIDEO: Initialize video subsystem.

As Falcon strings and character manipulation is mainly unicode, this init method automatically enables SDL unicode in event generation. If this is not desired, it is possible to call SDL.EnableUNICODE to disable it after init.

InitAuto

Initialize SDL system and provide automatic cleanup.

SDL.InitAuto( flags )
flags SDL initialization flags
Returnhandle for SDL termination.
Raise
SDLError on initialization failure

This method initializes SDL, and sets up an handle for SDL cleanup. The returned handle has a Quit() method that can be called autonomously by the application i.e. to return to text mode and perform final screen output. In case of abnormal termination (i.e. on exception raise), the handle calls its Quit() method automatically right before being collected at VM termination. If the handle is stored in a global variable of the main module, it will stay alive until the VM exits, and then it will be called to properly reset SDL status.

See also: SDL.

IsBigEndian

Returns true if the host system is big endian.

SDL.IsBigEndian()
Returntrue if the host system is big endian.

JoystickEventState

Changes joystick event propagation settings.

SDL.JoystickEventState( mode )
mode Wether to disable, enable or query the joystick.
ReturnCurrent joystick event propagation segging.

This function is used to enable or disable joystick event processing. With joystick event processing disabled you will have to update joystick states with SDL.JoystickUpdate and read the joystick information manually. state is either SDL.QUERY, SDL.ENABLE or SDL.IGNORE.

Note: Joystick event handling is prefered

JoystickUpdate

Updates the state(position, buttons, etc.) of all open joysticks.

SDL.JoystickUpdate()

If joystick events have been enabled with SDL_JoystickEventState then this is called automatically in the event loop.

ListModes

Returns a list of possible modes.

SDL.ListModes( [format],[flags] )
format An SDLPixelFormat structure to filter modes or nil.
flags Initialization flags that must be supported by returned mode.
ReturnAn array of x,y pairs containing the sizes of the available modes, nil or -1.
Raise
SDLError if the system is not initialized.

The function mimics the workings of SDL_ListModes, returning an array of pairs (2 element arrays) with x, y items, if a set of mode was found, nil if no mode is available and -1 if SDL says "all the modes" are available.

If passing nil as the desired pixel format, then the default screen pixel format will be used.

LoadBMP

Loads an image from a BMP file.

SDL.LoadBMP( filename )
filename a filename to load.
Returna SDLSurface instance containing the loaded image.
Raise
SDLError on load failure

Loads an image from a BMP file and returns a new SDLSurface instance that can be manipulated through blit and similar functions.

The filename is totally subject to SDL rules, as it is simply passed to SDL engine. No Falcon URI parsing is perfomred before invoking SDL; as such, it is advisable to use this function only in simple applications.

See also: SDLSurface.

MakeCursor

Builds an SDL cursor taking an array of strings as input.

SDL.MakeCursor( aImage, hotX, hotY )
aImage a string image.
hotX X coordinate of the hotspot.
hotY Y coordinate of the hotspot.

As it is generally quite hard to build a cursor writing directly its binary data, this helper method takes a set of strings in input and convers their visual representation to a valid cursor.

The strings must have a lenght mutliple of 8, as each of its element will fill a bit in the final cursor.

The hotspot coordinates must be equal to or smaller than the width and the height of the cursor. The width of the cursor is determined by the width of the strings, while its height is determined the size of the vector.

The characters in the image are considered as follows:

- "@": white opaque pixel

In example, the following code generates a small cross with white borders, a reverse inner part and a small black shadow:


      strImage = [
         "         @XXX@          ",
         "         @XXX@          ",
         "         @XXX@          ",
         "         @X.X@          ",
         "  @@@@@@@@X.X@@@@@@@@   ",
         "  XXXXXXXXX.XXXXXXXXX.  ",
         "  XXXXXXXXX.XXXXXXXXX.  ",
         "  @@@@@@@@X.X@@@@@@@@.  ",
         "         @X.X@........  ",
         "         @XXX@.         ",
         "         @XXX@.         ",
         "         @XXX@.         ",
         "          ....          " ]

      SDL.MakeCursor( strImage, 12, 7 ).SetCursor()

PollEvent

Polls for event and calls handlers if events are incoming.

SDL.PollEvent()
Returntrue if an event has been processed.

This method checks the SDL event queue, and if an event is ready for processing, it calls the handler provided by this instance.

To provide event handlers, it is necessary to derive a subclass from SDLEventHandler overloading the callbacks that must be handled, and then call PollEvent or WaitEvent on the instance.

If there isn't any event to be processed, this method returns immediately false.

PumpEvents

Update event listing and queueing during long operations.

SDL.PumpEvents()

Normally, a responsive SDL-Falcon program should issue a SDL.WaitEvent loop in its main code to start marshalling events to listeners, but it is also possible to periodically poll the status of keyboard and other devices with direct query functions.

To ensure the status is updated even when not calling WaitEvents, this method can be called. This will update all the internal device status representation, that will be then accurate if queried soon after.

Quit

Turns off SDL system.

SDL.Quit()

This call shuts down SDL and resets system status. It is possible to turn off only some subsystems using the a SDL.QuitSubSystem function.

QuitSubSystem

Shuts down a subset of SDL.

SDL.QuitSubSystem( subsys )
subsys bitwise or'd init flags mask.

This call shuts down one or more SDL subsystems.

See also: SDL.

SetGamma

Sets the gamma function values for the active SDL output.

SDL.SetGamma( red, green, blue )
red Red gamma correction value.
green Green gamma correction value.
blue Blue gamma correction value.
Raise
SDLError if the hardware doesn't support gamma

SetGammaRamp

Set Gamma ramps for this hardware.

SDL.SetGammaRamp( redbuf, greenbuf, bluebuf )
redbuf A 2 bytes 256 elements memory buffer for the red channel, or nil.
greenbuf A 2 bytes 256 elements memory buffer for the blue channel, or nil.
bluebuf A 2 bytes 256 elements memory buffer for the green channel, or nil.
Raise
SDLError if the hardware doesn't support gamma.

Each membuf is a 2 bytes memory vector of 256 binary values. If one of the channels needs not to be changed, nil can be placed instead.

SetModState

Sets current keyboard modifier state.

SDL.SetModState( state )
state the state to be set.

This method will alter the keyboard modifier state for the application. The state parameter can be a or'd combination of SDLKMOD enumeration elements.

SetVideoMode

Changes the video mode and/or starts SDL context window.

SDL.SetVideoMode( width, height, [bpp],[flags] )
width - desired width.
height - desired height.
bpp - byte per pixel in the desired modesired heightde (defaults to automatic).
flags - flags to be eventually specified.
Returna SDLScreen instance representing the SDL output device.
Raise
SDLError on initialization failure

This function starts a graphic video mode and, on success, returns a SDLScreen class instance. This class is a Falcon object which encapsulate SDL_Surface structures, and has specific accessors and methods to handle the special SDL_Surface that is considered a "screen" by SDL.

Flags can be one of the following value; also, some or'd combinations are possible.

- SDL.SWSURFACE

For a complete explanation of the flags, please refer to SDL official documentation.

See also: SDLScreen.

ShowCursor

Changes or query the visibility of the mouse cursor.

SDL.ShowCursor( [request] )
request The request for the cursor.
ReturnCurrent status of cursor visibility.

Toggle whether or not the cursor is shown on the screen. Passing SDL.ENABLE displays the cursor and passing SDL.DISABLE hides it. The current state of the mouse cursor can be queried by passing SDL.QUERY, either SDL.DISABLE or SDL.ENABLE will be returned.

The cursor starts off displayed, but can be turned off.

If the request parameter is not given, it defaults to SDL.ENABLE.

StartEvents

Stats dispatching of SDL events to this VM.

SDL.StartEvents()

This automatically starts an event listen loop on this virtual machine. Events are routed through the standard broadcasts.

If a previous event listener thread, eventually on a different virtual machine, was active, it is stopped.

Events are generated as broadcast message that can be received via standard subscribe.

Here follows the list of generated events.

Event sdl_Active

Application visibility event handler.

Parameters of the event:

See SDL_ActiveEvent description in SDL documentation.

Subscribe to this message method to receive ActiveEvent notifications.

Event sdl_KeyDown

Keyboard key down event handler. Parameters generated:

- state: SDL.PRESSED or SDL.RELEASED

See SDL_KeyboardEvent description in SDL documentation.

Subscribe to this message method to receive SDL_KEYDOWN notifications.

Event sdl_KeyUp

Keyboard key up event handler. Parameters:

- state: SDL.PRESSED or SDL.RELEASED

See SDL_KeyboardEvent description in SDL documentation.

Subscribe to this message method to receive SDL_KEYUP notifications.

Event sdl_MouseMotion

Mouse motion event handler. Parameters:

- state: The current button state

See SDL_MouseMotionEvent description in SDL documentation.

Subscribe to this message method to receive SDL_MOUSEMOTION notifications.

Event sdl_MouseButtonDown

Mouse button event handler. Parameters:

See SDL_MouseButtonEvent description in SDL documentation.

Subscribe to this message method to receive SDL_MOUSEBUTTONDOWN notifications.

Event sdl_MouseButtonUp

Mouse button event handler. Generated parameters:

- state: The current button state

See SDL_MouseButtonEvent description in SDL documentation.

Subscribe to this message method to receive SDL_MOUSEBUTTONUP notifications.

Event sdl_JoyAxisMotion

Joystick axis motion event handler. Parameters:

- which: Joystick device index

See SDL_JoyAxisEvent description in SDL documentation.

Subscribe to this message method to receive SDL_JOYAXISMOTION notifications.

Event sdl_JoyButtonDown

Joystick button event handler. Parameters

- which: Joystick device index

See SDL_JoyButtonEvent description in SDL documentation.

Subscribe to this message method to receive SDL_JOYBUTTONDOWN notifications.

Event sdl_JoyButtonUp

Joystick button event handler

- which: Joystick device index

See SDL_JoyButtonEvent description in SDL documentation.

Subscribe to this message method to receive SDL_JOYBUTTONUP notifications.

Event sdl_JoyHatMotion

Joystick hat position change event handler. Parameters:

- which: Joystick device index

See SDL_JoyHatEvent description in SDL documentation.

Subscribe to this message method to receive SDL_JOYHATMOTION notifications.

Event sdl_JoyBallMotion

Joystick trackball motion event handler. Parameters:

- which: Joystick device index

See SDL_JoyBallEvent description in SDL documentation.

Subscribe to this message method to receive SDL_JOYBALLMOTION notifications.

Event sdl_Resize

Window resize event handler. Parameters:

- w: New width of the window

See SDL_ResizeEvent description in SDL documentation.

Subscribe to this message method to receive SDL_VIDEORESIZE notifications.

Event sdl_Expose

Window exposition (need redraw) notification. This event doesn't generate any parameter.

See SDL_ExposeEvent description in SDL documentation.

Subscribe to this message method to receive SDL_VIDEOEXPOSE notifications.

Event sdl_Quit

Quit requested event.

See SDL_Quit description in SDL documentation.

Subscribe to this message method to receive SDL_Quit events.

This notification means that the user asked the application to terminate. The application should call exit(0) if no other cleanup routines are needed, or perform cleanup and notifications for clean exit to other threads/coroutines.

StopEvents

Stops dispatching of SDL events.

SDL.StopEvents()

This immediately stops dispatching events. It is NOT necessary to perform this call before closing a program, but a VM may want to start manage events on its own, or to ignore them.

If asynchronous event dispatching wasn't active, this call has no effect.

VideoDriverName

Returns the name of the used video driver.

SDL.VideoDriverName()
ReturnA simple description of the video driver being used.
Raise
SDLError if the system is not initialized.

VideoModeOK

Verifies if a given video mode is ok

SDL.VideoModeOK( width, height, [bpp],[flags] )
width - desired width.
height - desired height.
bpp - byte per pixel in the desired modesired heightde (defaults to automatic).
flags - flags to be eventually specified.
Return0 if the mode isn't available, or a bit per pixel value for the given mode.

The function can be used to checked if a video mode can be used prior to starting it. If the mode is available, a preferred bit per pixel value is returned, otherwise the function returns zero.

WaitEvent

Waits forever until an event is received.

SDL.WaitEvent()

This method blocks the current coroutine until a SDL event is received. However, the VM is able to proceed with other coroutines.

As soon as a message is received and processed, the function returns, so it is possible to set a global flag in the message processors to communicate new program status to the subsequent code.

In example, the following is a minimal responsive SDL Falcon application.


      object handler
         shouldQuit = false

         function on_sdl_Quit()
            self.shouldQuit = true
         end
      end

      ...
      ...
      
      // main code
      subscribe( "sdl_Quit", handler )
      
      while not handler.shouldQuit
         SDL.WaitEvent()
      end

Note: You can also start an automatic event listener and dispatcher in a parallel thread with SDL.StartEvents. This will oviate the need for a polling or waiting loop.

WasInit

Detects if some SDL subsystem was initialized.

SDL.WasInit( [flags] )
flags SDL initialziation flags.
Returna bitmask containing the initialized subsystems (among the ones requested).

The parameter defautls to SDL_INIT_EVERYTHING if not provided.

Made with http://www.falconpl.org