Code Snippets http://relishgames.com/forum/index.php?p=/categories/code-snippets/feed.rss Sun, 19 May 13 21:48:58 -0400 Code Snippets en-CA hgePlugin Update Thread http://relishgames.com/forum/index.php?p=/discussion/6369/hgeplugin-update-thread Sun, 28 Oct 2012 00:27:27 -0400 SantalLican 6369@/forum/index.php?p=/discussions
There are some small but powerful plugins (helpers)... Hope it will be helpful with someone.
More helpers will be added in future.

Now, let's enjoy guys !

1 - hgeAVI (v 0.01) - Video (rename to test.avi) - Lib (If necessary)
2 - hgePNGWriter (v 0.01)

Other (Not mine) :

TAngle class (degrees, radians, clamping)

Please report if one of these links is broken.
Thanks !]]>
TAngle class (degrees, radians, clamping) http://relishgames.com/forum/index.php?p=/discussion/5747/tangle-class-degrees-radians-clamping Wed, 21 Jul 2010 16:32:14 -0400 kvakvs 5747@/forum/index.php?p=/discussions
#pragma once

//! multiplier to translate degrees to radians
#define EE_DEG_TO_RAD (3.1415926f / 180.0f)

//! multiplier to translate radians to degrees
#define EE_RAD_TO_DEG (180.0f / 3.1415926f)

//! some random constant
#define EE_PI 3.14159265358979f

//! double some random constant
#define EE_DOUBLE_PI (2.0f * EE_PI)

//! The Angle
class TAngle
{
protected:
float Rad;

TAngle (float r): Rad (r)
{
}

public:
TAngle(): Rad(0.0f)
{
}

static TAngle Radians (float r)
{
return TAngle (r);
}

static TAngle Degrees (float d)
{
return TAngle (d * EE_DEG_TO_RAD);
}

inline float GetRadians() { return Rad; }
inline float GetDegrees() { return Rad * EE_RAD_TO_DEG; }

inline void SetRadians (float r) { Rad = r; }
inline void SetDegrees (float d) { Rad = d * EE_DEG_TO_RAD; }

inline float Cos() { return cosf (Rad); }
inline float Sin() { return sinf (Rad); }
inline float Abs() { return (float)fabs (Rad); }

inline void Clamp360()
{
if (Rad > EE_DOUBLE_PI)
{
Rad -= floorf (Rad / EE_DOUBLE_PI) * EE_DOUBLE_PI;
}
while (Rad < 0)
{
Rad += EE_DOUBLE_PI;
}
}
};

]]>
Solution: Get Render Target contents (DX8) http://relishgames.com/forum/index.php?p=/discussion/4785/solution-get-render-target-contents-dx8 Fri, 06 Mar 2009 10:46:36 -0500 kvakvs 4785@/forum/index.php?p=/discussions Render target contents was lost when application loses focus. I was coding Canvas-like functionality where game script could do drawing calls to Canvas render target and contents would be preserved as long as its needed, not getting lost on task switching. I searched for solutions to save render target contents.
Details: All searches on this forum gave me idea that Render Target contents CANNOT be acquired, because you can't lock Render Target texture. Although, you CAN copy textures - solution for DirectX 8 HGE is below.
Keywords: Render Target, Texture, Focus lost, gained, copy texture, CopyTexture

Prerequisites: You must add Gfx_GetDevice() function to HGE and HGE_Impl classes, so it requires little patching.

IDirect3DDevice8 * CALL HGE_Impl::Gfx_GetDevice()
{
return this->pD3DDevice;
}


Then add a new function to your own graphic module (I've made Graphics class to hide most of drawing code specifics from game). This function will do the copying job. As you see only surface level 0 is copied, so no mipmaps supported in this code, if you were going to use them - add more copy calls for other surface levels.

void Graphics::CopyTexture (HTEXTURE src, HTEXTURE dst)
{
LPDIRECT3DSURFACE8 srcSurface = NULL;
LPDIRECT3DTEXTURE8(src)->GetSurfaceLevel (0, & srcSurface);

LPDIRECT3DSURFACE8 dstSurface = NULL;
LPDIRECT3DTEXTURE8(dst)->GetSurfaceLevel (0, & dstSurface);

hge->Gfx_GetDevice()->CopyRects (srcSurface, NULL, 0, dstSurface, NULL);

srcSurface->Release();
dstSurface->Release();
}


Then finally - Usage example. Not the optimal code (creating texture on every render pass is bad bad!), but it proves the concept - texture contents is copied to texture and texture is rendered on screen.
	HTEXTURE	targetTex = hge->Target_GetTexture(mTarget);
HTEXTURE newTex = hge->Texture_Create (mWidth, mHeight);
Graphics::CopyTexture (targetTex, newTex);

hgeSprite contents (newTex, 0, 0, mWidth, mHeight);
contents.SetBlendMode (Graphics::GetBlending());
contents.SetColor (Graphics::mColor.GetHWColor());
contents.Render ( 0, 0 );

hge->Texture_Free (newTex);


P.S. For DX9 code will be little different due to CopyRects function changed name and params.]]>
Game State Engine http://relishgames.com/forum/index.php?p=/discussion/4089/game-state-engine Thu, 03 Jul 2008 20:37:56 -0400 Sharkgod999 4089@/forum/index.php?p=/discussions
Link:
[list]Full Package:
http://radishes.org/users/sharkgod999/GSE/downloads.htm
Docs:
http://radishes.org/users/sharkgod999/GSE/index.htm[/list:u]
Feel free to leave any comments or change anything in the source. Just post it here if you do.

Edit:
Here's a little explanation on how to set this up. I've also added some info on state changes.
http://radishes.org/users/sharkgod999/GSE/how_to_use_gse_with_hge.htm]]>
HGE TileMapXML http://relishgames.com/forum/index.php?p=/discussion/5969/hge-tilemapxml Thu, 20 Jan 2011 07:07:25 -0500 Jonathan.Deceptive 5969@/forum/index.php?p=/discussions http://www.mapeditor.org/) which enables TMX files to be displayed in HGE.

http://deceptivestudios.com/files/hgeTileMapXML.rar

I've supplied everything it needs including TinyXML and zlib, so it should be just a matter of adding it to your game and doing:


// add this to header
hgeTileMapXML *maps;

// in init function
maps = new hgeTileMapXML();
// repeat this for each map you wish to load, you can load them all at once if you wish or delete and new the maps pointer for each map
maps->LoadMap("MyMap1", hge->Resource_MakePath("mymap1.tmx"));
maps->LoadMap("MyMap2", hge->Resource_MakePath("mymap2.tmx"));

// in your render function
// iXPos and iYPos is current location
// this is used as center of screen unless you are getting close to edge then it will render up to the edge
maps->Render("MyMap1", iXPos, iYPos);

// you can also render specific layers (as defined in tiled-qt)
maps->RenderLayer("MyMap1", "Ground", iXPos, iYPos);
player->Render(iXPos, iYPos); // render above ground, but below stuff
maps->RenderLayer("MyMap1", "Stuff", iXPos, iYPos);


Hope this is useful to someone else out there.

Jonathan @ Deceptive]]>
hgeTTF v2.0 [NEW] http://relishgames.com/forum/index.php?p=/discussion/3860/hgettf-v2.0-new Sun, 10 Feb 2008 12:54:13 -0500 dewyatt 3860@/forum/index.php?p=/discussions Screenshots
imageimageimageimage

Download
Lib/Src/Example
http://www.sapian.net/files/hgeTTF2.7z
Thanks to Krakken for hosting.
Try the test program: Test/Test_Release.exe

Description
hgeTTF v2.0 has improved greatly since v1.0.
Bugs have been fixed.
Performance has been improved a significant amount.
hgeTTF turned into sfmlTTF when I switched to SFML.
But I ported it back to HGE for you HGEers.
You do not need anything except hge+hgehelp to use the library.
It is already linked with FreeType2.

Changes
Everything is now in the hgeTTF namespace.
No more singletons.

Features
-UNICODE support (via wstring/wchar_t)
-Uses FreeType2
-Uses hgeSprite for rotations, coloring, etc
-Uses kerning for fonts that support it
-Very easy to use
-Extremely fast
-Cache system

Usage
Add the include/lib directories to your project.
- Includes: hgeTTF/include
- Libs: hgeTTF/lib
Link with the library: hgeTTF_Debug.lib or hgeTTF_Release.lib

In your code you'll need to:
1 - Init hgeTTF::FontManager
2 - Load the font through the manager
4 - Draw

Here's an example:

hgeTTF::FontManager FontMgr;
FontMgr.Initialize();
FontMgr.loadFont("Font.ttf");
hgeTTF::Font* Font = FontMgr.getFont("Font.ttf");
Font->setSize(22);
Font->drawString(L"Test", 10, 50);
Font->printf(100, 100, L".2f", 2.0f);

First you need a hgeTTF::FontManager.
You must initialize this manager with Initialize(). If it is already initialized, this has no effect.
Then you use the manager to load a font - loadFont(Filename).
Then get the font from the manager using the filename - getFont(Filename).

Here we didn't check any return values, just to keep things simple.

Docs
There's no real documentation but you don't really need any.
Just view the header files.
Or hopefully you have some form of code completion (like VisualAssist).

Notes
-setHotSpot is relative. So 0.5,0.5 is the center.
-Compiled under VS2008 and includes those project files.]]>
TTF Fonts & runtime bitmap font creation http://relishgames.com/forum/index.php?p=/discussion/3767/ttf-fonts-runtime-bitmap-font-creation Sat, 05 Jan 2008 16:31:22 -0500 Kalith 3767@/forum/index.php?p=/discussions
I've always wanted to use .ttf fonts in my game, but I've experienced a few problems using them directly.
Why not using hgeFont ?
Well, we know that hgeFont is a pretty fast method to draw text. But it relies on a texture, which you must create before running your program with fonted.
That's not very handy.
So I though of creating this texture directly in my game from a .TTF file. Why not ?
To make it, I had to find a way to get the font name out of the .TTF file (there is no pre-built function for that...), borrow some code out of fonted and edit hgeFont to create a new constructor.
That eventualy worked !
I made a FontManager class to handle all that, and here it is if you are interested. (only using STL, nothing more. It's not very clean, but it works)
[edit] : forgot the new constructor...

FontManager.h :
#include "hge/hgefont.h"

#include

#include
#include

class FontManager
{
public :

static FontManager* getSingleton();

hgeFont* getFont(bool file, std::string szFontName, int nSize, bool bBold, bool bItalic);
void clear();

protected :

FontManager();

private:

static FontManager* mFontMgr;
std::map fntList;
std::vector ttfList;
};


FontManager.cpp :
#include 
#include
#include

#define MAX_TEXTURE_SIZE 1024

using namespace std;

extern HGE* hge;

struct CSymbolRange
{
unsigned short First;
unsigned short Last;
};

CHAR_DESC vChars[256];

//This is TTF file header
typedef struct _tagTT_OFFSET_TABLE
{
unsigned short uMajorVersion;
unsigned short uMinorVersion;
unsigned short uNumOfTables;
unsigned short uSearchRange;
unsigned short uEntrySelector;
unsigned short uRangeShift;
}TT_OFFSET_TABLE;

//Tables in TTF file and there placement and name (tag)
typedef struct _tagTT_TABLE_DIRECTORY
{
char* szTag; //table name
unsigned long uCheckSum; //Check sum
unsigned long uOffset; //Offset from beginning of file
unsigned long uLength; //length of the table in bytes

}TT_TABLE_DIRECTORY;

//Header of names table
typedef struct _tagTT_NAME_TABLE_HEADER
{
unsigned short uFSelector; //format selector. Always 0
unsigned short uNRCount; //Name Records count
unsigned short uStorageOffset; //Offset for strings storage, from start of the table

}TT_NAME_TABLE_HEADER;

//Record in names table
typedef struct _tagTT_NAME_RECORD
{
unsigned short uPlatformID;
unsigned short uEncodingID;
unsigned short uLanguageID;
unsigned short uNameID;
unsigned short uStringLength;
unsigned short uStringOffset; //from start of storage area

}TT_NAME_RECORD;

extern HGE *hge;

using namespace std;

FontManager::FontManager() {}

FontManager* FontManager::mFontMgr = NULL;

FontManager* FontManager::getSingleton()
{
if (mFontMgr == NULL)
mFontMgr = new FontManager;
return mFontMgr;
}

void FontManager::clear()
{
// Delete fonts
map::iterator iter;
while (!fntList.empty())
{
iter = fntList.begin();
delete iter->second;
fntList.erase(iter);
}

// Unreg TTF files
vector::iterator iter2;
while (!ttfList.empty())
{
iter2 = ttfList.begin();
RemoveFontResource(iter2->c_str());
ttfList.erase(iter2);
}
}

bool PlaceSymbols(int nWidth, int nHeight, CSymbolRange *pRanges, int nRangeCount)
{
int i, j;
int x=1, y=1;

for(i=0; i {
for(j=pRanges[i].First; j<=pRanges[i].Last; j++ )<br /> {
if(y+vChars[j].h+1 >= nHeight) return false;
if(x+vChars[j].w+1 >= nWidth)
{
x=1;
y+=vChars[j].h+1;
if(y+vChars[j].h+1 >= nHeight) return false;
}

vChars[j].x = x;
vChars[j].y = y;
x+=vChars[j].w+1;
}
}

return true;
}

HTEXTURE TextureGenerate(char *szFontName,
int nSize,
bool bBold,
bool bItalic,
CSymbolRange *pRanges,
int nRangeCount)
{
int i,j;
int nWidth, nHeight;

HDC hBMDC;
HBITMAP hBM;
BITMAPINFO bmi;
HFONT hFont;
ABCFLOAT abc;
TEXTMETRIC tTextMetrics;

HTEXTURE tex;
DWORD *pPixels, *pTexData, dwPixel;

// create font
hFont = CreateFont
(
-nSize, 0, 0, 0, (bBold) ? FW_BOLD : FW_NORMAL,
bItalic, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
//ANTIALIASED_QUALITY,
PROOF_QUALITY, // Renders much better small fonts !
DEFAULT_PITCH | FF_DONTCARE, szFontName
);

if(!hFont) return 0;

// create and setup compatible DC
hBMDC = CreateCompatibleDC(0);
SetTextColor(hBMDC, RGB(255,255,255));
SetBkColor(hBMDC, RGB(0,0,0));
SetBkMode(hBMDC, TRANSPARENT);
SetMapMode(hBMDC, MM_TEXT);
SetTextAlign(hBMDC, TA_TOP);
SelectObject(hBMDC, hFont);

// calculate symbols metrics
GetTextMetrics(hBMDC, &tTextMetrics);

for (i = 0; i < nRangeCount; i++ )
{
for (j = pRanges[i].First; j <= pRanges[i].Last; j++ )<br /> {
GetCharABCWidthsFloat(hBMDC, j, j, &abc);

// reserve pixels for antialiasing
vChars[j].a = int(abc.abcfA)-1;
vChars[j].c = int(abc.abcfC)-1;
vChars[j].w = int(abc.abcfB)+2;
vChars[j].h = tTextMetrics.tmHeight;
}
}

// calculate symbols placement
nWidth=32; nHeight=32;

for(;;)
{
if(PlaceSymbols(nWidth, nHeight, pRanges, nRangeCount)) break;

if(nWidth<=nHeight) nWidth<<=1;<br /> else nHeight<<=1;<br />
if(nWidth > MAX_TEXTURE_SIZE || nHeight > MAX_TEXTURE_SIZE)
{
DeleteObject(hFont);
DeleteDC(hBMDC);
return 0;
}
}

// create DC bitmap
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biWidth = nWidth;
bmi.bmiHeader.biHeight = -nHeight;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

hBM = CreateDIBSection(hBMDC, &bmi, DIB_RGB_COLORS, (void**)&pPixels, 0, 0);
if(!hBM)
{
DeleteObject(hFont);
DeleteDC(hBMDC);
return 0;
}

SelectObject(hBMDC, hBM);

// draw symbols onto DC bitmap
for (i = 0; i < nRangeCount; i++ )
{
for (j = pRanges[i].First; j <= pRanges[i].Last; j++ )<br /> {
char c = (char)j;
TextOut(hBMDC, vChars[j].x-vChars[j].a, vChars[j].y, &c, 1);
}
}
GdiFlush();

// transfer DC bitmap onto HGE texture with alpha channel
tex=hge->Texture_Create(nWidth, nHeight);
pTexData=hge->Texture_Lock(tex, false);

for (i=0; i {
for (j=0; j {
dwPixel = pPixels[i*nWidth+j];
dwPixel = 0xFFFFFF | ((dwPixel & 0xFF) << 24);<br /> pTexData[i*nWidth+j] = dwPixel;
}
}

hge->Texture_Unlock(tex);

// clean up
DeleteObject(hBM);
DeleteObject(hFont);
DeleteDC(hBMDC);

return tex;
}

string IntToHex( int i )
{
if (i < 0) i = 256+i;
char* c = new char[256];
itoa(i, c, 16);
string s = c;
delete c;

if (s.size() == 1)
s = "0" + s;

return s;
}

int HexToInt( const char* c )
{
int i;
stringstream iss;
iss << c;<br /> iss >> std::hex >> i;

return i;
}

unsigned long HexToULong( const char* c )
{
unsigned long u;
stringstream iss;
iss << c;<br /> iss >> std::hex >> u;

return u;
}

void GetErrors(fstream* f)
{
if (f->eof())
hge->System_Log("#Error parsing font file : end of file");
if (f->bad())
hge->System_Log("#Error parsing font file : bad");
else if (f->fail())
hge->System_Log("#Error parsing font file : fail");
}

unsigned short GetUSHORT(fstream* f, int* pos)
{
if (f->good() && *pos != -1)
{
f->seekg(*pos);
char* tmp = new char[256];
f->read(tmp, sizeof(unsigned short));
string s = "";
int i1 = tmp[0]; int i2 = tmp[1];
s += IntToHex(i1);
s += IntToHex(i2);
unsigned short u = HexToInt(s.c_str());

//hge->System_Log("USHORT(%d) : %u, %s", *pos, u, s.c_str());

*pos += sizeof(unsigned short);

delete tmp;

return u;
}
else
{
GetErrors(f);
*pos = -1;
return 0;
}
}

unsigned long GetULONG(fstream* f, int* pos)
{
if (f->good() && *pos != -1)
{
f->seekg(*pos);
char* tmp = new char[256];
f->read(tmp, sizeof(unsigned long));
string s = "";
int i1 = tmp[0]; int i2 = tmp[1]; int i3 = tmp[2]; int i4 = tmp[3];
s += IntToHex(i1);
s += IntToHex(i2);
s += IntToHex(i3);
s += IntToHex(i4);
unsigned long u = HexToULong(s.c_str());

//hge->System_Log("ULONG(%d) : %u, %s", *pos, u, s.c_str());

*pos += sizeof(unsigned long);

delete tmp;

return u;
}
else
{
GetErrors(f);
*pos = -1;
return 0;
}
}

string GetFontName(string lpszFilePath)
{
fstream f(lpszFilePath.c_str(), ios::in | ios::binary);
string csRetVal = "";

//lpszFilePath is the path to our font file
if (f.is_open())
{
//define and read file header
TT_OFFSET_TABLE ttOffsetTable;
int pos = ios::beg;

ttOffsetTable.uMajorVersion = GetUSHORT(&f, &pos);
ttOffsetTable.uMinorVersion = GetUSHORT(&f, &pos);
ttOffsetTable.uNumOfTables = GetUSHORT(&f, &pos);
ttOffsetTable.uSearchRange = GetUSHORT(&f, &pos);
ttOffsetTable.uEntrySelector = GetUSHORT(&f, &pos);
ttOffsetTable.uRangeShift = GetUSHORT(&f, &pos);

if (pos == -1)
return csRetVal;

//check is this is a true type font and the version is 1.0
if(ttOffsetTable.uMajorVersion != 1 || ttOffsetTable.uMinorVersion != 0)
return csRetVal;

TT_TABLE_DIRECTORY tblDir;
bool bFound = false;
string csTemp;

for (int i=0; i< ttOffsetTable.uNumOfTables; i++)
{
tblDir.szTag = new char[4];
f.read(tblDir.szTag, sizeof(char[4]));
pos += sizeof(char[4]);
tblDir.uCheckSum = GetULONG(&f, &pos);
tblDir.uOffset = GetULONG(&f, &pos);
tblDir.uLength = GetULONG(&f, &pos);

if (pos == -1)
return csRetVal;

//table's tag cannot exceed 4 characters
csTemp = tblDir.szTag;
csTemp.erase(4);

delete tblDir.szTag;

if (csTemp == "name")
{
//we found our table
bFound = true;
break;
}
}

if (bFound)
{
//move to offset we got from Offsets Table
pos = tblDir.uOffset;
TT_NAME_TABLE_HEADER ttNTHeader;
ttNTHeader.uFSelector = GetUSHORT(&f, &pos);
ttNTHeader.uNRCount = GetUSHORT(&f, &pos);
ttNTHeader.uStorageOffset = GetUSHORT(&f, &pos);

if (pos == -1)
return csRetVal;

TT_NAME_RECORD ttRecord;
bFound = true;
for (int i=0; i {
ttRecord.uPlatformID = GetUSHORT(&f, &pos);
ttRecord.uEncodingID = GetUSHORT(&f, &pos);
ttRecord.uLanguageID = GetUSHORT(&f, &pos);
ttRecord.uNameID = GetUSHORT(&f, &pos);
ttRecord.uStringLength = GetUSHORT(&f, &pos);
ttRecord.uStringOffset = GetUSHORT(&f, &pos);

if (pos == -1)
return csRetVal;

//1 says that this is font name. 0 for example determines copyright info
if (ttRecord.uNameID == 1)
{
//save file position, so we can return to continue with search
int nPos = f.tellg();
f.seekg(tblDir.uOffset + ttRecord.uStringOffset + ttNTHeader.uStorageOffset);

char* lpszNameBuf = new char[ttRecord.uStringLength + 1];
f.read(lpszNameBuf, ttRecord.uStringLength);
csTemp = lpszNameBuf;

//yes, still need to check if the font name is not empty
//if it is, continue the search
if (csTemp.length() > 0)
{
csRetVal = csTemp.erase(ttRecord.uStringLength);
break;
}
}
}
}
}

return csRetVal;
}

bool fileExists(string fileName)
{
fstream f;
f.open(fileName.c_str(), ios::in);
if (f.is_open())
{
f.close();
return true;
}
f.close();
return false;
}

string toString( float f )
{
ostringstream s;
s << f;<br /> return s.str();
}

hgeFont* FontManager::getFont(bool file, string szFontName, int nSize, bool bBold, bool bItalic)
{
string fntName;
if (file)
fntName = GetFontName(szFontName);
else
fntName = szFontName;

string id = fntName + "|" + toString(nSize) + "|" + toString(bBold) + "|" + toString(bItalic);
if (fntList.find(id) != fntList.end())
{
return fntList[id];
}
else
{
if ( (fileExists(szFontName) && file) || !file)
{
bool fFound = false;
vector::iterator iter;
while (iter != ttfList.end())
{
if (*iter == szFontName)
{
fFound = true;
break;
}
}

if (!fFound)
AddFontResource(szFontName.c_str());

CSymbolRange pRanges[2];
pRanges[0].First = 32;
pRanges[0].Last = 256;

// Generate the glyphs
HTEXTURE fntTex = TextureGenerate(
(char*)fntName.c_str(),
nSize, bBold, bItalic,
pRanges, 1
);

// Create the hgeFont interface
fntList[id] = new hgeFont(vChars, fntTex);

return fntList[id];
}
else
{
hge->System_Log("#Error# : Unknown font file : \"%s\"", szFontName.c_str());
return NULL;
}
}
}


hgefont.h, add :
struct CHAR_DESC
{
int x, y, w, h;
int a, c;
};

class hgeFont
{
public:
// ...
hgeFont(CHAR_DESC* vChar, HTEXTURE hTexture);


hgefont.cpp, add :
hgeFont::hgeFont(CHAR_DESC* vChar, HTEXTURE tex)
{
// Setup variables

hge=hgeCreate(HGE_VERSION);

hTexture=tex;
nMipMap=false;
fHeight=0.0f;
fScale=1.0f;
fProportion=1.0f;
fRot=0.0f;
fTracking=0.0f;
fSpacing=1.0f;

fZ=0.5f;
nBlend=BLEND_COLORMUL | BLEND_ALPHABLEND | BLEND_NOZWRITE;
dwCol=0xFFFFFFFF;

ZeroMemory( &letters, sizeof(letters) );
ZeroMemory( &pre, sizeof(letters) );
ZeroMemory( &post, sizeof(letters) );

for(int i=32; i<=256; i++)<br /> {
letters[i] = new hgeSprite(
hTexture,
(float)vChar[i].x, (float)vChar[i].y,
(float)vChar[i].w, (float)vChar[i].h
);
pre[i]=(float)vChar[i].a;
post[i]=(float)vChar[i].c;
if(vChar[i].h>fHeight) fHeight=(float)vChar[i].h;
}
}


Sample :
	// Create the FontManager
FontManager *mFontMgr = FontManager::getSingleton();

// Create an hgeFont from a ttf file, not bold, not italic
hgeFont *fnt1 = mFontMgr->getFont(true, "calibri.ttf", 16, false, false);
// Create an hgeFont from a font name, bold, not italic
hgeFont *fnt2 = mFontMgr->getFont(false, "Courier", 10, true, false);

// Your fonts are ready to print text !

// And just before System_Shutdown
mFontMgr->clear();
delete mFontMgr;
]]>
Camera question http://relishgames.com/forum/index.php?p=/discussion/6294/camera-question Sun, 15 Jan 2012 03:40:07 -0500 Kennedy 6294@/forum/index.php?p=/discussions ask for a right way.
thank U

// include head files
#include "..\include\hge.h"
#include "..\include\hgeanim.h"
#include "..\include\hgefont.h"
#include "..\include\hgesprite.h"
// declare varieties
HGE *hge=0;
hgeFont *fnt;

hgeRect *box1_rect;
hgeRect *box2_rect;

float vct_camera_x=0;
float vct_camera_y=0;

float vct_hero_x=0;
float vct_hero_y=0;

hgeSprite *sp_road;
hgeSprite *sp_box1;
hgeSprite *sp_box2;

HTEXTURE tx_road;
HTEXTURE tx_box;
// frame function
bool FrameFunc()
{
if (hge->Input_GetKeyState(HGEK_A)) vct_hero_x--;
if (hge->Input_GetKeyState(HGEK_D)) vct_hero_x++;
if (hge->Input_GetKeyState(HGEK_W)) vct_hero_y--;
if (hge->Input_GetKeyState(HGEK_S)) vct_hero_y++;

if (vct_hero_x-vct_camera_x>300) vct_camera_x=vct_hero_x-300;
if (vct_hero_x-vct_camera_x<0) vct_camera_x=vct_hero_x+0;<br />
if (vct_hero_y-vct_camera_y>200) vct_camera_y=vct_hero_y-200;
if (vct_hero_y-vct_camera_y<0) vct_camera_y=vct_hero_y+0;<br />
if (vct_hero_x<0) vct_hero_x=0;<br /> if (vct_hero_x>3000) vct_hero_x=3000;
if (vct_camera_x<0) vct_camera_x=0;<br /> if (vct_camera_x>1500) vct_camera_x=1500;

box1_rect=sp_box1->GetBoundingBox(vct_hero_x,vct_hero_y,box1_rect);
box2_rect=sp_box2->GetBoundingBox(400,300,box2_rect);

// detect collision
if ((vct_hero_y>box2_rect->y1-128)&&(vct_hero_yy2))
{
if ((vct_hero_x>=box2_rect->x1-128)&&(vct_hero_x<=box2_rect->x1-127)) vct_hero_x=box2_rect->x1-128;
}
if ((vct_hero_y>box2_rect->y1-128)&&(vct_hero_yy2))
{
if ((vct_hero_x<=box2_rect->x2)&&(vct_hero_x>=box2_rect->x2-1)) vct_hero_x=box2_rect->x2;
}
if ((vct_hero_x>box2_rect->x1-128)&&(vct_hero_xx2))
{
if ((vct_hero_y>=box2_rect->y1-128)&&(vct_hero_y<=box2_rect->y1-127)) vct_hero_y=box2_rect->y1-128;
}
if ((vct_hero_x>box2_rect->x1-128)&&(vct_hero_xx2))
{
if ((vct_hero_y<=box2_rect->y2)&&(vct_hero_y>=box2_rect->y2-1)) vct_hero_y=box2_rect->y2;
}


return false;
}
// render function
bool RenderFunc()
{
hge->Gfx_BeginScene();
hge->Gfx_Clear(0);

sp_road->Render(0-vct_camera_x,500-vct_camera_y);
sp_box1->Render(vct_hero_x-vct_camera_x,vct_hero_y-vct_camera_y);
sp_box2->Render(400-vct_camera_x,300-vct_camera_y);

hge->Gfx_EndScene();
return false;
}
// winmain function
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
hge=hgeCreate(HGE_VERSION);

hge->System_SetState(HGE_WINDOWED,true);
hge->System_SetState(HGE_SHOWSPLASH,false);
hge->System_SetState(HGE_HIDEMOUSE,false);
hge->System_SetState(HGE_FPS,1000);

hge->System_SetState(HGE_FRAMEFUNC,FrameFunc);
hge->System_SetState(HGE_RENDERFUNC,RenderFunc);

hge->System_Initiate();

tx_road=hge->Texture_Load("road.png");
tx_box=hge->Texture_Load("box.png");

sp_road=new hgeSprite(tx_road,0,0,2560,128);
sp_box1=new hgeSprite(tx_box,0,0,128,128);
sp_box2=new hgeSprite(tx_box,0,0,128,128);

box1_rect=new hgeRect(0,0,0,0);
box2_rect=new hgeRect(0,0,0,0);

fnt=new hgeFont("font1.fnt");

hge->System_Start();

delete fnt;
delete box2_rect;
delete box1_rect;
delete sp_box2;
delete sp_box1;
delete sp_road;

hge->Texture_Free(tx_box);
hge->Texture_Free(tx_road);

hge->System_Shutdown();
hge->Release();
return 0;
}
]]>
VideoPlayer with Theora codec http://relishgames.com/forum/index.php?p=/discussion/5962/videoplayer-with-theora-codec Fri, 14 Jan 2011 12:07:40 -0500 stayer 5962@/forum/index.php?p=/discussions First: Sorry for my english.
Second:
VideoPlayer.h

#ifndef VideoPlayer_h
#define VideoPlayer_h

#if (_MSC_VER > 1000) || (__GNUC__ >= 3)
#pragma once
#endif

#include
#include
#include
#include

class VideoPlayer
{
public:
VideoPlayer();
~VideoPlayer();
bool Open(const std::string& fileName);
void Close();
bool Update(float time);
void Render() const;
bool IsPlaying() const;
HTEXTURE GetTexture() const
{
return mTexture;
}
const char* LoadFile(const std::string& fileName, DWORD& size);

private: // disable copying
VideoPlayer(const VideoPlayer&);
VideoPlayer& operator=(const VideoPlayer&);

private:
class Impl;
std::auto_ptr mImpl;
HTEXTURE mTexture;
float mTime;
HGE* mHge;
hgeSprite* mSprite;
math::Vec2 mScale;
};

#endif // VideoPlayer_h

VideoPlayer.cpp

#include
#include
#include "Player.h"

#ifdef WIN32
#ifdef _MSC_VER
#ifdef _DEBUG
#pragma comment(lib, "libogg_static_d.lib")
#pragma comment(lib, "libtheora_static_d.lib")
#else
#pragma comment(lib, "libogg_static.lib")
#pragma comment(lib, "libtheora_static.lib")
#endif
#endif
#endif

#include
#include

template T clamp(const T& _v, const T& _a, const T& _b)
{
return _v < _a ? _a : _v > _b ? _b : _v;
}

class VideoPlayer::Impl
{
public:
Impl(const char* d, std::size_t size, HGE* hge) :
data(&d[0], &d[size]), status(true), current(0), t_ctx(0), t_frame_time(0), t_time(0), pp_inc(0),
frames(0), dropped(0), y_offset(0), uv_offset(0), mHge(hge)
{
ogg_sync_init(&o_state);
th_info_init(&t_info);
th_comment_init(&t_comment);
}

~Impl()
{
th_info_clear(&t_info);
th_comment_clear(&t_comment);
th_decode_free(t_ctx);
ogg_stream_clear(&t_state);
ogg_sync_clear(&o_state);
}

bool FeedPage()
{
while (true)
{
if (ogg_sync_pageout(&o_state, &o_page) > 0)
{
return true;
}
if (current >= data.size())
{
return false;
}
std::size_t size(data.size() - current);
if (size > 4096)
{
size = 4096;
}
char* buffer(ogg_sync_buffer(&o_state, size));
memcpy(buffer, &data[current], size);
ogg_sync_wrote(&o_state, size);
current += size;
if (size == 0)
{
return false;
}
}
}

bool FeedPacket()
{
while (true)
{
int ret(ogg_stream_packetout(&t_state, &o_packet));
if (ret == 1)
{
return true;
}
if (ret < 0)
{
break;
}
if (!FeedPage())
{
break;
}
int serialno(ogg_page_serialno(&o_page));
if (serialno == t_state.serialno)
{
ogg_stream_pagein(&t_state, &o_page);
}
}
return status = false;
}

bool FeedHeaders()
{
bool t_found(false);
th_setup_info* t_setup(0);
while (true)
{
if (!FeedPage())
{
return status = false;
}
if (!t_found)
{
if (ogg_page_bos(&o_page))
{
ogg_stream_init(&t_state, ogg_page_serialno(&o_page));
}
else
{
return status = false;
}
}
if (!ogg_stream_pagein(&t_state, &o_page) && ogg_stream_packetout(&t_state, &o_packet) == 1)
{
int ret(th_decode_headerin(&t_info, &t_comment, &t_setup, &o_packet));
if (ret == 0)
{
t_ctx = th_decode_alloc(&t_info, t_setup);
th_setup_free(t_setup);
break;
}
else if (ret < 0)
{
ogg_stream_clear(&t_state);
if (t_found)
{
th_setup_free(t_setup);
return status = false;
}
}
else
{
t_found = true;
}
}
}
t_frame_time = 1.f * t_info.fps_denominator / t_info.fps_numerator;
th_decode_ctl(t_ctx, TH_DECCTL_GET_PPLEVEL_MAX, &pp_level_max, sizeof(pp_level_max));
pp_level = pp_level_max;
th_decode_ctl(t_ctx, TH_DECCTL_SET_PPLEVEL, &pp_level, sizeof(pp_level));
y_offset = t_info.pic_x + t_info.frame_width * t_info.pic_y;
uv_offset = y_offset / 2;
return status;
}

HTEXTURE CreateTexture(const std::string& name) const
{
return mHge->Texture_Create(t_info.pic_width, t_info.pic_height);
}

bool Update(float time, HTEXTURE texture)
{
if (!status)
{
return false;
}
if (t_time > time)
{
return true;
}
while (FeedPacket())
{
if (pp_inc)
{
pp_level += pp_inc;
th_decode_ctl(t_ctx, TH_DECCTL_SET_PPLEVEL, &pp_level, sizeof(pp_level));
pp_inc = 0;
}
if (o_packet.granulepos >= 0)
{
th_decode_ctl(t_ctx, TH_DECCTL_SET_GRANPOS, &o_packet.granulepos, sizeof(o_packet.granulepos));
}
ogg_int64_t videobuf_granulepos;
if (th_decode_packetin(t_ctx, &o_packet, &videobuf_granulepos) == 0)
{
t_time = videobuf_granulepos < 0 ? -1 : t_frame_time * (1 + th_granule_frame(t_ctx, videobuf_granulepos));
++frames;

if (t_time >= time)
{
break;
}
pp_inc = pp_level > 0 ? -1 : 0;
++dropped;
}
}
float tdiff(t_time - time);
if (tdiff > t_frame_time)
{
pp_inc = pp_level < pp_level_max ? 1 : 0;
}
else if (tdiff < t_frame_time)
{
pp_inc = pp_level > 0 ? -1 : 0;
}
Output(texture);
return true;
}

DWORD* LockTexture(HTEXTURE texture, int& stride) const
{
stride = t_info.pic_width;
return mHge->Texture_Lock(texture, false, 0, 0, t_info.pic_width, t_info.pic_height);
}

void UnlockTexture(HTEXTURE texture, BYTE*)
{
mHge->Texture_Unlock(texture);
}

void Output(HTEXTURE texture)
{
th_ycbcr_buffer yuv;
th_decode_ycbcr_out(t_ctx, yuv);
int dstStride(0);
if (BYTE* buffer = (BYTE*)LockTexture(texture, dstStride))
{
dstStride -= mHge->Texture_GetWidth(texture);// - 4 * t_info.pic_width;
BYTE* bytes(buffer);

const unsigned char* y_data(yuv[0].data + y_offset);
const unsigned char* u_data(yuv[1].data + uv_offset);
const unsigned char* v_data(yuv[2].data + uv_offset);

int yStride(yuv[0].stride);
int uvStride(yuv[1].stride);

for (unsigned i = 0; i < t_info.pic_height; ++i, bytes += dstStride, y_data += yStride)
{
const unsigned char* y_p(y_data);
const unsigned char* u_p(u_data);
const unsigned char* v_p(v_data);

for (unsigned j = 0; j < t_info.pic_width; ++j, bytes += 4, ++y_p)
{
int y(9535 * (*y_p - 16));
int u(*u_p - 128);
int v(*v_p - 128);
// red
bytes[2] = clamp((y + 13074 * v) >> 13, 0, 255);
// green
bytes[1] = clamp((y - 6660 * v - 3203 * u) >> 13, 0, 255);
// blue
bytes[0] = clamp((y + 16531 * u) >> 13, 0, 255);
//alpha
bytes[3] = 255;

if (j & 1)
{
++u_p;
++v_p;
}
}
if (i & 1)
{
u_data += uvStride;
v_data += uvStride;
}
}
UnlockTexture(texture, buffer);
}
}
bool GetStatus() const
{
return status;
}
private:
std::vector data;
bool status;
std::size_t current;
ogg_sync_state o_state;
ogg_page o_page;
ogg_packet o_packet;
ogg_stream_state t_state;
th_info t_info;
th_comment t_comment;
th_dec_ctx* t_ctx;
float t_frame_time;
float t_time;
int pp_level;
int pp_level_max;
int pp_inc;
int frames;
int dropped;
int y_offset;
int uv_offset;
HGE* mHge;
};

VideoPlayer::VideoPlayer() :
mTexture(0), mTime(0)
{
mHge = hgeCreate(HGE_VERSION);
}


VideoPlayer::~VideoPlayer()
{
Close();
}

const char* VideoPlayer::LoadFile(const std::string& fileName, DWORD& size)
{
wchar_t wFileName[64] = {0};
C2W(fileName.c_str(), wFileName, 64);
return (const char*)mHge->Resource_Load(wFileName, &size);
}

bool VideoPlayer::Open(const std::string& fileName)
{
if (mTexture)
{
Close();
}
DWORD size(0);

const char* data = LoadFile(fileName, size);
mImpl.reset(new Impl(data, (size_t)size, mHge));
if (mImpl->FeedHeaders())
{
mTexture = mImpl->CreateTexture(fileName);
float w = (float)mHge->Texture_GetWidth(mTexture);
float h = (float)mHge->Texture_GetHeight(mTexture);
mSprite = new Sprite(mTexture, 0, 0, w, h);
mScale.assign(1024.f / w, 768.f / h);
return true;
}
mImpl.reset();
return false;
}

void VideoPlayer::Close()
{
if (mTexture)
{
mHge->Texture_Free(mTexture);
mTexture = 0;
}
mTime = 0;
mImpl.reset();
mHge->Release();
}

bool VideoPlayer::Update(float time)
{
mTime += time;
return mImpl->Update(mTime, mTexture);
}

bool VideoPlayer::IsPlaying() const
{
return mImpl.get() && mImpl->GetStatus();
}

void VideoPlayer::Render() const
{
mSprite->RenderEx(math::Vec2(0, 0), 0, mScale.x, mScale.y);
}
]]>
Code Snipped: Basic OpenAL HGE Implementing http://relishgames.com/forum/index.php?p=/discussion/6142/code-snipped-basic-openal-hge-implementing Sat, 18 Jun 2011 12:27:16 -0400 bryan226 6142@/forum/index.php?p=/discussions
I was going to implement OpenAL into HGE a while ago but never really got into it, anyway ended up using another audio library. :)

Had this piece of code finished I think, should work playing a *.wav file.


Librarys needed: OpenAL32.lib & alut.lib


SoundAL.cpp:

/*
** Haaf's Game Engine 1.8
** Copyright (C) 2003-2007, Relish Games
** hge.relishgames.com
**
** Core functions implementation: OpenAL audio routines
*/

#include "hge_impl.h"

//OpenAL CoreSDK v.3.05 + Alut 1.1.0
#include "C:\Program Files (x86)\OpenAL 1.1 SDK\include\al.h"
#include "C:\Program Files (x86)\OpenAL 1.1 SDK\include\alc.h"
#include "C:\Program Files (x86)\OpenAL 1.1 SDK\freealut-1.1.0-bin\include\AL\alut.h"

ALCcontext *Context;
ALCdevice *Device;

ALEFFECT CALL HGE_Impl::AL_Load(const char *filename, DWORD _size)
{
ALsizei size, length, samples;
ALuint Buffer;
ALuint Source;
ALvoid *buffer, *data;

if(bSilent) return 1;

else
{
data=Resource_Load(filename,0);
if(!data) return NULL;
}

// Load wav data into a buffer.
alGenBuffers(1, &Buffer);
if (alGetError() != AL_NO_ERROR) _PostError("Can't load sound into buffer | LN37 SoundAL");

// Variables to load into.

ALenum format;
ALsizei freq;
ALboolean loop;


alutLoadWAVFile((ALbyte *)data, &format, &data, &size, &freq, &loop);
alBufferData(Buffer, format, data, size, freq);
alutUnloadWAV(format, data, size, freq);
// Bind buffer with a source.
alGenSources(1, &Source);

alSourcei (Source, AL_BUFFER, Buffer);

if(!size) Resource_Free(data);
return Source;
}

void HGE_Impl::AL_Initalize()
{
// Initialization
Device = alcOpenDevice(0); // select the "preferred device"
if(Device)
{
Context=alcCreateContext(Device,0);
alcMakeContextCurrent(Context);
System_Log("AL: Initalize()");
}
else _PostError("AL: Device initalization failed");
}

void HGE_Impl::AL_Shutdown()
{
// Exit
Context=alcGetCurrentContext();
Device=alcGetContextsDevice(Context);
alcMakeContextCurrent(NULL);
alcDestroyContext(Context);
alcCloseDevice(Device);
System_Log("AL: Shutdown()");
}

void HGE_Impl::AL_PlayWAV(ALEFFECT Source)
{

// Position of the source sound.
ALfloat SourcePos[] = { 0.0, 0.0, 0.0 };

// Velocity of the source sound.
ALfloat SourceVel[] = { 0.0, 0.0, 0.0 };


// Position of the listener.
ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 };

// Velocity of the listener.
ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 };

// Orientation of the listener. (first 3 elements are "at", second 3 are "up")
ALfloat ListenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 };
ALboolean loop;

alSourcef (Source, AL_PITCH, 1.0f );
alSourcef (Source, AL_GAIN, 1.0f );
alSourcefv(Source, AL_POSITION, SourcePos);
alSourcefv(Source, AL_VELOCITY, SourceVel);
// alSourcei (Source, AL_LOOPING, loop );
alSourcePlay(Source);
}


hge_impl.h:


virtual ALEFFECT CALL AL_Load(const char* filename, DWORD size=0);
virtual void CALL AL_Initalize();
virtual void CALL AL_Shutdown();
virtual void CALL AL_PlayWAV(ALEFFECT Source);



hge.h:


virtual ALEFFECT CALL AL_Load(const char* filename, DWORD size=0) = 0;
virtual void CALL AL_Initalize() = 0;
virtual void CALL AL_Shutdown() = 0;
virtual void CALL AL_PlayWAV(ALEFFECT Source) = 0;


Before using it you must call AL_Initalize(), load a file using AL_Load("/test.wav") and finally play it with AL_PlayWAV().

Example:


ALEFFECT Test;

hge->AL_Initalize();

Test = hge->AL_Load("test.wav");

//...
if(hge->Input_KeyDown(HGEK_F3)) hge->AL_PlayWAV(Test);
//...
hge->AL_Shutdown();


This might makes it easier for some people to implement OpenAL into HGE. Happy Coding :D
-bryan]]>
hgeGUITickBox class http://relishgames.com/forum/index.php?p=/discussion/6091/hgeguitickbox-class Sun, 01 May 2011 10:42:26 -0400 minas1 6091@/forum/index.php?p=/discussions

#ifndef __HGE_GUI_TICK_BOX_H__
#define __HGE_GUI_TICK_BOT_H__

#include
#include
#include

#include

namespace hge
{
namespace gui
{
class TickBox : public hgeGUIObject
{
public:
enum { TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT };

TickBox(int _id, float _x = 0, float _y = 0, float _w = 49.0f, bool _selected = false);
~TickBox() { }

// set color to given corner
void Color(uint8_t corner, DWORD newColor) { quad.v[corner].col = newColor; }

// get color
DWORD Color(uint8_t corner) const { return quad.v[corner].col; }

void TickColor(DWORD newColor) { tickColor = newColor; }
DWORD TickColor() const { return tickColor; }

// set position
void Position(const hgeRect &newPos)
{
rect = newPos;
quad.v[0].x = rect.x1; quad.v[0].y = rect.y1;
quad.v[1].x = rect.x2; quad.v[1].y = rect.y1;
quad.v[2].x = rect.x2; quad.v[2].y = rect.y2;
quad.v[3].x = rect.x1; quad.v[3].y = rect.y2;
}

// get position
hgeRect Position() const { return rect; }

// draw
void Render();

void Tick(bool tick = true) { selected = tick; }
bool IsTicked() const { return selected; }

// update
void Update(float dt) { }

bool MouseLButton(bool buttonDown);

private:
hgeQuad quad;
DWORD tickColor;
bool selected;
};
}
}

typedef hge::gui::TickBox hgeGUITickBox;

#endif



#include "hgeGUITickBox.h"

#include

using namespace hge::gui;

TickBox::TickBox(int _id, float _x, float _y, float _w, bool _selected) : selected(_selected), tickColor(ARGB(255, 0, 0, 0))
{
quad.blend = BLEND_DEFAULT;
quad.tex = 0;

id = _id;
rect = hgeRect(_x, _y, _x + _w, _y + _w);
bStatic = true;
bVisible = true;
bEnabled = true;

// Set up quad's texture coordinates [0,0] : top left, [1,1] : bottom right
quad.v[0].tx = 0.0f; quad.v[0].ty = 0.0f;
quad.v[1].tx = 1.0f; quad.v[1].ty = 0.0f;
quad.v[2].tx = 1.0f; quad.v[2].ty = 1.0f;
quad.v[3].tx = 0.0f; quad.v[3].ty = 1.0f;

// screen position
quad.v[0].x = rect.x1; quad.v[0].y = rect.y1;
quad.v[1].x = rect.x2; quad.v[1].y = rect.y1;
quad.v[2].x = rect.x2; quad.v[2].y = rect.y2;
quad.v[3].x = rect.x1; quad.v[3].y = rect.y2;

for(uint8_t i = 0; i <4>Gfx_RenderQuad(&quad);

if( selected )
{
uint16_t i, limit = ceil(fabs(rect.x2 - rect.x1) * 0.25f);

for(i = 0; i Gfx_RenderLine(rect.x1, (rect.y2 + rect.y1) / 2 /*- i*/, (rect.x2 + rect.x1) / 2, rect.y2 - i, tickColor);

limit = ceil(fabs(rect.y2 - rect.y1) * 0.25f);

for(i = 0; i Gfx_RenderLine((rect.x2 + rect.x1) / 2, rect.y2 - i, rect.x2, rect.y1, tickColor);
}
}

bool TickBox::MouseLButton(bool buttonDown)
{
// returns true if was change

if( buttonDown )
selected = !selected;

return false;
}


You do not need to call Update(). It does nothing.

I have wrapped the class in the namespace hge::gui - I like using namespaces. If you want to use the traditional HGE convention, just use hgeGUITickBox, which is not inside the namespace.

image[/img]]]>
Lockable render target textures http://relishgames.com/forum/index.php?p=/discussion/6082/lockable-render-target-textures Mon, 25 Apr 2011 14:44:31 -0400 kijanek6 6082@/forum/index.php?p=/discussions http://blog.kijedi.tk/2011/04/hge-lockable-render-target-textures/
Written for DirectX9 version, tested with transparent RT's (should work without problems with default too).]]>
Example of running HGE in a child window http://relishgames.com/forum/index.php?p=/discussion/2669/example-of-running-hge-in-a-child-window Wed, 11 Jul 2007 23:16:49 -0400 radishes 2669@/forum/index.php?p=/discussions toolbar window and a workspace window, and then initiates HGE in the workspace window. This code comes from my current HGE project. I've created a map editor tool and this is the skeleton of that code. Any improvements to this code are welcome.

A screenshot of this sample program can be viewed at http://radishes.org/images/hge_child.png

( The following paragraph is no longer true as of HGE version 1.8 )

One caveat is that this code will crash with the HGE 1.7 version hge.dll file, which is currently the newest HGE. This was discussed here: http://relishgames.com/forum/viewtopic.php?t=2651 and DaiShiva came up with the resolution, which requires recompiling HGE. The new hge.dll file, which differs from Official HGE by only 1 line of code, has been compiled by me and is available at http://radishes.org/hge.dll. This problem may be fixed in a future version of HGE. This code compiles and runs fine for me, as long as the recompiled 1.7 hge.dll is used.


#include
#include

HGE* hge = NULL;

LRESULT CALLBACK ToolProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK HGEProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);


// This function will be called by HGE once per frame.
bool FrameFunc()
{
// Continue execution
return false;
}


// This function will be called by HGE when
// the application window should be redrawn.
// Put your rendering code here.
bool RenderFunc()
{
// Begin rendering quads.
// This function must be called
// before any actual rendering.
hge->Gfx_BeginScene();
// Clear screen with black color
hge->Gfx_Clear(0);

// End rendering and update the screen
hge->Gfx_EndScene();
// RenderFunc should always return false
return false;
}


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR, int iCmdShow)
{
HWND hwndTool; // handle to toolbar window
HWND hwndHGE; // handle to HGE's parent window

MSG msg;
WNDCLASS wndclass;
char szToolbarName[] = "Toolbar";
char szHGEName[] = "HGE Workspace";

wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = ToolProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szToolbarName;

if ( !RegisterClass(&wndclass) )
{
MessageBox(NULL, "Unable to open the toolbar window!", szToolbarName, MB_ICONERROR);
return 0;
}

hwndTool = CreateWindowEx(WS_EX_CLIENTEDGE,
szToolbarName,
szToolbarName,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
16, 128,
256, 768,
NULL,
NULL,
hInstance,
NULL);

if(hwndTool == NULL)
{
MessageBox(NULL, "Tool Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}

ShowWindow(hwndTool, iCmdShow);
UpdateWindow(hwndTool);

wndclass.lpfnWndProc = HGEProc;
wndclass.lpszClassName = szHGEName;

if ( !RegisterClass(&wndclass) )
{
MessageBox(NULL, "Unable to open the HGE window!", szToolbarName, MB_ICONERROR);
return 0;
}

hwndHGE = CreateWindowEx(WS_EX_CLIENTEDGE,
szHGEName,
szHGEName,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
300, 128,
1024,768,
hwndTool,
NULL,
hInstance,
NULL);

if (hwndHGE == NULL)
{
MessageBox(NULL, "HGE Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}

ShowWindow(hwndHGE, iCmdShow);
UpdateWindow(hwndHGE);

RECT hgeClient;
GetClientRect(hwndHGE, &hgeClient);

// Get HGE interface
hge = hgeCreate(HGE_VERSION);

hge->System_SetState(HGE_FRAMEFUNC, FrameFunc);
hge->System_SetState(HGE_RENDERFUNC, RenderFunc);
hge->System_SetState(HGE_USESOUND, false); // with this set, we don't need bass.dll
hge->System_SetState(HGE_WINDOWED, true);
hge->System_SetState(HGE_SCREENWIDTH, hgeClient.right);
hge->System_SetState(HGE_SCREENHEIGHT, hgeClient.bottom);
hge->System_SetState(HGE_SCREENBPP, 32);
hge->System_SetState(HGE_HIDEMOUSE, false);
hge->System_SetState(HGE_HWNDPARENT, hwndHGE ); // set parent window

if (hge->System_Initiate() )
{

// game objects which depend on HGE can be initialized here, before we enter the main loop

while (1)
{
if(hge->System_GetState(HGE_HWND))
hge->System_Start();

if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}

hge->System_Shutdown();
hge->Release();

return msg.wParam;
}





LRESULT CALLBACK ToolProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;

switch (msg)
{
case WM_CREATE:

return 0;

case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
return 0;

case WM_DESTROY:

PostQuitMessage(0);
return 0;
}

return DefWindowProc(hwnd, msg, wParam, lParam);
}


LRESULT CALLBACK HGEProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;


switch (msg)
{
case WM_CREATE:



return 0;

case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
return 0;

case WM_DESTROY:

return 0;

default:
return DefWindowProc(hwnd, msg, wParam, lParam);

}

return 0;
}

]]>
Fader class http://relishgames.com/forum/index.php?p=/discussion/718/fader-class Fri, 06 May 2005 06:39:41 -0400 xSKOTTIEx 718@/forum/index.php?p=/discussions

heres the h file

//Created by Scott Conner
//May 2005
//INCLUDES/////////////////
#include
///////////////////////////
#pragma once


//CLASS/////////////////////
class cFader
{
private:
hgeQuad fader;
float alpha;
int direction;
protected:
public:
cFader();
~cFader();
void update( float timeDelta );
void render();
void fadeIn();
void fadeOut();

bool doneFading();
};
////////////////////////////


heres the cpp file

//INCLUDES//////////
#include "cFader.h"
int const SCREEN_WIDTH = 1024;
int const SCREEN_HEIGHT = 768;
////////////////////

//external
extern HGE* hge;

//CONSTRUCTORS//////
cFader::cFader()
{
//starts the alpha at full black, and is ready to fade in
alpha = 255;
direction = -1;

//sets up the quad to the coords of the screen
fader.v[0].x = 0;
fader.v[0].y = 0;
fader.v[1].x = SCREEN_WIDTH;
fader.v[1].y = 0;
fader.v[2].x = SCREEN_WIDTH;
fader.v[2].y = SCREEN_HEIGHT;
fader.v[3].x = 0;
fader.v[3].y = SCREEN_HEIGHT;
fader.v[0].z = 1.0f;
fader.v[1].z = 1.0f;
fader.v[2].z = 1.0f;
fader.v[3].z = 1.0f;

//sets the color of the quad
for ( int x = 0; x < 4; x++ )
{
fader.v[x].col = ARGB( alpha, 0, 0, 0 );
}

fader.tex = 0;
fader.blend = BLEND_DEFAULT;
}

cFader::~cFader()
{

}

void cFader::update( float timeDelta )
{
if ( direction == 0 )
{
return;
}

//updates the fader/////////////
//note: 300 can be replaced for any fader speed, could even
//be a parameter if you so chose. 300 works well.
alpha += timeDelta * 300 * direction;

//caps//////////
if ( alpha >= 255 )
{
alpha = 255;
direction = 0;
}
else if ( alpha <= 0 )<br /> {
direction = 0;
alpha = 0;
}
////////////////

for ( int x = 0; x < 4; x++)
{
fader.v[x].col = ARGB( alpha,0,0,0 );
}

////////////////////////////////
}

void cFader::render()
{
if ( alpha != 0 )
{
hge->Gfx_RenderQuad( &fader );
}
}

void cFader::fadeIn()
{
direction = -1;
}

void cFader::fadeOut()
{
direction = 1;
}

bool cFader::doneFading()
{
return direction == 0;
}
////////////////////


enjoy ! :-D]]>
More GUI elements !! http://relishgames.com/forum/index.php?p=/discussion/606/more-gui-elements- Sat, 12 Mar 2005 14:27:36 -0500 Isometric God 606@/forum/index.php?p=/discussions
I did some more GUI element and wanted to share them with the community. The hgeGUIImage is supposed to have most functions hgeSprite has, but I didn´t want to recode the whole thing. It would be great if Haaf could put some of the hgeSprite code in there. The hgeEditBox is still very basic and will be improved soon. Next thing I will do is hgeGUIListBox and some smaller tasks. If you guys are interested, I will post the code here someday.
Here´s what I have :

hgeGUILabel:
- supports alignment ( not working in hgeGUIText )
- supports multi-line texts
- fully functional SetAlign, SetText, SetColor ( buggy in hgeGUIText )
- alignment, text and color can be set in constructor
- supports scaled fonts

hgeGUIImage:
- displays and image in GUI enviroment
- extremely easy to use

hgeGUIEditBox:
- basic edit-box functionality
- blinking caret :)

If you want to improve one of the controls, please contact me and I will post the code here, so everybody will have the advantage. Thank you.

http://people.freenet.de/isometric_god/hgeguictrls2.cpp
http://people.freenet.de/isometric_god/hgeguictrls2.h]]>
REQUEST: hgeAnimation Tutorial/Example http://relishgames.com/forum/index.php?p=/discussion/5935/request-hgeanimation-tutorialexample Sun, 26 Dec 2010 21:44:03 -0500 bryan226 5935@/forum/index.php?p=/discussions
I can't get hge Animation proberly working, I'm trying to make a player walk animation.

		
PLAYER = new hgeAnimation(PlayerRTX,2,60,2,1,16,24);
PLAYER->SetMode(HGEANIM_FWD | HGEANIM_LOOP);


It's displaying the first frame proberly but the second one is displaced, I wasnt able yet to figure out why :?

Could somebody please write an example how to actually load the frames from a picture? ( Might a piece of code + the picture to it with a few frames inside)

Cheers,
bryan]]>
UTF-8/BMFONT/HGEFont renderer abstraction layer http://relishgames.com/forum/index.php?p=/discussion/5623/utf-8bmfonthgefont-renderer-abstraction-layer Wed, 12 May 2010 12:25:57 -0400 kvakvs 5623@/forum/index.php?p=/discussions Open and edit according to your own preferences and renderer.
Old link
DOWNLOAD HERE

String/ folder
Include string to get String, StringCRef, StringList and other definitions + Unicode handling functions
Включите файл String.h из папки String/ чтобы появились нужные типы данных и функции работы с юникодом


интерфейсы для шрифтовых рисовалок + класс шрифт менеджера
Font renderer interface + Font manager class - include this only

BitmapFont.h


загружалка и рисовалка BMFONT (UTF-8 юникод)
BMFONT loader and renderer (UTF-8 Unicode compatible)

BitmapFontBmfont.h

эмулятор для стандартных HGE шрифтов под такой же интерфейс (8-бит кодировка)
Standard HGE fonts emulation layer (single-byte encoding)

BitmapFontHge.h

Loading example / Пример загрузки
CFontManager::LoadFont ("serif24", "serif24.fnt", 0);

Rendering example / Пример рисования
if (CFontManager::HaveFont("serif24"))
{
GetFont("serif24")->Print (0, 0, 1, "ERROR: No scene loaded");
}


Word wrap rendering example / Пример с переносом слов
typedef enum {
ALIGN_LEFT = 0,
ALIGN_CENTER = 1,
ALIGN_RIGHT = 2
} AlignType;

GetFont(mFontId)->PrintWordWrap (x, y,
1.0f /*scale*/,
text,
500, /* wrap at 500 pixels width */
1.4f /* line spacing */,
mAlignType, /* align type constant */
& text_height );

outputs rendered text height to text_height variable]]>
Box2D DebugDraw class http://relishgames.com/forum/index.php?p=/discussion/5908/box2d-debugdraw-class Thu, 09 Dec 2010 23:25:14 -0500 Boogy 5908@/forum/index.php?p=/discussions
I started using this game engine a while ago and recently I integrated box2D. After some googling for a debug drawer I found this one.
It was a little outdated so I updated it.

This code is compatible with Box2D v2.1.2 and HGE 1.81

EDIT: Apparently the forum removes lines of code between the [ code] & [ /code] sections. I have added mirrors to download the source code :)

Header File:

/*
* Copyright (c) 2008 Vitaliano Palmieri Neto
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once

// Forward declarations
class HGE;
struct b2Vec2;
struct b2Color;
struct b2Transform;

class PhysicsDebugDraw : public b2DebugDraw
{
public:
PhysicsDebugDraw();

void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
void DrawTransform(const b2Transform& xf);

private:
HGE* m_HGE;
};


Mirror 1
Mirror 2
Mirror 3

Original source here]]>
Polygon & Circle Collisions with Mask Tool & Example http://relishgames.com/forum/index.php?p=/discussion/5904/polygon-circle-collisions-with-mask-tool-example Tue, 07 Dec 2010 13:02:55 -0500 cj_h4x0r 5904@/forum/index.php?p=/discussions
Now this includes a masking tool!

To use put your image into the resources.zip archive. Then edit the resource.res file like so:
[list]file.png=your image's file name
WIDTH=your image's width
HEIGHT=your image's height
ORIGINX=your image's origin x (usually width/2)
ORIGINY=your image's origin y (usually height/2)[/list:u]
Texture t_picture
{
filename=file.png
}

Animation s_picture
{
texture=t_picture
rect=0,0,WIDTH,HEIGHT
frames=8
fps=0.0
mode=FORWARD,LOOP
hotspot=ORIGINX,ORIGINY
}


Start the tool up, and create the mask around your image, controls are:
WASD - Move "View" Around
Right MB - Create New Polygon
Left MB - Move Vertex of Polygon
Ctrl+Right MB - Delete Vertex of Polygon
Shift+Left MB - Snap One Vertex to Another
Ctrl+S - Save Mask Information
Scroll Wheel - Zoom in and out (you might have to do this to see the sprite I have to begin with in there, it's kinda small)
Esc - Exit


When it starts up you'll see your image along with a red dot on it (that's the origin of your image).

When you save a file called mask.txt is made. The format is for my game, you can change this format by editing include\classes.cpp around line 277.

Everything is compiled with the newest CodeBlocks (10.something or other). If anyone needs help feel free to ask. Hopefully my clutter of a project folder makes sense.

In addition to the Mask Tool folder is another folder called Bifrost, which is a very early version of the game I'm making. It's using the mask stuff, so since it doesn't have much more I figured I'd include it as an example. Used WASD and the mouse to move the character around and see those spectacular collisions! Or not, that's up to you... The small guy walking may or may not be used in the game, I'm thinking of switching to 3d rendered sprites...but that's not a sure thing so please don't use them!

Hopefully this will help someone out there...
Link

Here is the link to the old stuff if anyone still wants it:
Old Stuff

Keep in mind that this is an early release of the Mask Tool, mostly because I wanted to put something up because I've been working on this for a while.

And just in case this is required:
Feel free to modify/use and all that jazz!

That looks like everything I wanted to say...
H4x

Edit:
Ya'll might be wondering why the lib and stuff are included in the project folder. That's because I work on a of different computers all of which you cannot save to, so I carry my projects around on a usb stick. If that violates any sort of license with Haaf, I'll happily re-upload a version without them!

H4x]]>
Randomly Changing BGs http://relishgames.com/forum/index.php?p=/discussion/5761/randomly-changing-bgs Tue, 03 Aug 2010 05:53:28 -0400 Lisergishnu 5761@/forum/index.php?p=/discussions
hgeDynamicbg.h
#ifndef HGEDYNAMICBG_H
#define HGEDYNAMICBG_H

#include
#include
#include



#define BG_MAXFILES 10

class hgeDynamicBG
{
public:
hgeDynamicBG();
virtual ~hgeDynamicBG();

void Render();

private:

static HGE* _hge;
std::string _filename[BG_MAXFILES];
hgeSprite* _bg;
HTEXTURE _tex;



};

#endif // HGEDYNAMICBG_H


hgeDynamicBG.cpp
#include "hgedynamicbg.h"

HGE* hgeDynamicBG::_hge = 0;

hgeDynamicBG::hgeDynamicBG()
{
_hge = hgeCreate(HGE_VERSION);

//searching and indexing backgrounds
int i = 0;

//here you may change where to look the files for. Don't forget the *!
char* temp = _hge->Resource_EnumFiles("gfx/gamebg/*.png");
while (temp != 0)
{

_filename[i] = temp;
_hge->System_Log("DYNAMIC BG: Found file: %s", temp);
i++;
temp = _hge->Resource_EnumFiles(0);

}

//choose one item at random (in range of course)
int choosen = _hge->Random_Int(0,i);

char temp2[255];

//here you need to change the path too!
sprintf(temp2, "gfx/gamebg/%s", _filename[choosen].c_str());

_tex = _hge->Texture_Load(temp2);
if(_tex)
_hge->System_Log("DYNAMIC BG: \"%s\" loaded.", temp2);

_bg = new hgeSprite(_tex,0,0,800,600);

}

hgeDynamicBG::~hgeDynamicBG()
{
delete _bg;
_hge->Target_Free(_tex);
_hge->Release();
}


/** @brief Render
*
* @todo: Renders the random bg
*/
void hgeDynamicBG::Render()
{
_bg->RenderStretch(0,0,_hge->System_GetState(HGE_SCREENWIDTH),_hge->System_GetState(HGE_SCREENWIDTH));
}




Setting it up is easy as 1-2-3

1.- Check than the filepath in the .cpp matches your desired construction, remind that it indexes all png files on that folder, but you can change the extension to any other that hge supports
2.- On your render loop put it first than any other object you want to draw
3.- Remember to initializate the pointer just like any other HGE helper


Enjoy!
Liser]]>
Widescreen to Normal toggle http://relishgames.com/forum/index.php?p=/discussion/5730/widescreen-to-normal-toggle Tue, 13 Jul 2010 19:58:23 -0400 bytewrench 5730@/forum/index.php?p=/discussions

#define SCREEN_WIDTH    800
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 16

#define DESIGN_WIDTH 640
#define DESIGN_HEIGHT 480

int origScreenX;
int origScreenY;
float mScreenScaleX,mScreenScaleY,aspect;
float OffsetX, OffsetY;
float scaleRenderWidth;
float scaleRenderHeight;
int adjustWidth;
int adjustHeight;
float clippingX, clippingY, clippingW, clippingH;
bool g_bWideScreen = true;

//--------------------------------





void setAspect(bool wide, bool bclear = false){

if (wide)
{

aspect = (float)origScreenX / origScreenY;
if (aspect >= (4.0f/3.0f))
{
mScreenScaleX = 1.0f - (1.0f - 1.33f / aspect);
mScreenScaleY = 1.0f;
} else {
mScreenScaleX = 1.0f;
mScreenScaleY = 1.0f;
}

scaleRenderWidth = (SCREEN_WIDTH * 1.f / DESIGN_WIDTH)*mScreenScaleX;
scaleRenderHeight = (SCREEN_HEIGHT * 1.f / DESIGN_HEIGHT)*mScreenScaleY;

OffsetX = (SCREEN_WIDTH - (DESIGN_WIDTH*scaleRenderWidth)) / 2 ;
OffsetY = (SCREEN_HEIGHT - (DESIGN_HEIGHT*scaleRenderHeight)) / 2;

adjustWidth= (DESIGN_HEIGHT * SCREEN_WIDTH > DESIGN_WIDTH * SCREEN_HEIGHT) ? (DESIGN_WIDTH * SCREEN_HEIGHT / DESIGN_HEIGHT) : SCREEN_WIDTH;
adjustHeight = (DESIGN_HEIGHT * SCREEN_WIDTH < DESIGN_WIDTH * SCREEN_HEIGHT) ? (DESIGN_HEIGHT * SCREEN_WIDTH / DESIGN_WIDTH) : SCREEN_HEIGHT;

clippingX = (SCREEN_WIDTH-adjustWidth)/2;
clippingY = (SCREEN_HEIGHT-adjustHeight)/2;
clippingW = adjustWidth;
clippingH = adjustHeight;
}else{

int scrW = SCREEN_WIDTH;
int scrH = SCREEN_HEIGHT;
int w = (DESIGN_HEIGHT * scrW > DESIGN_WIDTH * scrH) ? (DESIGN_WIDTH * scrH / DESIGN_HEIGHT) : scrW;
int h = (DESIGN_HEIGHT * scrW < DESIGN_WIDTH * scrH) ? (DESIGN_HEIGHT * scrW / DESIGN_WIDTH) : scrH;
clippingX = (scrW-w)/2;
clippingY = (scrH-h)/2;
clippingW = w;
clippingH = h;
scaleRenderWidth = scrW * 1.f / DESIGN_WIDTH;
scaleRenderHeight = scrH * 1.f / DESIGN_HEIGHT;
OffsetX = OffsetY = 0;
}
if (bclear)
{
hgeMain->Gfx_Clear(0);
}

}



bool RenderFunc(){
hgeMain->Gfx_BeginScene();
hgeMain->Gfx_SetClipping(clippingX, clippingY,clippingW, clippingH);
hgeMain->Gfx_SetTransform(0, 0, OffsetX, OffsetY, 0, scaleRenderWidth,scaleRenderHeight);
render_frame();
hgeMain->Gfx_EndScene();

return false;
}

//-----------------------------
// and somewhere, check to see if user wants to switch
if (hgeMain->Input_GetKeyState(HGEK_PGDN))
{
g_bWideScreen = true;
setAspect(g_bWideScreen,true);
}else if (hgeMain->Input_GetKeyState(HGEK_PGUP))
{
g_bWideScreen = false;
setAspect(g_bWideScreen,true);
}
]]>
How to determine screenposition of OPAL-objects http://relishgames.com/forum/index.php?p=/discussion/5464/how-to-determine-screenposition-of-opal-objects Wed, 27 Jan 2010 20:10:35 -0500 Einhдnder 5464@/forum/index.php?p=/discussions

I work around with some snippets of HGE and OPAL.
So I created a small map, wirth a player that moves from left to right.
When I jump the player does a sound.

To locate the position of the sound (to render the stereo-audio) I should know the Position of the player "onscreen", but I dont know how to get the X & Y values of the screen.

The only values I have, are the Position of the player "onmap".
So Y is 0 and X depends on the distance from spawnpoint to end of the map.


I found the code "MapToScreen", but I really dont know how to use it.





Here is some code I use:


#ifndef PLAYER_H
#define PLAYER_H


#include
#include
#include "../../include/hgeEntityEx.h"


int PlayerPosX, PlayerPosY, PlayerSpeedX, PlayerSpeedY;


class Player : public hgeEntityEx
{
protected:


hgeAnimation *current_animation;
hgeAnimation *idle_right;
hgeAnimation *run_right;
hgeAnimation *idle_left;
hgeAnimation *run_left;
hgeAnimation *jump_left;
hgeAnimation *jump_right;


hgeVector position;
hgeVector velocity;


bool facing_right;
bool jumping;


// Spawn Position
hgeVector spawn_pos;



public:

Player() : hgeEntityEx(HEL_MIDDLE1, false) {}
Player *Spawn() { return new Player(); }


void Free()
{
delete idle_left;
delete idle_right;
delete run_left;
delete run_right;
delete jump_left;
delete jump_right;
}




void Jump()
{

jumping = true;

if (facing_right) current_animation = jump_right;
else current_animation = jump_left;
current_animation->SetFrame(0);
current_animation->Play();
velocity.y = -320;







boom();






}





void Initialize()
{

position = hgeVector(aabb.x1, aabb.y1);
spawn_pos = position;

SetHotSpot( hgeVector(0,0) );


idle_right = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 1, 10, 294, 0, 42, 62);
idle_left = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 1, 10, 294, 62, 42, 62);

run_right = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 8, 10, 0, 0, 42, 62);
run_right->Play();
run_left = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 8, 10, 0, 62, 42, 62);
run_left->Play();

jump_left = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 4, 10, 0, 248, 42, 62);
jump_left->SetMode(hgeANIM_NOLOOP + hgeANIM_FWD );
jump_right = new hgeAnimation(hge->Texture_Load("data/ents/character.png"), 4, 10, 0, 186, 42, 62);
jump_right->SetMode(hgeANIM_NOLOOP + hgeANIM_FWD );

current_animation = idle_right;
facing_right = true;

}



void Update(float dt)
{

// gravity
velocity += hgeVector(0, 800 * dt);


if (!jumping)
if (hge->Input_GetKeyState(hgeK_LEFT) )
{
facing_right = false;
current_animation = run_left;
}
else if (hge->Input_GetKeyState(hgeK_RIGHT))
{
facing_right = true;
current_animation = run_right;
}
else
{
if (facing_right)
current_animation = idle_right;
else
current_animation = idle_left;
}



if (hge->Input_GetKeyState(hgeK_LEFT))
{
velocity.x -= 30;
}
if (hge->Input_GetKeyState(hgeK_RIGHT))
{
velocity.x += 30;
}
if (hge->Input_GetKeyState(hgeK_UP))
{
jump();
}
if (hge->Input_GetKeyState(hgeK_DOWN))
{
velocity.y += 30;
}




current_animation->Update(dt);




hgePolygon *p = 0;
hgeCircle circ = hgeCircle(GetCenter() + hgeVector(0, 10), 20);
hgeIntersect test = map->Test( &circ, velocity * dt, &p, COLLIDE_STATIC + COLLIDE_MULTI, "", hgeLAYER_MIDDLE );


if (test.collides)
{

test.SetResponseVector(&velocity, 0.1f);


velocity *= 1-dt*7;


jumping = false;
}
else

velocity.x *= 1-dt*4;
velocity.y *= 1-dt*4;



position += velocity * dt;
SetPosition( position );








PlayerPosX = position.x;
PlayerPosY = position.y;
PlayerSpeedX = velocity.x;
PlayerSpeedY = velocity.y;












map->SetTransform( position );
}


void Render()
{

current_animation->Render(position.x, position.y);
}

};

#endif






So, how can I determine or convert the mapposition to screenposition?


my regards]]>
Distortion Mesh Tutorial http://relishgames.com/forum/index.php?p=/discussion/1475/distortion-mesh-tutorial Tue, 25 Apr 2006 07:36:44 -0400 blueglasses 1475@/forum/index.php?p=/discussions
So if you're interested in distortion meshes and don't know where to start, take a look at my tutorial.

[Update]

Alright, the tutorial is completed regarding the important stuff of distortion meshes.

Now i'll need some more examples on how to use distortion meshes to be included there. I'd appreciate it if you guys can help me as i'm not a thinking machine and got plenty of other things to cope with. Nevertheless, have fun!

http://scratch.arcticgeckostudios.com/tutorials/DisMesh/]]>
How to Retrieve the Hardware ID http://relishgames.com/forum/index.php?p=/discussion/5461/how-to-retrieve-the-hardware-id Tue, 26 Jan 2010 17:29:36 -0500 stef 5461@/forum/index.php?p=/discussions
I have been trying to make a passcode solution for my game.
I know that everything is hackable but I just want to put on something simple.

I'm using the Dev C++ IDE.
I have only 1 question.

Using C++, what is the command/code to retrieve the computer's unique information like
(a) Unique Hardware ID (b) or MAC Address (c) CPU ID

Thanks

Stef

PS

Of course if there is some sort of FREE prebuilt solution out there that would allow me to implement this in a snap I would be glad to hear it.]]>
create an arbitrary transparency window http://relishgames.com/forum/index.php?p=/discussion/5280/create-an-arbitrary-transparency-window Thu, 17 Dec 2009 04:50:06 -0500 change_cn 5280@/forum/index.php?p=/discussions The screenshot link:
http://docs.google.com/View?id=dgjrkgmf_4cvj9bsf9
The API I am using is:
::SetWindowLong(hWnd,GWL_EXSTYLE,GetWindowLong(hWnd,GWL_EXSTYLE)|WS_EX_LAYERED);
SetLayeredWindowAttributes(hWnd,0,(255*70)/150,LWA_ALPHA);

You should put these two statements after hge->System_Initiate(),and write down
#define   _WIN32_WINNT   0x5000 

before the include files declaration list.]]>
String Parsing Function http://relishgames.com/forum/index.php?p=/discussion/2392/string-parsing-function Mon, 19 Feb 2007 08:15:38 -0500 Sharkgod999 2392@/forum/index.php?p=/discussions

void SetScript(std::string _script)
{
std::string subscript;

std::string::size_type nbegin = 0;
std::string::size_type nend = 0;

std::string::size_type nlinestart = 0;
std::string::size_type nlastline = 0;

float text_h = 0.0f;
float text_w = 0.0f;
float run_over = 0.0f;

while(nend != std::string::npos)
{
// Create a copy of the subscript
std::string copy = subscript;
std::string linecopy;

// Find the next word in the script
nbegin = _script.find_first_not_of(" ",nend);
nend = _script.find_first_of(" ",nbegin);

// Append next word to subscript
if(nend == std::string::npos)
subscript.append(_script,nbegin,nend);
else
subscript.append(_script,nbegin,nend-nbegin+1);

linecopy = subscript.substr(nlinestart);

// Get the length of the line
float last_text_w = text_w;
text_w = (font->GetStringWidth(linecopy.c_str()) * GetFontScale()) + run_over;

// If the line is greater than the width of the text areas
// add the scaled height to the total height
// GetWidth is returns the windows width
if(text_w >= GetWidth())
{
run_over = (GetWidth() - (last_text_w + run_over)) + ((text_w - run_over) - GetWidth());
text_w = 0.0f;
text_h += (font->GetHeight() * GetFontScale());
nlinestart = (nend + 1) - nlastline;
}

// If the height of the text is greater than the text areas
// add the subscript to the list and start a new section
// GetHeight is returns the windows height
if(text_h > GetHeight())
{
script.push_back(copy.substr());
subscript.erase();
nend = nbegin;
nlastline = nlinestart;
nlinestart = 0;
text_w = 0.0f;
text_h = (font->GetHeight() * GetFontScale());
}

// If the height of the text is equal to the text areas
// add the subscript to the list and start a new section
else if(text_h == GetHeight())
{
script.push_back(subscript.substr());
subscript.erase();
nend = nbegin;
nlastline = nlinestart;
nlinestart = 0;
text_w = 0.0f;
text_h = 0.0f;
}

// If nend is equal to npos add the subscript to the list
else if(nend == std::string::npos)
script.push_back(subscript.substr());
}
}
]]>
hge helper class http://relishgames.com/forum/index.php?p=/discussion/2911/hge-helper-class Mon, 12 Nov 2007 19:52:39 -0500 mos 2911@/forum/index.php?p=/discussions
/////////////////////////////////////////////////
class HGE_Handle
{
public:
//////////////////////////////////////////////
explicit HGE_Handle(int ver)
: mpHGE(hgeCreate(ver))
{
if(!mpHGE)
throw std::runtime_error("Error aqcuiring handle to HGE interface.");
}

HGE_Handle()
: mpHGE(hgeCreate(HGE_VERSION))
{
if(!mpHGE)
throw std::runtime_error("Error aqcuiring handle to HGE interface.");
}

//////////////////////////////////////////////
~HGE_Handle()
{
mpHGE->Release();
}

//////////////////////////////////////////////
HGE *operator->()
{
return mpHGE;
}

const HGE *operator->() const
{
return mpHGE;
}

//////////////////////////////////////////////
HGE &operator*()
{
return *mpHGE;
}

const HGE &operator*() const
{
return *mpHGE;
}

private:
HGE *mpHGE;
};



{
HGE_Handle hge; // automatically calls hgeCreate here
hge->System_SetState(...
hge->System_SetState(...
} // automatically calls hge::Release() here
]]>
Text input field http://relishgames.com/forum/index.php?p=/discussion/598/text-input-field Fri, 04 Mar 2005 20:37:37 -0500 Anonymous 598@/forum/index.php?p=/discussions I looked into the forums for a text input field and didn´t find something useful. So I made one for my game.

Perhaps someone will find this useful for Highscores etc.. It is limited to 30 characters. You must specify the max. length of the string. This doesn´t include the caret.
The field gets focus by leftclicking it. It loses focus by pressing enter. When focused a caret blinks.

Comments are welcome. I'm quite new to c++.

ciao


//Small Input textfield
class Forminput : public hgeGUIObject{

public:
Forminput(hgeFont* _fnt, int _id, float xPos, float yPos,
float length, char* prevalue);
~Forminput();
virtual void Render();
//void Render(float x, float y);
virtual bool MouseLButton(bool bDown);
virtual void Focus(bool bFocused);
virtual bool KeyClick(int key, int chr);
virtual void Update(float fDeltaTime);
void setText(char *newText);
char *getText();

protected:
int caretposition;
char* caret;
bool caretVisible; //for blinking effect
bool focused;
float caretTimer; //for blinking effect
const static int maxchar = 30;
float xPos;
float yPos;
hgeFont *font;
float length;
char *content;
};


Forminput::Forminput(hgeFont* _fnt, int _id, float _xPos, float _yPos,
float _length, char *prevalue){
font = _fnt;
id = _id;
length = _length;
xPos = _xPos;
yPos = _yPos;
bStatic = false;
bVisible = true;
bEnabled = true;
caretVisible = true;
focused = false;
caretTimer = 0.0f;
caret = "_";
content = new char[maxchar+1]; //maxchar is defined in the header
strncpy(content, prevalue, maxchar);
int prevalue_length = (int)strlen(prevalue);
if (prevalue_length < maxchar){
caretposition = prevalue_length;
}
else{
caretposition = maxchar-1;
}
content[caretposition] = '\0';
content[maxchar+1] = '\0'; //Last char will always be a string terminator
rect.Set(xPos, yPos, xPos+length, yPos+(font->GetHeight()));
};

Forminput::~Forminput(){
delete font;
}

void Forminput::Render(){
font->Render(xPos, yPos, content, HGETEXT_LEFT);
//Renders the caret
if (focused && caretVisible){
float width = font->GetStringWidth(content);
font->Render(xPos+width, yPos, caret);
}
}

//Gets Focus with LeftMouseKlick
bool Forminput::MouseLButton(bool bDown){
if (bDown){
return false;
}
gui->SetFocus(id);
return false;
};

//Saving focus state in focused
void Forminput::Focus(bool bFocused){
if (!bFocused){
focused = false;
}
else{
focused = true;
}

};

void Forminput::Update(float fDeltaTime){
caretTimer += fDeltaTime;
/*Makes the caret blinking effect
You might want to change the value below for slower/faster blinking*/
if (caretTimer >= 0.1f){
caretVisible = !caretVisible;
caretTimer = 0.0f;
}
}

bool Forminput::KeyClick(int key, int chr){
//Loses Focus with Enter
if (key == HGEK_ENTER){
gui->SetFocus(-1);
return false;
}
char tmp[maxchar+1];
strncpy(tmp, content, maxchar+1);
if (key == HGEK_BACKSPACE){ //Delete one character per backspace
if (caretposition != 0){
caretposition -=1;
tmp[caretposition] = '\0'; //Put string terminator one character back
}
strcpy(content, tmp);
return false;
}
/*When chr==0 no ascii-key (e.g. shift) is pressed and chr would
be saved as string terminator. The other thing to look after, is
whether we have max. characters*/
if (chr != 0 && caretposition < maxchar-1){
tmp[caretposition] = chr;
tmp[caretposition+1] = '\0'; //add overwritten string terminator
//Assures that the String will not take to much place
if (font->GetStringWidth(tmp) <= length){<br /> strcpy(content, tmp); //Store back
caretposition+=1;
}
}
return false;
};

//Setting the Text
void Forminput::setText(char *newtext){
strncpy(content ,newtext ,maxchar);
content = newtext;
};

char *Forminput::getText(){
return content;
}
]]>
b2DebugDraw to Box2D with HGE http://relishgames.com/forum/index.php?p=/discussion/4383/b2debugdraw-to-box2d-with-hge Sun, 07 Dec 2008 01:36:42 -0500 Legionaryu 4383@/forum/index.php?p=/discussions
I'm going to use Box2D and HGE in my future projects, and I can't find anything about b2DebugDraw Class used in HGE.

Then I put myself in the front of my computer and do this little thing, HGEDebugDraw class.

This class is supposed to be used like DebugDraw class in Box2D TestBed examples.

Here the code of HGEDebugDraw.h
/*
* Copyright (c) 2008 Vitaliano Palmieri Neto
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef RENDER_H
#define RENDER_H

#include "Box2D.h"
#include
#include
#include
#include
#include

struct b2AABB;

class HGEDebugDraw :
public b2DebugDraw
{
private:
HGE* hge;
public:
HGEDebugDraw(){};
HGEDebugDraw(HGE* draw):hge(draw){};
void SetHGE(HGE* draw){ hge = draw;};
void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);

void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);

void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);

void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);

void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);

void DrawXForm(const b2XForm& xf);
};

void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);
void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);

void DrawString(int x, int y, const char* string, ...);
void DrawAABB(b2AABB* aabb, const b2Color& color);

#endif


And here the code of HGEDebugDraw.cpp
/*
* Copyright (c) 2008 Vitaliano Palmieri Neto
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#include "HGEDebugDraw.h"

void HGEDebugDraw::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

//hge->Gfx_BeginScene();
for (int32 i = 0, j = 1; i =vertexCount)?0:j;
hge->Gfx_RenderLine(adjustW + vertices[i].x, adjustH - vertices[i].y, adjustW + vertices[j].x, adjustH - vertices[j].y, ARGB(255,color.r*255,color.g*255,color.b*255));
}
//hge->Gfx_EndScene();
}

void HGEDebugDraw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

//hge->Gfx_BeginScene();
for (int32 i = 0, j = 1; i =vertexCount)?0:j;
hge->Gfx_RenderLine(adjustW + vertices[i].x, adjustH - vertices[i].y, adjustW + vertices[j].x, adjustH - vertices[j].y, ARGB(200,color.r*128,color.g*128,color.b*128));
}
//hge->Gfx_EndScene();
}

void HGEDebugDraw::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

int NUMPOINTS = 24+(int)radius/20;//24;
const float PI = 3.14159f;

std::vector vertices;
//hgeVector Circle[NUMPOINTS + 1];
int i;//,j;
float X;
float Y;
float Theta;
float WedgeAngle; //Size of angle between two points on the circle (single wedge)

//Precompute WedgeAngle
WedgeAngle = (float)((2*PI) / NUMPOINTS);

//Set up vertices for a circle
//Used <= in the for statement to ensure last point meets first point (closed circle)<br /> for(i=0; iGfx_BeginScene();
for (int32 k = 0, j = 1; k =(signed)vertices.size())?0:j;
hge->Gfx_RenderLine(adjustW + vertices[k].x, adjustH - vertices[k].y, adjustW + vertices[j].x, adjustH - vertices[j].y, ARGB(255,color.r*255,color.g*255,color.b*255));
}
//hge->Gfx_EndScene();
}

void HGEDebugDraw::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

int NUMPOINTS = 24+(int)radius/20;//24;
const float PI = 3.14159f;

std::vector vertices;
//hgeVector Circle[NUMPOINTS + 1];
int i;//,j;
float X;
float Y;
float Theta;
float WedgeAngle; //Size of angle between two points on the circle (single wedge)

//Precompute WedgeAngle
WedgeAngle = (float)((2*PI) / NUMPOINTS);

//Set up vertices for a circle
//Used <= in the for statement to ensure last point meets first point (closed circle)<br /> for(i=0; iGfx_BeginScene();

for (int32 k = 0, j = 1; k =(signed)vertices.size())?0:j;
hge->Gfx_RenderLine(adjustW + vertices[k].x, adjustH - vertices[k].y, adjustW + vertices[j].x, adjustH - vertices[j].y, ARGB(200,color.r*128,color.g*128,color.b*128));
}
//hge->Gfx_EndScene();
}

void HGEDebugDraw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

//hge->Gfx_BeginScene();
hge->Gfx_RenderLine(adjustW + p1.x, adjustH - p1.y, adjustW + p2.x, adjustH - p2.y, ARGB(255,color.r*255,color.g*255,color.b*255));
//hge->Gfx_EndScene();
}

void HGEDebugDraw::DrawXForm(const b2XForm& xf)
{
if(!hge) return;

float adjustW = hge->System_GetState(HGE_SCREENWIDTH)/2.0f;
float adjustH = hge->System_GetState(HGE_SCREENHEIGHT)/2.0f;

b2Vec2 p1 = xf.position, p2;
const float32 k_axisScale = 0.4f;
//hge->Gfx_BeginScene();

p2 = p1 + k_axisScale * xf.R.col1;
hge->Gfx_RenderLine(adjustW + p1.x, adjustH - p1.y, adjustW + p2.x, adjustH - p2.y, ARGB(255,255,0,0));

p2 = p1 + k_axisScale * xf.R.col2;
hge->Gfx_RenderLine(adjustW + p1.x, adjustH - p1.y, adjustW + p2.x, adjustH - p2.y, ARGB(255,0,255,0));

//hge->Gfx_EndScene();
}


Also have an example, the link is above (source included):

http://www.4shared.com/file/74801132/3f7e12af/HGEDebugDraw.html
http://www.megaupload.com/pt/?d=DYSLH7RC
http://rapidshare.com/files/170951751/HGEDebugDraw.zip
http://sites.google.com/site/legionaryu/files/HGEDebugDraw.zip

Yeah, I know! :D Lot of mirrors.

Thanks]]>
Animation Tutorial (plus expanded animation class) http://relishgames.com/forum/index.php?p=/discussion/4250/animation-tutorial-plus-expanded-animation-class Fri, 05 Sep 2008 08:27:14 -0400 AnimateDream 4250@/forum/index.php?p=/discussions
image

http://stephenlujan.com/IsometricGame/files/Walking%20Test.rar


NOTE: This project requires my expanded animation class. I added support to play frames in a specific range. For example...
 play(12,24); // this should loop through the animation contained in frames 12 through 24


here's my "include\hgeanim.h"
http://stephenlujan.com/IsometricGame/files/hgeanim.h
and here's my "src\helpers\hgeanim.cpp"
http://stephenlujan.com/IsometricGame/files/hgeanim.cpp

If you would like to incorporate my animation class changes into your own I recommend a utility like this http://www.winmerge.org/ for merging codes.[/code]]]>