This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| OpenGL Screen Saver Framework Submitted by

I searched the web for an OpenGL screen saver framework and didn't find anything I liked. There is one already here at Flipcode, but it uses MFC, which I don't like very much (MFC I mean, not the other framework). I also found a very messy screen saver example in C somewhere (sorry, I lost the link). It didn't use MFC, so I started cleaning it up and converting it to an easily reusable C++ frame work. So, here is the result of my work. I added a few utility classes such as registry wrapper (SSUtlReg), performancer counter (SSClock) wrapper, OpenGL texture (SSTexture) that can read from BMP file (using glaux.lib). There is a base class SSBaseApp that contains all the annoying screen saver/window creation/OpenGL context stuff. You don't even need to look at it, but it is there anyway. The only thing you have to do is derive a class from SSBaseApp and implement the virtual functions (there are 6 of them). I provided a simple example class SSMinimalApp. Part of the code for SSMinimalApp is taken from Nehe's tutorials. Once you have created your class, you have to modify the file SSMain.cpp to create an instance of your class instead of SSMinimalApp. Also, the other part is to modify the dialog box to have the configuration options that your screen saver will need. The code should be self explanatory for that part (well, I hope). You just need to modify the dialog box call back procedure to fit with the dialog box ressources. So, that's it. I hope you enjoy this code and use it to make your very own OpenGL screen savers to impress your collegue(s)/parent(s)/girlfriend(s) with it!! Ciao! Jean-Sebastien Perrier

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSUtils.h] - (2,839 bytes)

    /* ******************************************************************************

    	FILE:			SSUtils.h
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	This file contains a collection of utility classes and
    					functions usefull for a screen saver application.

    	$History::                                                                  $

    ****************************************************************************** */
    #ifdef _MSC_VER
    	#pragma once
    #endif
    #ifndef SSUTILS_H
    #define SSUTILS_H

    // Includes ****************************************************************** //

    // Defines ******************************************************************* //

    // Types ********************************************************************* //

    ////////////////////////////////////////////////////////////////////////////////
    // CLASS:			SSUtlReg
    // INHERITS FROM:	None
    // DESCRIPTION:		Utility class to encapsluate the ugly windows registry
    //					management code.
    // REMARKS:			None
    ////////////////////////////////////////////////////////////////////////////////
    class SSUtlReg
    {
    private:
    	HKEY m_hKey;
    public:
    	bool Open(const char *a_szPath);	// Open a key
    	bool Create(const char *a_szPath);	// Create a key
    	void Close();						// Close the key

    	DWORD ReadDWord(const char *a_szKey, DWORD a_dwDefault);
    	bool WriteDWord(const char *a_szKey, DWORD a_dwValue);
    	bool ReadString(const char *a_szKey, char *a_szString, int a_nDim);
    	bool WriteString(const char *a_szKey, const char *a_szString);
    };

    ////////////////////////////////////////////////////////////////////////////////
    // CLASS:			SSClock
    // INHERITS FROM:	None
    // DESCRIPTION:		Utility class to encapsulate the performance counter code
    //					and provide a simple interface to get the current time.
    // REMARKS:			None
    ////////////////////////////////////////////////////////////////////////////////
    class SSClock
    {
    private:
    	static float s_fPeriod;
    public:
    	static void Init();
    	static float GetTime();
    };

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //

    // Function Prototypes ******************************************************* //

    // -- Screen saver password stuff --
    BOOL SSUtl_VerifyPassword(HWND hwnd);
    void SSUtl_ChangePassword(HWND hwnd);
    // -- Argument parser (similar to strok but doesn't use global var.) --
    char *SSUtl_GetArg(char *a_szString, char *a_szDest, const char *a_szDelimiters);

    // Module External Functions ************************************************* //

    // Module Internal Functions ************************************************* //

    #endif //SSUTILS_H

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSUtils.cpp] - (10,535 bytes)

    /* ******************************************************************************

    	FILE:			SSUtils.cpp
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	This file contains a collection of utility classes and
    					functions usefull for a screen saver application.
    					Yes, I know, the classes should have been in a different
    					file, sorry for not following the coding standards.

    	$History::                                                                  $

    ****************************************************************************** */

    // Includes ****************************************************************** //
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <regstr.h>
    #include <stdlib.h>
    #include <string.h>

    #include "SSUtils.h"

    // Defines ******************************************************************* //

    // Types ********************************************************************* //

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //

    float SSClock::s_fPeriod = 0;	// Period, in seconds, of the performance counter.

    // Function Prototypes ******************************************************* //

    // Module External Functions ************************************************* //

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SSUtl_GetArg
    // DESCRIPTION:	Isolate the argument (or token) contained in the string.
    //				The delimiters are given as a string.
    // PARAMETERS:	(in) a_szString	-	Source string.
    //				(in) a_szDest	-	Destination string where the token is copied.
    //				(in) a_szDelimiters	-	String of delimiters.
    // RETURN VALUE: Pointer to the start of the next token in the source string.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    char *SSUtl_GetArg(char *a_szString, char *a_szDest, const char *a_szDelimiters)
    {
    	while(!strchr(a_szDelimiters, *a_szString) && *a_szString)
    	{
    		*a_szDest = *a_szString;
    		a_szDest++;
    		a_szString++;
    	}
    	// Put the end of string to the token
    	*a_szDest = 0;

    	if(*a_szString)
    	{	// Go to the start of next argument
    		while(strchr(a_szDelimiters, *a_szString)) a_szString++;
    		// check again if this is the end of string
    		if(*a_szString)	return a_szString;
    		else return NULL;
    	}
    	else return NULL;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SSUtl_VerifyPassword
    // DESCRIPTION:	Verify the password.
    // PARAMETERS:	(in) hwnd	-	Window handle.
    // RETURN VALUE: True or false.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    BOOL SSUtl_VerifyPassword(HWND hwnd)
    {
    	// Under NT, we return true immediately. This lets the saver quit, and the system manages passwords.
    	// Under '95, we call VerifyScreenSavePwd. This checks the appropriate registry key and, if necessary, pops up a verify dialog
    	OSVERSIONINFO osv;
    	osv.dwOSVersionInfoSize = sizeof(osv);

    	GetVersionEx(&osv);

    	if( osv.dwPlatformId==VER_PLATFORM_WIN32_NT )
    		return true;

    	HINSTANCE hpwdcpl = ::LoadLibrary("PASSWORD.CPL");
    	if( hpwdcpl==NULL )
    		return true;

    	typedef BOOL (WINAPI *VERIFYSCREENSAVEPWD)(HWND hwnd);
    	VERIFYSCREENSAVEPWD VerifyScreenSavePwd;
    	VerifyScreenSavePwd = (VERIFYSCREENSAVEPWD)GetProcAddress(hpwdcpl,"VerifyScreenSavePwd");

    	if( VerifyScreenSavePwd==NULL )
    	{
    		FreeLibrary(hpwdcpl);
    		return true;
    	}

    	BOOL bres = VerifyScreenSavePwd(hwnd);
    	FreeLibrary(hpwdcpl);
    	return bres;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SSUtl_ChangePassword
    // DESCRIPTION:	Change the password for this screen saver.
    // PARAMETERS:	(in) hwnd	-	Window handle.
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSUtl_ChangePassword(HWND hwnd)
    {
    	// This only ever gets called under '95, when started with the /a option.
    	HINSTANCE hmpr = ::LoadLibrary("MPR.DLL");
    	if( hmpr==NULL )
    		return;

    	typedef VOID (WINAPI *PWDCHANGEPASSWORD) (LPCSTR lpcRegkeyname,HWND hwnd,UINT uiReserved1,UINT uiReserved2);
    	PWDCHANGEPASSWORD PwdChangePassword=(PWDCHANGEPASSWORD)::GetProcAddress(hmpr,"PwdChangePasswordA");
    	if( PwdChangePassword==NULL )
    	{
    		FreeLibrary(hmpr);
    		return;
    	}

    	PwdChangePassword("SCRSAVE",hwnd,0,0); FreeLibrary(hmpr);
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Open
    // DESCRIPTION:	Open the registry with the current key path.
    // PARAMETERS:	(in) a_szPath	-	key path to open.
    // RETURN VALUE: true if it succeded. false otherwise.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    bool SSUtlReg::Open(const char *a_szPath)
    {
    	LONG res = RegOpenKeyEx(HKEY_CURRENT_USER,a_szPath,0,KEY_ALL_ACCESS,&m_hKey);
    	if(res!=ERROR_SUCCESS)	return false;
    	return true;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Create
    // DESCRIPTION:	Create a registry, opens it if it already exists.
    // PARAMETERS:	(in) a_szPath	-	Path of the key to open.
    // RETURN VALUE: true on success, false otherwise.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    bool SSUtlReg::Create(const char *a_szPath)
    {
    	LONG res;
    	DWORD disp;
    	res = RegCreateKeyEx(HKEY_CURRENT_USER,a_szPath,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&m_hKey,&disp);
    	/* if(disp == REG_CREATED_NEW_KEY)
    	{
    		// The key did not exist before and was created.
    	}
    	else
    	{
    		// The key existed before, it was simply opened.
    	}*/
    	if( res!=ERROR_SUCCESS ) return false;
    	return true;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Close
    // DESCRIPTION:	Close the registry key.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSUtlReg::Close()
    {
    	RegCloseKey(m_hKey);
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	ReadDWord
    // DESCRIPTION:	Read a double word (32 bit value) from the registry of the
    //				given key name.
    // PARAMETERS:	(in) a_szKey	-	Key name to get the value from.
    //				(in) a_dwDefault	-	Default value if not found.
    // RETURN VALUE: Value read.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    DWORD SSUtlReg::ReadDWord(const char *a_szKey, DWORD a_dwDefault)
    {
    	DWORD valtype, valsize, val;
    	valsize = sizeof(val);
    	LONG res = RegQueryValueEx(m_hKey, a_szKey , 0, &valtype, (LPBYTE)&val, &valsize);
    	return (res == ERROR_SUCCESS) ? val : a_dwDefault;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	WriteDWord
    // DESCRIPTION:	Write a value in the given key.
    // PARAMETERS:	(in) a_szKey	-	Key name.
    //				(in) a_dwValue	-	Value to write into the key.
    // RETURN VALUE: true if the write was sucessfull, false otherwise.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    bool SSUtlReg::WriteDWord(const char *a_szKey, DWORD a_dwValue)
    {
    	LONG res = RegSetValueEx(m_hKey, a_szKey, 0, REG_DWORD, (CONST BYTE*)&a_dwValue, sizeof(DWORD));
    	return (res == ERROR_SUCCESS) ? true : false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	ReadString
    // DESCRIPTION:	Read a null terminated string from registry.
    // PARAMETERS:	(in) a_szKey		-	Key name
    //				(out) a_szString	-	Buffer that will hold the string
    //				(in) a_nDim			-	Size of the buffer.
    // RETURN VALUE: true if read was ok. False otherwise.
    // REMARKS:		It may be possible that the buffer is not big enought,
    //				in that case, the user has to create a bigger buffer.
    /////////////////////////////////////////////////////////////////////////////////
    bool SSUtlReg::ReadString(const char *a_szKey, char *a_szString, int a_nDim)
    {
    	DWORD valtype, valsize;
    	valsize = a_nDim;
    	LONG res = RegQueryValueEx(m_hKey, a_szKey , 0, &valtype, (LPBYTE)a_szString, &valsize);
    	return (res == ERROR_SUCCESS) ? true : false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	WriteString
    // DESCRIPTION:	Write a null-terminated string to registry
    // PARAMETERS:	(in) a_szKey	-	Key name
    //				(in) a_szString	-	Null terminating String
    // RETURN VALUE: true if write successfull, false otherwise.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    bool SSUtlReg::WriteString(const char *a_szKey, const char *a_szString)
    {
    	DWORD valsize = strlen(a_szString) + 1;
    	LONG res = RegSetValueEx(m_hKey, a_szKey, 0, REG_SZ, (CONST BYTE*)a_szString, valsize);
    	return (res == ERROR_SUCCESS) ? true : false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Init
    // DESCRIPTION:	Get the performance counter's period in seconds.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSClock::Init()
    {
    	// Get the performance counter frequency
    	LARGE_INTEGER Frequency;
    	// The frequency is in Hz (1/sec).
    	QueryPerformanceFrequency(&Frequency);
    	// Transform the frequency into a floating point value
    	float fFrequency = (float)Frequency.QuadPart;
    	// Get the period in seconds.
    	s_fPeriod = 1/fFrequency;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	GetTime
    // DESCRIPTION:	Query the performance counter and transform it into seconds.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    float SSClock::GetTime()
    {
    	LARGE_INTEGER Counter;
    	QueryPerformanceCounter(&Counter);
    	float fCounter = (float)Counter.QuadPart;
    	return fCounter*s_fPeriod;
    }

    // Module Internal Functions ************************************************* //

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSTexture.h] - (1,406 bytes)

    /* ******************************************************************************

    	FILE:			SSTexture.h
    	AUTHOR:			Jean-Sebastien Perrier

    	DESCRIPTION:	OpenGL wrapper for texture management.

    ****************************************************************************** */

    #ifdef _MSC_VER
    	#pragma once
    #endif
    #ifndef SSTEXTURE_H
    #define SSTEXTURE_H

    // Includes ****************************************************************** //

    // Defines ******************************************************************* //

    // Forward definitions ******************************************************* //

    // Types ********************************************************************* //

    class SSTexture
    {
    private:
    	char m_szFilename[128];
    	bool m_bLoaded;
    	bool m_bMipmap;
    	unsigned int m_unTextureID;		// OpenGL's texture ID.

    private:
    	bool LoadImage();
    	static SSTexture *s_pLastApplied;

    public:

    	SSTexture(const char *filename, bool a_bMipmap = true);
    	virtual ~SSTexture();

    	void Apply();
    };

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Function Prototypes ******************************************************* //

    // Inline Functions ********************************************************** //

    #endif // SSTEXTURE_H

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSTexture.cpp] - (3,857 bytes)

    /* ******************************************************************************

    	FILE:			SSTexture.cpp
    	AUTHOR:			Jean-Sebastien Perrier

    	DESCRIPTION:	OpenGL wrapper for texture management.

    ****************************************************************************** */

    // Includes ****************************************************************** //
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glaux.h>
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>

    #include "SSTexture.h"

    // Defines ******************************************************************* //

    // Types ********************************************************************* //

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //

    SSTexture *SSTexture::s_pLastApplied = NULL;

    // Function Prototypes ******************************************************* //

    static AUX_RGBImageRec *LoadBMP(const char *Filename);

    // Module External Functions ************************************************* //

    SSTexture::SSTexture(const char *a_szFilename, bool a_bMipmap) :
    m_bLoaded(false),
    m_bMipmap(a_bMipmap),
    m_unTextureID(0)
    {
    	strcpy(m_szFilename, a_szFilename);
    	m_bLoaded = LoadImage();
    }

    SSTexture::~SSTexture()
    {
    	if(m_bLoaded)
    	{	// delete the texture from the driver
    		glDeleteTextures(1, &m_unTextureID);
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Apply
    // DESCRIPTION:	Applies (bind) the texture to the device driver.
    //				State caching is performed in order to prevent
    //				binding the same texture over and over again. This
    //				may cause a slow down on some graphic cards.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSTexture::Apply()
    {
    	if(s_pLastApplied != this)
    	{
    		glBindTexture(GL_TEXTURE_2D, m_unTextureID);
    		s_pLastApplied = this;
    	}
    }

    // Module Internal Functions ************************************************* //

    bool SSTexture::LoadImage()
    {
    	AUX_RGBImageRec *pImage = LoadBMP(m_szFilename);
    	// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
    	if(pImage)
    	{
    		glGenTextures(1, &m_unTextureID);					// Create The Texture

    		// Typical Texture Generation Using Data From The Bitmap
    		glBindTexture(GL_TEXTURE_2D, m_unTextureID);

    		if(m_bMipmap)
    		{
    			// Trilinear filtering (uses mipmaps).
    			gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pImage->sizeX, pImage->sizeY, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
    			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
    			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    		}
    		else
    		{
    			// Bilinear filtering (no mipmap, less memory required, better for older cards).
    			glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->sizeX, pImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
    			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    		}

    		// The texture is binded to the driver, so we can delete the image itself.
    		free(pImage->data);
    		free(pImage);
    		return true;
    	}
    	return false;
    }

    AUX_RGBImageRec *LoadBMP(const char *a_szFilename)
    {
    	FILE *File=NULL;				// File Handle
    	if(!a_szFilename)	return NULL;

    	File = fopen(a_szFilename,"r");	// Check To See If The File Exists
    	if(File)						// Does The File Exist?
    	{
    		fclose(File);				// Close The Handle
    		return auxDIBImageLoad(a_szFilename);
    	}
    	return NULL;
    }

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSMinimalApp.h] - (2,896 bytes)

    /* ******************************************************************************

    	FILE:			SSMinimalApp.h
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	Minimal screen saver implementation example.
    					It shows a texture spinning cube with a flashing
    					background.

    	$History::                                                                  $

    ****************************************************************************** */
    #ifdef _MSC_VER
    	#pragma once
    #endif
    #ifndef SSMINIMALAPP_H
    #define SSMINIMALAPP_H

    // Includes ****************************************************************** //
    #include "SSBaseApp.h"
    #include "SSTexture.h"

    // Defines ******************************************************************* //

    // Forward definitions ******************************************************* //

    // Types ********************************************************************* //

    ////////////////////////////////////////////////////////////////////////////////
    // CLASS:			SSMinimalApp
    // INHERITS FROM:	SSBaseApp
    // DESCRIPTION:		Minimal screen saver.
    // REMARKS:			None
    ////////////////////////////////////////////////////////////////////////////////
    class SSMinimalApp : public SSBaseApp
    {
    private:
    	BOOL m_bRotate;				// Rotation flag.
    	BOOL m_bFlash;				// Flash flag.
    	char m_szTextureFile[256];	// Texture file name

    	// -- Internal stuff --
    	float m_fLastTime;			// Time for the last frame.
    	// Parameters for the rotation effect
    	float m_afRot[3];			// X Y Z rotation angles in degrees.
    	float m_afRotSpeed[3];		// X Y Z rotation speed in degrees/sec.
    	// Parameters for the flashing effect
    	float m_afFlashColor[3];	// RGB Color for the flash effect.
    	float m_fNextFlash;			// Time for the next flash.
    	float m_fFlashPeriod;		// Time between each flash.
    	bool m_bFlashed;			// true if the flash occured.

    	SSTexture *m_pTexture;		// Texture for this example.

    public:
    	SSMinimalApp(HINSTANCE a_hInstance);
    	virtual ~SSMinimalApp() {}

    	virtual void ReadConfigRegistry();
    	virtual void WriteConfigRegistry();
    	virtual bool InitGL(int w, int h);
    	virtual void ReleaseGL();
    	virtual void Update();
    	virtual void Display();

    	// Get methods
    	BOOL GetRotate() const {return m_bRotate;}
    	BOOL GetFlash() const {return m_bFlash;}
    	char *GetTextureFile() {return m_szTextureFile;}
    	// Set methods
    	void SetRotate(BOOL val) {m_bRotate = val;}
    	void SetFlash(BOOL val) {m_bFlash = val;}
    	void SetTextureFile(const char *a_szName);
    };

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Function Prototypes ******************************************************* //

    // Inline Functions ********************************************************** //

    #endif // SSMINIMALAPP_H

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSMinimalApp.cpp] - (10,340 bytes)

    /* ******************************************************************************

    	FILE:			Minimal.cpp
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	Screen saver application.

    	$History::                                                                  $

    ****************************************************************************** */

    // Includes ****************************************************************** //
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <GL/gl.h>
    #include <GL/glu.h>

    #include "SSMinimalApp.h"
    #include "SSUtils.h"

    // Defines ******************************************************************* //
    #define REGSTR_PATH_CONFIG  ("Software\\FlipcodeStuff\\SSMinimalApp")

    // Types ********************************************************************* //

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //

    // Function Prototypes ******************************************************* //

    // Module External Functions ************************************************* //

    // Module Internal Functions ************************************************* //

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SSMinimalApp
    // DESCRIPTION:	Initialise the application's internal values. It is important
    //				that the constructor initialise all the parameters to
    //				a default value because they will get propagated in the
    //				dialog box if the configuration has not been saved in the
    //				registry.
    // PARAMETERS:	(in) a_hInstance	-	Instance of the application.
    // RETURN VALUE: None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    SSMinimalApp::SSMinimalApp(HINSTANCE a_hInstance) :
    	SSBaseApp(a_hInstance),
    	m_bRotate(TRUE),
    	m_bFlash(TRUE),
    	m_pTexture(NULL)
    {
    	// Set the default texture file name
    	SetTextureFile("SSTexture.bmp");
    	// Setup initial position to 0 degrees.
    	memset(m_afRot, 0, sizeof(float)*3);
    	// Setup rotation speeds on the 3 axis in degrees/sec.
    	m_afRotSpeed[0] = 35;
    	m_afRotSpeed[1] = 20;
    	m_afRotSpeed[2] = 10;
    	// Setup flash effect
    	m_afFlashColor[0] = 1;	// Red component
    	m_afFlashColor[1] = 1;	// Green component
    	m_afFlashColor[2] = 0;	// Blue component
    	m_fFlashPeriod = 3;	// 5 second period.
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	ReadConfigRegistry
    // DESCRIPTION:	Load configuration values from the registry.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::ReadConfigRegistry()
    {
    	SSUtlReg Reg;
    	if(Reg.Open(REGSTR_PATH_CONFIG))
    	{
    		m_bRotate = Reg.ReadDWord("Rotate", m_bRotate);
    		m_bFlash = Reg.ReadDWord("Flash", m_bFlash);
    		Reg.ReadString("TextureFile", m_szTextureFile, 256);
    		Reg.Close();
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	WriteConfigRegistry
    // DESCRIPTION:	Save the configuration values into the registry.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::WriteConfigRegistry()
    {
    	SSUtlReg Reg;
    	if(Reg.Create(REGSTR_PATH_CONFIG))
    	{
    		Reg.WriteDWord("Rotate", m_bRotate);
    		Reg.WriteDWord("Flash", m_bFlash);
    		Reg.WriteString("TextureFile", m_szTextureFile);
    		Reg.Close();
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SetTextureFile
    // DESCRIPTION:	Set the texture file name.
    // PARAMETERS:	(in) a_szName	-	Name of the file (full path).
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::SetTextureFile(const char *a_szName)
    {
    	strcpy(m_szTextureFile, a_szName);
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	InitGL
    // DESCRIPTION:	Initialize the openGL ressources.
    // PARAMETERS:	(in) width	-	With of the window in pixels.
    //				(in) height	-	Height of the window in pixels.
    // RETURN VALUE: true if success, false otherwise.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    bool SSMinimalApp::InitGL(int width, int height)
    {
    	// Load a texture
    	if(!m_pTexture)
    	{
    		m_pTexture = new SSTexture(GetTextureFile());
    	}

    	glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping ( NEW )
    	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
    	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
    	glClearDepth(1.0f);									// Depth Buffer Setup
    	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
    	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
    	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

    	glViewport(0,0,width,height);						// Reset The Current Viewport

    	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
    	glLoadIdentity();									// Reset The Projection Matrix

    	// Calculate The Aspect Ratio Of The Window
    	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

    	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
    	glLoadIdentity();									// Reset The Modelview Matrix

    	// We are going to need the clock, so initialize it:
    	SSClock::Init();
    	m_fLastTime = SSClock::GetTime();
    	m_fNextFlash = m_fLastTime + m_fFlashPeriod;
    	return true;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	ReleaseGL
    // DESCRIPTION:	This function gets called when the application still has the
    //				OpenGL context. It is used to release OpenGL ressources like
    //				the textures or display lists. It is important to do this
    //				since allocated OpenGL ressource may stay alive in the driver
    //				even if the context is dead and this is not good. A well behaved
    //				OpenGL screen saver always clean up after himself! :)
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::ReleaseGL()
    {
    	// Release the texture from OpenGL
    	delete m_pTexture;
    	// Set the pointer to NULL so that we don't redelete it
    	// by mistake in the destructor.
    	m_pTexture = NULL;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Update
    // DESCRIPTION:	Called every frame to update the application.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::Update()
    {
    	// Query the time and compute elapsed time since last
    	// update of the application.
    	float fTime = SSClock::GetTime();
    	float fDeltaTime = fTime - m_fLastTime;
    	m_fLastTime = fTime;	// Prepare for next time.

    	// Update the rotation for each axis.
    	for(int i=0; i < 3; i++)
    	{
    		// Update the rotation of the cube on axe i.
    		m_afRot[i] += (m_afRotSpeed[i] * fDeltaTime);
    		// Wrap angles around 360 degrees.
    		if(m_afRot[i] > 360) m_afRot[i] -= 360;
    	}

    	// Update the flashing effect
    	if(fTime > m_fNextFlash)
    	{	// It is time to flash, so we change the clear color.
    		glClearColor(m_afFlashColor[0], m_afFlashColor[1], m_afFlashColor[2], 1);
    		m_bFlashed = true;
    		// Prepare next flash time.
    		m_fNextFlash = fTime + m_fFlashPeriod;
    	}
    	else
    	{
    		if(m_bFlashed)
    		{	// Reset the clear color to black.
    			glClearColor(0, 0, 0, 1);
    		}
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	Display
    // DESCRIPTION:	Called every frame to display the scene.
    // PARAMETERS:	None
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSMinimalApp::Display()
    {
    	// Clear The Screen And The Depth Buffer
    	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    	// Reset The View
    	glLoadIdentity();
    	glTranslatef(0.0f,0.0f,-5.0f);
    	// Apply the rotation to the ModelView matrix.
    	if(m_bRotate)
    	{
    		glRotatef(m_afRot[0], 1.0f, 0.0f, 0.0f);
    		glRotatef(m_afRot[1], 0.0f, 1.0f, 0.0f);
    		glRotatef(m_afRot[2], 0.0f, 0.0f, 1.0f);
    	}
    	// Apply the texture
    	m_pTexture->Apply();
    	// Draw a cube.
    	glBegin(GL_QUADS);
    		// Front Face
    		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
    		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
    		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
    		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
    		// Back Face
    		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
    		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
    		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
    		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
    		// Top Face
    		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
    		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
    		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
    		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
    		// Bottom Face
    		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
    		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
    		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
    		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
    		// Right face
    		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
    		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
    		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
    		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
    		// Left Face
    		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
    		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
    		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
    		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
    	glEnd();
    }

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSMain.cpp] - (4,027 bytes)

    /* ******************************************************************************

    	FILE:			Minimal.cpp
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	Main file. Contains the entry point of the program.
    					Also, it contains the callback function for the configuration
    					dialog box.

    	$History::                                                                  $

    ****************************************************************************** */

    // Includes ****************************************************************** //
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include "resource.h"

    #include "SSMinimalApp.h"
    #include "SSUtils.h"

    // Defines ******************************************************************* //

    // Types ********************************************************************* //

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //

    // Function Prototypes ******************************************************* //

    static BOOL CALLBACK ConfigDialogProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);

    // Module External Functions ************************************************* //

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	WinMain
    // DESCRIPTION:	Program's entry point.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    int WINAPI WinMain(HINSTANCE a_hInst, HINSTANCE,LPSTR,int a_nCmdShow)
    {
    	// Create the application instance.
    	SSMinimalApp *pApp = new SSMinimalApp(a_hInst);

    	// Load application settings (or set defaults value if no
    	// registry was previously created).
    	pApp->ReadConfigRegistry();

    	// Process the command line to know running mode (preview, config, etc...)
    	HWND hParentWnd = pApp->ProcessCommandLine(GetCommandLine());

    	// Handle the different running mode:
    	switch(pApp->GetMode())
    	{
    	case SSBaseApp::smPassword:
    		SSUtl_ChangePassword(hParentWnd);
    		break;
    	case SSBaseApp::smConfig:
    		DialogBox(a_hInst, MAKEINTRESOURCE(DLG_CONFIG), hParentWnd, ConfigDialogProc);
    		break;
    	case SSBaseApp::smSaver:
    	case SSBaseApp::smPreview:
    		pApp->RunScreenSaver(hParentWnd, a_nCmdShow);
    		break;
    	default:
    		MessageBox(NULL, "Something when wrong in parsing cmd line, \nbailing out...", "Error", MB_OK);
    		break;
    	}

    	// Delete the application before quitting.
    	delete pApp;
    	return 0;
    }

    // Module Internal Functions ************************************************* //

    // Callback function for the dialog box.
    BOOL CALLBACK ConfigDialogProc(HWND hwnd,UINT msg, WPARAM wParam, LPARAM lParam)
    {
    	// Get the application's instance.
    	SSMinimalApp *pApp = (SSMinimalApp *)SSBaseApp::GetGlobalInstance();
    	switch (msg)
    	{
    	case WM_INITDIALOG:
    		{
    			// Get the values from the application and propagate them
    			// into the dialog box controls.
    			CheckDlgButton(hwnd,IDC_CHECK_ROTATE, pApp->GetRotate());
    			CheckDlgButton(hwnd,IDC_CHECK_FLASH, pApp->GetFlash());
    			SetDlgItemText(hwnd, IDC_EDIT_TEXTUREFILE, pApp->GetTextureFile());
    			return true;
    		}
        case WM_COMMAND:
    		{
    			int id = LOWORD(wParam);
    			if( id==IDOK )
    			{
    				// Get the values from the dialog box controls and
    				// propagate them into the application.
    				char szBuffer[256];
    				pApp->SetRotate(IsDlgButtonChecked(hwnd,IDC_CHECK_ROTATE)==BST_CHECKED);
    				pApp->SetFlash(IsDlgButtonChecked(hwnd,IDC_CHECK_FLASH)==BST_CHECKED);
    				// Read the file name specified.
    				GetDlgItemText(hwnd, IDC_EDIT_TEXTUREFILE, szBuffer, 256);
    				pApp->SetTextureFile(szBuffer);

    				// Then, save the configuration.
    				pApp->WriteConfigRegistry();
    			}

    			if( id==IDOK || id==IDCANCEL )	EndDialog(hwnd,id);
    		} break;
    	}
    	return false;
    }

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSBaseApp.h] - (4,006 bytes)

    /* ******************************************************************************

    	FILE:			SSBaseApp.h
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	Base class for an OpenGL screen saver application. This
    					class handles everything a screen saver should do. It creates
    					the window and handles the OpenGL context creation. A lot of
    					things have been hard coded in order to simplify the class
    					(such as the pixel format and frame buffer configuration for
    					the Opengl context).

    	$History::                                                                  $

    ****************************************************************************** */
    #ifdef _MSC_VER
    	#pragma once
    #endif
    #ifndef SSBASEAPP_H
    #define SSBASEAPP_H

    // Includes ****************************************************************** //

    // Defines ******************************************************************* //

    // Forward definitions ******************************************************* //

    // Types ********************************************************************* //

    ////////////////////////////////////////////////////////////////////////////////
    // CLASS:			SSBaseApp
    // INHERITS FROM:	None
    // DESCRIPTION:		Base class for an OpenGL screen saver application. This
    //					class contains pure virtual functions, it has to be
    //					derived in order to be instanciated.
    // REMARKS:			None.
    ////////////////////////////////////////////////////////////////////////////////
    class SSBaseApp
    {
    public:
    	// Running mode enumeration.
    	enum ModeEnum
    	{
    		smNone,
    		smConfig,
    		smPassword,
    		smPreview,
    		smSaver
    	};

    private:
    	char m_szWindowName[256];	// Application window's name
    	char m_szWindowClassName[256];	// Window class name.
    	ModeEnum m_eMode;	// Application mode (config, preview, saver, etc).

    	HINSTANCE m_hInstance;	// Application's instance handle.
    	HWND m_hWnd;			// Window handle of the application

    	static SSBaseApp *s_pInstance;	// Required for windows call back function.

    	// Stuff needed for screen saver management.
    	DWORD m_dwPasswordDelay;	// in seconds
    	DWORD m_dwMouseThreshold;	// in pixels
    	BOOL  m_bMuteSound;

    	POINT m_InitCursorPos;		//	Initial cursor position
    	DWORD m_dwInitTime;			// in ms
    	BOOL  m_bIsDialogActive;
    	BOOL  m_bReallyClose;		// for NT, so we know if a WM_CLOSE came from us or it.

    private:
    	// The window's callback function has to be static so that we
    	// can give it's resolved address to the window class.
    	static LRESULT CALLBACK SaverWindowProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);

    public:
    	SSBaseApp(HINSTANCE a_hInstance);
    	virtual ~SSBaseApp() {}

    	HWND ProcessCommandLine(char *a_szCmd);

    	void OnCreate(HWND a_hWnd);
    	void RunScreenSaver(HWND a_hParentWnd, int nCmdShow);
    	void CloseSaverWindow();
    	void StartDialog();
    	void EndDialog();

    	// Get methods
    	const char *GetWindowName() const {return m_szWindowName;}
    	const char *GetWindowClassName() const {return m_szWindowClassName;}
    	ModeEnum GetMode() const {return m_eMode;}
    	HWND GetWindowHandle() const {return m_hWnd;}

    	// Set methods
    	void SetWindowHandle(HWND a_hWnd) {m_hWnd = a_hWnd;}

    	// Global methods
    	static SSBaseApp *GetGlobalInstance() { return s_pInstance;}
    	static void SetGlobalInstance(SSBaseApp *a_pInstance) {s_pInstance = a_pInstance;}

    	// Derived functions
    	virtual void ReadConfigRegistry() = 0;
    	virtual void WriteConfigRegistry() = 0;
    	virtual bool InitGL(int w, int h) = 0;
    	virtual void ReleaseGL() = 0;
    	virtual void Update() = 0;
    	virtual void Display() = 0;
    };

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Function Prototypes ******************************************************* //

    // Inline Functions ********************************************************** //

    #endif // SSBASEAPP_H

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [SSBaseApp.cpp] - (12,789 bytes)

    /* ******************************************************************************

    	FILE:			SSBaseApp.cpp
    	AUTHOR:			Jean-Sébastien Perrier

    	DESCRIPTION:	Base class for an OpenGL screen saver application. This
    					class handles everything a screen saver should do. It creates
    					the window and handles the OpenGL context creation. A lot of
    					things have been hard coded in order to simplify the class
    					(such as the pixel format and frame buffer configuration for
    					the Opengl context).

    	$History::                                                                  $

    ****************************************************************************** */

    // Includes ****************************************************************** //
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #include <regstr.h>
    #include <stdlib.h>		// for atoi
    #include <string.h>		// for strcpy
    #include <math.h>		// for abs

    #include "SSBaseApp.h"
    #include "SSUtils.h"

    // Defines ******************************************************************* //
    // Standard screen saver path for common settings.
    #define REGSTR_PATH_PLUSSCR (REGSTR_PATH_SETUP "\\Screen Savers")

    // Types ********************************************************************* //

    // Consts ******************************************************************** //

    // Globals ******************************************************************* //

    // Static Members Storage Point ********************************************** //
    // Global instance of the application (Like a singleton).
    SSBaseApp *SSBaseApp::s_pInstance = NULL;

    // Function Prototypes ******************************************************* //

    // Module External Functions ************************************************* //

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SSBaseApp
    // DESCRIPTION:	Class constructor.
    // PARAMETERS:	(in) a_hInstance	-	Handle to the application's instance.
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    SSBaseApp::SSBaseApp(HINSTANCE a_hInstance) :
    	m_hInstance(a_hInstance),
    	// Setup default values.
    	m_hWnd(NULL),
    	m_bReallyClose(FALSE),
    	m_bIsDialogActive(FALSE),
    	m_dwPasswordDelay(15),
    	m_dwMouseThreshold(50),
    	m_bMuteSound(0),
    	m_eMode(smNone)
    {
    	// Set the current global instance
    	SSBaseApp::SetGlobalInstance(this);

    	// Setup the default names. These can be overriden by
    	// the derived classes.
    	strcpy(m_szWindowName, "ScreenSaverWnd");
    	strcpy(m_szWindowClassName, "ScreenSaverWndClass");

    	// Read the General screen saver settings from the registry.
    	SSUtlReg Reg;
    	if(Reg.Open(REGSTR_PATH_PLUSSCR))
    	{
    		m_dwPasswordDelay = Reg.ReadDWord("Password Delay", m_dwPasswordDelay);
    		m_dwMouseThreshold = Reg.ReadDWord("Mouse Threshold", m_dwMouseThreshold);
    		m_bMuteSound = Reg.ReadDWord("Mute Sound", m_bMuteSound);
    		Reg.Close();
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	ProcessCommandLine
    // DESCRIPTION:	Parse the command line and setup the application's mode and
    //				get the window handle, if any.
    // PARAMETERS:	None
    // RETURN VALUE: Window handle.
    // REMARKS:		This function will set the application's mode.
    /////////////////////////////////////////////////////////////////////////////////
    HWND SSBaseApp::ProcessCommandLine(char *a_szCmd)
    {
    	HWND hParentWnd=NULL;		// Parent window's handle.
    	char szArg[256];			// Buffer to hold the isolated argument
    	char *szLimit = " ";		// Default command line delimiter
    	char *szCmd = a_szCmd;		// Pointer to command line string.

    	// We read the first argument, this
    	// should be the name of the program.
    	szCmd = SSUtl_GetArg(szCmd, szArg, szLimit);

    	if(!szCmd)
    	{	// No more argument, then we are in configuration mode.
    		m_eMode = smConfig;
    	}
    	else
    	{	// Get the second argument
    		szCmd = SSUtl_GetArg(szCmd, szArg, szLimit);
    		switch(szArg[1])
    		{
    		// PREVIEW MODE
    		case 'p':	case 'P':
    		case 'l':	case 'L':
    			m_eMode = smPreview;
    			// Get the window's handle
    			szCmd = SSUtl_GetArg(szCmd, szArg, szLimit);
    			hParentWnd = (HWND)atoi(szArg);
    			break;
    		// SCREEN SAVER MODE
    		case 's':	case 'S':
    			m_eMode = smSaver;
    			break;
    		// CONFIGURATION MODE
    		case 'c':	case 'C':
    			m_eMode = smConfig;
    			// Get window's handle
    			szCmd = SSUtl_GetArg(szCmd, szArg, " :");
    			if(*szArg)	hParentWnd = (HWND)atoi(szArg);
    			else		hParentWnd = GetForegroundWindow();
    			break;
    		// PASSWORD MODE
    		case 'a':	case 'A':
    			szCmd = SSUtl_GetArg(szCmd, szArg, " :");
    			hParentWnd = (HWND)atoi(szArg);
    			m_eMode = smPassword;
    			break;
    		}
    	}
    	return hParentWnd;
    }

    void SSBaseApp::CloseSaverWindow()
    {
    	m_bReallyClose = true;
    	PostMessage(m_hWnd,WM_CLOSE,0,0);
    }

    void SSBaseApp::StartDialog()
    {
    	m_bIsDialogActive = true;
    	SendMessage(m_hWnd,WM_SETCURSOR,0,0);
    }

    void SSBaseApp::EndDialog()
    {
    	m_bIsDialogActive = false;
    	SendMessage(m_hWnd,WM_SETCURSOR,0,0);
    	GetCursorPos(&m_InitCursorPos);
    }

    void SSBaseApp::OnCreate(HWND a_hWnd)
    {
    	SetWindowHandle(a_hWnd);
    	GetCursorPos(&m_InitCursorPos);
    	m_dwInitTime = GetTickCount();
    }

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	RunScreenSaver
    // DESCRIPTION:	This functions is very central to the whole screen saver
    //				application. It creates the windows and opengl context,
    //				then run the main loop and finally, clean up and return.
    // PARAMETERS:	(in) a_hParentWnd	-	Handle the parent window (can be NULL).
    //				(in) nCmdShow	-	Sent by windows on creation.
    // RETURN VALUE:None
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    void SSBaseApp::RunScreenSaver(HWND a_hParentWnd, int nCmdShow)
    {
    	//-----------------------------------------------------
    	// STEP 1 - REGISTER WINDOW CLASS
    	//-----------------------------------------------------
    	WNDCLASS wc;
    	wc.style=CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    	wc.lpfnWndProc	= SaverWindowProc;
    	wc.cbClsExtra	= 0;
    	wc.cbWndExtra	= 0;
    	wc.hInstance	= m_hInstance;
    	wc.hIcon		= NULL;
    	wc.hCursor		= NULL;
    	wc.hbrBackground = NULL;
    	wc.lpszMenuName	= NULL;
    	wc.lpszClassName	= GetWindowClassName();

    	if(!RegisterClass(&wc))
    	{
    		MessageBox(NULL, "RegisterClass() failed:  "
    			"Cannot register window class.", "Error", MB_OK);
    		return;
    	}

    	//-----------------------------------------------------
    	// STEP 2 - CREATE MAIN WINDOW
    	//-----------------------------------------------------
    	int cx, cy;
    	HWND hParentWnd = NULL;
    	DWORD dwStyle;

    	if(GetMode() == smPreview)
    	{
    		RECT rc;
    		GetWindowRect(a_hParentWnd,&rc);
    		cx = rc.right - rc.left;
    		cy = rc.bottom - rc.top;
    		dwStyle = WS_CHILD|WS_VISIBLE;
    		hParentWnd = a_hParentWnd;

    	}
    	else
    	{
    		cx = GetSystemMetrics(SM_CXSCREEN);
    		cy = GetSystemMetrics(SM_CYSCREEN);
    		dwStyle = WS_POPUP|WS_VISIBLE;
    	}

    	// Create the window for the screen saver
    	HWND hScrWnd =	CreateWindow(GetWindowClassName(), GetWindowName(),
    		dwStyle, 0, 0, cx, cy, hParentWnd, NULL, m_hInstance, NULL);

    	// Unable to create window, quit.
    	if(hScrWnd == NULL) return;

    	// Tell windows that a screen saver is running.
    	UINT oldval;
    	if(GetMode() == smSaver)
    		SystemParametersInfo(SPI_SCREENSAVERRUNNING,1,&oldval,0);

    	//-----------------------------------------------------
    	// STEP 3 - CREATE OPENGL RENDERING CONTEXT
    	//-----------------------------------------------------
    	HDC hDC = GetDC(hScrWnd);
    	// First, we create a pixel format descriptor.
    	PIXELFORMATDESCRIPTOR pfd;
        memset(&pfd, 0, sizeof(pfd));
        pfd.nSize        = sizeof(pfd);
        pfd.nVersion     = 1;
        pfd.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
        pfd.iPixelType   = PFD_TYPE_RGBA;
        pfd.cColorBits   = 32;
    	// Find a suitable pixel format.
    	int pf = ChoosePixelFormat(hDC, &pfd);
        if (pf == 0)
    	{
    		MessageBox(NULL, "ChoosePixelFormat() failed:  "
    			"Cannot find a suitable pixel format.", "Error", MB_OK);
    		return;
        }
    	// Apply this pixel format to the device context.
        if (SetPixelFormat(hDC, pf, &pfd) == FALSE)
    	{
    		MessageBox(NULL, "SetPixelFormat() failed:  "
    			"Cannot set format specified.", "Error", MB_OK);
    		return;
        }
        DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

    	// Finally, create the rendering context.
    	HGLRC hRC = wglCreateContext(hDC);
    	// Then bind it to this thread.
        wglMakeCurrent(hDC, hRC);

    	//-----------------------------------------------------
    	// STEP 4 - INIT THE APPLICATION ITSELF
    	//-----------------------------------------------------
    	if(!InitGL(cx, cy))
    	{
    		MessageBox(NULL, "Application Init failed, bailing out...", "Error", MB_OK);
    		return;
    	}

    	//-----------------------------------------------------
    	// STEP 5 - SCREEN SAVER MAIN LOOP
    	//-----------------------------------------------------
    	ShowWindow(hScrWnd, nCmdShow);

    	MSG msg;

    	bool done = false;
    	while(!done)									// Loop That Runs While done=FALSE
    	{
    		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
    		{
    			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
    				done=TRUE;							// If So done=TRUE
    			else									// If Not, Deal With Window Messages
    			{
    				TranslateMessage(&msg);				// Translate The Message
    				DispatchMessage(&msg);				// Dispatch The Message
    			}
    		}
    		else										// If There Are No Messages
    		{
    			// Update and display application
    			Update();
    			Display();
    			SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
    		}
    	}

    	//-----------------------------------------------------
    	// STEP 6 - RELEASE RESSOURCES
    	//-----------------------------------------------------
    	ReleaseGL();	// Destroy OpenGL Ressources allocated by the application.
    	wglMakeCurrent(NULL, NULL);
        ReleaseDC(hScrWnd, hDC);
        wglDeleteContext(hRC);

    	if(GetMode() == smSaver)
    		SystemParametersInfo(SPI_SCREENSAVERRUNNING,0,&oldval,0);
    	return;
    }

    // Module Internal Functions ************************************************* //

    /////////////////////////////////////////////////////////////////////////////////
    // FUNCTION:	SaverWindowProc
    // DESCRIPTION:	Yep, the big and ugly window procedure. It handles everything a
    //				screen saver should do.
    // PARAMETERS:	...
    // RETURN VALUE: ...
    // REMARKS:		None
    /////////////////////////////////////////////////////////////////////////////////
    LRESULT CALLBACK SSBaseApp::SaverWindowProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
    {
    	SSBaseApp *pApp = SSBaseApp::GetGlobalInstance();

    	switch (msg)
    	{
    	case WM_CREATE:		pApp->OnCreate(hwnd);	break;
        case WM_ACTIVATE:
    	case WM_ACTIVATEAPP:
    	case WM_NCACTIVATE:
    		{
    			if(	pApp->GetMode() == smSaver && !pApp->m_bIsDialogActive &&
    				LOWORD(wParam) == WA_INACTIVE)
    			{
    				pApp->CloseSaverWindow();
    			}
    		} break;
    	case WM_SETCURSOR:
    		{
    			if( pApp->GetMode()== smSaver && !pApp->m_bIsDialogActive )
    				SetCursor(NULL);
    			else
    				SetCursor(LoadCursor(NULL,IDC_ARROW));
    		} break;
        case WM_LBUTTONDOWN:
    	case WM_MBUTTONDOWN:
    	case WM_RBUTTONDOWN:
    	case WM_KEYDOWN:
    		{
    			if( pApp->GetMode()== smSaver && !pApp->m_bIsDialogActive )
    				pApp->CloseSaverWindow();
    		} break;
    	case WM_MOUSEMOVE:
    		{
    			if( pApp->GetMode() == smSaver && !pApp->m_bIsDialogActive )
    			{
    				POINT pt;
    				GetCursorPos(&pt);
    				int dx = abs(pt.x - pApp->m_InitCursorPos.x);
    				int dy = abs(pt.y - pApp->m_InitCursorPos.y);
    				if(dx > (int)pApp->m_dwMouseThreshold || dy > (int)pApp->m_dwMouseThreshold)
    				{
    					pApp->CloseSaverWindow();
    				}
    			}
    		}
    		break;
    	case WM_SYSCOMMAND:
    		{
    			if( pApp->GetMode() == smSaver )
    			{
    				if( wParam==SC_SCREENSAVE )
    					return false;
    				if( wParam==SC_CLOSE )
    					return false;
    			}
    		}
    		break;
    	case WM_CLOSE:
    		{
    			if( pApp->GetMode()== smSaver && pApp->m_bReallyClose && !pApp->m_bIsDialogActive)
    			{
    				BOOL bCanClose = TRUE;
    				if(GetTickCount()-pApp->m_dwInitTime > 1000*pApp->m_dwPasswordDelay )
    				{
    					pApp->StartDialog();
    					bCanClose = SSUtl_VerifyPassword(hwnd);
    					pApp->EndDialog();
    				}
    				if(bCanClose)	DestroyWindow(hwnd);
    			}
    			if(pApp->GetMode()==SSBaseApp::smSaver)
    			{
    				// so that DefWindowProc doesn't get called,
    				// because it would just DestroyWindow
    				return false;
    			}
    		}
    		break;
    	case WM_DESTROY:
    		PostQuitMessage(0);
    		break;
      }
      return DefWindowProc(hwnd,msg,wParam,lParam);
    }

Currently browsing [ScreenSaver.zip] (77,250 bytes) - [resource.h] - (594 bytes)

    //{{NO_DEPENDENCIES}}
    // Microsoft Developer Studio generated include file.
    // Used by minimal.rc
    //
    #define DLG_CONFIG                      104
    #define IDC_CHECK_ROTATE                1000
    #define IDC_EDIT_TEXTUREFILE            1005
    #define IDC_CHECK_FLASH                 1006

    // Next default values for new objects
    //
    #ifdef APSTUDIO_INVOKED
    #ifndef APSTUDIO_READONLY_SYMBOLS
    #define _APS_NEXT_RESOURCE_VALUE        109
    #define _APS_NEXT_COMMAND_VALUE         40001
    #define _APS_NEXT_CONTROL_VALUE         1007
    #define _APS_NEXT_SYMED_VALUE           101
    #endif
    #endif

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.