Click here to Skip to main content
15,867,317 members
Articles / Multimedia / DirectX
Article

A DirectX Wrapper

Rate me:
Please Sign up or sign in to vote.
4.69/5 (20 votes)
18 Jul 200333 min read 180.7K   4.3K   66   14
A DirectX Wrapper

Image 1

Table Of Contents

Installation

Unzip the project in any directory of your choosing.  The main workspace can be opened using the "DXSmithLib.dsw" workspace.  The program requires at least DirectX 7.0 to compile and run.

[editor's note--the programs have been compiled and run successfully using VS6 on a Win2K machine with DirectX 9.0 SDK installed]

  • testwin - A simple demonstration program (see above screenshot)
  • testgui  - Tests a gui full-screen. It is a command line app. Run the batch file "use_testgui.bat". The mouse_cursor.bmp MUST be in a sub-dir called data located in the directory that testgui.exe is located.
  • testsprite - View a sprite full screen to see how it looks on a black background. It is mainly an example of using a sprite in a simple program.  It takes only one parameter: the name of a spritebank (file.spr) created by SpriteEdit.  The .SPR file and its required .BMP files must be in a directory called data, located where the exe is.
  • SpriteEdit - The sprite editor
  • GuiEdit - The GUI editor

DXSmith - Overview

DXSmith is a wrapper around Microsoft's DirectX graphic libraries. The current version wraps the Direct Draw 2D graphics, I/O, sound, and music for DX7. No 3D functions are wrapped or used. The DXSmith wrapper provides a set of higher level functions that are easier to use and learn than the DirectX API. DXSmith makes it easier for beginners to use DirectX. DirectX is a very flexible API, but that very flexibility also makes it fairly complicated. DXSmith also provides tools to create and draw animated sprites, and simple GUI's without using MFC calls. A number of GDI calls are also wrapped to provide higher level functions like lines, circles, text, and pie sections. DXSmith also provides "resource management". Place all your data files in a sub-directory, or libraries in the sub-directory and the resource manager will load, unload, and track the resources in memory.

DXSmith provides everything for the amateur game programmer to get started with DirectX.

DXSmith I/O Library

  • The I/O library provides the graphic primitives, user input, and sound and music functions that are the building blocks of all other DXSmith utilities.
  • See testwin for an example of using the DXSmith lib. TestWin is a bare-bones windows program that uses the DXSmith i/o library. It is an excellent example of using the library, and is simple enough to easily modify for your own use.
  • Test1 is a console program that exercises all key parts of the library.
  • TestGUI allows you to test gui panels created with GUIEdit.

Miscellaneous Functions

GetLastError

int 
GetLastError(CString *errStr);
Return the last error code and string set by a CgsdxIO() function. GSDX_OK is returned if no errors have yet occurred.

errStr: the last error string is copied to this.

RETURNS: Last error code.

GetINI (version 1)

DWORD 
GetINI(LPCSTR pSectionName, LPCSTR pKeyName, LPCSTR \<BR>pDefault, char 
*pReturnedString, DWORD sizeRetStr, LPCSTR pFileName);

Read text data from a normal text INI file.

pSectionName   name of the section to read the data from. Do not include the "[ ]" in the section name.
pKeyName   name of the key within the section to read.
pDefault   value to return if the section or key is not found.
pReturnedString   string to copy the requested value to from the INI file.
sizeRetStr   length of pReturnedString. If the length of the data exceeds sizeRetStr it will be truncated.
pFileName   name of the INI file to read from. If the filename includes a path (detected by searching for the back-slash "\" character) the resource paths are not searched. If the filename has no path, then the currently registered resource paths are searched for the INI file.

RETURNS: Length of the string copied to pReturnedString.

Example:

char str[90];
GetINI("main_section", "one_key", "default_value", str, 90, "foobar.ini");

GetINI (version 2)

DWORD 
GetINI(LPCSTR pSectionName, LPCSTR pKeyName, long \<BR>defaultValue, long 
*pReturnedLong, LPCSTR pFileName); 

Read integer data from a normal text INI file. Attempts to convert the text to an integer.

pSectionNamename of the section to read the data from. Do not include the "[ ]" in the section name.
pKeyNamename of the key within the section to read.
pDefaultvalue to return if the section or key is not found.
pReturnedLonginteger to copy the requested value to from the INI file.
pFileNamename of the INI file to read from. If the filename includes a path (detected by searching for the back-slash "\" character) the resource paths are not searched. If the filename has no path, then the currently registered resource paths are searched for the INI file.

RETURNS: Length of the string representing the integer copied to pReturnedLong.

Example:

long val;
GetINI("main_section", "one_key", 999, &val, "foobar.ini");

SetINI (Version 1)

int SetINI(LPCSTR pSectionName, LPCSTR pKeyName, LPCSTR pString, LPCSTR pFileName);

Write text data to a normal text INI file.

pSectionNamename of the section to write the data to. Do not include the "[ ]" in the section name.
pKeyNamename of the key within the section to set.
pStringvalue to set the key to.
pFileNamename of the INI file to write to. If the filename includes a path (detected by searching for the back-slash "\" character) the resource paths are not searched. If the filename has no path, then the currently registered resource paths are searched for the INI file.

RETURNS: Non-zero on success.

Example:

SetINI("main_section", "one_key", "key_value", "foobar.ini");

SetINI (Version 2)

int 
SetINI(LPCSTR pSectionName, LPCSTR pKeyName, long value, LPCSTR 
pFileName);

Write integer data to a normal text INI file. Converts the integer to text.

pSectionNamename of the section to write the data to. Do not include the "[ ]" in the section name.
pKeyNamename of the key within the section to set.
valuevalue to set the key to.
pFileNamename of the INI file to write to. If the filename includes a path (detected by searching for the back-slash "\" character) the resource paths are not searched. If the filename has no path, then the currently registered resource paths are searched for the INI file.

RETURNS: Non-zero on success.

Example:

SetINI("main_section", "one_key", 1234, "foobar.ini");

Graphics

Blit

int Blit(RECT *pDest, gsdxBitmap_t *pSrc, int transparent=1, HDC 
hdc=NULL);

Draw a bitmap to the off-screen buffer. Call Flip() to display the current off-screen buffer. Use pDest to set the size and location of the bitmap. By changing the destination size you can scale the bitmap to any desired size. Clipping is supported. If clipping is disabled be sure that pDest does not exceed the off-screen buffer's boundaries.

pDestthe destination position and size of the bitmap to be blitted. Note that the (right - left) equals the width, not the width -1, and (bottom - top) equals the height.
pScrsource bitmap, loaded by LoadBitpmap().  Transparent--if non-zero then all pixels matching the top-left pixel are transparent. Transparency not supported in GDI mode.
hdcif not NULL the specified hdc is used instead of the default full-screen hdc.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Blit

int Blit(POINT *pDest, gsdxBitmap_t *src, int transparent=1, HDC 
hdc=NULL);

Draw a bitmap to the off-screen buffer. Call Flip() to display the current off-screen buffer. Use pDest to set location of the bitmap. The bitmap is displayed at its original size. If clipping is disabled be sure that blitted bitmap does not exceed the off-screen buffer's boundaries.

pDest the destination position of the bitmap to be blitted.
pScr source bitmap, loaded by LoadBitpmap().  Transparent--if non-zero then all pixels matching the top-left pixel are transparent.  Not supported in GDI mode.
hdc if not NULL the specified hdc is used instead of the default full-screen hdc.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

ConvertRGB

DWORD CgsdxIO::ConvertRGB(DWORD rgb);

Convert an RGB colour for use with the current video mode. Not required for any function that uses GDI (Line(), Ellipse(), PieFill()). Should be used for any DirectX function that takes a color parameter (Blit()). Only valid for full-screen modes, and requires that InitGraphics() be called previously.

RETURNS: A DWORD that is the converted colour.

EnableClipping

int EnableClipping(int enable=1);

Enable and disable clipping. Must call SetClipping() before enabling clipping.

enable: if no-zero clipping is enabled, if zero clipping is disabled.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

EllipseFill

int EllipseFill(int left, int top, int right, int bottom, DWORD colour, 
HDC hdc);

Draw a filled ellipse in the rectangle bounded by left, top, right, bottom. Colour is a RGB colour.

RETURNS: Zero on success.

Flip

int Flip(void);

Display the current off-screen buffer, and make the currently displayed buffer the off-screen buffer. The normal procedure is to call the various drawing functions until the complete frame is ready, then call Flip() to display it.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetGraphicModeInfo

inline gsdxMode_t *GetGraphicModeInfo(int index);

Return information for the selected graphics mode. Must call GetModes() before calling this function. Use GetNumGraphicModes() to get the number of detected graphics modes.

index: index of graphics mode to get information for. Indexes start at zero.

typedef struct
{
int width, height; // size of logical screen
int colorBits; // color depth
}
gsdxMode_t;
RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetModes

int GetModes(void);

Detect all the supported video modes. After calling this function GetGraphicModeInfo() and GetNumGraphicModes() can be called to get information on all supported graphics modes.

RETURNS: Zero on success. A GSDX_ERROR_... code on failure.

GetNumGraphicModes

inline int GetNumGraphicModes(void);

Returns the number of detected video modes. Must call GetModes() before calling this function.

RETURNS:
Number of detected video modes.

InitGraphics

int InitGraphics(int width, int height, int colorDepth, DWORD 
options);

Initialize the graphics mode. For the full-screen option setup a primary buffer and off-screen buffer. Use GetModes() and GetGraphicsModeInfo() to detect support widths, heights, and color depths. If the GDI mode is selected the current video mode is NOT changed, and no buffers are prepared.

This function must be called before any other graphics function is called.

widthwidth of the screen in pixels.
heightheight of the screen in pixels.
colorDepthnumber of bits per pixel.
optionsfull-screen or GDI. If full screen the GDSX_CONSOLE_MODE option must also be used if the exe if a console application.

 

GSDX_FULL_SCREEN   Exclusive full screen mode with double buffering.
GSDX_WINDOWED_GDI   Retain the current video mode. (NOTE: some functions will not be supported or have reduced function).
GSDX_CONSOLE_MODE   Only use with the full screen option if the exe is a console application. Failing to use this option with console applications will cause the application to crash.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

IsMode

int IsMode(int width, int height, int colorDepth);

Returns non-zero if the specified video mode is supported in full-screen mode.

widthwidth in pixels of mode to check.
heightheight in pixels of mode to check.
colorDepthcolorDepth, in bits, of mode to check.

RETURNS: Non-zero if the specified video mode is support, zero if the mode is not supported.

Line

int Line(int x0, int y0, int x1, int y1, int width, DWORD 
colour);

Draw line from (x0, y0) to (x1, y1) using the width and color specified. Note that the value passed to color depends on the pixel format of the selected mode.

x0starting X position
y0starting Y position
x1ending X position
y1ending Y position
widthwidth of the line in pixels
colourcolour of the line. Note that same value of colour will give different colours on the screen depending on the current video mode and pixel format for that mode.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

LoadBitmap

gsdxBitmap_t *LoadBitmap(LPCSTR pFileName, RECT *pRect);

Load a bitmap from a file and prepare it to be blitted for the currently selected video mode. InitResource() must be called first.

If the image is already loaded the currently loaded image is used for the bitmap. One image can have many bitmaps stored on it. Each bitmap will point to the area of the main image containing its region.

The returned bitmap must be `deleted' when the bitmap is no longer required.  This only deletes this particular bitmap (which includes a pointer to the main source image), NOT the main source image in memory. Call UnLoadAllBitmaps() to unload all the main source images.

pFileNamename of the bitmap to be loaded. The resource paths and libraries are searched if there is no path included in the name.  Currently only BMP format files are supported, and must have the .bmp file extenstion.
pRectif NULL the returned bitmap is the whole source image. If pRect is not NULL and right and bottom are not zero then it defines the region of the source image to return as the bitmap. This enables multiple bitmaps to be stored in one image file. If pREct is not NULL, but right and bottom are zero then pRect is filled in with the size of the whole source image.

RETURNS: Pointer to the loaded bitmap.

PieFill

int PieFill(int left, int top, int right, int bottom, \<BR>int x1, int 
y1, int x2, int y2, DWORD colour,HDC hdc=NULL);

Draw pie-shaped filled section. The Pie is `cut' from an ellipse bounded by left, top, right, bottom, and bounded by lines starting at the centre of the bounding box and going out through (x1,y1) and (x2,y2) in a counter-clock wise direction.

RectFill

int RectFill(RECT *rect, DWORD color, HDC hdc=NULL);

Draw a solid filled rectangle. Note that the same value of color will give different colors on screen depending on the current video mode's pixel format. Use ConvertRGB() to change an RGB() value to a video mode specific value. This function may be faster than Line() for vertical and horizontal lines.

rectdefines the rectangular region to be filled.
colorcolour of the filled rectangle. Note that the same value of color will give different colours on screen depending on the current video mode's pixel format.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

SetBlitOptions

int SetBlitOptions(DWORD optionFlags);

Not implemented.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

SetClipping

int SetClipping(RECT *pClipRect, int numRects=1);

Define multiple clipping regions. Use EnableClipping() after calling this function to enable the defined clipping regions. All Blits() and RectFills() that fall outside of the defined regions will be clipped (not displayed). A second call to SetClipping() deletes the previous clipping regions and sets up the new regions.

pClipRects array of RECTS, each of which defines one clipping region.
numRects number of RECTS in pClipRects.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Example:

RECT *clips, r;

clips=new RECT[2];
clips[0].right=900;
clips[0].left=100;
clips[0].top=100;
clips[0].bottom=500;
clips[1].right=90;
clips[1].left=0;
clips[1].top=0;
clips[1].bottom=90;

SetClipping(clips, 2);

r.left=100;
r.right=900;
r.top=100;
r.bottom=500;

SetClipping(&r); // default 1 rect
EnableClipping(); // default ON

UnLoadAllBitmaps

int UnLoadAllBitmaps(void);

Unloads ALL main source bitmap images. All loaded bitmaps MUST be `deleted' in addition to calling this function.

RETURNS: Zero on success. A GSDX_ERROR_... code on failure.

Text Functions

DrawText

int DrawText(HFONT font, int x, int y, DWORD fore, DWORD back, 
\<BR>LPCSTR s, SIZE *size=NULL, HDC hdc=NULL);

int 
DrawText(HFONT font, int x, int y, DWORD fore, DWORD back, \ <BR>LPCSTR s, int 
len, SIZE *size, HDC hdc);

int DrawText(HFONT font, int x, int y, DWORD fore, DWORD back, char 
\<BR>a, SIZE *size, HDC hdc);

Draw text on the screen using the specified font, colour, and position.

font if NULL, use the default font. If not NULL it must be a font created by CreateFont().
x, y position on the screen of the top left pixel of the text.
fore colour of the text. Note that the same value of colour will display different colours depending on the pixel format of the current video mode.
back background colour. Use GSDX_TRANSPARENT_TEXT for a transparent background.
s if using the version without `len' s is a null terminated string. If len is specified then s is at least len long.
len length of the string s.
size if not NULL it is filled with the region that the text was drawn to.
hdc if not NULL it over-rides the default full-screen hdc.

RETURNS:
Zero on success. A GSDX_ERROR_ code on failure.

DeleteFont

int DeleteFont(HFONT font);

Delete a font created with CreateFont().

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

CreateFont

HFONT CreateFont(int height, int weight, int proportional=1, int 
serif=1);

Create a font to be used with DrawText().

height logical height of the font. Not quite the same as pixels.
weight how `thick' the font is. 0 is `don't care' and the default will be used.  Must be between 0 and 1000.
proportional set to non-zero for a proportional font (each letter is a different width), or zero for a fixed-width font (each letter is the same width). Generally, proportional fonts look nicer.
serif set to non-zero for a serif font, zero for a non-serif font. Serif fonts have the little bars at the letters ends (eg Times), and non-serif lack these little bars (eg Arial).

These MS defined values can be used:

FW_THIN100
FW_EXTRALIGHT200
FW_LIGHT300
FW_NORMAL400
FW_MEDIUM500
FW_SEMIBOLD600
FW_BOLD700
FW_EXTRABOLD800
FW_HEAVY900


RETURNS: A pointer to a font that can be used with DrawText().

Example:

HFONT font=NULL;

font=CreateFont(24, FW_MEDIUM, 0, 1);
DrawText(font, 10, 100, RGB(255, 0,0), 0, "Hi World");
DeleteFont(font);

GetTextSize

int GetTextSize(HFONT font, char *s, SIZE *size, HDC 
hdc=NULL);

Get the dimensions of the string s for the font. size.cx is the width, size.cy is the height.

RETURNS: Zero if successful.

Example:
HFONT font;
SIZE size;

Font=CreateFont(24, 300, 1,1);
GetTextSize(font, "hi world", &size);

UnLoadAllFonts

int UnLoadAllFonts(void);

Completely delete all fonts created with CreateFont().

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Resources

AddResourcePath

int AddResourcePath(LPCSTR path);

Add a path to the list of paths search by the resource loading functions.

The resource loading functions search these directories:
exe_path/DATA
CD_DRIVE:/DATA
Paths added by AddResourcePath()

path: null terminated path to add.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Example:
AddResourcePath("<A href="file:///c://data//maps//">c:\\data\\maps\\</A>");

GetFullResourcePath

int GetFullResourcePath(LPCSTR pName, char *fullPath);

Search for pName in the resource directories, and return its full-path in fullPath if found.

pNamename of the file to find. Do not include any path, do include the extension.
fullPaththe full path and filename will be copied to fullPath if the file is found. Be sure fullPath is long enough for the longest legal path and filename.

RETURNS:
Zero on success. A GSDX_ERROR_ code on failure.

Example:

char path[MAX_PATH = 1];

GetFullResourcePath("foo.map", path);
path will be set to something like: c:\data\foo.map

GetResource

void * GetResource(DWORD index);

Get a pointer to a previously loaded resource. Does NOT increase its count. Does not load it if not found.

index: index of a previously loaded resource, as returned by LoadResource()

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Example:
long index;
Mapt_t *map1, *map1_alias;

map1=LoadResource("foo.map", &index);
map1_alias=GetResource(index);

InitResource

int InitResource(DWORD options);

Must be called before using ANY resource related function. LoadBitmap() and LoadSound() also requires that this be called as they use the resource functions. Does not depend on InitGraphics(). Default paths are added: exe_path\data, and cd_drive:\data where exe_path is the path that the exe ran from. cd_drive is the drive letter for any cd drive detected.

For example:
Foo.exe is run from c:\myexe on a computer with two cd drives, e: and f: and calls InitResource()
The default paths that are searched will be:

C:\myexe\data
E:\data
F:\data

options: not defined, set to zero.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

LoadResource

void * LoadResource(LPCSTR pName, DWORD *pIndex=NULL, DWORD 
*pSize=NULL);

Load a file into memory. The resource paths are searched for the file. Libraries in the resource paths are also searched. The last `good' path or library is searched first - always call LoadResource() on files in the same directory in batches if possible. If the file is already loaded its count is increased and the existing pointer is returned.

pName name of file to load into memory.
pIndex pointer to a DOWRD to return the INDEX in. Can be used by GetResource() to quickly get a pointer to a previously loaded resource. Using GetResource() is MUCH faster than calling LoadResource().
pSize pointer to a DWORD to hold the size, in bytes, of the file loaded into memory.

RETURNS: NULL on error, a pointer to the loaded file if OK. Call GetLastError() to get detailed error information.

Example:

Map_t *map;
DWORD index, size;
map=LoadResource("foo.map");
map=LoadResource("foo.map", &index, &size);

UnLoadAllResources

int UnLoadAllResources(void);

Unload all currently loaded resources. Ignores the count.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

UnLoadResource

int UnLoadResource(LPCSTR pName);

int UnLoadResource(DWORD index);

Decrement a resource count, and unloads from memory it if its count reaches zero.

pName name of a previously loaded resource without a path.
index index of a resource as returned by LoadResource()

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

Sound and Music

InitSound

int InitSound(DWORD options, WORD bits=8, WORD rate=22050);

Initializes sound and music. InitSound() MUST be called first. No sound or music functions will work until InitSound is called.

options not defined, use zero.
bits sample size for digital sound.
rate sampling rate for digital sound.

NOTES: For best performance all digital sounds should be created using the same bits and rate value which should be set correctly when InitSound() is called.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

LoadSound

int LoadSound(LPCSTR pName, DWORD *pID);

Pre-Load a sound so that it can be played by Playsound(). InitResource() must be called before this is called.

pName name of the WAV file to pre-load. The resource paths and libraries are searched.
pID the ID of the sound is copied to pID and is used to play the sound using PlaySound().

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

PlayMusic

int PlayMusic(LPCSTR pName, int loop=1);

Load and play a MIDI song. If a song is playing, it will be stopped and unloaded before the next is started.

pName name of the MID file to play. The resource paths are searched, but libraries cannot be used to store MIDI songs. If pName is NULL the current song  is stopped and unloaded.
loop set to non-zero to loop forever.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

PlaySound

int PlaySound(DWORD id, int loop=0, int pan=0, int 
pan_speed=0);

Plays a previously loaded sound.

id id value set by LoadSound().
loop set to non-zero to loop forever. Set to -1 to stop a currently playing sound. Does not unload the sound if it is stopped.
pan not implemented, set to zero.
pan_speed not implemented, set to zero.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

UnLoadAllSounds

int UnLoadAllSounds(void);

Stops and unloads all loaded sounds. A sound must be reloaded using LoadSound() after UnLoadAllSounds() is called before it can be played again.

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

User I/O

AcquireAllDevices

int AcquireAllDevices(void);

Used to re-acquire all I/O devices if they are lost. Often used in the WndProc() function for the WM_ACTIVATE message.

RETURNS: Zero on success.

GetAutoRepeat

DWORD GetAutoRepeat(void);

Return the current Keyboard auto-repeat rate in milliseconds.

GetAutoRepeatStart

DWORD GetAutoRepeatStart(void);

Return the current delay before the keyboard auto-repeat starts in milliseconds.

GetCapState

int GetCapState(void);

RETURNS: Zero if CAPSLOCK is off, non-zero if it is on.

GetEvent

gsdxEvent_t * GetEvent(gsdxEvent_t *pEvent=NULL);

This function should be called frequently to ensure all user i/o is processed correctly. This function updates internal data structures that are used by the i/o state functions. Even if you never use any events and only poll the i/o devices this function MUST be called frequently (a minimum of 60Hz is recommended).

If pEvent is NULL the user I/O is processed, but the latest event is discarded. All state information (eg joystick and mouse x, y position) is updated each time this function is called. InitIO() must be called with the events desired turned on. If a gsdxEvent_t pointer is passed in then the oldest event is copied to it.

Events:

  • Keyboard: each key press and release is an event.

Joystick:

  • X,Y, Rudder: moving to left/right/top/bottom or returning to centre generates an event.
  • Throttle (Z): each movement of more than 100th of the total throttle range generates an event.
  • Buttons: all presses and releases generate an event.
  • HAT: any change generates an event.

Mouse:

  • Buttons: each press and release generates an event.
  • X, Y: any movement generates an event.
  • Wheel: each `click' generates an event.

Please see the definition of gsdxEvent_t for details on the data returned in an event.

pEvent: pointer to gsdxEvent_t to hold the event information.

RETURNS: NULL if no event is ready, or no event passed in. Returns a pointer to pEvent if an event is available.

GetIoMode

DWORD GetIoMode(void);

Return the current I/O mode. A bitmask containing these options:

GSDX_IO_WANT_MOUSE_EVENTS
GSDX_IO_WANT_KEY_EVENTS
GSDX_IO_WANT_JOYSTICK_EVENTS
GSDX_IO_KEY_AUTO_REPEAT
GSDX_IO_WANT_ALL_EVENTS

GetJoystickInfo

int GetJoystickInfo(gsdxJoystickInfo_t *pJinfo, int 
index=0);

Return information about the detected joysticks.

pJinfo pointer to structure to hold the information for the selected joystick.
index index number of the joystick to get information on. Joysticks index start at zero (0).

Use GetNumberOfJoysticks() to get the maximum index.

// joystick enumeration information
typedef struct
{
int num_buttons; // joy buttons
int num_axis; // x, y, throttle, rudder etc...
int num_povs; // number of pov devices, eg a 'hat'
}
gsdxJoystickInfo_t;
RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetJoystickState

int GetJoystickState(gsdxJoystickState_t *pState, int 
index=0);

Return the current state of the selected joystick, that is, the current X, Y throttle, etc. values.

pState pointer to structure to hold the selected joysticks state.
index index to select joystick, indexes start at zero.
// current joystick state
typedef struct
{
int x, y, z; // z is throttle on MS sidewinder
int rx, ry, rz; // three 'rudders' rz is used by MS sidewinder
int pov[GSDX_MAX_POV]; // multiple pov's
DWORD buttons; // 32 buttons, if a bit is set the button is DOWN
}
gsdxJoystickState_t;
Example:
gsdxJoystickState_t joyState;
char temp[100], *t1;
DWORD mask;

GetEvent(NULL);
GetJoyStickState(&joyState);

// check the first 10 buttons
t1=temp;
for ( mask=1,i=0; i < 10; i++, mask<<=1 )
{
if ( (mask & joyState.buttons) )
*t1='*';
else
*t1=' ';
t1++;
}
RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetNumberOfJoysticks

inline int GetNumberOfJoysticks(void);

Get the number of active joysticks detected.

RETURNS: Number of active joysticks detected.

GetNumState

int GetNumState(void);

RETURNS: Zero if the NUMLOCK is off, non-zero if it is on.

GetMouseInfo

int GetMouseInfo(gsdxMouseInfo_t *pMinfo);

Return information on the type of mouse detected.

pMinfo: pointer to a gsdxMouseInfo_t to hold the mouse information.
typedef struct
{
int num_buttons; // left, right, wheel button, other buttons
int num_axis; // X Y are 2 axis, wheel mouse adds a third axis.
}
gsdxMouseInfo_t;
RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetMouseState

int GetMouseState(gsdxMouseState_t *pState);

Return the current state of the mouse, X, Y, wheel position, buttons.

pState: pointer to structure to hold the current mouse state.
// current mouse state
typedef struct
{
int x, y, z; // wheel is z, current value for each of these
int dx, dy, dz; // wheel is z, change in each value since last call
DWORD buttons; // if a bit is set the button is down.
int max_x, max_y, max_z; // Max_x and max_y 
// default to the screen resolution in pixels.
}
gsdxMouseState_t;
RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

GetScrollState

int GetScrollState(void);

RETURNS: Zero if the SCROLLOCK is off, non-zero if it is on.

InitIO

int InitIO(DWORD options=GSDX_IO_WANT_ALL_EVENTS);

Must be called before using any other i/o functions. InitGraphics() MUST be called before InitIO() is called.

options: controls the type of events generated by GetEvent(). Use a logical OR to combine the desired events.

GSDX_IO_WANT_MOUSE_EVENTS
GSDX_IO_WANT_KEY_EVENTS
GSDX_IO_WANT_JOYSTICK_EVENTS
GSDX_IO_KEY_AUTO_REPEAT
GSDX_IO_WANT_ALL_EVENTS

RETURNS: Zero on success. A GSDX_ERROR_ code on failure.

IsKeyDown

int IsKeyDown(DWORD index);

Return the current status of one key on the keyboard. Note that due to limitations of keyboard hardware that only a limited number of keys can be held down simultaneously.

index: the DIK_ code (as defined by the MS include file) of the key to query.

RETURNS: Zero if the key is not currently pressed, no-zero if it is currently pressed.

Example:
if ( IsKeyDown(DIK_ESCAPE) )
printf("ESC is pressed\n");
All supported DIK codes (not all keyboards have all these keys):
[Editor's note: this is a long list]
DIK_ESCAPE
DIK_1
DIK_2
DIK_3
DIK_4
DIK_5
DIK_6
DIK_7
DIK_8
DIK_9
DIK_0
DIK_MINUS
DIK_EQUALS
DIK_BACK

DIK_TAB
DIK_Q
DIK_W
DIK_E
DIK_R
DIK_T
DIK_Y
DIK_U
DIK_I
DIK_O
DIK_P
DIK_LBRACKET
DIK_RBRACKET
DIK_RETURN
DIK_LCONTROL

DIK_A
DIK_S
DIK_D
DIK_F
DIK_G
DIK_H
DIK_J
DIK_K
DIK_L
DIK_SEMICOLON
DIK_APOSTROPHE
DIK_GRAVE

DIK_LSHIFT
DIK_BACKSLASH
DIK_Z
DIK_X
DIK_C
DIK_V
DIK_B
DIK_N
DIK_M
DIK_COMMA
DIK_PERIOD
DIK_SLASH
DIK_RSHIFT
DIK_MULTIPLY

DIK_LMENU
DIK_SPACE
DIK_CAPITAL

DIK_F1
DIK_F2
DIK_F3
DIK_F4
DIK_F5
DIK_F6
DIK_F7
DIK_F8
DIK_F9
DIK_F10

DIK_NUMLOCK
DIK_SCROLL

DIK_NUMPAD7
DIK_NUMPAD8
DIK_NUMPAD9
DIK_SUBTRACT
DIK_NUMPAD4
DIK_NUMPAD5
DIK_NUMPAD6
DIK_ADD
DIK_NUMPAD1
DIK_NUMPAD2
DIK_NUMPAD3
DIK_NUMPAD0
DIK_DECIMAL

DIK_OEM_102
DIK_F11
DIK_F12
DIK_F13
DIK_F14
DIK_F15

DIK_KANA
DIK_ABNT_C1
DIK_CONVERT
DIK_NOCONVERT
DIK_YEN
DIK_ABNT_C2
DIK_NUMPADEQUALS
DIK_PREVTRACK
DIK_AT
DIK_COLON
DIK_UNDERLINE
DIK_KANJI
DIK_STOP
DIK_AX
DIK_UNLABELED
DIK_NEXTTRACK
DIK_NUMPADENTER
DIK_RCONTROL
DIK_MUTE
DIK_CALCULATOR
DIK_PLAYPAUSE
DIK_MEDIASTOP
DIK_VOLUMEDOWN
DIK_VOLUMEUP
DIK_WEBHOME
DIK_NUMPADCOMMA
DIK_DIVIDE
DIK_SYSRQ
DIK_RMENU
DIK_PAUSE

DIK_HOME
DIK_UP
DIK_PRIOR
DIK_LEFT
DIK_RIGHT
DIK_END
DIK_DOWN
DIK_NEXT
DIK_INSERT
DIK_DELETE

DIK_LWIN
DIK_RWIN
DIK_APPS

DIK_POWER
DIK_SLEEP
DIK_WAKE

DIK_WEBSEARCH
DIK_WEBFAVORITES
DIK_WEBREFRESH
DIK_WEBSTOP
DIK_WEBFORWARD
DIK_WEBBACK
DIK_MYCOMPUTER
DIK_MAIL
DIK_MEDIASELECT

SetAutoRepeat

void SetAutoRepeat(DWORD rep);

Set the keyboard auto-repeat rate in milliseconds.

SetAutoRepeatStart

void SetAutoRepeatStart(DWORD rep);

Set the keyboard auto-repeat rate in milliseconds.

SetIoMode

void SetIoMode(DWORD ioMode);

Set the i/o mode.  Use these values:

GSDX_IO_WANT_MOUSE_EVENTS
GSDX_IO_WANT_KEY_EVENTS
GSDX_IO_WANT_JOYSTICK_EVENTS
GSDX_IO_KEY_AUTO_REPEAT
GSDX_IO_WANT_ALL_EVENTS (includes auto-repeat)

Example:

DWORD currMode;

// turn off keyboard autorepeat
currMode=GetIoMode();
currMode&=~ GSDX_IO_KEY_AUTO_REPEAT;
SetIoMode(currMode);

// and turn it back on
currMode=GetIoMode();
currMode|= GSDX_IO_KEY_AUTO_REPEAT;
SetIoMode(currMode);

GuiLib

GuiLib provides functions that display and use simple graphical user interfaces suitable for use with games without using any MFC or win32 calls. Use GUIEdit to create GUI panels.  Multiple panels can be loaded, but only the last loaded panel is active and returns events.

Initialization

CGui::CGui(CgsdxIO *dx);

dx: pointer to a fully initialised CgsdxIO object. dx is used for all i/o operations, including drawing the gui panel.

RETURNS: void

Example:
if ( dx.InitResource(0) )
 return 0;
if ( dx.InitGraphics(640, 480, 32, GSDX_FULL_SCREEN, g_hInst, g_hMainWnd) )
 return 0;
if ( dx.InitSound() )
 return 0;
if ( dx.InitIO() )
 return 0;

CGui gui(&dx);
CGui::~CGui();

On exit the current gui panel is unloaded.

See testgui for an example of using the gui lib.

gui_load_gadget

int gui_load_gadget(char *fname);

int gui_load_gadget(BYTE *buff);

Load a new gui panel, and prepare it for use. Makes it the active panel (loads onto tail of panel list)

fname name of the gui panel to load. The dx resource loader is used to locate the file.
buff pointer to a memory buffer holding a raw gui panel file.

RETURNS: zero if no errors.

gui_pop_gadget

void gui_pop_gadget(void)


Free the last gadget (panel) from the list and make the previous gadget the current gadget (panel).

gui_unload_gadget

void gui_unload_gadget(gui_list_t *gui_list);

Unload one panel, freeing all memory being used. An advanced function - generally gui_pop_gadget() is used to free the last gadget.

gui_unload_all_gadgets

int gui_unload_all_gadgets()

Unload ALL gadgets (panels) and free any memory they use.

gui_load_mouse

void gui_load_mouse(char *mouse_name);

Load a bitmap to be used as the mouse pointer.

mouse_name: name of a bmp file to be loaded and used as the mouse pointer. The WHOLE bitmap is used.

gui_hide_mouse

void gui_hide_mouse(void);

gui_show_mouse

void gui_show_mouse(void);

Hide or show the mouse. These calls can be nested. The mouse is hidden initially.

gui_do_gadget

int gui_do_gadget(gsdxEvent_t *event);

Do all logic related to a gui panel. Does not draw the gui panel. Takes user input and updates the status of the gui panel. See testgui for a complete example of its use in a normal windows program. The gadget (panel) last loaded is active.

event: pointer an event to return any user i/o in. The event type will indicate if it is a gui event, or other type of user i/o. The ID will indicate which gadget was used if it is a gui event.

RETURNS: non-zero if the user generated any events.

Example:

typedef struct

{
  HFONT font;
  int frame_count;
  DWORD last_time, elapsed;
  int paused;
  int done;
  char msg[MSGLEN+1];
  CGui *m_pGui;
}

TestInfo_t;
TestInfo_t tt;

int DoTestLogic(CgsdxIO *dx)
{
  gsdxEvent_t event;
  if ( tt.paused ) return tt.done;

  if ( tt.m_pGui->gui_do_gadget(&event) )
  {
      if ( event.type == GSDX_IO_TYPE_GUI)
      {
         switch ( event.event.gui.type )
         {
           case GUI_BUTTON:
                sprintf(tt.msg, "Button id %d clicked",
                event.event.gui.id);
                break;
  
           case GUI_RADIO:
                sprintf(tt.msg, "Radio id %d clicked, active = %d",
                event.event.gui.id,
                event.event.gui.parm1);
                break;
           case GUI_SLIDER:
                sprintf(tt.msg, "Slider id %d height = %d",
                event.event.gui.id,
                event.event.gui.parm1);
               break;
           case GUI_STRING_INPUT:
                sprintf(tt.msg, "Input id %d",
                event.event.gui.id);
               break;
           case GUI_PLIST:
                sprintf(tt.msg, "Plist id %d cursor item = %d",
                event.event.gui.id,
                event.event.gui.parm1);
                break;
         }
     }
     if ( dx->IsKeyDown(DIK_ESCAPE) ) tt.done=1;
  }
  return tt.done;
}

gui_draw_gadget

void gui_draw_gadget(void);

Draw the active gadget (panel). Should be called once per frame to update the gui panel to reflect user interaction.

Example:
int DoTestDraw(CgsdxIO *dx)
{
int err=0;
char temp[128];

if ( tt.paused ) return 0;

dx->RectFill(NULL, 0); // fill screen black
tt.m_pGui->gui_draw_gadget();

// draw some text
tt.frame_count++;
if ( tt.frame_count > 100 )
{
tt.elapsed=timeGetTime() - tt.last_time;
tt.last_time=timeGetTime();
tt.frame_count=0;
}
sprintf(temp, "frameRate: %04d", tt.elapsed/10);
dx->DrawText(tt.font, 1,1, RGB(0,255,0), 0, temp);
dx->DrawText(tt.font, 150,1, RGB(0,255,0), 0, tt.msg);

tt.m_pGui->gui_draw_mouse();

dx->Flip();

return err;
}

gui_draw_all_gadgets

void CGui::gui_draw_all_gadgets()

Draw ALL currently loaded gadgets.

GuiEdit

Image 2

GuiEdit is a visual editor for creating gui panels that can be used with the GUI lib. Gadgets can be added, deleted, copied, moved, resized, and the details edited. Use TestGui to display and test your gui panels under fullscreen mode. The TestGui source code also is a good example of using a gui panel created with GUIEdit.

This version of GuiEdit supports lists, buttons, radio buttons, text, and sliders.

NOTE! Use ID's higher than 99 for the gadgets you create to avoid conflicts with system created gadgets.

Menus

  • Menus
    • File
    • Save, Load gui panels. Works as expected.
  • Edit
    • Not used.
  • View
    • Turn on/off tool bars.
  • Gui
    • Grid - Set grid related options. When the Grid is ON, gadgets can only be moved and sized on the `grid'
    • Default Values - set default values used when creating new gadgets. These are NOT saved automatically on program exit.
    • Save Defaults - save the current defaults. Only one set can be saved.
    • Tab Order - When this is turned on the tab-order of each gadget is displayed at its top-left corner. Click on the gadgets in the order you want them to tab through. If gadgets are already in order you must still click on them in order. The next tab number is displayed at the lower-left of the view window. Choose this option again to leave the tab-order mode.
  • Context (Right-click)
    • Right-click on a gadget or the main rectangle to bring up this menu.
    • Add Gadget - add a gadget at the current mouse position. The top-left corner of the new gadget will be at the mouse position. Choose the desired gadget from the sub-menu.
    • Properties - will pop up a dialog allowing all options for the gadget under the mouse to be set.
    • Copy - copy the gadget under the mouse.
    • Delete - delete the gadget under the mouse.
  • Gadgets
    • Static Text, Used to place text on the gui panel. Cannot be edited.
    • Input Box, Allows the user to enter text. If the `password' option is enabled then only asterisks `*' are displayed. If the `numbers' option is selected only digits and the period `.' can be entered. Text entered can be up to 255 characters long. The input box supports horizontal scrolling.
    • Button - text
    • Button - bitmap
    • Button - sprite, a button that can be clicked on with one of the preceding items displayed on it.
    • Slider, a vertical or horizontal slider.
    • Radio buttons, a set of mutually exclusive buttons. Only one can be active.
    • Pick-List, display a list of text items and allow one, or multiple items to be selected.
  • General
    • Left-click on a gadget and drag to move it. Left-click on a gadget's lower, right corner and drag to re-size it. Right click on a gadget to access its properties.

SpriteLib

SpriteLib provides simple functions to load and display sprites created with SpriteEdit. A sprite is a collection of small bitmaps that are animated, eg bitmaps for a walking character.

CSprite

CSprite(CgsdxIO *dx);

Create a spriteObject. Each sprite object can hold multiple sprites, as created with SpriteEdit.

dx: pointer to a initialized CgsdxIO object.

RETURNS: void

DrawSprite

int DrawSprite(int index, int x, int y)

Each sprite in the currently loaded set is indexed, starting at zero. This function draws one sprite, using its current frame at position x, y. X, Y is the position of the top left corner of the sprite (plus adjustments as made in the sprite editor).

RETURNS: zero if no error, non-zero if error.

IncrementSprite

int IncrementSprite(int sprite_index, int direction);

Make the next or previous frame of the sprite current. Ignores the changeMode of the sprite. Useful for sprites with a manual changeMode.

sprite_index index of sprite to increment.
direction set to greater than zero for the next frame, set to less than zero for the previous frame. Will wrap the frame to the beginning/end if max/min frame is exceeded.

RETURNS: zero if no error, non-zero if error.

AnimateSpriteBank

int AnimateSpriteBank(void);

Move all sprites to the next frame if it is time to move them. Each sprite can have an independent animation speed which is honoured by this function.

RETURNS: zero if no error, non-zero if error.

FreeSpriteBank

int FreeSpriteBank(void);

Free all resources associated with all sprites in the bank;

RETURNS: zero if no error, non-zero if error.

LoadSpriteBank

int LoadSpriteBank(char *fname);

int LoadSpriteBank(BYTE *buff);

Load a sprite bank, as created by SpriteEdit into memory.

Fname name of a spritebank file. Uses the DX resource functions, thus requires that InitResources() has been called.
buff pointer to memory holding a valid spritebank file image.

RETURNS: zero if no error, non-zero if error.

GetWidest/Highest

int GetWidest(int index);

int GetHighest(int index);

Return the index of the Widest/Highest sprite in the current bank.

RETURNS: zero if no error, non-zero if error.

SetHDC

inline void SetHDC(HDC hdc);

SetSpriteBank

inline void SetSpriteBank(spriteBank_t *bank);

RETURNS: zero if no error, non-zero if error.

GetSpriteBank

inline spriteBank_t *GetSpriteBank(void);

Returns a pointer to the internal spriteBank structure. Not reccomended that you use this function! It allows you to directly change ANY value in the sprite bank.

See spritelib.h for details of the structure.

GetDrawMode

inline DWORD GetDrawMode(void);

Get the drawMode. Has no effect currently.

SetDrawMode

inline void SetDrawMode(DWORD mode);

Get the drawMode. Has no effect currently.

GetCollisionRect

inline RECT *GetCollisionRect(int index);

Get the collision rect of the current frame for the sprite indicated by index.

GetCurrentFrame

inline spriteFrame_t *GetCurrentFrame(int index);

Get a pointer to the internal data for the current frame of the sprite indicated by index. Allows any value of the current frame to be changed.

See spritelib.h for details of the structure.

GetCurrentFrameNum

inline int GetCurrentFrameNum(int index);

Get the current frame number (starting at zero) for the sprite indicated by index.

GetNumAttachPoints

inline int GetNumAttachPoints(int index);

Get the number of attach points defined for the sprite indicated by index.

GetNumFrames

inline int GetNumFrames(int index);

Get the number of frames for the sprite indicated by index.

GetAttachPoints

inline POINT *GetAttachPoints(int index, int 
indexAttach);

Get a pointer to the POINT structure for the attach point for the current frame.

Index sprite index;
IndexAttach index of the attach point to get for the current frame.

GetAttachPoints

inline POINT *GetAttachPoints(int index);

Get ALL the attach points for the current frame of the sprite indicted by index. Points are returned as an array of POINT structures.

GetID

inline DWORD GetID(int index);

Return the ID of the sprite indicated by index. Each sprite can have an ID set in SpriteEdit.

SetID

inline void SetID(int index, DWORD id);

Set the ID of a sprite.

GetDelay

inline DWORD GetDelay(int index);

Get the delay between changing to the next frame. The delay controls how fast the sprite is animated. The delay is in milliseconds (not terribly accurate).

SetDelay

inline void SetDelay(int index, DWORD delay);

Set the delay between frame changes, in milliseconds for a sprite.

GetDX/DY

inline int GetDX(int index);

inline int GetDY(int index);

Get dx or dy for the current frame. Dx/Dy is added the position the sprite is drawn at. This is set using the editor to make sprites line up nicely when animated.

GetChangeMode

inline DWORD GetChangeMode(int index);

Get the current changeMode of a sprite. Will be one of:

CHANGE_MANUAL: animation is OFF
CHANGE_CYCLE: 0 to n, back to n, ...
CHANGE_PONG: 0 to n, n to 0, 0 to n...

SetChangeMode

inline void SetChangeMode(int index, DWORD mode);

change the sprites changemode to one of:

CHANGE_MANUAL: animation is OFF
CHANGE_CYCLE: 0 to n, back to n, ...
CHANGE_PONG: 0 to n, n to 0, 0 to n...

SetDX/DY

inline void SetDX(int index, int dx);

inline void SetDY(int index, int dy);

Set the dx/dy for the current frame of the sprite. Dx/dy is added to the drawing position.

GetNumSprites

inline int GetNumSprites(void);

Get the number of sprites in the bank. Valid index are 0 to the number returned minus one.

SpriteEdit

Image 3

A sprite is a small graphic that can be moved across (animated) on the screen. Each sprite is made up of multiple frames that can be animated also. SpriteEdit allows you to load a bitmap, and select regions of the bitmap to be the frames of a sprite. Multiple sprites can be made from a single bitmap, and multiple bitmaps can be loaded into one "spritebank".

In general:

  1. Load a bitmap
  2. Create a new sprite
  3. Add frames to the sprite
  4. Save the sprite

Glossary

  • Load Rect: rectangular region of a bitmap surrounding one frame of a sprite.
  • Collision Rect: a rectangle, no larger than the current sprite frame, indicating where collision detection takes place.
  • Attach point: a point on the frame used as a reference for other actions, eg tip of a weapon where bullets would shoot from.
  • Frame: one image in a sprite.
  • Sprite: a collection of frames that can be animated
  • Bitmap: a picture containing artwork for one or more frames.

Menus

  • File
    • Save, Load sprite banks. Works as expected.
  • Edit
    • Not used.
  • View
    • Turn on/off tool bars.
  • Sprite
    • Animate Frames - toggle animation
    • Display Load Rect - toggle display of Load Rectangle outlines
    • Display Collision Rect - toggle display of collision rectangle outlines
    • Display Attach Points - toggle display of attach points
    • Load Bitmap - load an new bitmap that frames can be selected from
    • Add Frame - add a new frame after the current frame
    • Add Attach Point - append a new attach point
    • Delete Frame - delete the current frame
    • Delete Attach Point - delete the LAST attach point
    • Properties - Properties for the current sprite, and the current frame
    • New Sprite - add a new sprite to this bank
    • Delete Sprite - delete the current sprite
  • General
    • Left click and drag on a visible rectangle to move it. Hold down the SHIFT key while dragging to resize a rectangle. Hold down the CTRL key while dragging a collision rectangle to adjust the dx/dy of the current frame.
    • When adding a frame the currently displayed bitmap is used.
    • When adding a new sprite it is created with one frame that uses the currently displayed bitmap.
    • Loading a bitmap has no effect on the current sprite or frame.
  • Toolbar
    • The first two arrow icons move to the previous and next frames of the current sprite. Hold down the shift key while clicking to move the previous and next bitmaps. The second pair of arrows moves to the previous and next sprite.
    • The left and right arrow keys also change frames. The up and down arrow keys change sprites.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Canada Canada
Professional Programmer living in Beautiful Vancouver, BC, Canada.

Comments and Discussions

 
GeneralCDX Pin
Ali Khanlarkhani19-Jul-03 19:04
Ali Khanlarkhani19-Jul-03 19:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.