Aide pour un projet en C++
Brenni
-
Valde_91 -
Valde_91 -
Salut!
Je suis un étudiant du Polythécnique de Lausanne en génie mécanique. Je un grand problème avec mon projet sémestrale de C++, qui je n'arrive pas à completer. Je doit programmer un jeu type Asteroid et l'énoncé du projet se trouve dans le site: cowww.epfl.ch/infgmel/ dans le répertoire projet..
Moi je suis arrive jusqu'au test_base et je n'arrive pas à aller plus loin, donc si quelqu'un veut me donner un'aide je lui serati infinitement reconnessaint...SVP!!!!!
PS: Je travvaille sur Unix et on compile avec xemacs et g++
Ciao Valde
Je suis un étudiant du Polythécnique de Lausanne en génie mécanique. Je un grand problème avec mon projet sémestrale de C++, qui je n'arrive pas à completer. Je doit programmer un jeu type Asteroid et l'énoncé du projet se trouve dans le site: cowww.epfl.ch/infgmel/ dans le répertoire projet..
Moi je suis arrive jusqu'au test_base et je n'arrive pas à aller plus loin, donc si quelqu'un veut me donner un'aide je lui serati infinitement reconnessaint...SVP!!!!!
PS: Je travvaille sur Unix et on compile avec xemacs et g++
Ciao Valde
A voir également:
- Aide pour un projet en C++
- Filigrane projet - Guide
- Gant projet - Télécharger - Gestion de projets
- Musique projet x - Forum Musique / Radio / Clip
- Comment projeter une image sur un mur - Forum TV & Vidéo
- J'aimerais projeter une image sur un mur - Forum TV & Vidéo
3 réponses
Resalut,
indiques nous précisément ce qui te bloque stp on va pas repasser sur tout le programme qd même.
indiques nous précisément ce qui te bloque stp on va pas repasser sur tout le programme qd même.
....je te envoit les classes dont je t'a parlait, mais les versions meuilleur je les a à l'école et je vais le poster demain
----------------------------------------------------------------------------
#ifndef __CONFIGFILE_H__
#define __CONFIGFILE_H__ 1
#include <iterator>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
// La classe ConfigFile permet d'aller lire un fichier de configuration.
class ConfigFile
{
public:
// constructeur
ConfigFile(string Filename);
// destructeur
~ConfigFile() {}
// retourne le double associé à la clef "name"
double doubleValueOf(string name);
// retourne l'entier associé à la clef "name"
int intValueOf(string name);
// retourne la table de définition
map<string, double> getMap() const;
// surcharge externe de l'opérateur <<
friend ostream& operator<<(ostream& sortie, const ConfigFile& config)
{
sortie << "Contenu de ConfigFile :" <<endl;
//parcours toute la table de définition à l'aide d'un itérateur => cours 18
for (map<string, double>::iterator mapIt(config.getMap().begin()); mapIt!=config.getMap().end(); mapIt++)
{
sortie << "\t" <<mapIt->first <<"="<< mapIt->second<< endl;
}
return sortie;
};
//Fonction de lecture dans un fichier de configuration
void Lecture(string Filename);
private:
//déclaration des variables
string Filename;
map<string, double> Configmap;
ifstream reading;
};
#endif
----------------------------------------------------------------------------
#ifndef __PLAYER_H__
#define __PLAYER_H__ 1
#include <string>
#include <iostream>
#include "Scores.h"
using namespace std;
class Player
{
public:
// constructeur
Player(string name, Scores* scores = new Scores());
// constructeur de copie
Player(const Player& player);
// destructeur
~Player();
// surchage interne de l'opérateur d'affectation
Player& operator=(const Player & player);
// indique que le vaisseau du joueur est mort
void setAlive(bool alive);
// verifie si le vaisseau du joueur est en vie
bool isAlive();
// retourne le nom du joueur
string getName();
// retourne l'objet Scores
Scores* getScores();
// definit l'attribut scores
void setScores(Scores* s);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Player& player);
private:
//déclaration des variables
string name;
bool alive;
Scores* scores;
string etat;
};
#endif
----------------------------------------------------------------------------
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
//constructeur de la classe Player
Player::Player(string name, Scores* scores)
{
this->name=name;
this->scores= new(Scores);
this->scores = scores;
}
//constructeur de copie de la classe Player
Player::Player(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
//destructeur de la classe Player
Player::~Player()
{
delete scores;
}
//ici on fait une surcharge de l operateur =
Player& Player::operator=(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
// test si le vessaeau du jouer est mort
void Player::setAlive(bool alive)
{
this->alive=alive;
}
//assigne un nom au joueur
string Player::getName(){return name;}
// verifeie si le vasseau du jouer est en vie
bool Player::isAlive()
{
if (alive == true) {
etat = 'est vivant'; }
else { etat = 'est mort';}
return alive;
}
//retourne l'objet scores
Scores* Player::getScores(){return scores;}
//definition de l'attribut scores
void Player::setScores(Scores* s)
{ scores=s;}
// surcharge d'operateur <<
ostream& operator<<(ostream& out,const Player& player)
{ out << "Le joueur " << player.name << " " << player.etat << " avec "<< *player.scores << endl;
return out;
}
----------------------------------------------------------------------------
#ifndef __SETUP_H__
#define __SETUP_H__ 1
#include <vector>
#include <iostream>
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
class Setup
{
public:
/*
* Pourquoi utiliser un vecteur de joueurs alors que le jeu en
* possede seulement deux? Tout simplement pour faciliter
* eventuelle extension: si l'on decide soudain que l'on veut
* pouvoir jouer a 4 joueurs, il ne sera pas necessaire de
* modifier le code de gestion de joueurs puisque le vecteur est
* dynamique.
*/
//constructeur
Setup(vector<Player> players, int difficulty);
// constructeur de copie
Setup(const Setup& setup);
// destructeur
~Setup();
// surcharge de l'operateur d'affectation
Setup& operator=(const Setup& setup);
// retourne la liste des joueurs
vector<Player>& getPlayers();
// retourne le niveau de jeu actuel
int getDifficulty();
// definit le niveau de jeu actuel
void setDifficulty(int diff);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Setup& setup);
private:
//déclaration des variables
int nbrPlayer;
vector <Player> players;
int difficulty;
};
#endif
----------------------------------------------------------------------------
#include <vector>
#include <iostream>
#include "Setup.h"
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
//constructeur de la classe Setup
Setup::Setup(vector<Player>players, int difficulty)
{
int nbrplayer=2;
for(int o(0);o<nbrplayer;o++)
{
players.push_back(o);
}
this->difficulty=difficulty;
for(int i(0);i < players.size();i++)
{
this->players[i]=players[i];
};
}
//constructeur de copie de la même classe
Setup::Setup(const Setup& setup)
{
this->difficulty=setup.difficulty;
for(int j(0);j<players.size();j++)
{
this->players[j]=Setup.players[j];
};
}
//ici on surcharge l'operateur d'affectation (=)
Setup& Setup::operator=(const Setup& setup)
{
difficulty=setup.difficulty;
for(int k(0);k<players.size();k++)
{
players[k]=Setup.players[k];
};
}
//on défini le getter de la liste des joueurs
vector<Player>& Setup::getPlayers(){return players;}
//on défini le getter de la difficulte
int Setup::getDifficulty(){return difficulty;}
//on défini le set de la difficulte
void Setup::setDifficulty(int diff){difficulty=diff;}
//ici on surcharge l'operateur d'affichage (<<)
Setup ostream& Setup::operator<<(ostream& out, const Setup& setup)
{
out << "La difficulte est " << setup.difficulty << endl;
for(int l(0);l<players.size();l++)
{
out << setup.players[l] << endl;
};
return out;
}
---------------------------------------------------------------------------
Salut!
----------------------------------------------------------------------------
#ifndef __CONFIGFILE_H__
#define __CONFIGFILE_H__ 1
#include <iterator>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
// La classe ConfigFile permet d'aller lire un fichier de configuration.
class ConfigFile
{
public:
// constructeur
ConfigFile(string Filename);
// destructeur
~ConfigFile() {}
// retourne le double associé à la clef "name"
double doubleValueOf(string name);
// retourne l'entier associé à la clef "name"
int intValueOf(string name);
// retourne la table de définition
map<string, double> getMap() const;
// surcharge externe de l'opérateur <<
friend ostream& operator<<(ostream& sortie, const ConfigFile& config)
{
sortie << "Contenu de ConfigFile :" <<endl;
//parcours toute la table de définition à l'aide d'un itérateur => cours 18
for (map<string, double>::iterator mapIt(config.getMap().begin()); mapIt!=config.getMap().end(); mapIt++)
{
sortie << "\t" <<mapIt->first <<"="<< mapIt->second<< endl;
}
return sortie;
};
//Fonction de lecture dans un fichier de configuration
void Lecture(string Filename);
private:
//déclaration des variables
string Filename;
map<string, double> Configmap;
ifstream reading;
};
#endif
----------------------------------------------------------------------------
#ifndef __PLAYER_H__
#define __PLAYER_H__ 1
#include <string>
#include <iostream>
#include "Scores.h"
using namespace std;
class Player
{
public:
// constructeur
Player(string name, Scores* scores = new Scores());
// constructeur de copie
Player(const Player& player);
// destructeur
~Player();
// surchage interne de l'opérateur d'affectation
Player& operator=(const Player & player);
// indique que le vaisseau du joueur est mort
void setAlive(bool alive);
// verifie si le vaisseau du joueur est en vie
bool isAlive();
// retourne le nom du joueur
string getName();
// retourne l'objet Scores
Scores* getScores();
// definit l'attribut scores
void setScores(Scores* s);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Player& player);
private:
//déclaration des variables
string name;
bool alive;
Scores* scores;
string etat;
};
#endif
----------------------------------------------------------------------------
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
//constructeur de la classe Player
Player::Player(string name, Scores* scores)
{
this->name=name;
this->scores= new(Scores);
this->scores = scores;
}
//constructeur de copie de la classe Player
Player::Player(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
//destructeur de la classe Player
Player::~Player()
{
delete scores;
}
//ici on fait une surcharge de l operateur =
Player& Player::operator=(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
// test si le vessaeau du jouer est mort
void Player::setAlive(bool alive)
{
this->alive=alive;
}
//assigne un nom au joueur
string Player::getName(){return name;}
// verifeie si le vasseau du jouer est en vie
bool Player::isAlive()
{
if (alive == true) {
etat = 'est vivant'; }
else { etat = 'est mort';}
return alive;
}
//retourne l'objet scores
Scores* Player::getScores(){return scores;}
//definition de l'attribut scores
void Player::setScores(Scores* s)
{ scores=s;}
// surcharge d'operateur <<
ostream& operator<<(ostream& out,const Player& player)
{ out << "Le joueur " << player.name << " " << player.etat << " avec "<< *player.scores << endl;
return out;
}
----------------------------------------------------------------------------
#ifndef __SETUP_H__
#define __SETUP_H__ 1
#include <vector>
#include <iostream>
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
class Setup
{
public:
/*
* Pourquoi utiliser un vecteur de joueurs alors que le jeu en
* possede seulement deux? Tout simplement pour faciliter
* eventuelle extension: si l'on decide soudain que l'on veut
* pouvoir jouer a 4 joueurs, il ne sera pas necessaire de
* modifier le code de gestion de joueurs puisque le vecteur est
* dynamique.
*/
//constructeur
Setup(vector<Player> players, int difficulty);
// constructeur de copie
Setup(const Setup& setup);
// destructeur
~Setup();
// surcharge de l'operateur d'affectation
Setup& operator=(const Setup& setup);
// retourne la liste des joueurs
vector<Player>& getPlayers();
// retourne le niveau de jeu actuel
int getDifficulty();
// definit le niveau de jeu actuel
void setDifficulty(int diff);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Setup& setup);
private:
//déclaration des variables
int nbrPlayer;
vector <Player> players;
int difficulty;
};
#endif
----------------------------------------------------------------------------
#include <vector>
#include <iostream>
#include "Setup.h"
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
//constructeur de la classe Setup
Setup::Setup(vector<Player>players, int difficulty)
{
int nbrplayer=2;
for(int o(0);o<nbrplayer;o++)
{
players.push_back(o);
}
this->difficulty=difficulty;
for(int i(0);i < players.size();i++)
{
this->players[i]=players[i];
};
}
//constructeur de copie de la même classe
Setup::Setup(const Setup& setup)
{
this->difficulty=setup.difficulty;
for(int j(0);j<players.size();j++)
{
this->players[j]=Setup.players[j];
};
}
//ici on surcharge l'operateur d'affectation (=)
Setup& Setup::operator=(const Setup& setup)
{
difficulty=setup.difficulty;
for(int k(0);k<players.size();k++)
{
players[k]=Setup.players[k];
};
}
//on défini le getter de la liste des joueurs
vector<Player>& Setup::getPlayers(){return players;}
//on défini le getter de la difficulte
int Setup::getDifficulty(){return difficulty;}
//on défini le set de la difficulte
void Setup::setDifficulty(int diff){difficulty=diff;}
//ici on surcharge l'operateur d'affichage (<<)
Setup ostream& Setup::operator<<(ostream& out, const Setup& setup)
{
out << "La difficulte est " << setup.difficulty << endl;
for(int l(0);l<players.size();l++)
{
out << setup.players[l] << endl;
};
return out;
}
---------------------------------------------------------------------------
Salut!
ça est ce que j'ai fait et ce qui mon donnée pour faire ce projet...
si vous voulez voir le site du projet lee site c'est cowww.epfl.ch/infgmel/et pas www. etc...salut et merci!
--------------------------------------------------------------------------------
#include <vector>
#include <iostream>
#include "Setup.h"
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
//constructeur de la classe Setup
Setup::Setup(vector<Player>players, int difficulty)
{
int nbrplayer=2;
for(int o(0);o<nbrplayer;o++)
{
players.push_back(o);
}
this->difficulty=difficulty;
for(int i(0);i < players.size();i++)
{
this->players[i]=players[i];
};
}
//constructeur de copie de la même classe
Setup::Setup(const Setup& setup)
{
this->difficulty=setup.difficulty;
for(int j(0);j<players.size();j++)
{
this->players[j]=Setup.players[j];
};
}
//ici on surcharge l'operateur d'affectation (=)
Setup& Setup::operator=(const Setup& setup)
{
difficulty=setup.difficulty;
for(int k(0);k<players.size();k++)
{
players[k]=Setup.players[k];
};
}
//on défini le getter de la liste des joueurs
vector<Player>& Setup::getPlayers(){return players;}
//on défini le getter de la difficulte
int Setup::getDifficulty(){return difficulty;}
//on défini le set de la difficulte
void Setup::setDifficulty(int diff){difficulty=diff;}
//ici on surcharge l'operateur d'affichage (<<)
Setup ostream& Setup::operator<<(ostream& out, const Setup& setup)
{
out << "La difficulte est " << setup.difficulty << endl;
for(int l(0);l<players.size();l++)
{
out << setup.players[l] << endl;
};
return out;
}
--------------------------------------------------------------------------------
#include "ConfigFile.h"
#include <iterator>
//constructeur
ConfigFile::ConfigFile(string fileName)
{
//ce methode va lire dans le fichier et "construit" la Map
ifstream read;
read.open(fileName.c_str());
if (read.fail())
{ cout << "Impossible to read" << fileName << endl; }
else
{
string cle;
string inutile;
string val;
while (!read.eof())
{read >>cle>>inutile>>val;
Map[cle] = atof(val.c_str());}
}
}
//Renvoi la valeur reél associe à la clef " name"
double ConfigFile::doubleValueOf(string name)
{
return Map.find(name)->second;
}
//Renvoi la valeur entier associe à la clef " name"
int ConfigFile::intValueOf(string name)
{
return (int)Map.find(name)->second;
}
//ça sert à faire retourner la table de définition
map<string, double> ConfigFile::getMap() const
{
return Map;
}
--------------------------------------------------------------------------------
#ifndef __CONFIGFILE_H__
#define __CONFIGFILE_H__ 1
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
// La classe ConfigFile permet d'aller lire un fichier de configuration.
class ConfigFile
{
public:
// constructeur
ConfigFile(string fileName);
// destructeur
~ConfigFile() {}
// retourne le double associé à la clef "name"
double doubleValueOf(string name);
// retourne l'entier associé à la clef "name"
int intValueOf(string name);
// retourne la table de définition
map<string, double> getMap() const;
// surcharge externe de l'opérateur <<
friend ostream& operator<<(ostream& sortie, const ConfigFile& config)
{
sortie << "Contenu de ConfigFile :" <<endl;
//parcours toute la table de définition à l'aide d'un itérateur => cours 18
for (map<string, double>::iterator mapIt(config.getMap().begin());
mapIt!=config.getMap().end(); mapIt++)
{
sortie << "\t" <<mapIt->first <<"="<< mapIt->second<< endl;
}
return sortie;
}
private:
// déclaration de la map
map <string, double> Map;
//declaration de la string qui est le nom du fichier de lecture
string fileName;
};
#endif
--------------------------------------------------------------------------------
#include "GameScreen.h"
using namespace std;
// ça défini le getteur de l'hauteur
double GameScreen::getHeight()
{return height;}
//ça défini le getteur de largeur
double GameScreen:: getWidth()
{return width;}
//ça défini le constructeur
GameScreen::GameScreen(double width, double height)
{
this->width=width;
this->height=height;
}
//ça défini le constructeur de copie
GameScreen::GameScreen(const GameScreen& GameScreen)
{
height=GameScreen.height;
width=GameScreen.width;
}
//ça défoni la surcharge de =
GameScreen& GameScreen::operator=(const GameScreen& GameScreen)
{
this->height=GameScreen.height;
this->width=GameScreen.width;
return(*this);
}
//ça défini la surcharge de <<
ostream& operator<<(ostream& cout , const GameScreen& GameScreen)
{
cout << "L ecran a une hauteur de " << GameScreen.height << " pixels et une largeur de " << GameScreen.width << " pixels." << endl;
return cout;
}
--------------------------------------------------------------------------------
#ifndef __GAME_SCREEN_H__
#define __GAME_SCREEN_H__ 1
#include <iostream>
using namespace std;
class GameScreen
{
public:
// constructeur
GameScreen(double width, double height);
// constructeur de copie
GameScreen(const GameScreen& GameScreen);
// destructeur
~GameScreen() {}
// surcharge de l'opérateur d'affectation
GameScreen& operator=(const GameScreen& gameScreen);
// retourne la hauteur
double getHeight();
// retourne la largeur
double getWidth();
// surcharge externe de l'opérateur <<
friend ostream& operator<<(ostream& cout, const GameScreen& GameScreen);
private:
//décalaration des variables
double height;
double width;
};
#endif
--------------------------------------------------------------------------------
## MAKEFILE POUR LE PROJET SPACEROCK
CFLAGS = -g -Wall `pkg-config gtk+-2.0 --cflags`
CXXFLAGS = -g -Wall `pkg-config gtk+-2.0 --cflags` -I/usr/local/mysql/include/mysql
DB_LIBS = -L/usr/local/mysql/lib/mysql -lmysqlclient
CC = gcc
CXX = g++
GL_LIBS = /usr/openwin/lib/libGL.so.1 /usr/openwin/lib/libGLU.so.1
GLUT_DIR = /home/infgmel3/projet/demo
GLUT_LIBS = $(GLUT_DIR)/libglut.so -lXmu -lXext -lXi -lX11 -lm
INFGMELHOME = /home/infgmel/pub/projet
# objets de base
BASEHDRS = ConfigFile.h GameScreen.h Player.h Scores.h Setup.h
BASEOBJS = ConfigFile.o GameScreen.o Player.o Scores.o Setup.o
PARTICLEOBJS = Particle.o Foe.o Friend.o Ship.o Bullet.o Rock.o ParticleType.o
PARTICLEHDRS = Particle.h Foe.h Friend.h Ship.h Bullet.h Rock.h
GLLHDRS = gll/gllSprite.h gll/gllProcess.h gll/gllFont.h gll/gllLibrary.h gll/gllTextures.h gll/gllBMParser.h
GLLOBJS = gll/gllSprite.o gll/gllProcess.o gll/gllFont.o gll/gllLibrary.o gll/gllTextures.o gll/gllBMParser.o
## COMMANDE PAR DEFAUT: tout construire
all: test_base test_particle sprite level SpaceRock
## MAKE SPACEROCK: pour construire le programme SpaceRock
SpaceRock: gllib $(BASEOBJS) $(PARTICLEOBJS) Game.o Level.o SetupPanel.o SpaceRock.o
$(CXX) $(CXXFLAGS) $(GL_LIBS) $(GLUT_LIBS) $(DB_LIBS) $(BASEOBJS) $(PARTICLEOBJS) $(GLLOBJS) Game.o Level.o\
$(INFGMELHOME)/objs/Database.o SetupPanel.o SpaceRock.o -o SpaceRock
## NETTOYAGE
clean:
rm -f core gll/*.o
rm -f core *.o SpaceRock test_base test_particle test_sprite test_level
## MAKE BASE: pour construire le programme test_base
test_base: $(BASEOBJS) test_base.o
$(CXX) $(CXXFLAGS) $(BASEOBJS) test_base.o -o test_base
test_base.o: $(BASEHDRS) test_base.cc
## MAKE PARTICLE: pour construire le programme test_particle
## attention, ce programme ne compilera plus tel quel lorsque vous aurez implémenté gllSprite
test_particle: $(PARTICLEOBJS) test_particle.o
$(CXX) $(CXXFLAGS) $(PARTICLEOBJS) $(BASEOBJS) test_particle.o -o test_particle
test_particle.o: $(PARTICLEHDRS) ConfigFile.h test_particle.cc
## MAKE SPRITE: pour construire le programme test_sprite
sprite: gllib $(BASEOBJS) $(PARTICLEOBJS) test_sprite.o
$(CXX) $(CXXFLAGS) $(GL_LIBS) $(GLUT_LIBS) $(GLLOBJS) $(BASEOBJS) $(PARTICLEOBJS) test_sprite.o -o test_sprite
test_sprite.o: $(BASEHDRS) $(PARTICLEHDRS) $(GLLHDRS) test_sprite.cc
## MAKE LEVEL: pour construire le programme test_level
level: gllib $(BASEOBJS) $(PARTICLEOBJS) Level.o test_level.o
$(CXX) $(CXXFLAGS) $(GL_LIBS) $(GLUT_LIBS) $(BASEOBJS) $(PARTICLEOBJS) $(GLLOBJS) Level.o test_level.o -o test_level
test_level.o: $(BASEHDRS) Particle.h $(GLLHDRS) test_level.cc
## REGLES POUR GLLIB
gllib: $(GLLOBJS)
gll/gllSprite.o: gll/gllSprite.cc $(GLLHDRS)
gll/gllProcess.o: gll/gllProcess.cc $(GLLHDRS)
gll/gllFont.o: gll/gllFont.cc $(GLLHDRS)
gll/gllLibrary.o: gll/gllLibrary.cc $(GLLHDRS)
gll/gllBMParser.o: gll/gllBMParser.cc $(GLLHDRS)
gll/gllTextures.o: gll/gllTextures.cc $(GLLHDRS)
## REGLES POUR LES FICHIERS STANDARDS
Bullet.o: Bullet.cc $(PARTICLEHDRS)
ConfigFile.o: ConfigFile.cc ConfigFile.h
Game.o: Game.cc Game.h $(BASEHDRS) $(PARTICLEHDRS) $(GLLHDRS)
GameScreen.o: GameScreen.cc GameScreen.h
Foe.o: Foe.cc Foe.h Particle.h
Friend.o: Friend.cc Friend.h Particle.h Player.h
Level.o: Level.cc Level.h GameScreen.h $(PARTICLEHDRS) $(GLLHDRS)
Particle.o: Particle.cc Particle.h GameScreen.h
ParticleType.o: ParticleType.cc ParticleType.h
Rock.o: Rock.cc Rock.h Particle.h ParticleType.h Foe.h ConfigFile.h
Player.o: Player.cc Player.h
Setup.o: Player.h Setup.h Scores.h ConfigFile.h Setup.cc
Scores.o: Player.h Setup.h Scores.h Scores.cc
SetupPanel.o: SetupPanel.cc SetupPanel.h Game.h
Ship.o: Ship.cc Ship.h Particle.h Friend.h ParticleType.h ConfigFile.h
SpaceRock.o: SpaceRock.cc Game.h SetupPanel.h HighScores.h $(INFGMELHOME)/include/Database.h
--------------------------------------------------------------------------------
#include "Particule.h"
#include <cmath>
using namespace std;
//constructeur
Particule::Particule(double coordx, double coordy, double vitesse, double direction,
double taille, double angleRotation,
GameScreen* ecran)
{
this->coordx = coordx;
this->coordy = coordy;
this->vitesse = vitesse;
this->direction = direction;
this->taille = taille;
this->angleRotation = angleRotation;
this->ecran = ecran;
}
//les getteurs:
double Particule::getCoordx(){return coordx;}
double Particule::getCoordy(){return coordy;}
double Particule::getVitesse(){return vitesse;}
double Particule::getDirection(){return direction;}
double Particule::getTaille(){return taille;}
double Particule::getAngleRotation(){return angleRotation;}
GameScreen* Particule::getEcran(){return ecran;}
//setteurs:
void Particule::setCoordx(double coordx){this->coordx = coordx;}
void Particule::setCoordy(double coordy){this->coordy = coordy;}
void Particule::setVitesse(double vitesse){this->vitesse = vitesse;}
void Particule::setDirection(double direction){this->direction = direction;}
void Particule::setTaille(double taille){this->taille = taille;}
void Particule::setAngleRotation(double angleRotation){this->angleRotation = angleRotation;}
void Particule::setEcran(GameScreen* ecran){this->ecran = ecran;}
//collision!!
bool Particule::Collision(Particule& a)
{
double distance;
distance = sqrt(pow(a.coordx-this->coordx , 2)+pow(a.coordy-this->coordy , 2));
if (distance<= ((0.8)*(a.taille+this->taille)))
return true;
else
return false;
}
//step
void Particule::Step (double t)
{
double deplacex;
double deplacey;
deplacex =coordx+ vitesse*t*cos(direction);
if ((deplacex) >(*ecran).getWidth())
coordx =deplacex-(*ecran).getWidth();
else if (deplacex < 0)
coordx = deplacex + (*ecran).getHeight();
else
coordx= deplacex;
deplacey = coordy +vitesse*t*sin(direction);
if (deplacey > (*ecran).getHeight())
coordy = deplacey - (*ecran).getHeight();
else if (deplacey<0)
coordy = deplacey + (*ecran).getHeight();
else
coordy = deplacey;
}
//surcharge externe de <<
ostream& operator << (ostream& out, const Particule* particle)
{
out << (*particle).coordx << (*particle).coordy;
out << (*particle).vitesse << (*particle).direction << (*particle).taille;
out << (*particle).angleRotation << (*particle).ecran <<endl;
}
--------------------------------------------------------------------------------
#include <iostream>
#include "GameScreen.h"
using namespace std;
class Particule
{protected:
//Constructeur et distructeur
Particule(double coordx, double coordy, double vitesse, double direction,
double taille, double angleRotation,
GameScreen* ecran);
~Particule(){}
//getteurs:
double getCoordx();
double getCoordy();
double getVitesse();
double getDirection();
double getTaille();
double getAngleRotation();
GameScreen* getEcran();
//et les setteurs
void setCoordx(double coordx);
void setCoordy(double coordy);
void setVitesse(double vitesse);
void setDirection(double direction);
void setTaille(double taille);
void setAngleRotation(double angleRotation);
void setEcran(GameScreen* ecran);
//methodes particuliérs:
//collision entre deux particules
bool Collision(Particule& a);
//step:celui qui calcule la nouvelle position, angluation, ecc
virtual void Step(double t);
//display qui est virtuel
virtual ostream& display (ostream& out)const =0;
//methodes Virtuelles:isFriend et getType
virtual bool isFriend();
virtual int getType();
//fonction virtuelle qui affichera:
virtual ostream display (ostream& out);
//surcharge externe de l'operateur <<
friend ostream& operator<< (ostream& , const Particule*);
private:
//declaration des attributs
//coordonnes
double coordx;
double coordy;
//vitesse linéaire
double vitesse;
//direction de mouvement
double direction;
//rayon de la taille de la particule
double taille;
//vitesse de rotation
double angleRotation;
//pointer sur l'ecran
GameScreen* ecran;
};
--------------------------------------------------------------------------------
#include "ParticleType.h"
ParticleType::ParticleType (){
Ship = 0 ;
Bullet = 1 ;
Rock = 2 ; }
bool ParticleType::isShip (int Var)
{
if ( Var == 0 )
return true;
else
return false;
}
bool ParticleType::isBullet (int Var)
{
if (Var == 1)
return true;
else
return false;
}
bool ParticleType::isRock (int Var)
{
if (Var ==2)
return true;
else
return false;
}
// getteur
int ParticleType::getShip ()
{
return 0;
}
int ParticleType::getBullet ()
{
return 1;
}
int ParticleType::getRock ()
{
return 2;
}
--------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class ParticleType
{
public:
//constructeur
ParticleType();
// vérificateur
bool isShip (int Var);
bool isBullet(int Var);
bool isRock(int Var);
//déclaration de getteurs
int getShip ();
int getBullet();
int getRock();
protected:
// attribution d'un éntier au trois type de particule
int Ship ;
int Bullet ;
int Rock ;
};
--------------------------------------------------------------------------------
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
//constructeur de la classe Player
Player::Player(string name, Scores* scores)
{
this->name=name;
this->scores= new(Scores);
this->scores = scores;
}
//constructeur de copie de la classe Player
Player::Player(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
//destructeur de la classe Player
Player::~Player()
{
delete scores;
}
//ici on fait une surcharge de l operateur =
Player& Player::operator=(const Player& player)
{
this->name=player.name;
this->scores=player.scores;
}
// killer du player
void Player::setAlive(bool alive)
{
this->alive=alive;
}
//assigne un nom au joueur
string Player::getName(){return name;}
// verifeie si le vasseau du jouer est en vie
bool Player::isAlive()
{
return alive;
}
//retourne l'objet scores
Scores* Player::getScores(){return scores;}
//definition de l'attribut scores
void Player::setScores(Scores* s)
{ scores=s;}
// surcharge d'operateur <<
ostream& operator<<(ostream& out,const Player& player)
{ out << "Nom du joueur " << player.name << endl << player.scores << endl;
return out;
}
--------------------------------------------------------------------------------
#ifndef __PLAYER_H__
#define __PLAYER_H__ 1
#include <string>
#include <iostream>
#include "Scores.h"
using namespace std;
class Player
{
public:
// constructeur
Player(string name, Scores* scores = new Scores());
// constructeur de copie
Player(const Player& player);
// destructeur
~Player();
// surchage interne de l'opérateur d'affectation
Player& operator=(const Player & player);
// indique que le vaisseau du joueur est mort
void setAlive(bool alive);
// verifie si le vaisseau du joueur est en vie
bool isAlive();
// retourne le nom du joueur
string getName();
// retourne l'objet Scores
Scores* getScores();
// definit l'attribut scores
void setScores(Scores* s);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Player& player);
private:
//déclaration des variables
string name;
bool alive;
Scores* scores;
};
#endif
--------------------------------------------------------------------------------
#include "Scores.h"
#include <iostream>
using namespace std;
// Constructeur de la classe scores
Scores::Scores(int lastLevelReached, int score)
{
this->lastLevelReached=lastLevelReached;
this->score=score;
}
//constructeur par defaut de la classe scores
Scores::Scores(){}
//constructeur de copie tousjours de la classe scores
Scores::Scores(const Scores& scores)
{
this->lastLevelReached=scores.lastLevelReached;
this->score=scores.score;
}
//ici on surcharge l'operateur d'affectation (=)
Scores& Scores::operator=(const Scores& scores)
{
this->lastLevelReached=scores.lastLevelReached;
this->score=scores.score;
return(*this);
}
//on définit le getter du dernier niveau atteint
int Scores::getLastLevelReached(){return lastLevelReached;}
//on définit le set du niveau atteint
void Scores::setLastLevelReached(int lastLevelReached){this->lastLevelReached=lastLevelReached;}
//on définit le getter du score
int Scores::getScore(){return score;}
//on définit le set du score
void Scores::setScore(int score){this->score=score;}
//ici on surcharge l' operateur d'affichage (<<)
ostream& operator<<(ostream& out, const Scores& scores)
{
out << "Scores: " << scores.score << endl << "Dernier niveau atteint: "
<< scores.lastLevelReached << endl;
return out;
}
--------------------------------------------------------------------------------
#ifndef __SCORES_H__
//Pour verifier qu'il n'y ait qu'une inclusion du fichier.
#define __SCORES_H__ 1
#include <iostream>
using namespace std;
/*
* Cette classe contient toutes les informations sur les scores
* d'un joueur:
* - son niveau maximum atteint a cette partie;
* - son score.
*/
class Scores
{
public:
// constructeur
Scores(int lastLevelReached, int score);
//constructeur par defaut
Scores();
// constructeur de copie
Scores(const Scores& scores);
// destructeur
~Scores();
// operateur d'affectation.
Scores& operator=(const Scores& scores);
// retourne le niveau maximal atteint
int getLastLevelReached();
// met à jour le dernier niveau atteint
void setLastLevelReached(int lastLevelReached);
// retourne le score
int getScore();
// met à jour le score
void setScore(int score);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Scores& scores);
private:
//déclaration des variables
int lastLevelReached;
int score;
};
#endif
--------------------------------------------------------------------------------
#include <vector>
#include <iostream>
#include "Setup.h"
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
//constructeur de la classe Setup
Setup::Setup(vector<Player>players, int difficulty)
{
this-> players=players;
this-> difficulty=difficulty;
}
//constructeur de copie de la même classe
Setup::Setup(const Setup& setup)
{
this->difficulty=setup.difficulty;
for(int j(0);j<players.size();j++)
{
this->players[j]=Setup.players[j];
};
}
//ici on surcharge l'operateur d'affectation (=)
Setup& Setup::operator=(const Setup& setup)
{
difficulty=setup.difficulty;
for(int k(0);k<players.size();k++)
{
players[k]=Setup.players[k];
};
}
//on défini le getter de la liste des joueurs
vector<Player>& Setup::getPlayers(){return players;}
//on défini le getter de la difficulte
int Setup::getDifficulty(){return difficulty;}
//on défini le set de la difficulte
void Setup::setDifficulty(int diff){difficulty=diff;}
//ici on surcharge l'operateur d'affichage (<<)
Setup ostream& Setup::operator<<(ostream& out, const Setup& setup)
{
out << "La difficulte est " << setup.difficulty << endl;
for(int l(0);l<players.size();l++)
{
out << setup.players[l] << endl;
};
return out;
}
--------------------------------------------------------------------------------
#ifndef __SETUP_H__
#define __SETUP_H__ 1
#include <vector>
#include <iostream>
#include "Player.h"
#include "ConfigFile.h"
using namespace std;
class Setup
{
public:
/*
* Pourquoi utiliser un vecteur de joueurs alors que le jeu en
* possede seulement deux? Tout simplement pour faciliter
* eventuelle extension: si l'on decide soudain que l'on veut
* pouvoir jouer a 4 joueurs, il ne sera pas necessaire de
* modifier le code de gestion de joueurs puisque le vecteur est
* dynamique.
*/
//constructeur
Setup(vector<Player> players, int difficulty);
// constructeur de copie
Setup(const Setup& setup);
// destructeur
~Setup();
// surcharge de l'operateur d'affectation
Setup& operator=(const Setup& setup);
// retourne la liste des joueurs
vector<Player>& getPlayers();
// retourne le niveau de jeu actuel
int getDifficulty();
// definit le niveau de jeu actuel
void setDifficulty(int diff);
// surcharge externe de <<
friend ostream& operator<<(ostream& out, const Setup& setup);
private:
//déclaration des variables
int nbrPlayer;
vector <Player> players;
int difficulty;
};
#endif
--------------------------------------------------------------------------------
#include "Scores.h"
#include "Setup.h"
#include "Player.h"
#include "ConfigFile.h"
#include "GameScreen.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
cout << "***Testing GameScreen******************************"<<endl;
GameScreen* gs = new GameScreen(1280,768);
cout << (*gs) << endl;
GameScreen gs_2 = *gs;
cout << "Width= "<<gs_2.getWidth()<<endl;
cout << "height= "<<gs_2.getHeight()<<endl;
cout << gs_2 <<endl;
cout << "***End Testing GameScreen**************************\n\n"<<endl;
cout << "***Testing Scores******************************"<<endl;
Scores score(3,500);
cout << score<<endl;
score.setLastLevelReached(10);
score.setScore(1000);
cout << "score.last level:=" << score.getLastLevelReached()<<endl;
cout << "score.score:=" << score.getScore()<<endl;
cout << score<<endl;
Scores score_2=score;
cout << "Score #2= " << score_2<<endl;
cout << "***End Testing Scores**************************\n\n"<<endl;
cout << "***Testing Player******************************"<<endl;
Scores* score_3= new Scores(score_2);
Player player("Vincent",score_3);
cout << player<<endl;
Player player_1=player;
cout << "Player #1" << player_1 <<endl;
Player player_2("Basile",player.getScores());
player_2.setAlive(false);
cout << "Player #2 " <<"state:=" << player_2.isAlive()<<endl;
cout << "Player #2 " <<"name:=" <<player_2.getName()<<endl;
player_2.setScores(new Scores(5,200));
cout << "Player #2 " <<"score:="<<*player_2.getScores()<<endl;
cout << "Player #2 " <<player_2<<endl;
cout << "***End Testing Player**************************\n\n"<<endl;
cout << "***Testing Setup*******************************"<<endl;
vector<Player> joueurs;
joueurs.push_back(player);
joueurs.push_back(player_2);
Setup setup(joueurs,0);
cout << setup<<endl;
Setup setup_2=setup;
setup_2.setDifficulty(20);
cout <<"Setup #2 " <<setup_2<<endl;
setup.getPlayers()[0].getScores()->setLastLevelReached(8);
cout << "Level =" << setup.getPlayers()[0].getScores()->getLastLevelReached()<<endl;
setup.getPlayers()[0].getScores()->setScore(101);
cout << "Score =" << setup.getPlayers()[0].getScores()->getScore()<<endl;
setup.getPlayers()[0].setAlive(true);
cout << "isAlive =" <<setup.getPlayers()[0].isAlive()<<endl;
cout<<setup<<endl;
cout << "***End Testing Setup***************************\n\n"<<endl;
cout << "***Testing ConfigFile****************************"<<endl;
ConfigFile cf("Rock.conf");
cout << cf;
cout << "Value of damage:= "<<cf.doubleValueOf("damage")<<endl;
cout << "***End Testing ConfigFile************************\n\n"<<endl;
}
--------------------------------------------------------------------------------
#include "gll/gllLibrary.h"
#include <iostream>
#include "Setup.h"
#include "Level.h"
#include "GameScreen.h"
#include "Rock.h"
#include "Ship.h"
#include "Bullet.h"
using namespace std;
GameScreen gs(640, 480);
Setup *setup;
Level *level;
// Boucle principale
void test_levelIdleFunc()
{
// A FAIRE : implémenter le comportement de ce processus
double dt = gllTimer(TIMER_GETELAPSEDTIME);
if (dt == 0.0)
{
gllout << gllsetup(16,11,640,480);
gllTimer(TIMER_RESET);
gllTimer(TIMER_START);
}
level->step(dt);
Level::LEVEL_OVER state;
if (state = level->isOver())
{
if (state == Level::ALL_SHIPS_DEAD)
{
delete level;
delete setup;
exit(0);
}
else{
gllTimer(TIMER_STOP);
level = new Level(level);
}
}
// Demande à glut de redessiner la fenêtre graphique
glutPostRedisplay();
}
// Fonction d'affichage
void test_levelDisplayFunc()
{
// Efface le contenu de la fenêtre
glClear(GL_COLOR_BUFFER_BIT);
// A FAIRE : Appeler les fonctions d'affichage
level->show();
// Met à jour le contenu de la fenêtre
glutSwapBuffers();
}
// FONCTION MAIN
int main(int argc, char *argv[])
{
// Processus gllib
gllProcessInformation *pi = new gllProcessInformation();
pi->name = "test_level_process";
pi->realTime = true;
pi->idleFunc = test_levelIdleFunc;
pi->displayFunc = test_levelDisplayFunc;
gllRegisterProcess(pi);
vector<Player> players;
players.push_back(Player("jean-claude"));
players.push_back(Player("popeye"));
setup = new Setup(players, 1);
level = new Level(setup, &gs);
// Démarre gllib
// Le processus donnée en dernier argument sera activé
// Les autres arguments servent à donner un nom à la fenêtre graphique
// ainsi que ses dimensions
gllMainLoop(argc, argv, argv[0], 640, 480, "test_level_process");
return 0;
}
--------------------------------------------------------------------------------
#include "Particle.h"
#include "Foe.h"
#include "Friend.h"
#include "Ship.h"
#include "Bullet.h"
#include "Rock.h"
#include "ConfigFile.h"
#include <vector>
#include <iostream>
using namespace std;
//le temps
const double dt=0.5;
int main(int argc, char *argv[])
{
Player* p1 = new Player("Vincent",new Scores(5,100));
Player* p2 = new Player("Basile",new Scores());
cout << "***Testing GameScreen******************************"<<endl;
GameScreen* gs = new GameScreen(1280,768);
cout << (*gs) << endl;
cout << "***End Testing GameScreen**************************\n\n"<<endl;
//contains the particles
vector<Particle *> particles;
cout << "***Testing Ship**********************************"<<endl;
Ship* s1= new Ship(gs,p1);
particles.push_back(s1);
cout << s1 <<endl;
Ship* s2= new Ship(gs,p2);
particles.push_back(s2);
cout << s2 <<endl;
cout << "***End Testing Ship******************************\n\n"<<endl;
cout << "***Testing Bullet**********************************"<<endl;
Bullet* b1= new Bullet(s1,gs);
particles.push_back(b1);
cout << b1 <<endl;
Bullet* b2= new Bullet(s2,gs);
particles.push_back(b2);
cout << b2 <<endl;
cout << "***End Testing Bullet******************************\n\n"<<endl;
cout << "***Testing Rock************************************"<<endl;
// le premier paramètre de Rock est le niveau de difficulté,
// qui est utilisé pour calculer leur vitesse
Rock* r1= new Rock(3,gs);
particles.push_back(r1);
cout << r1 <<endl;
cout << "***End Testing Rock******************************\n\n"<<endl;
cout << "***Testing virtual method step*******************"<<endl;
cout << "Timestamp= "<<dt << endl;
for (int i=0;i<particles.size();i++)
{
particles[i]->step(dt);
if (particles[i]->isFriend())
cout<<"Allie (type "<<particles[i]->getType()<<")=>" ;
else
cout<<"Ennemie (type "<<particles[i]->getType()<<")=>" ;
cout << particles[i] << endl;
}
//fait avancer seulement la particule 0
for (int i=0;i<500;i++)
{
particles[0]->step(dt);
}
cout << particles[0] << endl;
cout << "***End Testing step******************************\n\n"<<endl;
cout << "***Testing method colision***********************"<<endl;
for (int i=0;i<particles.size()-1;i++)
{
if (particles[i]->collision(*particles[i+1]))
cout << "Particles "<<i<< " en collision avec particles "<<i+1<<endl;
if (particles[i]->collision(*particles[i]))
cout << "Particles "<<i<< " en collision avec elle meme "<<endl;
}
cout << "***End Testing collision******************************\n\n"<<endl;
}
--------------------------------------------------------------------------------
#include "gll/gllLibrary.h"
#include <iostream>
#include "GameScreen.h"
#include "Rock.h"
#include "Ship.h"
#include "Bullet.h"
using namespace std;
gllSprite sprite(10.0, -1);
double x_pos = 0.0;
GameScreen gs(320, 240);
Rock rock(0, &gs);
Scores scores;
Player player("a_player",&scores);
Ship ship(&gs, &player);
Bullet bullet(&ship, &gs);
// Boucle principale
void test_spriteIdleFunc()
{
// A FAIRE : implémenter le comportement de ce processus
double dt = gllTimer(TIMER_GETELAPSEDTIME);
x_pos += 40.0 * dt;
while (x_pos > 320.0)
x_pos -= 320.0;
sprite.translate(x_pos, 120.0);
rock.step(dt);
ship.step(dt);
bullet.step(dt);
// Demande à glut de redessiner la fenêtre graphique
glutPostRedisplay();
}
// Fonction d'affichage
void test_spriteDisplayFunc()
{
// Efface le contenu de la fenêtre
glClear(GL_COLOR_BUFFER_BIT);
// A FAIRE : Appeler les fonctions d'affichage
glColor4f(0.1,0.3,0.2,0.7);
gllDrawRect(0,20,320,200,-1);
sprite.blit();
rock.blit();
ship.blit();
bullet.blit();
// Met à jour le contenu de la fenêtre
glutSwapBuffers();
}
// FONCTION MAIN
int main(int argc, char *argv[])
{
// Processus gllib
gllProcessInformation *pi = new gllProcessInformation();
pi->name = "test_sprite_process";
pi->realTime = true;
pi->idleFunc = test_spriteIdleFunc;
pi->displayFunc = test_spriteDisplayFunc;
gllRegisterProcess(pi);
sprite.color(1.0, 0.0, 0.0, 0.6);
ship.x = 160;
ship.y= 120;
ship.direction = PI/2.0;
bullet.x = 160;
bullet.y = 110;
bullet.direction = PI/2.0;
gllTimer(TIMER_START);
// Démarre gllib
// Le processus donnée en dernier argument sera activé
// Les autres arguments servent à donner un nom à la fenêtre graphique
// ainsi que ses dimensions
gllMainLoop(argc, argv, argv[0], 320, 240, "test_sprite_process");
return 0;
}
--------------------------------------------------------------------------------
/*---------------------------------------------------------------------*\
| GLLIB : FONCTIONS GRAPHIQUES / ENTREES / TEMPS REEL |
| |
| Fichier: gllBMParser.bmp |
\*---------------------------------------------------------------------*/
/*
BMParser.cpp
Copyright (c) 2003 Thibault Genessay
See the header 'gllBMParser.h' for informations
*/
#ifdef WIN32
#include "windows.h"
#endif
#include <GL/gl.h>
#include <GL/glut.h>
#include "stdio.h"
#include "math.h"
#include <string.h>
#include "gllBMParser.h"
BMParser::BMParser(const char* bitmap) {
iErrors = 0;
strcpy(filename,bitmap);
pBitmap = NULL;
file = NULL;
if (strcmp(bitmap, "") == 0)
{
printf("BMP loader error : no file name specified\n");
iErrors++;
}else
if ((file = fopen(bitmap, "rb"))==NULL)
{
printf("BMP loader error : could not open file\n");
iErrors++;
}
sz = 0;
}
BMParser::~BMParser() {
if (file != NULL)
fclose(file);
}
void BMParser::Read(void* lpBuf, UINT nCount, bool inverse) {
if (fread(lpBuf, nCount, 1, file) != 1)
error("unexpected end of file");
#ifndef WIN32
if (inverse)
{
// inverse data for non x86 processors
char* begin = (char*)lpBuf, *end = (char*)lpBuf+nCount-1;
while (begin < end)
{
char tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--;
}
}
#endif
sz+= nCount;
}
Bitmap* BMParser::Parse()
{
try {
// printf("reading header\n");
if (iErrors)
error("file is not open");
pBitmap = new Bitmap;
Read(pBitmap->sIdentifier, 2);
Read(&pBitmap->dwFileSize, sizeof(DWORD));
Read(&pBitmap->dwReserved, sizeof(DWORD));
Read(&pBitmap->dwDataOffset, sizeof(DWORD));
Read(&pBitmap->dwHeaderSize, sizeof(DWORD));
Read(&pBitmap->dwWidth, sizeof(DWORD));
Read(&pBitmap->dwHeight, sizeof(DWORD));
Read(&pBitmap->wPlanes, sizeof(WORD));
// printf("# of planes : %d\n", pBitmap->wPlanes);
if (pBitmap->wPlanes != 1)
error("only one plane supported, multiple encountered");
Read(&pBitmap->wBpp, sizeof(WORD));
Read(&pBitmap->dwCompression, sizeof(DWORD));
Read(&pBitmap->dwDataSize, sizeof(DWORD));
pBitmap->dwPitch = (pBitmap->wBpp / 8) * pBitmap->dwWidth;
if (pBitmap->dwPitch%4 != 0)
pBitmap->dwPitch += 4-pBitmap->dwPitch%4;
if (pBitmap->dwDataSize == 0) // if size is not present, compute it
pBitmap->dwDataSize = pBitmap->dwPitch * pBitmap->dwHeight;
else
if (pBitmap->dwDataSize != pBitmap->dwPitch * pBitmap->dwHeight)
error("scan-line width * height != bitmap size !! <- this is an unexpected error, probably due to an incorrect file format");
Read(&pBitmap->dwHRes, sizeof(DWORD));
Read(&pBitmap->dwVRes, sizeof(DWORD));
Read(&pBitmap->dwColors, sizeof(DWORD));
Read(&pBitmap->dwImportantColors, sizeof(DWORD));
// printf("reading palette\n");
ReadPalette();
// printf("reading data\n");
ReadData();
return pBitmap;
} catch (BMError* e) {
printf("BMP parser error : %s\n", e->msg);
if (pBitmap)
delete pBitmap;
return NULL;
}
}
void BMParser::ReadPalette()
{
if (pBitmap->wBpp == BPP_MONOCHROME)
error("unsupported format : monochrome BMP");
if (pBitmap->wBpp == BPP_16COLORS)
error("unsupported format : 4 bpp BMP");
if (pBitmap->wBpp == BPP_256COLORS)
{
/* pBitmap->pPalette = new DWORD[256];
Read(pBitmap->pPalette, pBitmap->dwColors*sizeof(DWORD));*/
error("unsupported format : 8 bpp BMP");
}
if (pBitmap->wBpp == BPP_HIGHCOLOR)
error("unsupported format : 16 bpp BMP");
// 24 bpp and 32 bpp bitmaps do not contain any palette entriy if dwCompression is BI_RGB
// which is always the case here since other compression formats are not supported
}
void BMParser::ReadData()
{
if (pBitmap->dwCompression != BI_RGB)
{
char buf[64];
strcpy(buf, "unsupported compressed format : ");
if (pBitmap->dwCompression == BI_RLE4)
strcat(buf, "BI_RLE4");
if (pBitmap->dwCompression == BI_RLE8)
strcat(buf, "BI_RLE8");
if (pBitmap->dwCompression == BI_BITFIELDS)
strcat(buf, "BI_BITFILEDS");
error(buf);
}
pBitmap->pData = new unsigned char[pBitmap->dwDataSize];
// bmp files are stored bottom-up, so we need to invert the scan-lines
// i.e. the first line in the file is the bottom line of the image
for (DWORD i=0;i<pBitmap->dwHeight;i++)
{
fseek(file, pBitmap->dwDataOffset+(pBitmap->dwHeight-i-1)*pBitmap->dwPitch, SEEK_SET);
Read(&pBitmap->pData[i*pBitmap->dwPitch], pBitmap->dwPitch, false);
}
if (pBitmap->wBpp == BPP_TRUECOLOR)
{ // in this format, a line is a sequence of triplets (b,g,r), so we invert them to get (r,g,b)
for (DWORD i=0;i<pBitmap->dwDataSize;i+=3)
{
char tmp = pBitmap->pData[i];
pBitmap->pData[i] = pBitmap->pData[i+2];
pBitmap->pData[i+2] = tmp;
}
}
if (pBitmap->wBpp == BPP_32)
{ // in this format, a line is a sequence of triplets (b,g,r,a), so we invert them to get (r,g,b,a)
for (DWORD i=0;i<pBitmap->dwDataSize;i+=4)
{
char tmp = pBitmap->pData[i];
pBitmap->pData[i] = pBitmap->pData[i+2];
pBitmap->pData[i+2] = tmp;
}
}
}
bool BMParser::Failed(char *reason)
{
if (reason != NULL)
{
if (iErrors)
strcpy(reason, lastError);
else
strcpy(reason, "No error");
}
return iErrors == 0;
}
bool Bitmap::ColorKey(unsigned char key_r, unsigned char key_g, unsigned char key_b)
{
// Make a few checks first
if (pData == NULL)
{
printf("ColorKey() failed : image is empty !\n");
return false;
}
if (wBpp != BPP_TRUECOLOR)
{
printf("ColorKey() failed : keying is only available for 24 bpp images\n");
return false;
}
// Kepp the old pitch value, we'll need it to index the old data
DWORD oldPitch = dwPitch;
// Set new file format (24->32bpp)
wBpp = BPP_32;
// Recompute the image pitch and size
dwPitch = 4*dwWidth;
dwDataSize = dwPitch * dwHeight;
// Allocate new memory
unsigned char *newData = new unsigned char[dwDataSize];
// The key to look for
unsigned int key = (key_r<<16) + (key_g<<8) + key_b;
// Loop through all the pixels
for (DWORD line=0;line<dwHeight;line++)
{
for (DWORD c=0;c<dwWidth;c++)
{
unsigned int ir,ig,ib;
// The color of the current pixel
ir = pData[line*oldPitch+3*c];
ig = pData[line*oldPitch+3*c+1];
ib = pData[line*oldPitch+3*c+2];
// Compare it with the key
bool isKey = ((ir<<16) + (ig<<8) + ib) == key;
int offset = line*dwPitch + 4*c;
// Fill in new values. Set to black all transparent pixels
newData[ offset ] = isKey ? 0 : ir;
newData[offset + 1] = isKey ? 0 : ig;
newData[offset + 2] = isKey ? 0 : ib;
newData[offset + 3] = isKey ? 0 : 0xFF;
}
}
// Update the pData pointer
delete[] pData;
pData = newData;
return true;
}
inline void Bitmap::ColorAt(unsigned int x, unsigned int y, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a)
{
int offset = y*dwPitch+(wBpp/8)*x;
*r = pData[offset];
*g = pData[offset+1];
*b = pData[offset+2];
if (wBpp == 32)
*a = pData[offset+3];
}
inline void Bitmap::ColorAt(unsigned int x, unsigned int y, unsigned char rgba[])
{
int offset = y*dwPitch+(wBpp/8)*x;
for (int i=0;i<wBpp/8;i++)
rgba[i] = pData[offset+i];
}
void Bitmap::Filter(int filter[3][3])
{
unsigned char* newData = new unsigned char[dwDataSize];
for (DWORD l=0;l<dwHeight;l++)
{
for (DWORD c=0;c<dwWidth;c++)
{
int rgba_dest[4];
unsigned char rgba_src[4];
if (c>0&&c<dwWidth-1&&l>0&&l<dwHeight-1)
{
for (int x=-1;x<=1;x++)
{
for (int y=-1;y<=1;y++)
{
int factor = filter[x+1][y+1];
ColorAt(c+x,l+y,rgba_src);
for (int i=0;i<wBpp/8;i++)
{
rgba_dest[i] += factor*rgba_src[i];
}
}
}
for (int i=0;i<wBpp/8;i++)
{
rgba_dest[i] /= 9;
if (rgba_dest[i]<0)
rgba_src[i] = 0;
else if (rgba_dest[i]>255)
rgba_src[i] = 255;
else rgba_src[i] = rgba_dest[i];
}
memcpy(&newData[l*dwPitch+(wBpp/8)*c], rgba_src, wBpp/8*sizeof(unsigned char));
}else{
memcpy(&newData[l*dwPitch+(wBpp/8)*c], &pData[l*dwPitch+(wBpp/8)*c], wBpp/8*sizeof(unsigned char));
}
}
}
delete[] pData;
pData = newData;
}
void Bitmap::Smooth()
{
int filter[3][3] = {{1,1,1},{1,1,1},{1,1,1}};
Filter(filter);
}
--------------------------------------------------------------------------------
/*---------------------------------------------------------------------*\
| GLLIB : FONCTIONS GRAPHIQUES / ENTREES / TEMPS REEL |
| |
| Fichier: gllBMParser.h |
| Description: |
| Voir ci-dessous (en anglais) |
\*---------------------------------------------------------------------*/
/*
BMParser.h
Copyright (c) 2003 Thibault Genessay
Defines the BMParser class which allows to load bitmaps for easy use with OpenGL
It supports both Unix/Linux and Win32 platforms
It only supports a few formats because I don't have enough time to complete it
Feel free to add the lacking functionalities
Supported BMP formats:
True Color (24 bpp, RGB)
True Color with transparency (32 bpp, RGBA)
Unsupported formats:
monochrome BMP (1 bpp)
16 color BMP (4 bpp)
256 color BMP (8 bpp)
65536 color BMP (16 bpp)
and any compressed format
Usage:
Create a BMParser instance with the filename as the constructor's parameter
Call BMParser::Parse()
- if the call succeeds, it returns a Bitmap structure. The bitmap data
is stored in the pData field of this structure
- if any kind of error occured, it returns NULL
Notes:
- it is your responsibility to delete the Bitmap structure when
you don't need it anymore
- the constructor call cannot fail, hence if the file was not found, you
won't be notified until you call Parse() or Failed()
*/
#ifndef __BMPARSER_H
#define __BMPARSER_H
typedef unsigned long DWORD;
typedef unsigned short WORD;
#define ID_WINDOWS "BM"
#define ID_OS2_ARRAY "BA"
#define ID_OS2_COLORICON "CI"
#define ID_OS2_COLORPOINTER "CP"
#define ID_OS2_ICON "IC"
#define ID_OS2_POINTER "PT"
#define BPP_MONOCHROME 1
#define BPP_16COLORS 4
#define BPP_256COLORS 8
#define BPP_HIGHCOLOR 16
#define BPP_TRUECOLOR 24
#define BPP_32 32
#ifndef WIN32 // already defined in windows GDI
#define BI_RGB 0 // no compression
#define BI_RLE8 1 // 8-bit RLE
#define BI_RLE4 2 // 4-bit RLE
#define BI_BITFIELDS 3 // rarely used format
#define UINT unsigned int // Windows doesn't like unsigned ints, but loves UINTs
#endif //WIN32
// Represents a BMP file
struct Bitmap
{
char sIdentifier[2]; // a member of ID_XXX
DWORD dwFileSize; // file size in bytes
DWORD dwReserved; // reserved for later use
DWORD dwDataOffset; // offset to the data
DWORD dwHeaderSize; // may be 28h for windows, OCh for OS/2 1.x and F0h for OS/2 2.x
DWORD dwWidth; // width of the bitmap in pixels
DWORD dwHeight; // height
WORD wPlanes; // 1
WORD wBpp; // a member of BPP_XXX
DWORD dwCompression; // a member of BI_XXX
DWORD dwDataSize; // 32-bit aligned size of the data
DWORD dwHRes, dwVRes; // resolutions in pixel/meter
DWORD dwColors; // # of colors used in the bitmap
DWORD dwImportantColors;// # of important colors
DWORD *pPalette; // palette: for each entry, 4 bytes R,G,B,X (X is a filler set to 0) if appliable (1,4,and 8 bpp; no palette for 16, 24 and 32 bpp)
unsigned char *pData; // actual bitmap data
DWORD dwPitch; // actual scan-line width (32-bit aligned value of dwWidth)
Bitmap() {
pData = NULL;
pPalette = NULL;
}
~Bitmap() {
if (pData)
delete[] pData;
if (pPalette)
delete[] pPalette;
}
inline void ColorAt(unsigned int x, unsigned int y, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a=NULL);
inline void ColorAt(unsigned int x, unsigned int y, unsigned char rgba[]);
bool ColorKey(unsigned char key_r, unsigned char key_g, unsigned char key_b);
void Filter(int filter[3][3]);
void Smooth();
};
// The parser itself
class BMParser
{
protected:
int iErrors;
struct BMError {
BMError(const char* _msg) {
strcpy(msg, _msg);
}
char msg[256];
};
void error(const char* msg) {
strcpy(lastError, msg);
iErrors++;
throw new BMError(msg);
}
int sz;
char filename[256];
FILE* file;
Bitmap* pBitmap;
void Read(void* lpBuf, UINT nCount, bool inverse = true);
void ReadPalette();
void ReadData();
char lastError[128];
public:
BMParser(const char* bitmap);
~BMParser();
Bitmap* Parse();
Bitmap* GetBitmap() { return pBitmap; };
bool Failed(char *reason);
};
#endif
--------------------------------------------------------------------------------
#include "gllFont.h"
gllFont gllout;
const int gllFont::bmpLines = 4;
const int gllFont::bmpColumns = 26;
gllFont::gllFont()
{
active = false;
for (int i=0;i<4;i++) color[i]=1.0f;
}
gllFont::CharPos gllFont::getCharPos(char ch)
{
int l,c;
if (ch >= 'a' && ch <= 'z')
{
l=0;
c=ch-'a';
}else if (ch >= 'A' && ch <= 'Z')
{
l=1;
c=ch-'A';
}else if (ch >= '0' && ch <= '9')
{
l=2;
c=ch-'0';
}else{
l=2;
switch (ch)
{
case 'à': c=10; break;
case 'â': c=11; break;
case '.': c=12; break;
case 'é': c=13; break;
case 'è': c=14; break;
case 'ê': c=15; break;
case 'ë': c=16; break;
case 'î': c=17; break;
case 'ï': c=18; break;
case 'ô': c=19; break;
case ',': c=20; break;
case 'ù': c=21; break;
case 'û': c=22; break;
case 'ü': c=23; break;
case '!': c=24; break;
case '?': c=25; break;
default:
{
l=3;
switch (ch) {
case '+': c=0; break;
case '-': c=1; break;
case '_': c=2; break;
case '=': c=3; break;
case '\'': c=4; break;
case '\"': c=5; break;
case ';': c=6; break;
case '^': c=7; break;
case '~': c=8; break;
case '*': c=9; break;
case 'ç': c=10; break;
case '%': c=11; break;
case '&': c=12; break;
case '/': c=13; break;
case '\\': c=14; break;
case '<': c=15; break;
case '>': c=16; break;
case '(': c=17; break;
case ')': c=18; break;
case '[': c=19; break;
case ']': c=20; break;
case '{': c=21; break;
case '}': c=22; break;
case '@': c=23; break;
case '#': c=24; break;
case ':': c=25; break;
}
}
}
}
return CharPos(l,c);
}
const float gllFont::TexCoords::tc_delta = 0.003f;
gllFont::TexCoords gllFont::getTexCoords(CharPos pos)
{
return TexCoords((float)pos.column/(float)bmpColumns,
(float)pos.line/(float)bmpLines,
(float)(pos.column+1)/(float)bmpColumns,
(float)(pos.line+1)/(float)bmpLines);
}
gllFont& gllFont::operator<<(FormatToken& token)
{
token.execute(*this);
return (*this);
}
#ifndef WIN32
gllFont& gllFont::operator<<(gllcolor token)
{
token.execute(*this);
return (*this);
}
gllFont& gllFont::operator<<(gllalign token)
{
token.execute(*this);
return (*this);
}
gllFont& gllFont::operator<<(gllgoto token)
{
token.execute(*this);
return (*this);
}
gllFont& gllFont::operator<<(gllsetup token)
{
token.execute(*this);
return (*this);
}
gllFont& gllFont::operator<<(gllskipl token)
{
token.execute(*this);
return (*this);
}
#endif
gllFont& gllFont::operator<<(const char* text)
{
int l = strlen(text);
// glBegin(GL_QUADS);
glColor4fv(color);
for (int i=0;i<l;i++)
{
if (text[i] == ' ') {
if (++column > maxColumns)
{
line++;
column = 0;
}
continue;
}
glPushMatrix();
glTranslatef((float)(column*columnSize)+hcs, (float)(screenHeight-line*lineSize)-hls,0.0f);
if (align == gllRIGHT)
glTranslatef((float)(screenWidth-l*columnSize),0.0f,0.0f);
else if (align == gllMIDDLE)
glTranslatef((float)(screenWidth-l*columnSize)/2.0f,0.0f,0.0f);
glBegin(GL_POLYGON);
// glRotatef(75,0,0,1);
gllFont::TexCoords tc = getTexCoords(getCharPos(text[i]));
glTexCoord2f(tc.u_min,tc.v_min);
glVertex2f(-hcs, hls);
glTexCoord2f(tc.u_max,tc.v_min);
glVertex2f(hcs,hls);
glTexCoord2f(tc.u_max,tc.v_max);
glVertex2f(hcs,-hls);
glTexCoord2f(tc.u_min,tc.v_max);
glVertex2f(-hcs,-hls);
if (++column > maxColumns)
{
line++;
column = 0;
}
glEnd();
glPopMatrix();
}
// glEnd();
return (*this);
}
gllFont& gllFont::operator<<(const string& str)
{
return this->operator<<(str.c_str());
}
gllFont& gllFont::operator<<(char c)
{
char buf[4];
sprintf(buf, "%c", c);
return this->operator <<(buf);
}
gllFont& gllFont::operator<<(int i)
{
char buf[32];
sprintf(buf, "%d", i);
return this->operator <<(buf);
}
gllFont& gllFont::operator<<(double d)
{
char buf[32];
sprintf(buf, "%f", d);
return this->operator <<(buf);
}
_gllendl gllendl;
void _gllendl::execute(gllFont& font)
{
font.line++;
font.column = 0;
}
_glltab glltab;
void _glltab::execute(gllFont& font)
{
font.column = (font.column/4)*5;
}
void gllskipl::execute(gllFont& font)
{
if (!noCR)
font.column = 0;
font.line += number;
}
void gllgoto::execute(gllFont& font)
{
font.line = l;
font.column = c;
}
void gllsetup::execute(gllFont& font)
{
font.lineSize = sl;
font.columnSize = sc;
font.hls = (float)font.lineSize/2.0f;
font.hcs = (float)font.columnSize/2.0f;
font.maxLines = h / sl;
font.screenHeight = h;
font.maxColumns = w / sc;
font.screenWidth = w;
font.line = 0;
font.column = 0;
}
_gllstart gllstart;
void _gllstart::execute(gllFont& font)
{
font.active = true;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureNames[TEX_FONT]);
font << gllcolor(1,1,1,1);
font << gllgoto(0,0);
font << gllalign(gllLEFT);
}
_gllend gllend;
void _gllend::execute(gllFont& font)
{
glDisable(GL_TEXTURE_2D);
font.active = false;
}
void gllcolor::execute(gllFont& font)
{
memcpy(font.color, col, 4*sizeof(float));
}
void gllalign::execute(gllFont& font)
{
font.align = type;
font.column = 0;
}
--------------------------------------------------------------------------------
/*---------------------------------------------------------------------*\
| GLLIB : FONCTIONS GRAPHIQUES / ENTREES / TEMPS REEL |
| |
| Fichier: gllFont.h |
| Description: |
\*---------------------------------------------------------------------*/
#ifndef __GLL_FONT_H__
#define __GLL_FONT_H__
#include "gllLibrary.h"
using namespace std;
class gllFont;
extern gllFont gllout;
struct FormatToken {
FormatToken() {}
virtual void execute(gllFont& font) = 0;
};
enum gllalign_type {
gllLEFT,
gllMIDDLE,
gllRIGHT
};
class gllFont
{
static const int bmpLines;
static const int bmpColumns;
struct CharPos {
CharPos(int l, int c) : line(l), column(c) {}
int line, column;
};
struct TexCoords {
static const float tc_delta;
TexCoords(float umin, float vmin, float umax, float vmax) :
u_min(umin+tc_delta), v_min(vmin+tc_delta), u_max(umax-tc_delta),v_max(vmax-tc_delta) {}
float u_min, v_min, u_max, v_max;
};
int line, column, maxLines, maxColumns, lineSize, columnSize, screenHeight, screenWidth;
float hls, hcs;
bool active;
float color[4];
gllalign_type align;
public:
gllFont();
int getLine() { return line; }
int getColumn() { return column; }
int getMaxLines() { return maxLines; }
int getMaxColums() { return maxColumns; }
public:
friend struct _gllendl;
friend struct _glltab;
friend struct gllgoto;
friend struct gllsetup;
friend struct gllskipl;
friend struct _gllstart;
friend struct _gllend;
friend struct gllcolor;
friend struct gllalign;
// void print(const char* text, ...);
// void printxy(int x, int y, const char* text, ...);
gllFont& operator<<(FormatToken& token);
#ifndef WIN32 // gcc n'accepte pas les commandes glout << glcolor directement
//il faut lui spécifier chaque classe ARRGGG !
// sous windows avec cl.exe (VC6) , pas de problème
gllFont& operator<<(gllcolor token);
gllFont& operator<<(gllgoto token);
gllFont& operator<<(gllalign token);
gllFont& operator<<(gllsetup token);
gllFont& operator<<(gllskipl token);
#endif
gllFont& operator<<(const char* text);
gllFont& operator<<(const string& str);
gllFont& operator<<(char c);
gllFont& operator<<(int i);
gllFont& operator<<(double d);
private:
CharPos getCharPos(char ch);
TexCoords getTexCoords(CharPos pos);
};
struct _gllendl : public FormatToken {
void execute(gllFont& font);
};
extern _gllendl gllendl;
struct _glltab : public FormatToken {
void execute(gllFont& font);
};
extern _glltab glltab;
struct gllskipl : public FormatToken {
int number;
bool noCR;
gllskipl(int nb, bool noCR = false) {
number = nb;
this->noCR = noCR;
}
void execute(gllFont& font);
};
struct gllgoto : public FormatToken {
int l,c;
gllgoto(int line, int col) {
l = line;
c = col;
}
void execute(gllFont& font);
};
struct _gllstart : public FormatToken {
void execute(gllFont& font);
};
extern _gllstart gllstart;
struct _gllend : public FormatToken {
void execute(gllFont& font);
};
extern _gllend gllend;
struct gllsetup : public FormatToken {
int w,h,sl,sc;
gllsetup(int linSize, int colSize, int screenWidth, int screenHeight) {
sl = linSize;
sc = colSize;
h = screenHeight;
w = screenWidth;
}
void execute(gllFont& font);
};
struct gllcolor : public FormatToken {
float col[4];
gllcolor(float r, float g, float b, float a) {
col[0]=r;col[1]=g;col[2]=b;col[3]=a;
}
void execute(gllFont& font);
};
struct gllalign : public FormatToken {
gllalign_type type;
gllalign(gllalign_type t) {
type = t;
}
void execute(gllFont& font);
};
#endif
--------------------------------------------------------------------------------
/*---------------------------------------------------------------------*\