1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-11-28 08:48:48 +02:00

Reintagrating netcode branch to the trunk.

This commit is contained in:
Michał W. Urbańczyk 2008-08-06 12:27:56 +00:00
commit a78311f63d
146 changed files with 11670 additions and 15534 deletions

View File

@ -10,6 +10,7 @@ void CEmptyAI::init(ICallback * CB)
}
void CEmptyAI::yourTurn()
{
cb->endTurn();
}
void CEmptyAI::heroKilled(const CGHeroInstance *)
{

View File

@ -1,30 +1,30 @@
#define VCMI_DLL
#include "../../AI_Base.h"
#include "CEmptyAI.h"
#include <cstring>
#include <set>
std::set<CGlobalAI*> ais;
DLL_EXPORT int GetGlobalAiVersion()
extern "C" DLL_EXPORT int GetGlobalAiVersion()
{
return AI_INTERFACE_VER;
}
DLL_EXPORT void GetAiName(char* name)
extern "C" DLL_EXPORT void GetAiName(char* name)
{
strcpy(name,NAME);
}
DLL_EXPORT char * GetAiNameS()
extern "C" DLL_EXPORT char * GetAiNameS()
{
char * ret = new char[50];
strcpy(ret,NAME);
return ret;
}
DLL_EXPORT CGlobalAI * GetNewAI()
extern "C" DLL_EXPORT CGlobalAI * GetNewAI()
{
return new CEmptyAI();
// return
}
DLL_EXPORT void ReleaseAI(CGlobalAI * i)
extern "C" DLL_EXPORT void ReleaseAI(CGlobalAI * i)
{
delete (CEmptyAI*)i;
ais.erase(i);

View File

@ -1,16 +1,15 @@
#pragma once
#include <vector>
#include <iostream>
#include "int3.h"
#include "CGameInterface.h"
#define AI_INTERFACE_VER 1
#ifdef _WIN32
#define DLL_EXPORT extern "C" __declspec(dllexport)
#define VCMI_API
#elif __GNUC__ >= 4
#define DLL_EXPORT extern "C" __attribute__ ((visibility("default")))
#define VCMI_API __attribute__ ((visibility("default")))
#else
#define VCMI_EXPORT extern "C"
#endif

View File

@ -1 +0,0 @@

View File

@ -7,6 +7,7 @@
#include "hch/CTownHandler.h"
#include "CLua.h"
#include "CCallback.h"
#include "client/Graphics.h"
AdventureMapButton::AdventureMapButton ()
{
type=2;
@ -31,14 +32,14 @@ AdventureMapButton::AdventureMapButton
helpBox=HelpBox;
colorChange = playerColoredButton;
int est = LOCPLINT->playerID;
CDefHandler * temp = CGI->spriteh->giveDef(defName);
CDefHandler * temp = CDefHandler::giveDef(defName);
temp->notFreeImgs = true;
for (int i=0;i<temp->ourImages.size();i++)
{
imgs.resize(1);
imgs[0].push_back(temp->ourImages[i].bitmap);
if(playerColoredButton)
CSDL_Ext::blueToPlayersAdv(imgs[curimg][i],LOCPLINT->playerID);
graphics->blueToPlayersAdv(imgs[curimg][i],LOCPLINT->playerID);
}
delete temp;
if (add)
@ -46,13 +47,13 @@ AdventureMapButton::AdventureMapButton
imgs.resize(imgs.size()+add->size());
for (int i=0; i<add->size();i++)
{
temp = CGI->spriteh->giveDef((*add)[i]);
temp = CDefHandler::giveDef((*add)[i]);
temp->notFreeImgs = true;
for (int j=0;j<temp->ourImages.size();j++)
{
imgs[i+1].push_back(temp->ourImages[j].bitmap);
if(playerColoredButton)
CSDL_Ext::blueToPlayersAdv(imgs[1+i][j],LOCPLINT->playerID);
graphics->blueToPlayersAdv(imgs[1+i][j],LOCPLINT->playerID);
}
delete temp;
}
@ -245,7 +246,7 @@ CSlider::CSlider(int x, int y, int totalw, boost::function<void(int)> Moved, int
{
moving = false;
strongInterest = true;
imgs = CGI->spriteh->giveDefEss("IGPCRDIV.DEF");
imgs = CDefHandler::giveDefEss("IGPCRDIV.DEF");
left.pos.y = slider.pos.y = right.pos.y = pos.y = y;
left.pos.x = pos.x = x;

View File

@ -1,9 +1,10 @@
#include "stdafx.h"
#include "CAdvmapInterface.h"
#include "hch/CLodHandler.h"
#include "client/CBitmapHandler.h"
#include "CPlayerInterface.h"
#include "hch/CPreGameTextHandler.h"
#include "hch/CGeneralTextHandler.h"
#include "hch/CDefHandler.h"
#include "hch/CTownHandler.h"
#include "CPathfinder.h"
#include "CGameInfo.h"
@ -19,7 +20,11 @@
#include <sstream>
#include "AdventureMapButton.h"
#include "CHeroWindow.h"
#pragma warning (disable : 4355)
#include "client/Graphics.h"
#include "hch/CObjectHandler.h"
#include <boost/thread.hpp>
#include "map.h"
#pragma warning (disable : 4355)
extern TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX; //fonts
using namespace boost::logic;
@ -62,7 +67,7 @@ CMinimap::CMinimap(bool draw)
}
SDL_SetColorKey(radar,SDL_SRCCOLORKEY,SDL_MapRGB(radar->format,0,255,255));
//radar = CGI->spriteh->giveDef("RADAR.DEF");
//radar = CDefHandler::giveDef("RADAR.DEF");
std::ifstream is("config/minimap.txt",std::ifstream::in);
for (int i=0;i<TERRAIN_TYPES;i++)
{
@ -112,11 +117,11 @@ void CMinimap::draw()
{
for (int jj=0; jj<ho; jj++)
{
SDL_PutPixel(temps,maplgp.x+ii,maplgp.y+jj,CGI->playerColors[hh[i]->getOwner()].r,CGI->playerColors[hh[i]->getOwner()].g,CGI->playerColors[hh[i]->getOwner()].b);
SDL_PutPixel(temps,maplgp.x+ii,maplgp.y+jj,graphics->playerColors[hh[i]->getOwner()].r,graphics->playerColors[hh[i]->getOwner()].g,graphics->playerColors[hh[i]->getOwner()].b);
}
}
}
blitAt(FoW[LOCPLINT->adventureInt->position.z],0,0,temps);
//blitAt(FoW[LOCPLINT->adventureInt->position.z],0,0,temps);
//draw radar
int bx = (((float)LOCPLINT->adventureInt->position.x)/(((float)CGI->mh->sizes.x)))*pos.w,
@ -127,7 +132,7 @@ void CMinimap::draw()
}
void CMinimap::redraw(int level)// (level==-1) => redraw all levels
{
(CGameInfo::mainObj);
(CGI);
for (int i=0; i<CGI->mh->sizes.z; i++)
{
SDL_Surface * pom ;
@ -142,9 +147,9 @@ void CMinimap::redraw(int level)// (level==-1) => redraw all levels
{
int mx=(CGI->mh->sizes.x*x)/pos.w;
int my=(CGI->mh->sizes.y*y)/pos.h;
if (CGI->mh->ttiles[mx][my][i].blocked && (!CGI->mh->ttiles[mx][my][i].visitable))
SDL_PutPixel(pom,x,y,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].r,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].g,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].b);
else SDL_PutPixel(pom,x,y,colors[CGI->mh->ttiles[mx][my][i].terType].r,colors[CGI->mh->ttiles[mx][my][i].terType].g,colors[CGI->mh->ttiles[mx][my][i].terType].b);
if (CGI->mh->ttiles[mx][my][i].tileInfo->blocked && (!CGI->mh->ttiles[mx][my][i].tileInfo->visitable))
SDL_PutPixel(pom,x,y,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].r,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].g,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].b);
else SDL_PutPixel(pom,x,y,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].r,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].g,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].b);
}
}
map.push_back(pom);
@ -212,17 +217,17 @@ void CMinimap::deactivate()
}
void CMinimap::showTile(int3 pos)
{
int mw = map[0]->w, mh = map[0]->h;
double wo = ((double)mw)/CGI->mh->sizes.x, ho = ((double)mh)/CGI->mh->sizes.y;
for (int ii=0; ii<wo; ii++)
{
for (int jj=0; jj<ho; jj++)
{
if ((pos.x*wo+ii<this->pos.w) && (pos.y*ho+jj<this->pos.h))
CSDL_Ext::SDL_PutPixel(FoW[pos.z],pos.x*wo+ii,pos.y*ho+jj,0,0,0,0,0);
//int mw = map[0]->w, mh = map[0]->h;
//double wo = ((double)mw)/CGI->mh->sizes.x, ho = ((double)mh)/CGI->mh->sizes.y;
//for (int ii=0; ii<wo; ii++)
//{
// for (int jj=0; jj<ho; jj++)
// {
// if ((pos.x*wo+ii<this->pos.w) && (pos.y*ho+jj<this->pos.h))
// CSDL_Ext::SDL_PutPixel(FoW[pos.z],pos.x*wo+ii,pos.y*ho+jj,0,0,0,0,0);
}
}
// }
//}
}
void CMinimap::hideTile(int3 pos)
{
@ -235,7 +240,7 @@ CTerrainRect::CTerrainRect():currentPath(NULL)
pos.y=6;
pos.w=593;
pos.h=547;
arrows = CGI->spriteh->giveDef("ADAG.DEF");
arrows = CDefHandler::giveDef("ADAG.DEF");
for(int y=0; y<arrows->ourImages.size(); ++y)
{
arrows->ourImages[y].bitmap = CSDL_Ext::alphaTransform(arrows->ourImages[y].bitmap);
@ -259,7 +264,6 @@ void CTerrainRect::deactivate()
};
void CTerrainRect::clickLeft(tribool down)
{
LOGE("Left mouse button down2");
if ((down==false) || indeterminate(down))
return;
if (LOCPLINT->adventureInt->selection.type != HEROI_TYPE)
@ -280,7 +284,9 @@ void CTerrainRect::clickLeft(tribool down)
if ( (currentPath->endPos()) == mp)
{ //move
CPath sended(*currentPath); //temporary path - engine will operate on it
LOCPLINT->pim->unlock();
mres = LOCPLINT->cb->moveHero( ((const CGHeroInstance*)LOCPLINT->adventureInt->selection.selected)->type->ID,&sended,1,0);
LOCPLINT->pim->lock();
if(!mres)
{
delete currentPath;
@ -557,7 +563,7 @@ void CTerrainRect::show()
SDL_Surface * teren = CGI->mh->terrainRect
(LOCPLINT->adventureInt->position.x,LOCPLINT->adventureInt->position.y,
tilesw,tilesh,LOCPLINT->adventureInt->position.z,LOCPLINT->adventureInt->anim,
LOCPLINT->cb->getVisibilityMap(), true, LOCPLINT->adventureInt->heroAnim,
&LOCPLINT->cb->getVisibilityMap(), true, LOCPLINT->adventureInt->heroAnim,
screen,&genRect(547,594,7,6)
);
//SDL_BlitSurface(teren,&genRect(pos.h,pos.w,0,0),screen,&genRect(547,594,7,6));
@ -593,13 +599,9 @@ void CResDataBar::deactivate()
}
CResDataBar::CResDataBar()
{
bg = CGI->bitmaph->loadBitmap("ZRESBAR.bmp");
bg = BitmapHandler::loadBitmap("ZRESBAR.bmp");
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
//std::vector<SDL_Color> kolory;
//SDL_Color p1={40,65,139,255}, p2={36,59,125,255}, p3={35,56,121,255};
//kolory+=p1,p2,p3;
//blueToPlayersAdv(bg,LOCPLINT->playerID,2,&kolory);
blueToPlayersAdv(bg,LOCPLINT->playerID,2);
graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
pos = genRect(bg->h,bg->w,3,575);
txtpos += (std::pair<int,int>(35,577)),(std::pair<int,int>(120,577)),(std::pair<int,int>(205,577)),
@ -638,11 +640,11 @@ CInfoBar::CInfoBar()
pos.y=389;
pos.w=194;
pos.h=186;
day = CGI->spriteh->giveDef("NEWDAY.DEF");
week1 = CGI->spriteh->giveDef("NEWWEEK1.DEF");
week2 = CGI->spriteh->giveDef("NEWWEEK2.DEF");
week3 = CGI->spriteh->giveDef("NEWWEEK3.DEF");
week4 = CGI->spriteh->giveDef("NEWWEEK4.DEF");
day = CDefHandler::giveDef("NEWDAY.DEF");
week1 = CDefHandler::giveDef("NEWWEEK1.DEF");
week2 = CDefHandler::giveDef("NEWWEEK2.DEF");
week3 = CDefHandler::giveDef("NEWWEEK3.DEF");
week4 = CDefHandler::giveDef("NEWWEEK4.DEF");
}
CInfoBar::~CInfoBar()
{
@ -680,14 +682,14 @@ void CInfoBar::draw(const CGObjectInstance * specific)
if(specific->ID == 34) //hero
{
if(LOCPLINT->heroWins.find(specific->subID)!=LOCPLINT->heroWins.end())
blitAt(LOCPLINT->heroWins[specific->subID],pos.x,pos.y);
if(graphics->heroWins.find(specific->subID)!=graphics->heroWins.end())
blitAt(graphics->heroWins[specific->subID],pos.x,pos.y);
}
else if (specific->ID == 98)
{
const CGTownInstance * t = static_cast<const CGTownInstance*>(specific);
if(LOCPLINT->townWins.find(t->identifier)!=LOCPLINT->townWins.end())
blitAt(LOCPLINT->townWins[t->identifier],pos.x,pos.y);
if(graphics->townWins.find(t->identifier)!=graphics->townWins.end())
blitAt(graphics->townWins[t->identifier],pos.x,pos.y);
}
//SDL_Surface * todr = LOCPLINT->infoWin(specific);
@ -775,7 +777,7 @@ void CInfoBar::newDay(int Day)
void CInfoBar::showComp(SComponent * comp, int time)
{
SDL_Surface * b = CGI->bitmaph->loadBitmap("ADSTATOT.bmp");
SDL_Surface * b = BitmapHandler::loadBitmap("ADSTATOT.bmp");
blitAt(b,pos.x+8,pos.y+11);
blitAt(comp->getImg(),pos.x+52,pos.y+54);
printAtMiddle(comp->subtitle,pos.x+91,pos.y+158,GEOR13,zwykly);
@ -849,8 +851,8 @@ townList(5,&genRect(192,48,747,196),747,196,747,372)
{
townList.fun = boost::bind(&CAdvMapInt::selectionChanged,this);
LOCPLINT->adventureInt=this;
bg = CGI->bitmaph->loadBitmap("ADVMAP.bmp");
blueToPlayersAdv(bg,player);
bg = BitmapHandler::loadBitmap("ADVMAP.bmp");
graphics->blueToPlayersAdv(bg,player);
scrollingLeft = false;
scrollingRight = false;
scrollingUp = false ;
@ -868,10 +870,10 @@ townList(5,&genRect(192,48,747,196),747,196,747,372)
heroWindow = new CHeroWindow(this->player);
gems.push_back(CGI->spriteh->giveDef("agemLL.def"));
gems.push_back(CGI->spriteh->giveDef("agemLR.def"));
gems.push_back(CGI->spriteh->giveDef("agemUL.def"));
gems.push_back(CGI->spriteh->giveDef("agemUR.def"));
gems.push_back(CDefHandler::giveDef("agemLL.def"));
gems.push_back(CDefHandler::giveDef("agemLR.def"));
gems.push_back(CDefHandler::giveDef("agemUL.def"));
gems.push_back(CDefHandler::giveDef("agemUR.def"));
}
void CAdvMapInt::fshowOverview()
@ -879,7 +881,7 @@ void CAdvMapInt::fshowOverview()
}
void CAdvMapInt::fswitchLevel()
{
if(!CGI->ac->map.twoLevel)
if(!CGI->mh->map->twoLevel)
return;
if (position.z)
{

View File

@ -4,15 +4,23 @@
#include "SDL_Extensions.h"
#include "CAdvmapInterface.h"
#include "AdventureMapButton.h"
#include "hch/CObjectHandler.h"
#include "hch/CHeroHandler.h"
#include "hch/CDefHandler.h"
#include "CCallback.h"
#include "CGameState.h"
#include "hch/CGeneralTextHandler.h"
#include "client/CCreatureAnimation.h"
#include "client/Graphics.h"
#include <queue>
#include <sstream>
#include "lib/CondSh.h"
#ifndef __GNUC__
const double M_PI = 3.14159265358979323846;
#else
#define _USE_MATH_DEFINES
#include <cmath>
#endif
extern SDL_Surface * screen;
extern TTF_Font * GEOR13;
@ -22,6 +30,7 @@ SDL_Surface * CBattleInterface::cellBorder, * CBattleInterface::cellShade;
CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2)
: printCellBorders(true), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0), activeStack(-1), givenCommand(NULL), attackingInfo(NULL), myTurn(false)
{
givenCommand = new CondSh<BattleAction *>(NULL);
//initializing armies
this->army1 = army1;
this->army2 = army2;
@ -35,14 +44,14 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
creDir[b->second.ID] = b->second.owner==attackingHeroInstance->tempOwner;
}
//preparing menu background and terrain
std::vector< std::string > & backref = CGI->mh->battleBacks[ LOCPLINT->cb->battleGetBattlefieldType() ];
background = CGI->bitmaph->loadBitmap(backref[ rand() % backref.size()] );
menu = CGI->bitmaph->loadBitmap("CBAR.BMP");
CSDL_Ext::blueToPlayersAdv(menu, hero1->tempOwner);
std::vector< std::string > & backref = graphics->battleBacks[ LOCPLINT->cb->battleGetBattlefieldType() ];
background = BitmapHandler::loadBitmap(backref[ rand() % backref.size()] );
menu = BitmapHandler::loadBitmap("CBAR.BMP");
graphics->blueToPlayersAdv(menu, hero1->tempOwner);
//preparing graphics for displaying amounts of creatures
amountBasic = CGI->bitmaph->loadBitmap("CMNUMWIN.BMP");
amountNormal = CGI->bitmaph->loadBitmap("CMNUMWIN.BMP");
amountBasic = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
CSDL_Ext::alphaTransform(amountNormal);
for(int g=0; g<amountNormal->format->palette->ncolors; ++g)
{
@ -81,7 +90,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
//loading hero animations
if(hero1) // attacking hero
{
attackingHero = new CBattleHero(CGI->mh->battleHeroes[hero1->type->heroType], 0, 0, false, hero1->tempOwner);
attackingHero = new CBattleHero(graphics->battleHeroes[hero1->type->heroType], 0, 0, false, hero1->tempOwner);
attackingHero->pos = genRect(attackingHero->dh->ourImages[0].bitmap->h, attackingHero->dh->ourImages[0].bitmap->w, -40, 0);
}
else
@ -90,7 +99,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
}
if(hero2) // defending hero
{
defendingHero = new CBattleHero(CGI->mh->battleHeroes[hero2->type->heroType], 0, 0, true, hero2->tempOwner);
defendingHero = new CBattleHero(graphics->battleHeroes[hero2->type->heroType], 0, 0, true, hero2->tempOwner);
defendingHero->pos = genRect(defendingHero->dh->ourImages[0].bitmap->h, defendingHero->dh->ourImages[0].bitmap->w, 690, 0);
}
else
@ -99,9 +108,9 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
}
//preparing cells and hexes
cellBorder = CGI->bitmaph->loadBitmap("CCELLGRD.BMP");
cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
CSDL_Ext::alphaTransform(cellBorder);
cellShade = CGI->bitmaph->loadBitmap("CCELLSHD.BMP");
cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
CSDL_Ext::alphaTransform(cellShade);
for(int h=0; h<187; ++h)
{
@ -124,7 +133,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
{
if(g->second.creature->isShooting() && CGI->creh->idToProjectile[g->second.creature->idNumber] != std::string())
{
idToProjectile[g->second.creature->idNumber] = CGI->spriteh->giveDef(CGI->creh->idToProjectile[g->second.creature->idNumber]);
idToProjectile[g->second.creature->idNumber] = CDefHandler::giveDef(CGI->creh->idToProjectile[g->second.creature->idNumber]);
if(idToProjectile[g->second.creature->idNumber]->ourImages.size() > 2) //add symmetric images
{
@ -161,6 +170,7 @@ CBattleInterface::~CBattleInterface()
delete bConsoleUp;
delete bConsoleDown;
delete console;
delete givenCommand;
delete attackingHero;
delete defendingHero;
@ -351,7 +361,7 @@ bool CBattleInterface::reverseCreature(int number, int hex, bool wideTrick)
}
creDir[number] = !creDir[number];
CStack curs = LOCPLINT->cb->battleGetStackByID(number);
CStack curs = *LOCPLINT->cb->battleGetStackByID(number);
std::pair <int, int> coords = CBattleHex::getXYUnitAnim(hex, creDir[number], curs.creature);
creAnims[number]->pos.x = coords.first;
//creAnims[number]->pos.y = coords.second;
@ -383,9 +393,7 @@ void CBattleInterface::bSurrenderf()
void CBattleInterface::bFleef()
{
BattleAction * ba = new BattleAction;
ba->actionType = 4;
givenCommand = ba;
giveCommand(4,0,0);
}
void CBattleInterface::bAutofightf()
@ -402,10 +410,7 @@ void CBattleInterface::bWaitf()
void CBattleInterface::bDefencef()
{
BattleAction * ba = new BattleAction;
ba->actionType = 3;
ba->stackNumber = activeStack;
givenCommand = ba;
giveCommand(3,0,activeStack);
}
void CBattleInterface::bConsoleUpf()
@ -439,7 +444,7 @@ void CBattleInterface::stackKilled(int ID, int dmg, int killed, int IDby, bool b
}
if(byShooting) //delay hit animation
{
CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
while(true)
{
bool found = false;
@ -474,7 +479,7 @@ void CBattleInterface::stackKilled(int ID, int dmg, int killed, int IDby, bool b
void CBattleInterface::stackActivated(int number)
{
givenCommand = NULL;
//givenCommand = NULL;
activeStack = number;
shadedHexes = LOCPLINT->cb->battleGetAvailableHexes(number);
myTurn = true;
@ -562,7 +567,7 @@ void CBattleInterface::stackMoved(int number, int destHex, bool startMoving, boo
CSDL_Ext::update();
SDL_framerateDelay(LOCPLINT->mainFPSmng);
}
if( (LOCPLINT->cb->battleGetStackByID(number).owner == attackingHeroInstance->tempOwner ) != creDir[number])
if( (LOCPLINT->cb->battleGetStackByID(number)->owner == attackingHeroInstance->tempOwner ) != creDir[number])
{
reverseCreature(number, curStackPos, true);
}
@ -643,7 +648,7 @@ void CBattleInterface::stackMoved(int number, int destHex, bool startMoving, boo
}
creAnims[number]->setType(2); //resetting to default
CStack curs = LOCPLINT->cb->battleGetStackByID(number);
CStack curs = *LOCPLINT->cb->battleGetStackByID(number);
if(endMoving) //resetting to default
{
if(creDir[number] != (curs.owner == attackingHeroInstance->tempOwner))
@ -664,7 +669,7 @@ void CBattleInterface::stackIsAttacked(int ID, int dmg, int killed, int IDby, bo
}
if(byShooting) //delay hit animation
{
CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
while(true)
{
bool found = false;
@ -704,7 +709,7 @@ void CBattleInterface::stackAttacking(int ID, int dest)
{
return; //something went wrong
}
CStack aStack = LOCPLINT->cb->battleGetStackByID(ID); //attacking stack
CStack aStack = *LOCPLINT->cb->battleGetStackByID(ID); //attacking stack
if(aStack.creature->isDoubleWide())
{
switch(CBattleHex::mutualPosition(aStack.position, dest)) //attack direction
@ -783,6 +788,16 @@ void CBattleInterface::newRound(int number)
console->addText(CGI->generaltexth->allTexts[412]);
}
void CBattleInterface::giveCommand(ui8 action, ui16 tile, ui32 stack)
{
BattleAction * ba = new BattleAction(); //to be deleted by engine
ba->actionType = action;
ba->destinationTile = tile;
ba->stackNumber = stack;
givenCommand->setn(ba);
myTurn = false;
}
void CBattleInterface::hexLclicked(int whichOne)
{
if((whichOne%17)!=0 && (whichOne%17)!=16) //if player is trying to attack enemey unit or move creature stack
@ -794,28 +809,16 @@ void CBattleInterface::hexLclicked(int whichOne)
//LOCPLINT->cb->battleGetCreature();
if(atCre==-1) //normal move action
{
BattleAction * ba = new BattleAction(); //to be deleted by engine
ba->actionType = 2;
ba->destinationTile = whichOne;
ba->stackNumber = activeStack;
givenCommand = ba;
giveCommand(2,whichOne,activeStack);
}
else if(LOCPLINT->cb->battleGetStackByID(atCre).owner != attackingHeroInstance->tempOwner
else if(LOCPLINT->cb->battleGetStackByID(atCre)->owner != attackingHeroInstance->tempOwner
&& LOCPLINT->cb->battleCanShoot(activeStack, whichOne)) //shooting
{
BattleAction * ba = new BattleAction(); //to be deleted by engine
ba->actionType = 7;
ba->destinationTile = whichOne;
ba->stackNumber = activeStack;
givenCommand = ba;
giveCommand(7,whichOne,activeStack);
}
else if(LOCPLINT->cb->battleGetStackByID(atCre).owner != attackingHeroInstance->tempOwner) //attacking
else if(LOCPLINT->cb->battleGetStackByID(atCre)->owner != attackingHeroInstance->tempOwner) //attacking
{
BattleAction * ba = new BattleAction(); //to be deleted by engine
ba->actionType = 6;
ba->destinationTile = whichOne;
ba->stackNumber = activeStack;
givenCommand = ba;
giveCommand(6,whichOne,activeStack);
}
}
}
@ -835,7 +838,7 @@ void CBattleInterface::stackIsShooting(int ID, int dest)
projectileAngle = -projectileAngle;
SProjectileInfo spi;
spi.creID = LOCPLINT->cb->battleGetStackByID(ID).creature->idNumber;
spi.creID = LOCPLINT->cb->battleGetStackByID(ID)->creature->idNumber;
spi.step = 0;
spi.frameNum = 0;
@ -907,7 +910,7 @@ void CBattleInterface::attackingShowHelper()
{
if(attackingInfo->frame == 0)
{
CStack aStack = LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
CStack aStack = *LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
if(attackingInfo->shooting)
{
creAnims[attackingInfo->ID]->setType(attackingInfo->shootingGroup);
@ -967,7 +970,7 @@ void CBattleInterface::attackingShowHelper()
else if(attackingInfo->frame == (attackingInfo->maxframe - 1))
{
attackingInfo->reversing = true;
CStack aStack = LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
CStack aStack = *LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
if(aStack.creature->isDoubleWide())
{
switch(CBattleHex::mutualPosition(aStack.position, attackingInfo->dest)) //attack direction
@ -1025,8 +1028,8 @@ void CBattleInterface::attackingShowHelper()
void CBattleInterface::printConsoleAttacked(int ID, int dmg, int killed, int IDby)
{
char tabh[200];
CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
CStack defender = LOCPLINT->cb->battleGetStackByID(ID);
CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
CStack defender = *LOCPLINT->cb->battleGetStackByID(ID);
int end = sprintf(tabh, CGI->generaltexth->allTexts[attacker.amount > 1 ? 377 : 376].c_str(),
(attacker.amount > 1 ? attacker.creature->namePl.c_str() : attacker.creature->nameSing.c_str()),
dmg);
@ -1123,7 +1126,7 @@ void CBattleHero::show(SDL_Surface *to)
CBattleHero::CBattleHero(std::string defName, int phaseG, int imageG, bool flipG, unsigned char player): phase(phaseG), image(imageG), flip(flipG), flagAnim(0)
{
dh = CGI->spriteh->giveDef( defName );
dh = CDefHandler::giveDef( defName );
for(int i=0; i<dh->ourImages.size(); ++i) //transforming images
{
if(flip)
@ -1137,15 +1140,15 @@ CBattleHero::CBattleHero(std::string defName, int phaseG, int imageG, bool flipG
dh->alphaTransformed = true;
if(flip)
flag = CGI->spriteh->giveDef("CMFLAGR.DEF");
flag = CDefHandler::giveDef("CMFLAGR.DEF");
else
flag = CGI->spriteh->giveDef("CMFLAGL.DEF");
flag = CDefHandler::giveDef("CMFLAGL.DEF");
//coloring flag and adding transparency
for(int i=0; i<flag->ourImages.size(); ++i)
{
flag->ourImages[i].bitmap = CSDL_Ext::alphaTransform(flag->ourImages[i].bitmap);
CSDL_Ext::blueToPlayersAdv(flag->ourImages[i].bitmap, player);
graphics->blueToPlayersAdv(flag->ourImages[i].bitmap, player);
}
}
@ -1249,11 +1252,11 @@ void CBattleHex::mouseMoved(SDL_MouseMotionEvent &sEvent)
if(hovered && strictHovered) //print attacked creature to console
{
if(myInterface->console->alterTxt.size() == 0 && LOCPLINT->cb->battleGetStack(myNumber) != -1 &&
LOCPLINT->cb->battleGetStackByPos(myNumber).owner != LOCPLINT->playerID &&
LOCPLINT->cb->battleGetStackByPos(myNumber).alive)
LOCPLINT->cb->battleGetStackByPos(myNumber)->owner != LOCPLINT->playerID &&
LOCPLINT->cb->battleGetStackByPos(myNumber)->alive)
{
char tabh[160];
CStack attackedStack = LOCPLINT->cb->battleGetStackByPos(myNumber);
CStack attackedStack = *LOCPLINT->cb->battleGetStackByPos(myNumber);
std::string attackedName = attackedStack.amount == 1 ? attackedStack.creature->nameSing : attackedStack.creature->namePl;
sprintf(tabh, CGI->generaltexth->allTexts[220].c_str(), attackedName.c_str());
myInterface->console->alterTxt = std::string(tabh);
@ -1280,7 +1283,7 @@ void CBattleHex::clickRight(boost::logic::tribool down)
int stID = LOCPLINT->cb->battleGetStack(myNumber); //id of stack being on this tile
if(hovered && strictHovered && stID!=-1)
{
CStack myst = LOCPLINT->cb->battleGetStackByID(stID); //stack info
CStack myst = *LOCPLINT->cb->battleGetStackByID(stID); //stack info
StackState *pom = NULL;
if(down)
{

View File

@ -9,6 +9,7 @@ class CDefHandler;
class CStack;
class CCallback;
class AdventureMapButton;
template <typename T> struct CondSh;
class CBattleHero : public IShowable, public CIntObject
{
@ -112,7 +113,7 @@ private:
};
std::list<SProjectileInfo> projectiles;
void projectileShowHelper(SDL_Surface * to=NULL); //prints projectiles present on the battlefield
void giveCommand(ui8 action, ui16 tile, ui32 stack);
public:
CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2); //c-tor
~CBattleInterface(); //d-tor
@ -122,7 +123,7 @@ public:
CBattleHex bfield[187]; //11 lines, 17 hexes on each
std::vector< CBattleObstacle * > obstacles; //vector of obstacles on the battlefield
static SDL_Surface * cellBorder, * cellShade;
BattleAction * givenCommand; //true if we have i.e. moved current unit
CondSh<BattleAction *> *givenCommand; //data != NULL if we have i.e. moved current unit
bool myTurn; //if true, interface is active (commands can be ordered
//button handle funcs:

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
#ifndef CCALLBACK_H
#define CCALLBACK_H
#include "mapHandler.h"
#include "global.h"
#ifdef _WIN32
#include "tchar.h"
#else
@ -9,15 +9,20 @@
#endif
#include "CGameState.h"
class CGHeroInstance;
class CGameState;
struct CPath;
class CGObjectInstance;
class CArmedInstance;
class SComponent;
class IChosen;
class CSelectableComponent;
struct BattleAction;
typedef struct lua_State lua_State;
class CGTownInstance;
struct StartInfo;
class CStack;
struct lua_State;
class CClient;
//structure gathering info about upgrade possibilites
struct UpgradeInfo
{
@ -40,11 +45,12 @@ public:
virtual void recruitCreatures(const CGObjectInstance *obj, int ID, int amount)=0;
virtual bool dismissCreature(const CArmedInstance *obj, int stackPos)=0;
virtual bool upgradeCreature(const CArmedInstance *obj, int stackPos, int newID=-1)=0; //if newID==-1 then best possible upgrade will be made
virtual void endTurn()=0;
//get info
virtual bool verifyPath(CPath * path, bool blockSea)=0;
virtual int getDate(int mode=0)=0; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
virtual PseudoV< PseudoV< PseudoV<unsigned char> > > & getVisibilityMap()=0; //returns visibility map (TODO: make it const)
virtual std::vector< std::vector< std::vector<unsigned char> > > & getVisibilityMap()=0; //returns visibility map (TODO: make it const)
virtual const CGHeroInstance * getHeroInfo(int player, int val, bool mode)=0; //mode = 0 -> val = serial; mode = 1 -> val = ID
virtual int getResourceAmount(int type)=0;
virtual int howManyHeroes()=0;
@ -58,13 +64,14 @@ public:
virtual int getHeroSerial(const CGHeroInstance * hero)=0;
virtual const CCreatureSet* getGarrison(const CGObjectInstance *obj)=0;
virtual UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos)=0;
virtual const StartInfo * getStartInfo()=0;
//battle
virtual int battleGetBattlefieldType()=0; // 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines 8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields 15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog 21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship
virtual int battleGetObstaclesAtTile(int tile)=0; //returns bitfield
virtual int battleGetStack(int pos)=0; //returns ID of stack on the tile
virtual CStack battleGetStackByID(int ID)=0; //returns stack info by given ID
virtual CStack battleGetStackByPos(int pos)=0; //returns stack info by given pos
virtual CStack * battleGetStackByID(int ID)=0; //returns stack info by given ID
virtual CStack * battleGetStackByPos(int pos)=0; //returns stack info by given pos
virtual int battleGetPos(int stack)=0; //returns position (tile ID) of stack
//virtual int battleMakeAction(BattleAction* action)=0;//perform action with an active stack (or custom action)
virtual std::map<int, CStack> battleGetStacks()=0; //returns stacks on battlefield
@ -77,6 +84,8 @@ public:
struct HeroMoveDetails
{
HeroMoveDetails(){};
HeroMoveDetails(int3 Src, int3 Dst, CGHeroInstance*Ho);
int3 src, dst; //source and destination points
CGHeroInstance * ho; //object instance of this hero
int owner;
@ -86,11 +95,9 @@ struct HeroMoveDetails
class CCallback : public ICallback
{
private:
void newTurn();
CCallback(CGameState * GS, int Player):gs(GS),player(Player){};
CCallback(CGameState * GS, int Player, CClient *C):gs(GS),player(Player),cl(C){};
CGameState * gs;
int lowestSpeed(CGHeroInstance * chi); //speed of the slowest stack
int valMovePoints(CGHeroInstance * chi);
CClient *cl;
bool isVisible(int3 pos, int Player);
protected:
@ -106,19 +113,19 @@ public:
int splitStack(const CGObjectInstance *s1, const CGObjectInstance *s2, int p1, int p2, int val);
bool dismissHero(const CGHeroInstance * hero);
bool swapArifacts(const CGHeroInstance * hero1, bool worn1, int pos1, const CGHeroInstance * hero2, bool worn2, int pos2);
bool buildBuilding(const CGTownInstance *town, int buildingID);
bool buildBuilding(const CGTownInstance *town, si32 buildingID);
void recruitCreatures(const CGObjectInstance *obj, int ID, int amount);
bool dismissCreature(const CArmedInstance *obj, int stackPos);
bool upgradeCreature(const CArmedInstance *obj, int stackPos, int newID=-1);
void endTurn();
//get info
bool verifyPath(CPath * path, bool blockSea);
int getDate(int mode=0); //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
PseudoV< PseudoV< PseudoV<unsigned char> > > & getVisibilityMap(); //returns visibility map (TODO: make it const)
std::vector< std::vector< std::vector<unsigned char> > > & getVisibilityMap(); //returns visibility map (TODO: make it const)
const CGHeroInstance * getHeroInfo(int player, int val, bool mode); //mode = 0 -> val = serial; mode = 1 -> val = ID
int getResourceAmount(int type);
std::vector<int> getResourceAmount();
std::vector<si32> getResourceAmount();
int howManyHeroes();
const CGTownInstance * getTownInfo(int val, bool mode); //mode = 0 -> val = serial; mode = 1 -> val = ID
std::vector < const CGTownInstance *> getTownsInfo(bool onlyOur=true);
@ -131,13 +138,14 @@ public:
int getMySerial();
const CCreatureSet* getGarrison(const CGObjectInstance *obj);
UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos);
virtual const StartInfo * getStartInfo();
//battle
int battleGetBattlefieldType(); // 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines 8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields 15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog 21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship
int battleGetObstaclesAtTile(int tile); //returns bitfield
int battleGetStack(int pos); //returns ID of stack on the tile
CStack battleGetStackByID(int ID); //returns stack info by given ID
CStack battleGetStackByPos(int pos); //returns stack info by given pos
CStack * battleGetStackByID(int ID); //returns stack info by given ID
CStack * battleGetStackByPos(int pos); //returns stack info by given pos
int battleGetPos(int stack); //returns position (tile ID) of stack
//int battleMakeAction(BattleAction* action);//perform action with an active stack (or custom action)
std::map<int, CStack> battleGetStacks(); //returns stacks on battlefield
@ -150,48 +158,11 @@ public:
//friends
friend class CClient;
#ifndef __GNUC__
friend int _tmain(int argc, _TCHAR* argv[]);
#else
friend int main(int argc, _TCHAR* argv[]);
#endif
};
class CScriptCallback
{
public:
CGameState * gs;
//get info
static int3 getPos(CGObjectInstance * ob);
int getHeroOwner(int heroID);
int getSelectedHero();
int getDate(int mode=0);
//do sth
static void changePrimSkill(int ID, int which, int val);
void showInfoDialog(int player, std::string text, std::vector<SComponent*> * components); //TODO: obslugiwac nulle
void showSelDialog(int player, std::string text, std::vector<CSelectableComponent*>*components, IChosen * asker);
void giveResource(int player, int which, int val);
void showCompInfo(int player, SComponent * comp);
void heroVisitCastle(CGObjectInstance * ob, int heroID);
void stopHeroVisitCastle(CGObjectInstance * ob, int heroID);
void giveHeroArtifact(int artid, int hid, int position); //pos==-1 - first free slot in backpack
void startBattle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2); //use hero=NULL for no hero
void startBattle(int heroID, CCreatureSet * army, int3 tile); //for hero<=>neutral army
//friends
friend void initGameState(CGameInfo * cgi);
};
class CLuaCallback : public CScriptCallback
{
private:
static void registerFuncs(lua_State * L);
static int getPos(lua_State * L);//(CGObjectInstance * object);
static int changePrimSkill(lua_State * L);//(int ID, int which, int val);
static int getGnrlText(lua_State * L);//(int ID, int which, int val);
static int getSelectedHero(lua_State * L);//()
friend void initGameState(CGameInfo * cgi);
};
#endif //CCALLBACK_H

View File

@ -8,15 +8,17 @@
#include "hch/CTownHandler.h"
#include "AdventureMapButton.h"
#include "hch/CBuildingHandler.h"
#include "hch/CDefHandler.h"
#include <sstream>
#include "CMessage.h"
#include "hch/CGeneralTextHandler.h"
#include "CCallback.h"
#include "client/Graphics.h"
extern TTF_Font * GEOR16;
CBuildingRect::CBuildingRect(Structure *Str)
:str(Str), moi(false), offset(0)
{
def = CGI->spriteh->giveDef(Str->defName);
def = CDefHandler::giveDef(Str->defName);
max = def->ourImages.size();
if(str->ID == 33 && str->townID == 4) //little 'hack' for estate in necropolis - background color is not always the first color in the palette
@ -36,11 +38,11 @@ CBuildingRect::CBuildingRect(Structure *Str)
area = border = NULL;
return;
}
if (border = CGI->bitmaph->loadBitmap(str->borderName))
if (border = BitmapHandler::loadBitmap(str->borderName))
SDL_SetColorKey(border,SDL_SRCCOLORKEY,SDL_MapRGB(border->format,0,255,255));
else
std::cout << "Warning: no border for "<<Str->ID<<std::endl;
if (area = CGI->bitmaph->loadBitmap(str->areaName))
if (area = BitmapHandler::loadBitmap(str->areaName))
;//SDL_SetColorKey(area,SDL_SRCCOLORKEY,SDL_MapRGB(area->format,0,255,255));
else
std::cout << "Warning: no area for "<<Str->ID<<std::endl;
@ -213,11 +215,11 @@ public:
CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
{
hall = NULL;
townInt = CGI->bitmaph->loadBitmap("TOWNSCRN.bmp");
cityBg = CGI->bitmaph->loadBitmap(getBgName(Town->subID));
hall = CGI->spriteh->giveDef("ITMTL.DEF");
fort = CGI->spriteh->giveDef("ITMCL.DEF");
flag = CGI->spriteh->giveDef("CREST58.DEF");
townInt = BitmapHandler::loadBitmap("TOWNSCRN.bmp");
cityBg = BitmapHandler::loadBitmap(getBgName(Town->subID));
hall = CDefHandler::giveDef("ITMTL.DEF");
fort = CDefHandler::giveDef("ITMCL.DEF");
flag = CDefHandler::giveDef("CREST58.DEF");
hBuild = NULL;
count=0;
town = Town;
@ -238,7 +240,7 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
if((townlist->selected+1) > townlist->SIZE)
townlist->from = townlist->selected - townlist->SIZE + 2;
CSDL_Ext::blueToPlayersAdv(townInt,LOCPLINT->playerID);
graphics->blueToPlayersAdv(townInt,LOCPLINT->playerID);
exit->bitmapOffset = 4;
@ -291,7 +293,7 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
throw new std::exception();
#endif
}
bicons = CGI->spriteh->giveDefEss(defname);
bicons = CDefHandler::giveDefEss(defname);
//blit buildings on bg
//for(int i=0;i<buildings.size();i++)
//{
@ -422,7 +424,7 @@ void CCastleInterface::showAll(SDL_Surface * to)
int pomx, pomy;
pomx = 22 + (55*((i>3)?(i-4):i));
pomy = (i>3)?(507):(459);
blitAt(CGI->creh->smallImgs[cid],pomx,pomy,to);
blitAt(graphics->smallImgs[cid],pomx,pomy,to);
std::ostringstream oss;
oss << '+' << town->creatureGrowth(i);
CSDL_Ext::printAtMiddle(oss.str(),pomx+16,pomy+37,GEOR13,zwykly,to);
@ -441,7 +443,7 @@ void CCastleInterface::showAll(SDL_Surface * to)
pom += F_NUMBER*2;
if(town->builded >= MAX_BUILDING_PER_TURN)
pom++;
blitAt(LOCPLINT->bigTownPic->ourImages[pom].bitmap,15,387,to);
blitAt(graphics->bigTownPic->ourImages[pom].bitmap,15,387,to);
//flag
if(town->getOwner()<PLAYER_LIMIT)
@ -516,7 +518,9 @@ void CCastleInterface::deactivate()
void CCastleInterface::addBuilding(int bid)
{
//TODO: lepiej by bylo tylko dodawac co trzeba pamietajac o grupach
deactivate();
recreateBuildings();
activate();
}
void CCastleInterface::removeBuilding(int bid)
@ -539,7 +543,7 @@ void CCastleInterface::recreateBuildings()
std::set< std::pair<int,int> > s; //group - id
for (std::set<int>::const_iterator i=town->builtBuildings.begin();i!=town->builtBuildings.end();i++)
for (std::set<si32>::const_iterator i=town->builtBuildings.begin();i!=town->builtBuildings.end();i++)
{
if(CGI->townh->structures.find(town->subID) != CGI->townh->structures.end()) //we have info about structures in this town
{
@ -669,9 +673,9 @@ void CHallInterface::CResDataBar::show(SDL_Surface * to)
}
CHallInterface::CResDataBar::CResDataBar()
{
bg = CGI->bitmaph->loadBitmap("Z2ESBAR.bmp");
bg = BitmapHandler::loadBitmap("Z2ESBAR.bmp");
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
CSDL_Ext::blueToPlayersAdv(bg,LOCPLINT->playerID);
graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
pos.x = 7;
pos.y = 575;
pos.w = bg->w;
@ -780,10 +784,10 @@ CHallInterface::CBuildingBox::CBuildingBox(int id, int x, int y)
CHallInterface::CHallInterface(CCastleInterface * owner)
{
bg = CGI->bitmaph->loadBitmap(CGI->buildh->hall[owner->town->subID].first);
CSDL_Ext::blueToPlayersAdv(bg,LOCPLINT->playerID);
bars = CGI->spriteh->giveDefEss("TPTHBAR.DEF");
status = CGI->spriteh->giveDefEss("TPTHCHK.DEF");
bg = BitmapHandler::loadBitmap(CGI->buildh->hall[owner->town->subID].first);
graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
bars = CDefHandler::giveDefEss("TPTHBAR.DEF");
status = CDefHandler::giveDefEss("TPTHCHK.DEF");
exit = new AdventureMapButton
(CGI->townh->tcommands[8],"",boost::bind(&CHallInterface::close,this),748,556,"TPMAGE1.DEF",false,NULL,false);
@ -926,12 +930,12 @@ void CHallInterface::CBuildWindow::deactivate()
}
void CHallInterface::CBuildWindow::Buy()
{
LOCPLINT->cb->buildBuilding(LOCPLINT->castleInt->town,bid);
deactivate();
delete this;
delete LOCPLINT->castleInt->hallInt;
LOCPLINT->castleInt->hallInt = NULL;
LOCPLINT->castleInt->activate();
LOCPLINT->cb->buildBuilding(LOCPLINT->castleInt->town,bid);
delete this;
delete LOCPLINT->castleInt->hallInt;
LOCPLINT->castleInt->showAll();
}
void CHallInterface::CBuildWindow::close()
@ -1019,13 +1023,13 @@ std::string CHallInterface::CBuildWindow::getTextForState(int state)
CHallInterface::CBuildWindow::CBuildWindow(int Tid, int Bid, int State, bool Mode)
:tid(Tid),bid(Bid),mode(Mode), state(State)
{
SDL_Surface *hhlp = CGI->bitmaph->loadBitmap("TPUBUILD.bmp");
SDL_Surface *hhlp = BitmapHandler::loadBitmap("TPUBUILD.bmp");
graphics->blueToPlayersAdv(hhlp,LOCPLINT->playerID);
bitmap = SDL_ConvertSurface(hhlp,screen->format,0); //na 8bitowej mapie by sie psulo
SDL_SetColorKey(hhlp,SDL_SRCCOLORKEY,SDL_MapRGB(hhlp->format,0,255,255));
SDL_FreeSurface(hhlp);
pos.x = screen->w/2 - bitmap->w/2;
pos.y = screen->h/2 - bitmap->h/2;
CSDL_Ext::blueToPlayersAdv(bitmap,LOCPLINT->playerID);
blitAt(LOCPLINT->castleInt->bicons->ourImages[bid].bitmap,125,50,bitmap);
std::vector<std::string> pom; pom.push_back(CGI->buildh->buildings[tid][bid]->name);
CSDL_Ext::printAtMiddleWB(CGI->buildh->buildings[tid][bid]->description,197,168,GEOR16,40,zwykly,bitmap);
@ -1045,12 +1049,12 @@ CHallInterface::CBuildWindow::CBuildWindow(int Tid, int Bid, int State, bool Mod
if(it<4)
{
CSDL_Ext::printAtMiddle(buf,(bitmap->w/2-row1w/2)+77*it+16,ah+42,GEOR16,zwykly,bitmap);
blitAt(CGI->townh->resources->ourImages[cn].bitmap,(bitmap->w/2-row1w/2)+77*it++,ah,bitmap);
blitAt(graphics->resources32->ourImages[cn].bitmap,(bitmap->w/2-row1w/2)+77*it++,ah,bitmap);
}
else
{
CSDL_Ext::printAtMiddle(buf,(bitmap->w/2-row2w/2)+77*it+16-308,ah+42,GEOR16,zwykly,bitmap);
blitAt(CGI->townh->resources->ourImages[cn].bitmap,(bitmap->w/2-row2w/2)+77*it++ - 308,ah,bitmap);
blitAt(graphics->resources32->ourImages[cn].bitmap,(bitmap->w/2-row2w/2)+77*it++ - 308,ah,bitmap);
}
if(it==4)
ah+=75;

View File

@ -53,7 +53,7 @@ int internalFunc(void * callback)
boost::filesystem::create_directory("Extracted_txts");
std::cout<<"Command accepted. Opening .lod file...\t";
CLodHandler * txth = new CLodHandler;
txth->init(std::string(DATADIR "Data" PATHSEPARATOR "H3bitmap.lod"));
txth->init(std::string(DATA_DIR "Data" PATHSEPARATOR "H3bitmap.lod"),"data");
std::cout<<"done.\nScanning .lod file\n";
int curp=0;
std::string pattern = ".TXT";
@ -79,80 +79,73 @@ int internalFunc(void * callback)
int heroZ;
switch (*cn.c_str())
{
case 'P':
std::cout<<"Policzyc sciezke."<<std::endl;
readed>>src>>dst;
p = CGI->pathf->GetPath(Coordinate(src),Coordinate(dst),CGI->heroh->heroInstances[0]);
LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->ConvertToOldFormat(p);
//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
break;
case 'm': //number of heroes
std::cout<<"Number of heroes: "<<CGI->heroh->heroInstances.size()<<std::endl;
break;
case 'H': //position of hero
readed>>heronum;
#ifndef __GNUC__
std::cout<<"Position of hero "<<heronum<<": "<<CGI->heroh->heroInstances[heronum]->getPosition(false)<<std::endl;
#else
heroX = CGI->heroh->heroInstances[heronum]->getPosition(false).x;
heroY = CGI->heroh->heroInstances[heronum]->getPosition(false).y;
heroZ = CGI->heroh->heroInstances[heronum]->getPosition(false).z;
std::cout<<"Position of hero "<<heronum<<": x:"<<heroX<<"- y:"<<heroY<<"- z:"<<heroZ<<std::endl;
#endif
break;
case 'M': //move heroa
{
readed>>heronum>>dest;
const CGHeroInstance * hero = cb->getHeroInfo(0,heronum,0);
p = CGI->pathf->GetPath(Coordinate(hero->getPosition(false)),Coordinate(dest),hero);
cb->moveHero(heronum, CGI->pathf->ConvertToOldFormat(p), 0, 0);
//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
break;
}
case 'D': //pos description
readed>>src;
CGI->mh->getObjDescriptions(src);
break;
case 'I':
{
SDL_Surface * temp = LOCPLINT->infoWin(NULL);
blitAtWR(temp,605,389);
SDL_FreeSurface(temp);
break;
}
case 'T': //test rect
readed>>src;
for(int g=0; g<8; ++g)
{
for(int v=0; v<8; ++v)
{
int3 csrc = src;
csrc.y+=g;
csrc.x+=v;
if(CGI->mh->getObjDescriptions(csrc).size())
std::cout<<'x';
else
std::cout<<'o';
}
std::cout<<std::endl;
}
break;
case 'A': //hide everything from map
for(int c=0; c<CGI->objh->objInstances.size(); ++c)
{
CGI->mh->hideObject(CGI->objh->objInstances[c]);
}
break;
case 'R': //restora all objects after A has been pressed
for(int c=0; c<CGI->objh->objInstances.size(); ++c)
{
CGI->mh->printObject(CGI->objh->objInstances[c]);
}
break;
//case 'P':
// std::cout<<"Policzyc sciezke."<<std::endl;
// readed>>src>>dst;
//
// p = CGI->pathf->GetPath(Coordinate(src),Coordinate(dst),CGI->heroh->heroInstances[0]);
// LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->ConvertToOldFormat(p);
// //LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
// break;
//case 'm': //number of heroes
// std::cout<<"Number of heroes: "<<CGI->heroh->heroInstances.size()<<std::endl;
// break;
//case 'H': //position of hero
// readed>>heronum;
// std::cout<<"Position of hero "<<heronum<<": "<<CGI->heroh->heroInstances[heronum]->getPosition(false)<<std::endl;
// break;
//case 'M': //move heroa
// {
// readed>>heronum>>dest;
// const CGHeroInstance * hero = cb->getHeroInfo(0,heronum,0);
// p = CGI->pathf->GetPath(Coordinate(hero->getPosition(false)),Coordinate(dest),hero);
// cb->moveHero(heronum, CGI->pathf->ConvertToOldFormat(p), 0, 0);
// //LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
// break;
// }
//case 'D': //pos description
// readed>>src;
// CGI->mh->getObjDescriptions(src);
// break;
//case 'I':
// {
// SDL_Surface * temp = LOCPLINT->infoWin(NULL);
// blitAtWR(temp,605,389);
// SDL_FreeSurface(temp);
// break;
// }
//case 'T': //test rect
// readed>>src;
// for(int g=0; g<8; ++g)
// {
// for(int v=0; v<8; ++v)
// {
// int3 csrc = src;
// csrc.y+=g;
// csrc.x+=v;
// if(CGI->mh->getObjDescriptions(csrc).size())
// std::cout<<'x';
// else
// std::cout<<'o';
// }
// std::cout<<std::endl;
// }
// break;
//case 'A': //hide everything from map
// for(int c=0; c<CGI->objh->objInstances.size(); ++c)
// {
// CGI->mh->hideObject(CGI->objh->objInstances[c]);
// }
// break;
//case 'R': //restora all objects after A has been pressed
// for(int c=0; c<CGI->objh->objInstances.size(); ++c)
// {
// CGI->mh->printObject(CGI->objh->objInstances[c]);
// }
// break;
}
//SDL_Delay(100);
delete p;
//delete p;
}
SDL_Delay(10);
}

View File

@ -7,6 +7,8 @@ class CConsoleHandler
public:
void runConsole();
friend class CClient;
#ifndef __GNUC__
friend int _tmain(int argc, _TCHAR* argv[]);
#else

View File

@ -1,237 +1,40 @@
#include "stdafx.h"
#include "CCursorHandler.h"
#include "SDL.h"
#include "SDL_thread.h"
#include "SDL_Extensions.h"
#include "CGameInfo.h"
#include "SDL_framerate.h"
#include "hch/CLodHandler.h"
#include "hch/CDefHandler.h"
extern SDL_Surface * screen;
/* Creates a new mouse cursor from an XPM */
/* XPM */
static const char *arrow[] = { //no cursor mode
/* width height num_colors chars_per_pixel */
" 32 32 3 1",
/* colors */
"X c #000000",
". c #ffffff",
" c None",
/* pixels */
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"0,0"
};
/* XPM */
static const char *arrow2[] = { //normal cursor
/* width height num_colors chars_per_pixel */
" 32 32 3 1",
/* colors */
"X c #000000",
". c #ffffff",
" c None",
/* pixels */
"X ",
"XX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.....XXXXX ",
"X..X..X ",
"X.X X..X ",
"XX X..X ",
"X X..X ",
" X..X ",
" X..X ",
" X..X ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"0,0"
};
static SDL_Cursor *init_system_cursor(const char *image[])
{
int i, row, col;
Uint8 data[4*32];
Uint8 mask[4*32];
int hot_x, hot_y;
i = -1;
for ( row=0; row<32; ++row ) {
for ( col=0; col<32; ++col ) {
if ( col % 8 ) {
data[i] <<= 1;
mask[i] <<= 1;
} else {
++i;
data[i] = mask[i] = 0;
}
switch (image[4+row][col]) {
case 'X':
data[i] |= 0x01;
//k[i] |= 0x01;
break;
case '.':
mask[i] |= 0x01;
break;
case ' ':
break;
}
}
}
sscanf(image[4+row], "%d,%d", &hot_x, &hot_y);
return SDL_CreateCursor(data, mask, 32, 32, hot_x, hot_y);
}
//int cursorHandlerFunc(void * cursorHandler)
//{
// FPSmanager * cursorFramerateKeeper = new FPSmanager;
// SDL_initFramerate(cursorFramerateKeeper);
// SDL_setFramerate(cursorFramerateKeeper, 200);
//
// CCursorHandler * ch = (CCursorHandler *) cursorHandler;
// while(true)
// {
// if(ch->xbef!=-1 && ch->ybef!=-1) //restore surface under cursor
// {
// blitAtWR(ch->behindCur, ch->xbef, ch->ybef);
// }
// ch->xbef = ch->xpos;
// ch->ybef = ch->ypos;
// //prepare part of surface to restore
// SDL_BlitSurface(screen, &genRect(32, 32, ch->xpos, ch->ypos), ch->behindCur, NULL);
// CSDL_Ext::update(ch->behindCur);
//
// //blit cursor
// if(ch->curVisible)
// {
// switch(ch->mode)
// {
// case 0:
// {
// break;
// }
// case 1:
// {
// break;
// }
// case 2:
// {
// blitAtWR(ch->deflt->ourImages[ch->number].bitmap, ch->xpos, ch->ypos);
// break;
// }
// }
// }
// SDL_framerateDelay(cursorFramerateKeeper);
// //SDL_Delay(5); //to avoid great usage of CPU
// }
// return 0;
//}
void CCursorHandler::initCursor()
{
//#if SDL_BYTEORDER == SDL_BIG_ENDIAN
// int rmask = 0xff000000;
// int gmask = 0x00ff0000;
// int bmask = 0x0000ff00;
// int amask = 0x000000ff;
//#else
// int rmask = 0x000000ff;
// int gmask = 0x0000ff00;
// int bmask = 0x00ff0000;
// int amask = 0xff000000;
//#endif
// curVisible = true;
// xpos = ypos = 0;
// behindCur = SDL_CreateRGBSurface(SDL_SWSURFACE, 32, 32, 32, rmask, gmask, bmask, amask);
// xbef = ybef = 0;
// adventure = CGI->spriteh->giveDef("CRADVNTR.DEF");
// combat = CGI->spriteh->giveDef("CRCOMBAT.DEF");
// deflt = CGI->spriteh->giveDef("CRDEFLT.DEF");
// spell = CGI->spriteh->giveDef("CRSPELL.DEF");
// //SDL_SetCursor(init_system_cursor(arrow));
// //SDL_Thread * myth = SDL_CreateThread(&cursorHandlerFunc, this);
mode = number = xpos = ypos = 0;
help = CSDL_Ext::newSurface(32,32);
cursors.push_back(CDefHandler::giveDef("CRADVNTR.DEF"));
cursors.push_back(CDefHandler::giveDef("CRCOMBAT.DEF"));
cursors.push_back(CDefHandler::giveDef("CRDEFLT.DEF"));
cursors.push_back(CDefHandler::giveDef("CRSPELL.DEF"));
SDL_ShowCursor(SDL_DISABLE);
}
void CCursorHandler::changeGraphic(int type, int no)
{
//mode = type;
//number = no;
mode = type;
number = no;
}
void CCursorHandler::cursorMove(int x, int y)
{
//xbef = xpos;
//ybef = ypos;
//xpos = x;
//ypos = y;
xpos = x;
ypos = y;
}
void CCursorHandler::hardwareCursor()
void CCursorHandler::draw1()
{
//curVisible = false;
//SDL_SetCursor(init_system_cursor(arrow2));
SDL_BlitSurface(screen,&genRect(32,32,xpos,ypos),help,&genRect(32,32,0,0));
blitAt(cursors[mode]->ourImages[number].bitmap,xpos,ypos);
}
void CCursorHandler::hideCursor()
void CCursorHandler::draw2()
{
//curVisible = false;
//SDL_SetCursor(init_system_cursor(arrow));
blitAt(help,xpos,ypos);
}
void CCursorHandler::showGraphicCursor()
{
//curVisible = true;
//SDL_SetCursor(init_system_cursor(arrow));
//changeGraphic(0, 0);
}

View File

@ -1,6 +1,7 @@
#ifndef CCURSORHANDLER_H
#define CCURSORHANDLER_H
#include "global.h"
#include <vector>
struct SDL_Thread;
class CDefHandler;
struct SDL_Surface;
@ -8,21 +9,16 @@ struct SDL_Surface;
class CCursorHandler //handles cursor
{
public:
SDL_Thread * myThread; //thread that updates cursor
bool curVisible; //true if cursor is visible
int mode, number;
SDL_Surface * behindCur;
int xbef, ybef; //position of cursor after last move (to restore background)
SDL_Surface * help;
CDefHandler * adventure, * combat, * deflt, * spell; //read - only
int xpos, ypos; //position of cursor - read only
std::vector<CDefHandler*> cursors;
int xpos, ypos; //position of cursor
void initCursor(); //inits cursorHandler
void showGraphicCursor(); //shows default graphic cursor
void cursorMove(int x, int y); //change cursor's positions to (x, y)
void changeGraphic(int type, int no); //changes cursor graphic for type type (0 - adventure, 1 - combat, 2 - default, 3 - spellbook) and frame no (not used for type 3)
void hideCursor(); //no cursor will be visible
void hardwareCursor(); // returns to hardware cursor mode
friend int cursorHandlerFunc(void * cursorHandler);
void draw1();
void draw2();
};

View File

@ -1,4 +1,4 @@
#include "stdafx.h"
#include "CGameInfo.h"
CGameInfo * CGameInfo::mainObj;
CGameInfo * CGI;

View File

@ -1,9 +1,10 @@
#ifndef CGAMEINFO_H
#define CGAMEINFO_H
#include "global.h"
#include "StartInfo.h"
#include "SDL.h"
#include "CPreGame.h"
#include <vector>
@ -40,7 +41,6 @@ class CDefHandler;
class CGameInfo
{
public:
static CGameInfo * mainObj; //pointer to main CGameInfo object
CGameState * state;
CArtHandler * arth;
CHeroHandler * heroh;
@ -48,7 +48,6 @@ public:
CAbilityHandler * abilh;
CSpellHandler * spellh;
CMapHandler * mh;
CAmbarCendamo * ac;
CPreGameTextHandler * preth;
CBuildingHandler * buildh;
CObjectHandler * objh;
@ -63,12 +62,6 @@ public:
CPathfinder * pathf;
CCursorHandler * curh;
CScreenHandler * screenh;
int localPlayer;
std::vector<CGameInterface *> playerint;
std::vector<SDL_Color> playerColors;
std::vector<CDefHandler *> playerColorInfo; //gems from adventure map interface
SDL_Color neutralColor;
StartInfo scenarioOps;
};
#endif //CGAMEINFO_H

View File

@ -5,7 +5,6 @@
#include "mapHandler.h"
#include "SDL_Extensions.h"
#include "SDL_framerate.h"
#include "CScreenHandler.h"
#include "CCursorHandler.h"
#include "CCallback.h"
#include "SDL_Extensions.h"
@ -25,7 +24,6 @@ using namespace CSDL_Ext;
CGlobalAI * CAIHandler::getNewAI(CCallback * cb, std::string dllname)
{
std::cout << "Opening "<<dllname/*<<" for player "<< cb->player*/<<std::endl;
dllname = "AI/"+dllname;
CGlobalAI * ret=NULL;
CGlobalAI*(*getAI)();

View File

@ -3,6 +3,7 @@
#include "global.h"
#include <set>
#include <vector>
#include "lib/BattleAction.h"
BOOST_TRIBOOL_THIRD_STATE(outOfRange)
using namespace boost::logic;
@ -10,6 +11,7 @@ class CCallback;
class ICallback;
class CGlobalAI;
class CGHeroInstance;
class Component;
class CSelectableComponent;
struct HeroMoveDetails;
class CGHeroInstance;
@ -17,21 +19,13 @@ class CGTownInstance;
class CGObjectInstance;
class CCreatureSet;
class CArmedInstance;
struct BattleResult;
class CObstacle
{
int ID;
int position;
//TODO: add some kind of the blockmap
};
struct BattleAction
{
bool side; //who made this action: false - left, true - right player
int stackNumber;//stack ID, -1 left hero, -2 right hero,
int actionType; // 0 = Cancel BattleAction 1 = Hero cast a spell 2 = Walk 3 = Defend 4 = Retreat from the battle 5 = Surrender 6 = Walk and Attack 7 = Shoot 8 = Wait 9 = Catapult 10 = Monster casts a spell (i.e. Faerie Dragons)
int destinationTile;
int additionalInfo; // e.g. spell number if type is 1 || 10
};
struct StackState
{
@ -59,17 +53,18 @@ public:
virtual void tileRevealed(int3 pos){};
virtual void tileHidden(int3 pos){};
virtual void receivedResource(int type, int val){};
virtual void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID){};
virtual void showInfoDialog(std::string text, std::vector<Component*> &components){};
virtual void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID)=0;
virtual void garrisonChanged(const CGObjectInstance * obj){};
virtual void buildChanged(const CGTownInstance *town, int buildingID, int what){}; //what: 1 - built, 2 - demolished
//battle call-ins
virtual void battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side){}; //called by engine when battle starts; side=0 - left, side=1 - right
virtual void battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side){}; //called by engine when battle starts; side=0 - left, side=1 - right
virtual void battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles){}; //called when battlefield is prepared, prior the battle beginning
virtual void battleNewRound(int round){}; //called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
virtual void actionStarted(BattleAction action){};//occurs BEFORE every action taken by any stack or by the hero
virtual void actionFinished(BattleAction action){};//occurs AFTER every action taken by any stack or by the hero
virtual BattleAction activeStack(int stackID)=0; //called when it's turn of that stack
virtual void battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner){};
virtual void battleEnd(BattleResult *br){};
virtual void battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)=0;
virtual void battleStackAttacking(int ID, int dest)=0;
virtual void battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting)=0;

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,12 @@
#ifndef CGAMESTATE_H
#define CGAMESTATE_H
#include "mapHandler.h"
#include "global.h"
#ifndef _MSC_VER
#include "../hch/CCreatureHandler.h"
#include "lib/VCMI_Lib.h"
#endif
#include <set>
#include <vector>
#ifdef _WIN32
#include <tchar.h>
#else
@ -16,88 +20,117 @@ class CCPPObjectScript;
class CCreatureSet;
class CStack;
class CGHeroInstance;
class CGTownInstance;
class CArmedInstance;
class CGDefInfo;
class CObjectScript;
class CGObjectInstance;
class CCreature;
struct Mapa;
struct StartInfo;
struct SDL_Surface;
class CMapHandler;
class CPathfinder;
struct IPack;
struct PlayerState
namespace boost
{
class shared_mutex;
}
struct DLL_EXPORT PlayerState
{
public:
int color, serial;
//std::vector<std::vector<std::vector<char> > > fogOfWarMap; //true - visible, false - hidden
PseudoV< PseudoV< PseudoV<unsigned char> > > fogOfWarMap; //true - visible, false - hidden
std::vector<int> resources;
ui8 color, serial;
std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
std::vector<si32> resources;
std::vector<CGHeroInstance *> heroes;
std::vector<CGTownInstance *> towns;
PlayerState():color(-1){};
};
struct BattleInfo
struct DLL_EXPORT BattleInfo
{
int side1, side2;
int round, activeStack;
int siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
ui8 side1, side2;
si32 round, activeStack;
ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
int3 tile; //for background and bonuses
CGHeroInstance *hero1, *hero2;
CCreatureSet * army1, * army2;
si32 hero1, hero2;
CCreatureSet army1, army2;
std::vector<CStack*> stacks;
bool stackActionPerformed; //true if current stack has been moved
template <typename Handler> void serialize(Handler &h, const int version)
{
h & side1 & side2 & round & activeStack & siege & tile & stacks & army1 & army2 & hero1 & hero2;
}
CStack * getStack(int stackID);
CStack * getStackT(int tileID);
void getAccessibilityMap(bool *accessibility); //send pointer to at least 187 allocated bytes
void getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide); //send pointer to at least 187 allocated bytes
void makeBFS(int start, bool*accessibility, int *predecessor, int *dists); //*accessibility must be prepared bool[187] array; last two pointers must point to the at least 187-elements int arrays - there is written result
std::vector<int> getPath(int start, int dest, bool*accessibility);
std::vector<int> getAccessibility(int stackID); //returns vector of accessible tiles (taking into account the creature range)
};
class CStack
class DLL_EXPORT CStack
{
public:
int ID; //unique ID of stack
ui32 ID; //unique ID of stack
CCreature * creature;
int amount;
int firstHPleft; //HP of first creature in stack
unsigned char owner;
bool attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
int position; //position on battlefield
bool alive; //true if it is alive
CStack(CCreature * C, int A, unsigned char O, int I, bool AO):creature(C),amount(A),owner(O), alive(true), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints){};
ui32 amount;
ui32 firstHPleft; //HP of first creature in stack
ui8 owner;
ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
ui16 position; //position on battlefield
ui8 alive; //true if it is alive
CStack(CCreature * C, int A, int O, int I, bool AO);
CStack() : creature(NULL),amount(-1),owner(255), alive(true), position(-1), ID(-1), attackerOwned(true), firstHPleft(-1){};
template <typename Handler> void save(Handler &h, const int version)
{
h & creature->idNumber;
}
template <typename Handler> void load(Handler &h, const int version)
{
ui32 id;
h & id;
creature = &VLC->creh->creatures[id];
}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & ID & amount & firstHPleft & owner & attackerOwned & position & alive;
if(h.saving)
save(h,version);
else
load(h,version);
}
};
class CGameState
class DLL_EXPORT CGameState
{
private:
int currentPlayer;
StartInfo* scenarioOps;
ui32 seed;
ui8 currentPlayer; //ID of player currently having turn
BattleInfo *curB; //current battle
int day; //total number of days in game
std::map<int,PlayerState> players; //color <-> playerstate
std::set<CCPPObjectScript *> cppscripts;
std::map<int, std::map<std::string, CObjectScript*> > objscr; //custom user scripts (as for now only Lua)
ui32 day; //total number of days in game
Mapa * map;
std::map<ui8,PlayerState> players; //ID <-> playerstate
std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
boost::shared_mutex *mx;
CGameState();
~CGameState();
void init(StartInfo * si, Mapa * map, int Seed);
void apply(IPack * pack);
void randomizeObject(CGObjectInstance *cur);
std::pair<int,int> pickObject(CGObjectInstance *obj);
int pickHero(int owner);
CGHeroInstance *getHero(int objid);
bool checkFunc(int obid, std::string name)
{
if (objscr.find(obid)!=objscr.end())
{
if(objscr[obid].find(name)!=objscr[obid].end())
{
return true;
}
}
return false;
}
CGHeroInstance * getHero(int ID, int mode)
{
if (mode != 0)
#ifndef __GNUC__
throw new std::exception("gs->getHero: This mode is not supported!");
#else
throw new std::exception();
#endif
for ( std::map<int, PlayerState>::iterator i=players.begin() ; i!=players.end();i++)
{
for (int j=0;j<(*i).second.heroes.size();j++)
{
if (i->second.heroes[j]->subID == ID)
return i->second.heroes[j];
}
}
return NULL;
}
void battle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CArmedInstance *hero1, CArmedInstance *hero2);
bool battleMoveCreatureStack(int ID, int dest);
bool battleAttackCreatureStack(int ID, int dest);
bool battleShootCreatureStack(int ID, int dest);
@ -105,20 +138,16 @@ private:
static int calculateDmg(const CStack* attacker, const CStack* defender); //TODO: add additional conditions and require necessary data
std::vector<int> battleGetRange(int ID); //called by std::vector<int> CCallback::battleGetAvailableHexes(int ID);
public:
int getDate(int mode=0) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
friend class CCallback;
friend class CPathfinder;;
friend class CLuaCallback;
#ifndef __GNUC__
friend int _tmain(int argc, _TCHAR* argv[]);
#else
friend int main(int argc, _TCHAR* argv[]);
#endif
friend void initGameState(CGameInfo * cgi);
friend class CClient;
friend void initGameState(Mapa * map, CGameInfo * cgi);
friend class CScriptCallback;
friend void handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script);
//CCallback * cb; //for communication between PlayerInterface/AI and GameState
friend SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, unsigned char anim, PseudoV< PseudoV< PseudoV<unsigned char> > > & visibilityMap, bool otherHeroAnim, unsigned char heroAnim, SDL_Surface * extSurf, SDL_Rect * extRect); //todo: wywalic koniecznie, tylko do flag obecnie!!!!
friend class CMapHandler;
friend class CGameHandler;
};
#endif //CGAMESTATE_H

View File

@ -12,8 +12,12 @@
#include "hch/CObjectHandler.h"
#include "CMessage.h"
#include "CCallback.h"
#include "hch/CArtHandler.h"
#include "hch/CAbilityHandler.h"
#include "hch/CDefHandler.h"
#include "client/CBitmapHandler.h"
#include <sstream>
#include "client/Graphics.h"
extern SDL_Surface * screen;
extern TTF_Font * GEOR16;
@ -21,8 +25,8 @@ CHeroWindow::CHeroWindow(int playerColor):
backpackPos(0), player(playerColor)
{
artWorn.resize(19);
background = CGI->bitmaph->loadBitmap("HEROSCR4.bmp");
CSDL_Ext::blueToPlayersAdv(background, playerColor);
background = BitmapHandler::loadBitmap("HEROSCR4.bmp");
graphics->blueToPlayersAdv(background, playerColor);
pos.x = 65;
pos.y = 8;
pos.h = background->h;
@ -58,8 +62,8 @@ CHeroWindow::CHeroWindow(int playerColor):
heroListMi[g]->id = g;
}
skillpics = CGI->spriteh->giveDef("pskil42.def");
flags = CGI->spriteh->giveDef("CREST58.DEF");
skillpics = CDefHandler::giveDef("pskil42.def");
flags = CDefHandler::giveDef("CREST58.DEF");
//areas
portraitArea = new LRClickableAreaWText();
portraitArea->pos.x = 83;
@ -181,8 +185,9 @@ void CHeroWindow::show(SDL_Surface *to)
}
}
void CHeroWindow::setHero(const CGHeroInstance *hero)
void CHeroWindow::setHero(const CGHeroInstance *Hero)
{
CGHeroInstance *hero = const_cast<CGHeroInstance*>(Hero); //but don't modify hero! - it's only for easy map reading
if(!hero) //something strange... no hero? it shouldn't happen
{
return;
@ -256,210 +261,210 @@ void CHeroWindow::setHero(const CGHeroInstance *hero)
}
backpack.clear();
artWorn[8] = new CArtPlace(hero->artifWorn[8]);
artWorn[8] = new CArtPlace(hero->getArt(8));
artWorn[8]->pos.x = 515;
artWorn[8]->pos.y = 295;
artWorn[8]->pos.h = artWorn[8]->pos.w = 44;
if(hero->artifWorn[8])
artWorn[8]->text = hero->artifWorn[8]->description;
if(hero->getArt(8))
artWorn[8]->text = hero->getArt(8)->description;
else
artWorn[8]->text = std::string();
artWorn[8]->ourWindow = this;
artWorn[8]->feet = true;
artWorn[0] = new CArtPlace(hero->artifWorn[0]);
artWorn[0] = new CArtPlace(hero->getArt(0));
artWorn[0]->pos.x = 509;
artWorn[0]->pos.y = 30;
artWorn[0]->pos.h = artWorn[0]->pos.w = 44;
if(hero->artifWorn[0])
artWorn[0]->text = hero->artifWorn[0]->description;
if(hero->getArt(0))
artWorn[0]->text = hero->getArt(0)->description;
else
artWorn[0]->text = std::string();
artWorn[0]->ourWindow = this;
artWorn[0]->head = true;
artWorn[4] = new CArtPlace(hero->artifWorn[4]);
artWorn[4] = new CArtPlace(hero->getArt(4));
artWorn[4]->pos.x = 564;
artWorn[4]->pos.y = 183;
artWorn[4]->pos.h = artWorn[4]->pos.w = 44;
if(hero->artifWorn[4])
artWorn[4]->text = hero->artifWorn[4]->description;
if(hero->getArt(4))
artWorn[4]->text = hero->getArt(4)->description;
else
artWorn[4]->text = std::string();
artWorn[4]->ourWindow = this;
artWorn[4]->lHand = true;
artWorn[7] = new CArtPlace(hero->artifWorn[7]);
artWorn[7] = new CArtPlace(hero->getArt(7));
artWorn[7]->pos.x = 610;
artWorn[7]->pos.y = 183;
artWorn[7]->pos.h = artWorn[7]->pos.w = 44;
if(hero->artifWorn[7])
artWorn[7]->text = hero->artifWorn[7]->description;
if(hero->getArt(7))
artWorn[7]->text = hero->getArt(7)->description;
else
artWorn[7]->text = std::string();
artWorn[7]->ourWindow = this;
artWorn[7]->lRing = true;
artWorn[13] = new CArtPlace(hero->artifWorn[13]);
artWorn[13] = new CArtPlace(hero->getArt(13));
artWorn[13]->pos.x = 564;
artWorn[13]->pos.y = 30;
artWorn[13]->pos.h = artWorn[13]->pos.w = 44;
if(hero->artifWorn[13])
artWorn[13]->text = hero->artifWorn[13]->description;
if(hero->getArt(13))
artWorn[13]->text = hero->getArt(13)->description;
else
artWorn[13]->text = std::string();
artWorn[13]->ourWindow = this;
artWorn[13]->warMachine1 = true;
artWorn[14] = new CArtPlace(hero->artifWorn[14]);
artWorn[14] = new CArtPlace(hero->getArt(14));
artWorn[14]->pos.x = 610;
artWorn[14]->pos.y = 30;
artWorn[14]->pos.h = artWorn[14]->pos.w = 44;
if(hero->artifWorn[14])
artWorn[14]->text = hero->artifWorn[14]->description;
if(hero->getArt(14))
artWorn[14]->text = hero->getArt(14)->description;
else
artWorn[14]->text = std::string();
artWorn[14]->ourWindow = this;
artWorn[14]->warMachine2 = true;
artWorn[15] = new CArtPlace(hero->artifWorn[15]);
artWorn[15] = new CArtPlace(hero->getArt(15));
artWorn[15]->pos.x = 610;
artWorn[15]->pos.y = 76;
artWorn[15]->pos.h = artWorn[15]->pos.w = 44;
if(hero->artifWorn[15])
artWorn[15]->text = hero->artifWorn[15]->description;
if(hero->getArt(15))
artWorn[15]->text = hero->getArt(15)->description;
else
artWorn[15]->text = std::string();
artWorn[15]->ourWindow = this;
artWorn[15]->warMachine3 = true;
artWorn[16] = new CArtPlace(hero->artifWorn[16]);
artWorn[16] = new CArtPlace(hero->getArt(16));
artWorn[16]->pos.x = 610;
artWorn[16]->pos.y = 122;
artWorn[16]->pos.h = artWorn[16]->pos.w = 44;
if(hero->artifWorn[16])
artWorn[16]->text = hero->artifWorn[16]->description;
if(hero->getArt(16))
artWorn[16]->text = hero->getArt(16)->description;
else
artWorn[16]->text = std::string();
artWorn[16]->ourWindow = this;
artWorn[16]->warMachine4 = true;
artWorn[9] = new CArtPlace(hero->artifWorn[9]);
artWorn[9] = new CArtPlace(hero->getArt(9));
artWorn[9]->pos.x = 383;
artWorn[9]->pos.y = 143;
artWorn[9]->pos.h = artWorn[9]->pos.w = 44;
if(hero->artifWorn[9])
artWorn[9]->text = hero->artifWorn[9]->description;
if(hero->getArt(9))
artWorn[9]->text = hero->getArt(9)->description;
else
artWorn[9]->text = std::string();
artWorn[9]->ourWindow = this;
artWorn[9]->misc1 = true;
artWorn[10] = new CArtPlace(hero->artifWorn[10]);
artWorn[10] = new CArtPlace(hero->getArt(10));
artWorn[10]->pos.x = 399;
artWorn[10]->pos.y = 194;
artWorn[10]->pos.h = artWorn[10]->pos.w = 44;
if(hero->artifWorn[10])
artWorn[10]->text = hero->artifWorn[10]->description;
if(hero->getArt(10))
artWorn[10]->text = hero->getArt(10)->description;
else
artWorn[10]->text = std::string();
artWorn[10]->ourWindow = this;
artWorn[10]->misc1 = true;
artWorn[11] = new CArtPlace(hero->artifWorn[11]);
artWorn[11] = new CArtPlace(hero->getArt(11));
artWorn[11]->pos.x = 415;
artWorn[11]->pos.y = 245;
artWorn[11]->pos.h = artWorn[11]->pos.w = 44;
if(hero->artifWorn[11])
artWorn[11]->text = hero->artifWorn[11]->description;
if(hero->getArt(11))
artWorn[11]->text = hero->getArt(11)->description;
else
artWorn[11]->text = std::string();
artWorn[11]->ourWindow = this;
artWorn[11]->misc3 = true;
artWorn[12] = new CArtPlace(hero->artifWorn[12]);
artWorn[12] = new CArtPlace(hero->getArt(12));
artWorn[12]->pos.x = 431;
artWorn[12]->pos.y = 296;
artWorn[12]->pos.h = artWorn[12]->pos.w = 44;
if(hero->artifWorn[12])
artWorn[12]->text = hero->artifWorn[12]->description;
if(hero->getArt(12))
artWorn[12]->text = hero->getArt(12)->description;
else
artWorn[12]->text = std::string();
artWorn[12]->ourWindow = this;
artWorn[12]->misc4 = true;
artWorn[18] = new CArtPlace(hero->artifWorn[18]);
artWorn[18] = new CArtPlace(hero->getArt(18));
artWorn[18]->pos.x = 381;
artWorn[18]->pos.y = 296;
artWorn[18]->pos.h = artWorn[18]->pos.w = 44;
if(hero->artifWorn[18])
artWorn[18]->text = hero->artifWorn[18]->description;
if(hero->getArt(18))
artWorn[18]->text = hero->getArt(18)->description;
else
artWorn[18]->text = std::string();
artWorn[18]->ourWindow = this;
artWorn[18]->misc5 = true;
artWorn[2] = new CArtPlace(hero->artifWorn[2]);
artWorn[2] = new CArtPlace(hero->getArt(2));
artWorn[2]->pos.x = 508;
artWorn[2]->pos.y = 79;
artWorn[2]->pos.h = artWorn[2]->pos.w = 44;
if(hero->artifWorn[2])
artWorn[2]->text = hero->artifWorn[2]->description;
if(hero->getArt(2))
artWorn[2]->text = hero->getArt(2)->description;
else
artWorn[2]->text = std::string();
artWorn[2]->ourWindow = this;
artWorn[2]->neck = true;
artWorn[3] = new CArtPlace(hero->artifWorn[3]);
artWorn[3] = new CArtPlace(hero->getArt(3));
artWorn[3]->pos.x = 383;
artWorn[3]->pos.y = 68;
artWorn[3]->pos.h = artWorn[3]->pos.w = 44;
if(hero->artifWorn[3])
artWorn[3]->text = hero->artifWorn[3]->description;
if(hero->getArt(3))
artWorn[3]->text = hero->getArt(3)->description;
else
artWorn[3]->text = std::string();
artWorn[3]->ourWindow = this;
artWorn[3]->rHand = true;
artWorn[6] = new CArtPlace(hero->artifWorn[6]);
artWorn[6] = new CArtPlace(hero->getArt(6));
artWorn[6]->pos.x = 431;
artWorn[6]->pos.y = 68;
artWorn[6]->pos.h = artWorn[6]->pos.w = 44;
if(hero->artifWorn[6])
artWorn[6]->text = hero->artifWorn[6]->description;
if(hero->getArt(6))
artWorn[6]->text = hero->getArt(6)->description;
else
artWorn[6]->text = std::string();
artWorn[6]->ourWindow = this;
artWorn[6]->rRing = true;
artWorn[1] = new CArtPlace(hero->artifWorn[1]);
artWorn[1] = new CArtPlace(hero->getArt(1));
artWorn[1]->pos.x = 567;
artWorn[1]->pos.y = 240;
artWorn[1]->pos.h = artWorn[1]->pos.w = 44;
if(hero->artifWorn[1])
artWorn[1]->text = hero->artifWorn[1]->description;
if(hero->getArt(1))
artWorn[1]->text = hero->getArt(1)->description;
else
artWorn[1]->text = std::string();
artWorn[1]->ourWindow = this;
artWorn[1]->shoulders = true;
artWorn[17] = new CArtPlace(hero->artifWorn[17]);
artWorn[17] = new CArtPlace(hero->getArt(17));
artWorn[17]->pos.x = 610;
artWorn[17]->pos.y = 310;
artWorn[17]->pos.h = artWorn[17]->pos.w = 44;
if(hero->artifWorn[17])
artWorn[17]->text = hero->artifWorn[17]->description;
if(hero->getArt(17))
artWorn[17]->text = hero->getArt(17)->description;
else
artWorn[17]->text = std::string();
artWorn[17]->ourWindow = this;
artWorn[17]->spellBook = true;
artWorn[5] = new CArtPlace(hero->artifWorn[5]);
artWorn[5] = new CArtPlace(hero->getArt(5));
artWorn[5]->pos.x = 509;
artWorn[5]->pos.y = 130;
artWorn[5]->pos.h = artWorn[5]->pos.w = 44;
if(hero->artifWorn[5])
artWorn[5]->text = hero->artifWorn[5]->description;
if(hero->getArt(5))
artWorn[5]->text = hero->getArt(5)->description;
else
artWorn[5]->text = std::string();
artWorn[5]->ourWindow = this;
@ -479,14 +484,14 @@ void CHeroWindow::setHero(const CGHeroInstance *hero)
{
CArtPlace * add;
if( s < curHero->artifacts.size() )
add = new CArtPlace(curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]);
add = new CArtPlace(&CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]]);
else
add = new CArtPlace(NULL);
add->pos.x = 403 + 46*s;
add->pos.y = 365;
add->pos.h = add->pos.w = 44;
if(s<hero->artifacts.size() && hero->artifacts[s])
add->text = hero->artifacts[s]->description;
add->text = hero->getArt(s)->description;
else
add->text = std::string();
add->ourWindow = this;
@ -676,7 +681,7 @@ void CHeroWindow::leftArtRoller()
for(int s=0; s<5 && s<curHero->artifacts.size(); ++s) //set new data
{
backpack[s]->ourArt = curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ];
backpack[s]->ourArt = &CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]];
if(backpack[s]->ourArt)
backpack[s]->text = backpack[s]->ourArt->description;
else
@ -693,7 +698,7 @@ void CHeroWindow::rightArtRoller()
for(int s=0; s<5 && s<curHero->artifacts.size(); ++s) //set new data
{
backpack[s]->ourArt = curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ];
backpack[s]->ourArt = &CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ] ];
if(backpack[s]->ourArt)
backpack[s]->text = backpack[s]->ourArt->description;
else
@ -731,7 +736,7 @@ void CHeroWindow::redrawCurBack()
blitAt(skillpics->ourImages[4].bitmap, 20, 230, curBack);
blitAt(skillpics->ourImages[3].bitmap, 162, 230, curBack);
blitAt(CGI->heroh->largePortraits[curHero->portrait], 19, 19, curBack);
blitAt(graphics->portraitLarge[curHero->portrait], 19, 19, curBack);
CSDL_Ext::printAtMiddle(curHero->name, 190, 40, GEORXX, tytulowy, curBack);
@ -787,8 +792,8 @@ void CHeroWindow::redrawCurBack()
primarySkill4<<curHero->primSkills[3];
CSDL_Ext::printAtMiddle(primarySkill4.str(), 263, 165, TNRB16, zwykly, curBack);
blitAt(LOCPLINT->luck42->ourImages[curHero->getCurrentLuck()+3].bitmap, 239, 182, curBack);
blitAt(LOCPLINT->morale42->ourImages[curHero->getCurrentMorale()+3].bitmap, 181, 182, curBack);
blitAt(graphics->luck42->ourImages[curHero->getCurrentLuck()+3].bitmap, 239, 182, curBack);
blitAt(graphics->morale42->ourImages[curHero->getCurrentMorale()+3].bitmap, 181, 182, curBack);
blitAt(flags->ourImages[player].bitmap, 606, 8, curBack);
@ -796,14 +801,14 @@ void CHeroWindow::redrawCurBack()
for(int g=0; g<LOCPLINT->cb->howManyHeroes(); ++g)
{
const CGHeroInstance * cur = LOCPLINT->cb->getHeroInfo(player, g, false);
blitAt(CGI->heroh->smallPortraits[cur->portrait], 611, 87+g*54, curBack);
blitAt(graphics->portraitSmall[cur->portrait], 611, 87+g*54, curBack);
//printing yellow border
if(cur->name == curHero->name)
{
for(int f=0; f<CGI->heroh->smallPortraits[cur->portrait]->w; ++f)
for(int f=0; f<graphics->portraitSmall[cur->portrait]->w; ++f)
{
for(int h=0; h<CGI->heroh->smallPortraits[cur->portrait]->h; ++h)
if(f==0 || h==0 || f==CGI->heroh->smallPortraits[cur->portrait]->w-1 || h==CGI->heroh->smallPortraits[cur->portrait]->h-1)
for(int h=0; h<graphics->portraitSmall[cur->portrait]->h; ++h)
if(f==0 || h==0 || f==graphics->portraitSmall[cur->portrait]->w-1 || h==graphics->portraitSmall[cur->portrait]->h-1)
{
CSDL_Ext::SDL_PutPixel(curBack, 611+f, 87+g*54+h, 240, 220, 120);
}
@ -862,7 +867,7 @@ void CHeroWindow::redrawCurBack()
}
//printing special ability
blitAt(CGI->heroh->un44->ourImages[curHero->subID].bitmap, 18, 180, curBack);
blitAt(graphics->un44->ourImages[curHero->subID].bitmap, 18, 180, curBack);
//printing necessery texts
CSDL_Ext::printAt(CGI->generaltexth->jktexts[6].substr(1, CGI->generaltexth->jktexts[6].size()-2), 69, 231, GEOR13, tytulowy, curBack);
@ -875,7 +880,7 @@ void CHeroWindow::redrawCurBack()
CSDL_Ext::printAt(manastr.str(), 212, 247, GEOR16, zwykly, curBack);
}
CArtPlace::CArtPlace(const CArtifact * const & art): ourArt(art), active(false), clicked(false),
CArtPlace::CArtPlace(const CArtifact* Art): ourArt(Art), active(false), clicked(false),
spellBook(false), warMachine1(false), warMachine2(false), warMachine3(false),
warMachine4(false),misc1(false), misc2(false), misc3(false), misc4(false),
misc5(false), feet(false), lRing(false), rRing(false), torso(false),
@ -978,7 +983,7 @@ void CArtPlace::show(SDL_Surface *to)
{
if(ourArt)
{
blitAt(CGI->arth->artDefs->ourImages[ourArt->id].bitmap, pos.x, pos.y, to);
blitAt(graphics->artDefs->ourImages[ourArt->id].bitmap, pos.x, pos.y, to);
}
if(clicked && active)
{
@ -1028,14 +1033,14 @@ void LClickableArea::deactivate()
}
void LClickableArea::clickLeft(boost::logic::tribool down)
{
if(!down)
{
#if !defined(__amigaos4__) && !defined(__unix__)
LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
#else
#warning error here!
#endif
}
//if(!down)
//{
// LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
//}
}
void RClickableArea::activate()
@ -1048,14 +1053,14 @@ void RClickableArea::deactivate()
}
void RClickableArea::clickRight(boost::logic::tribool down)
{
if(!down)
{
#if !defined(__amigaos4__) && !defined(__unix__)
LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
#else
#warning error here!
#endif
}
//if(!down)
//{
// LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
//}
}
void LRClickableAreaWText::clickLeft(boost::logic::tribool down)

View File

@ -70,7 +70,7 @@ public:
bool clicked;
CHeroWindow * ourWindow;
const CArtifact * ourArt;
CArtPlace(const CArtifact * const & art);
CArtPlace(const CArtifact * Art);
void clickLeft (tribool down);
void clickRight (tribool down);
void activate();
@ -117,7 +117,7 @@ public:
int player;
CHeroWindow(int playerColor); //c-tor
~CHeroWindow(); //d-tor
void setHero(const CGHeroInstance * hero); //sets main displayed hero
void setHero(const CGHeroInstance * Hero); //sets main displayed hero
void activate(); //activates hero window;
void deactivate(); //activates hero window;
virtual void show(SDL_Surface * to = NULL); //shows hero window

732
CLua.cpp
View File

@ -1,42 +1,33 @@
#include "stdafx.h"
#include "CLua.h"
#include "CLuaHandler.h"
#include "hch/CHeroHandler.h"
#ifndef _MSC_VER
extern "C" {
#endif
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lobject.h"
#include "lgc.h"
#include "lapi.h"
#ifndef _MSC_VER
}
#endif
#include "CGameInfo.h"
#include "CGameState.h"
#include <sstream>
#include "hch/CObjectHandler.h"
#include "hch/CTownHandler.h"
#include "CCallback.h"
#include "hch/CGeneralTextHandler.h"
#include <sstream>
#include "CPlayerInterface.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "hch/CHeroHandler.h"
#include "hch/CObjectHandler.h"
#include "hch/CTownHandler.h"
#include "hch/CArtHandler.h"
#include "hch/CDefObjInfoHandler.h"
//#include "lua.h"
//#include "lualib.h"
//#include "lauxlib.h"
//#include "lobject.h"
//#include "lgc.h"
//#include "lapi.h"
#include "CLua.h"
#include "CGameState.h"
#include "lib/VCMI_Lib.h"
#include "map.h"
#include "server/CScriptCallback.h"
#include "lib/NetPacks.h"
#pragma warning (disable : 4311)
#define DEFOS const CGObjectInstance *os = cb->getObj(objid)
bool getGlobalFunc(lua_State * L, std::string fname)
{
unsigned int hash = lua_calchash(fname.c_str(), fname.size());
lua_pushhstring(L, hash, fname.c_str(), fname.size());
lua_gettable(L, LUA_GLOBALSINDEX);
return lua_isfunction(L, -1);
//unsigned int hash = lua_calchash(fname.c_str(), fname.size());
//lua_pushhstring(L, hash, fname.c_str(), fname.size());
//lua_gettable(L, LUA_GLOBALSINDEX);
//return lua_isfunction(L, -1);
return false;
}
CObjectScript::CObjectScript()
@ -72,24 +63,20 @@ CLua::CLua()
}
void CLua::open(std::string initpath)
{
LST = lua_open();
opened = true;
LUA_OPEN_LIB(LST, luaopen_base);
LUA_OPEN_LIB(LST, luaopen_io);
if ((luaL_loadfile (LST, initpath.c_str())) == 0)
{
lua_pcall (LST, 0, LUA_MULTRET, 0);
}
else
{
#ifndef __GNUC__
std::string temp = "Cannot open script ";
temp += initpath;
throw std::exception(temp.c_str());
#else
throw std::exception();
#endif
}
//LST = lua_open();
//opened = true;
//LUA_OPEN_LIB(LST, luaopen_base);
//LUA_OPEN_LIB(LST, luaopen_io);
//if ((luaL_loadfile (LST, initpath.c_str())) == 0)
//{
// lua_pcall (LST, 0, LUA_MULTRET, 0);
//}
//else
//{
// std::string temp = "Cannot open script ";
// temp += initpath;
// throw std::exception(temp.c_str());
//}
}
void CLua::registerCLuaCallback()
{
@ -97,35 +84,31 @@ void CLua::registerCLuaCallback()
CLua::~CLua()
{
//std::cout << "Usuwam obiekt clua "<<this<<std::endl;
if (opened)
{
std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<std::endl;
lua_close(LST);
}
////std::cout << "Usuwam obiekt clua "<<this<<std::endl;
//if (opened)
//{
// std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<std::endl;
// lua_close(LST);
//}
}
void CLua::findF(std::string fname)
{
lua_getfield(is, LUA_GLOBALSINDEX, fname.c_str()); /* function to be called */
// lua_getfield(is, LUA_GLOBALSINDEX, fname.c_str()); /* function to be called */
}
void CLua::findF2(std::string fname)
{
lua_pushstring (is, fname.c_str());
lua_gettable (is, LUA_GLOBALSINDEX);
//lua_pushstring (is, fname.c_str());
//lua_gettable (is, LUA_GLOBALSINDEX);
}
void CLua::findFS(std::string fname)
{
lua_settop(is, 0);
if (!getGlobalFunc(is,fname))
{
lua_settop(is, 0);
#ifndef __GNUC__
throw new std::exception((fname + ": function not defined").c_str()); // the call is not defined
#else
throw std::exception();
#endif
}
//lua_settop(is, 0);
//if (!getGlobalFunc(is,fname))
//{
// lua_settop(is, 0);
// throw new std::exception((fname + ": function not defined").c_str()); // the call is not defined
//}
}
#undef LST
@ -152,79 +135,102 @@ std::string CLuaObjectScript::genFN(std::string base, int ID)
return sts.str();
}
void CLuaObjectScript::newObject(CGObjectInstance *os)
void CLuaObjectScript::newObject(int objid)
{
findF(genFN("newObject",os->ID));
lua_pushinteger(is, (int)os);
if (lua_pcall (is, 1, 0, 0))
{
lua_settop(is, 0);
#ifndef __GNUC__
throw new std::exception(("Failed to call "+genFN("newObject",os->ID)+" function in lua script.").c_str());
#else
throw std::exception();
#endif
}
lua_settop(is, 0);
//findF(genFN("newObject",os->ID));
//lua_pushinteger(is, (int)os);
//if (lua_pcall (is, 1, 0, 0))
//{
// lua_settop(is, 0);
// throw new std::exception(("Failed to call "+genFN("newObject",os->ID)+" function in lua script.").c_str());
//}
//lua_settop(is, 0);
return;
}
void CLuaObjectScript::onHeroVisit(CGObjectInstance *os, int heroID)
void CLuaObjectScript::onHeroVisit(int objid, int heroID)
{
findF(genFN("heroVisit",os->ID));
lua_pushinteger(is, (int)os);
lua_pushinteger(is, heroID);
if (lua_pcall (is, 2, 0, 0))
{
lua_settop(is, 0);
#ifndef __GNUC__
throw new std::exception(("Failed to call "+genFN("heroVisit",os->ID)+" function in lua script.").c_str());
#else
throw std::exception();
#endif
}
lua_settop(is, 0);
}
std::string CLuaObjectScript::hoverText(CGObjectInstance *os)
{
findF(genFN("hoverText",os->ID));
lua_pushinteger(is, (int)os);
if (lua_pcall (is, 1, 1, 0))
{
lua_settop(is, 0);
#ifndef __GNUC__
throw new std::exception(("Failed to call "+genFN("hoverText",os->ID)+" function in lua script.").c_str());
#else
throw std::exception();
#endif
}
std::string ret = lua_tostring(is,1);
lua_settop(is, 0);
return ret;
//findF(genFN("heroVisit",os->ID));
//lua_pushinteger(is, (int)os);
//lua_pushinteger(is, heroID);
//if (lua_pcall (is, 2, 0, 0))
//{
// lua_settop(is, 0);
// throw new std::exception(("Failed to call "+genFN("heroVisit",os->ID)+" function in lua script.").c_str());
//}
//lua_settop(is, 0);
}
//std::string CLuaObjectScript::hoverText(int objid)
//{
// //findF(genFN("hoverText",os->ID));
// //lua_pushinteger(is, (int)os);
// //if (lua_pcall (is, 1, 1, 0))
// //{
// // lua_settop(is, 0);
// // throw new std::exception(("Failed to call "+genFN("hoverText",os->ID)+" function in lua script.").c_str());
// //}
// //std::string ret = lua_tostring(is,1);
// //lua_settop(is, 0);
// return "";
//}
std::string CCPPObjectScript::hoverText(CGObjectInstance *os)
{
return CGI->objh->objects[os->defInfo->id].name;
}
void CVisitableOPH::newObject(CGObjectInstance *os)
void CVisitableOPH::newObject(int objid)
{
visitors.insert
(std::pair<CGObjectInstance*,std::set<int> >(os,std::set<int>()));
(std::pair<int,std::set<int> >(objid,std::set<int>()));
DEFOS;
MetaString hovername;
int pom;
switch(os->ID)
{
case 51:
pom = 8;
break;
case 23:
pom = 7;
break;
case 61:
pom = 11;
break;
case 32:
pom = 4;
break;
case 100:
pom = 5;
break;
default:
#ifndef __GNUC__
throw new std::exception("Unsupported ID in CVisitableOPH::hoverText");
#else
throw new std::exception();
#endif
}
hovername << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(2,pom);
cb->setHoverName(objid,&hovername);
//int heroID = cb->getSelectedHero();
//if (heroID>=0)
//{
//add += ( (visitors[os].find(heroID) == visitors[os].end())
// ?
// (VLC->generaltexth->allTexts[353]) //not visited
// :
// ( VLC->generaltexth->allTexts[352]) ); //visited
//}
};
void CVisitableOPH::onHeroVisit(CGObjectInstance *os, int heroID)
void CVisitableOPH::onHeroVisit(int objid, int heroID)
{
if (visitors.find(os)!=visitors.end())
if (visitors.find(objid)!=visitors.end())
{
if(visitors[os].find(heroID)==visitors[os].end())
if(visitors[objid].find(heroID)==visitors[objid].end())
{
onNAHeroVisit(os,heroID, false);
visitors[os].insert(heroID);
onNAHeroVisit(objid,heroID, false);
visitors[objid].insert(heroID);
}
else
{
onNAHeroVisit(os,heroID, true);
onNAHeroVisit(objid,heroID, true);
}
}
else
@ -232,12 +238,13 @@ void CVisitableOPH::onHeroVisit(CGObjectInstance *os, int heroID)
#ifndef __GNUC__
throw new std::exception("Skrypt nie zainicjalizowal instancji tego obiektu. :(");
#else
throw std::exception();
throw new std::exception();
#endif
}
};
void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited)
void CVisitableOPH::onNAHeroVisit(int objid, int heroID, bool alreadyVisited)
{
const CGObjectInstance *os = cb->getObj(objid);
int w=0, ot=0, vvv=1;
switch(os->ID)
{
@ -273,21 +280,21 @@ void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
case 32:
{
cb->changePrimSkill(heroID,w,vvv);
std::vector<SComponent*> weko;
weko.push_back(new SComponent(SComponent::primskill,w,vvv));
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&weko);
//for (int ii=0; ii<weko.size();ii++)
// delete weko[ii];
InfoWindow iw;
iw.components.push_back(Component(0,w,vvv,0));
iw.text << std::pair<ui8,ui32>(11,ot);
iw.player = cb->getHeroOwner(heroID);
cb->showInfoDialog(&iw);
break;
}
case 100:
case 100: //give 1000 exp
{
cb->changePrimSkill(heroID,w,vvv);
std::vector<SComponent*> weko;
weko.push_back(new SComponent(SComponent::experience,0,vvv));
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&weko);
//for (int ii=0; ii<weko.size();ii++)
// delete weko[ii];
InfoWindow iw;
iw.components.push_back(Component(0,4,vvv,0));
iw.player = cb->getHeroOwner(heroID);
iw.text << std::pair<ui8,ui32>(11,ot);
cb->showInfoDialog(&iw);
break;
}
}
@ -295,7 +302,10 @@ void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
else
{
ot++;
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&std::vector<SComponent*>());
InfoWindow iw;
iw.player = cb->getHeroOwner(heroID);
iw.text << std::pair<ui8,ui32>(11,ot);
cb->showInfoDialog(&iw);
}
}
@ -310,49 +320,9 @@ std::vector<int> CVisitableOPH::yourObjects()
return ret;
}
std::string CVisitableOPH::hoverText(CGObjectInstance *os)
{
std::string add;
int pom;
switch(os->ID)
{
case 51:
pom = 8;
break;
case 23:
pom = 7;
break;
case 61:
pom = 11;
break;
case 32:
pom = 4;
break;
case 100:
pom = 5;
break;
default:
#ifndef __GNUC__
throw new std::exception("Unsupported ID in CVisitableOPH::hoverText");
#else
throw std::exception();
#endif
}
add = " " + CGI->objh->xtrainfo[pom] + " ";
int heroID = cb->getSelectedHero();
if (heroID>=0)
{
add += ( (visitors[os].find(heroID) == visitors[os].end())
?
(CGI->generaltexth->allTexts[353]) //not visited
:
( CGI->generaltexth->allTexts[352]) ); //visited
}
return CGI->objh->objects[os->defInfo->id].name + add;
}
void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited)
void CVisitableOPW::onNAHeroVisit(int objid, int heroID, bool alreadyVisited)
{
DEFOS;
int mid;
switch (os->ID)
{
@ -370,14 +340,18 @@ void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
{
if (os->ID!=112)
mid++;
else
else
mid--;
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[mid],&std::vector<SComponent*>()); //TODO: maybe we have memory leak with these windows
InfoWindow iw;
iw.player = cb->getHero(heroID)->tempOwner;
iw.text << std::pair<ui8,ui32>(11,mid);
cb->showInfoDialog(&iw);
}
else
{
int type, sub, val;
type = SComponent::resource;
type = 2;
switch (os->ID)
{
case 55:
@ -405,35 +379,48 @@ void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
else
val = 1000;
}
SComponent * com = new SComponent((SComponent::Etype)type,sub,val);
std::vector<SComponent*> weko;
weko.push_back(com);
cb->giveResource(cb->getHeroOwner(heroID),sub,val);
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[mid],&weko);
visited[os] = true;
int player = cb->getHeroOwner(heroID);
cb->giveResource(player,sub,val);
InfoWindow iw;
iw.player = player;
iw.components.push_back(Component(type,sub,val,0));
iw.text << std::pair<ui8,ui32>(11,mid);
cb->showInfoDialog(&iw);
visited[objid] = true;
MetaString ms; //set text to "visited"
ms << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(1,352);
cb->setHoverName(objid,&ms);
}
}
void CVisitableOPW::newTurn ()
{
if (cb->getDate(1)==1)
if (cb->getDate(1)==1) //first day of week
{
for (std::map<CGObjectInstance*,bool>::iterator i = visited.begin(); i != visited.end(); i++)
for (std::map<int,bool>::iterator i = visited.begin(); i != visited.end(); i++)
{
(*i).second = false;
MetaString ms; //set text to "not visited"
ms << std::pair<ui8,ui32>(3,cb->getObj(i->first)->ID) << " " << std::pair<ui8,ui32>(1,353);
cb->setHoverName(i->first,&ms);
}
}
}
void CVisitableOPW::newObject(CGObjectInstance *os)
}
void CVisitableOPW::newObject(int objid)
{
visited.insert(std::pair<CGObjectInstance*,bool>(os,false));
visited.insert(std::pair<int,bool>(objid,false));
DEFOS;
MetaString ms;
ms << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(1,visited[objid] ? 352 : 353);
cb->setHoverName(objid,&ms);
}
void CVisitableOPW::onHeroVisit(CGObjectInstance *os, int heroID)
void CVisitableOPW::onHeroVisit(int objid, int heroID)
{
if(visited[os])
onNAHeroVisit(os,heroID,true);
else
onNAHeroVisit(os,heroID,false);
if(visited[objid])
onNAHeroVisit(objid,heroID,true);
else
onNAHeroVisit(objid,heroID,false);
}
std::vector<int> CVisitableOPW::yourObjects() //returns IDs of objects which are handled by script
@ -445,75 +432,88 @@ std::vector<int> CVisitableOPW::yourObjects() //returns IDs of objects which are
return ret;
}
std::string CVisitableOPW::hoverText(CGObjectInstance *os)
void CMines::newObject(int objid)
{
return CGI->objh->objects[os->defInfo->id].name + " " + ( (visited[os]) ? (CGI->generaltexth->allTexts[352]) : (CGI->generaltexth->allTexts[353])) ;
ourObjs.push_back(objid);
cb->setOwner(objid,NEUTRAL_PLAYER);
DEFOS;
MetaString ms;
ms << std::pair<ui8,ui32>(3,os->ID);
cb->setHoverName(objid,&ms);
}
void CMines::onHeroVisit(int objid, int heroID)
{
//TODO: this is code for standard mines, no support for abandoned mine (subId==7)
DEFOS;
const CGHeroInstance *h = cb->getHero(heroID);
if(h->tempOwner == os->tempOwner)
return; //TODO: leaving garrison
cb->setOwner(objid,h->tempOwner);
MetaString ms;
ms << std::pair<ui8,ui32>(9,os->subID) << " " << std::pair<ui8,ui32>(6,23+h->tempOwner);
cb->setHoverName(objid,&ms);
ms.clear();
void CMines::newObject(CGObjectInstance *os)
{
ourObjs.push_back(os);
os->tempOwner = NEUTRAL_PLAYER;
}
void CMines::onHeroVisit(CGObjectInstance *os, int heroID)
{
int vv = 1;
int vv=1; //amount of resource per turn
if (os->subID==0 || os->subID==2)
vv++;
else if (os->subID==6)
vv = 1000;
if (os->tempOwner == cb->getHeroOwner(heroID))
{
//TODO: garrison
}
else
{
if (os->subID==7)
return; //TODO: support for abandoned mine
os->tempOwner = cb->getHeroOwner(heroID);
SComponent * com = new SComponent(SComponent::resource,os->subID,vv);
com->subtitle+=CGI->generaltexth->allTexts[3].substr(2,CGI->generaltexth->allTexts[3].length()-2);
std::vector<SComponent*> weko;
weko.push_back(com);
cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->mines[os->subID].second,&weko);
}
InfoWindow iw;
iw.text << std::pair<ui8,ui32>(10,os->subID);
iw.player = h->tempOwner;
iw.components.push_back(Component(2,os->subID,vv,-1));
cb->showInfoDialog(&iw);
}
std::vector<int> CMines::yourObjects()
{
std::vector<int> ret(1);
std::vector<int> ret;
ret.push_back(53);
return ret;
}
std::string CMines::hoverText(CGObjectInstance *os)
{
if (os->tempOwner == NEUTRAL_PLAYER)
return CGI->objh->mines[os->subID].first;
else
return CGI->objh->mines[os->subID].first + " " + CGI->generaltexth->arraytxt[23+os->tempOwner];
}
void CMines::newTurn ()
{
for (int i=0;i<ourObjs.size();i++)
const CGObjectInstance * obj;
for (unsigned i=0;i<ourObjs.size();i++)
{
if (ourObjs[i]->tempOwner == NEUTRAL_PLAYER)
obj = cb->getObj(ourObjs[i]);
if (obj->tempOwner == NEUTRAL_PLAYER)
continue;
int vv = 1;
if (ourObjs[i]->subID==0 || ourObjs[i]->subID==2)
if (obj->subID==0 || obj->subID==2)
vv++;
else if (ourObjs[i]->subID==6)
else if (obj->subID==6)
vv = 1000;
cb->giveResource(ourObjs[i]->tempOwner,ourObjs[i]->subID,vv);
cb->giveResource(obj->tempOwner,obj->subID,vv);
}
}
void CPickable::newObject(CGObjectInstance *os)
void CPickable::newObject(int objid)
{
os->blockVisit = true;
cb->setBlockVis(objid,true);
MetaString ms;
DEFOS;
switch (os->ID)
{
case 79:
ms << std::pair<ui8,ui32>(4,os->subID);
break;
case 5:
ms << std::pair<ui8,ui32>(5,os->subID);
break;
default:
ms << std::pair<ui8,ui32>(3,os->ID);
break;
}
cb->setHoverName(objid,&ms);
}
void CPickable::onHeroVisit(CGObjectInstance *os, int heroID)
void CPickable::onHeroVisit(int objid, int heroID)
{
DEFOS;
switch(os->ID)
{
case 5:
@ -544,92 +544,81 @@ void CPickable::onHeroVisit(CGObjectInstance *os, int heroID)
}
}
if(t2->message.length())
cb->showInfoDialog(cb->getHeroOwner(heroID),t2->message,&std::vector<SComponent*>());
SComponent ccc(SComponent::resource,os->subID,val);
ccc.description = CGI->objh->advobtxt[113];
boost::algorithm::replace_first(ccc.description,"%s",CGI->objh->restypes[os->subID]);
{
InfoWindow iw;
iw.player = cb->getHero(heroID)->tempOwner;
iw.text << t2->message;
cb->showInfoDialog(&iw);
}
cb->giveResource(cb->getHeroOwner(heroID),os->subID,val);
cb->showCompInfo(cb->getHeroOwner(heroID),&ccc);
ShowInInfobox sii;
sii.player = cb->getHeroOwner(heroID);
sii.c = Component(2,os->subID,val,0);
sii.text << std::pair<ui8,ui32>(11,113);
sii.text.replacements.push_back(VLC->objh->restypes[os->subID]);
cb->showCompInfo(&sii);
break;
}
case 101:
{
if (os->subID)
break; //not OH3 treasure chest
int wyn = rand()%100;
if (wyn<32)
{
tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
}//1k/0.5k
else if(wyn<64)
{
tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1500));
tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1000));
}//1.5k/1k
else if(wyn<95)
{
tempStore.push_back(new CSelectableComponent(SComponent::resource,6,2000));
tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1500));
}//2k/1.5k
else
{
if (1/*TODO: backpack is full*/)
{
tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
}
else
{
//TODO: give treasure artifact
break;
}
}//random treasure artifact, or (if backapack is full) 1k/0.5k
tempStore[1]->ID = heroID;
player = cb->getHeroOwner(heroID);
cb->showSelDialog(player,CGI->objh->advobtxt[146],&tempStore,this);
//if (os->subID)
// break; //not OH3 treasure chest
//int wyn = rand()%100;
//if (wyn<32)
//{
// tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
// tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
//}//1k/0.5k
//else if(wyn<64)
//{
// tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1500));
// tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1000));
//}//1.5k/1k
//else if(wyn<95)
//{
// tempStore.push_back(new CSelectableComponent(SComponent::resource,6,2000));
// tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1500));
//}//2k/1.5k
//else
//{
// if (1/*TODO: backpack is full*/)
// {
// tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
// tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
// }
// else
// {
// //TODO: give treasure artifact
// break;
// }
//}//random treasure artifact, or (if backapack is full) 1k/0.5k
//tempStore[1]->ID = heroID;
//player = cb->getHeroOwner(heroID);
//cb->showSelDialog(player,VLC->objh->advobtxt[146],&tempStore,this);
break;
}
}
CGI->mh->removeObject(os);
//VLC->mh->removeObject(os);
}
void CPickable::chosen(int which)
{
switch(tempStore[which]->type)
{
case SComponent::resource:
cb->giveResource(player,tempStore[which]->subtype,tempStore[which]->val);
break;
case SComponent::experience:
cb->changePrimSkill(tempStore[which]->ID,4,tempStore[which]->val);
break;
default:
#ifndef __GNUC__
throw new std::exception("Unhandled choice");
#else
throw std::exception();
#endif
}
for (int i=0;i<tempStore.size();i++)
delete tempStore[i];
tempStore.clear();
}
std::string CPickable::hoverText(CGObjectInstance *os)
{
switch (os->ID)
{
case 79:
return CGI->objh->restypes[os->subID];
break;
case 5:
return CGI->arth->artifacts[os->subID].name;
break;
default:
return CGI->objh->objects[os->defInfo->id].name;
break;
}
//switch(tempStore[which]->type)
//{
//case SComponent::resource:
// cb->giveResource(player,tempStore[which]->subtype,tempStore[which]->val);
// break;
//case SComponent::experience:
// cb->changePrimSkill(tempStore[which]->ID,4,tempStore[which]->val);
// break;
//default:
// throw new std::exception("Unhandled choice");
//
//}
//for (int i=0;i<tempStore.size();i++)
// delete tempStore[i];
//tempStore.clear();
}
std::vector<int> CPickable::yourObjects() //returns IDs of objects which are handled by script
@ -641,20 +630,22 @@ std::vector<int> CPickable::yourObjects() //returns IDs of objects which are han
return ret;
}
void CTownScript::onHeroVisit(CGObjectInstance *os, int heroID)
void CTownScript::onHeroVisit(int objid, int heroID)
{
cb->heroVisitCastle(os,heroID);
cb->heroVisitCastle(objid,heroID);
}
void CTownScript::onHeroLeave(CGObjectInstance *os, int heroID)
void CTownScript::newObject(int objid)
{
cb->stopHeroVisitCastle(os,heroID);
MetaString ms;
const CGTownInstance * n = cb->getTown(objid);
ms << n->name << ", " << n->town->name;
cb->setHoverName(objid,&ms);
}
std::string CTownScript::hoverText(CGObjectInstance *os)
void CTownScript::onHeroLeave(int objid, int heroID)
{
CGTownInstance * n;
if(n = dynamic_cast<CGTownInstance*>(os))
return n->name + ", " + n->town->name;
else return "";
cb->stopHeroVisitCastle(objid,heroID);
}
std::vector<int> CTownScript::yourObjects() //returns IDs of objects which are handled by script
@ -664,27 +655,33 @@ std::vector<int> CTownScript::yourObjects() //returns IDs of objects which are h
return ret;
}
void CHeroScript::newObject(CGObjectInstance *os)
void CHeroScript::newObject(int objid)
{
os->blockVisit = true;
heroes.insert(std::pair<int,CGObjectInstance*>(os->subID,os));
cb->setBlockVis(objid,true);
MetaString ms;
ms << std::pair<ui8,ui32>(1,15);
ms.replacements.push_back(cb->getHero(objid)->name);
ms.replacements.push_back(cb->getHero(objid)->type->heroClass->name);
cb->setHoverName(objid,&ms);
}
void CHeroScript::onHeroVisit(CGObjectInstance *os, int heroID)
void CHeroScript::onHeroVisit(int objid, int heroID)
{
//TODO: check for allies
if(static_cast<CGHeroInstance*>(heroes[heroID])->tempOwner == static_cast<CGHeroInstance*>(os)->tempOwner) //one of allied cases
const CGHeroInstance *my = cb->getHero(objid),
*vis = cb->getHero(objid);
if(my->tempOwner == vis->tempOwner) //one of allied cases
{
//exchange
}
else
{
cb->startBattle(
&(static_cast<CGHeroInstance*>(heroes[heroID]))->army,
&(static_cast<CGHeroInstance*>(os))->army,
os->pos,
static_cast<CGHeroInstance*>(heroes[heroID]),
static_cast<CGHeroInstance*>(os));
&my->army,
&vis->army,
my->pos,
my,
vis);
}
}
std::vector<int> CHeroScript::yourObjects() //returns IDs of objects which are handled by script
@ -693,65 +690,58 @@ std::vector<int> CHeroScript::yourObjects() //returns IDs of objects which are h
ret.push_back(34); //hero
return ret;
}
std::string CHeroScript::hoverText(CGObjectInstance *os)
{
CGHeroInstance* h = static_cast<CGHeroInstance*>(os);
std::string ret = CGI->generaltexth->allTexts[15];
boost::algorithm::replace_first(ret,"%s",h->name);
boost::algorithm::replace_first(ret,"%s",h->type->heroClass->name);
return ret;
}
void CMonsterS::newObject(CGObjectInstance *os)
void CMonsterS::newObject(int objid)
{
//os->blockVisit = true;
switch(CGI->creh->creatures[os->subID].level)
DEFOS;
switch(VLC->creh->creatures[os->subID].level)
{
case 1:
((CCreatureObjInfo*)os->info)->number = rand()%31+20;
amounts[objid] = rand()%31+20;
break;
case 2:
((CCreatureObjInfo*)os->info)->number = rand()%16+15;
amounts[objid] = rand()%16+15;
break;
case 3:
((CCreatureObjInfo*)os->info)->number = rand()%16+10;
amounts[objid] = rand()%16+10;
break;
case 4:
((CCreatureObjInfo*)os->info)->number = rand()%11+10;
amounts[objid] = rand()%11+10;
break;
case 5:
((CCreatureObjInfo*)os->info)->number = rand()%9+8;
amounts[objid] = rand()%9+8;
break;
case 6:
((CCreatureObjInfo*)os->info)->number = rand()%8+5;
amounts[objid] = rand()%8+5;
break;
case 7:
((CCreatureObjInfo*)os->info)->number = rand()%7+3;
amounts[objid] = rand()%7+3;
break;
case 8:
((CCreatureObjInfo*)os->info)->number = rand()%4+2;
amounts[objid] = rand()%4+2;
break;
case 9:
((CCreatureObjInfo*)os->info)->number = rand()%3+2;
amounts[objid] = rand()%3+2;
break;
case 10:
((CCreatureObjInfo*)os->info)->number = rand()%3+1;
amounts[objid] = rand()%3+1;
break;
}
}
std::string CMonsterS::hoverText(CGObjectInstance *os)
{
int pom = CCreature::getQuantityID(((CCreatureObjInfo*)os->info)->number);
MetaString ms;
int pom = CCreature::getQuantityID(amounts[objid]);
pom = 174 + 3*pom + 1;
return CGI->generaltexth->arraytxt[pom] + " " + CGI->creh->creatures[os->subID].namePl;
ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,os->subID);
cb->setHoverName(objid,&ms);
}
void CMonsterS::onHeroVisit(CGObjectInstance *os, int heroID)
void CMonsterS::onHeroVisit(int objid, int heroID)
{
DEFOS;
CCreatureSet set;
//TODO: zrobic secik w sposob wyrafinowany
set.slots[0] = std::pair<CCreature*,int>(&CGI->creh->creatures[os->subID],((CCreatureObjInfo*)os->info)->number);
cb->startBattle(heroID,&set,os->pos);
set.slots[0] = std::pair<ui32,si32>(os->subID,amounts[objid]);
cb->startBattle(heroID,set,os->pos);
}
std::vector<int> CMonsterS::yourObjects() //returns IDs of objects which are handled by script
{
@ -761,15 +751,15 @@ std::vector<int> CMonsterS::yourObjects() //returns IDs of objects which are han
}
void CCreatureGen::newObject(CGObjectInstance *os)
void CCreatureGen::newObject(int objid)
{
amount[os] = CGI->creh->creatures[CGI->objh->cregens[os->subID]].growth;
DEFOS;
amount[objid] = VLC->creh->creatures[VLC->objh->cregens[os->subID]].growth;
MetaString ms;
ms << std::pair<ui8,ui32>(8,os->subID);
cb->setHoverName(objid,&ms);
}
std::string CCreatureGen::hoverText(CGObjectInstance *os)
{
return CGI->objh->creGens[os->subID];
}
void CCreatureGen::onHeroVisit(CGObjectInstance *os, int heroID)
void CCreatureGen::onHeroVisit(int objid, int heroID)
{
}
std::vector<int> CCreatureGen::yourObjects() //returns IDs of objects which are handled by script

107
CLua.h
View File

@ -1,12 +1,11 @@
#pragma once
#include "global.h"
#ifndef _MSC_VER
extern "C" {
#endif
#include "lstate.h"
//#include "lstate.h"
#ifndef _MSC_VER
}
@ -22,6 +21,9 @@ class CGHeroInstance;
class CScriptCallback;
class SComponent;
class CSelectableComponent;
class CGameState;
struct Mapa;
struct lua_State;
enum ESLan{UNDEF=-1,CPP,ERM,LUA};
class CObjectScript
{
@ -36,10 +38,10 @@ public:
//functions to be called in script
//virtual void init(){};
virtual void newObject(CGObjectInstance *os){};
virtual void onHeroVisit(CGObjectInstance *os, int heroID){};
virtual void onHeroLeave(CGObjectInstance *os, int heroID){};
virtual std::string hoverText(CGObjectInstance *os){return "";};
virtual void newObject(int objid){};
virtual void onHeroVisit(int objid, int heroID){};
virtual void onHeroLeave(int objid, int heroID){};
virtual std::string hoverText(int objid){return "";};
virtual void newTurn (){};
@ -80,7 +82,7 @@ public:
void findFS(std::string fname);
friend void initGameState(CGameInfo * cgi);
friend class CGameState;
};
class CLuaObjectScript : public CLua, public CObjectScript
@ -91,122 +93,101 @@ public:
static std::string genFN(std::string base, int ID);
void init();
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
std::string hoverText(CGObjectInstance *os);
friend void initGameState(CGameInfo * cgi);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
};
class CCPPObjectScript: public CObjectScript
{
protected:
public:
CScriptCallback * cb;
CCPPObjectScript(CScriptCallback * CB){cb=CB;};
public:
virtual std::vector<int> yourObjects()=0; //returns IDs of objects which are handled by script
virtual std::string hoverText(CGObjectInstance *os);
};
class CVisitableOPH : public CCPPObjectScript //once per hero
{
public:
CVisitableOPH(CScriptCallback * CB):CCPPObjectScript(CB){};
std::map<CGObjectInstance*,std::set<int> > visitors;
std::map<int,std::set<int> > visitors;
void onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited);
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
void onNAHeroVisit(int objid, int heroID, bool alreadyVisited);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
std::string hoverText(CGObjectInstance *os);
friend void initGameState(CGameInfo * cgi);
};
class CVisitableOPW : public CCPPObjectScript //once per week
{
public:
CVisitableOPW(CScriptCallback * CB):CCPPObjectScript(CB){};
std::map<CGObjectInstance*,bool> visited;
void onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited);
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
std::map<int,bool> visited;
void onNAHeroVisit(int objid, int heroID, bool alreadyVisited);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
std::string hoverText(CGObjectInstance *os);
void newTurn ();
friend void initGameState(CGameInfo * cgi);
};
class CMines : public CCPPObjectScript //flaggable, and giving resource at each day
{
public:
CMines(CScriptCallback * CB):CCPPObjectScript(CB){};
std::vector<CGObjectInstance*> ourObjs;
std::vector<int> ourObjs;
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
std::string hoverText(CGObjectInstance *os);
void newTurn ();
friend void initGameState(CGameInfo * cgi);
};
class CPickable : public CCPPObjectScript, public IChosen //pickable - resources, artifacts, etc
{
public:
std::vector<CSelectableComponent*> tempStore;
int player;
CPickable(CScriptCallback * CB):CCPPObjectScript(CB){};
void chosen(int which);
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
std::string hoverText(CGObjectInstance *os);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
friend void initGameState(CGameInfo * cgi);
};
class CTownScript : public CCPPObjectScript //pickable - resources, artifacts, etc
{
public:
CTownScript(CScriptCallback * CB):CCPPObjectScript(CB){};
void onHeroVisit(CGObjectInstance *os, int heroID);
void onHeroLeave(CGObjectInstance *os, int heroID);
std::string hoverText(CGObjectInstance *os);
void onHeroVisit(int objid, int heroID);
void onHeroLeave(int objid, int heroID);
void newObject(int objid);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
friend void initGameState(CGameInfo * cgi);
};
class CHeroScript : public CCPPObjectScript
{
std::map<int, CGObjectInstance*> heroes;
public:
CHeroScript(CScriptCallback * CB):CCPPObjectScript(CB){};
void newObject(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
std::string hoverText(CGObjectInstance *os);
friend void initGameState(CGameInfo * cgi);
};
class CMonsterS : public CCPPObjectScript
{
std::map<int, CGObjectInstance*> heroes;
public:
std::map<int, int> amounts; //monster id -> stack quantity
CMonsterS(CScriptCallback * CB):CCPPObjectScript(CB){};
void newObject(CGObjectInstance *os);
std::string hoverText(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
friend void initGameState(CGameInfo * cgi);
};
class CCreatureGen : public CCPPObjectScript
{
std::map<CGObjectInstance*, int> amount; //amount of creatures in each dwelling
public:
std::map<int, int> amount; //amount of creatures in each dwelling
CCreatureGen(CScriptCallback * CB):CCPPObjectScript(CB){};
void newObject(CGObjectInstance *os);
std::string hoverText(CGObjectInstance *os);
void onHeroVisit(CGObjectInstance *os, int heroID);
void newObject(int objid);
void onHeroVisit(int objid, int heroID);
std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
friend void initGameState(CGameInfo * cgi);
};

View File

@ -32,45 +32,45 @@ CLuaHandler::~CLuaHandler()
}
void CLuaHandler::test()
{
int iErr = 0;
lua_State *lua = lua_open (); // Open Lua
LUA_OPEN_LIB(lua, luaopen_base);
LUA_OPEN_LIB(lua, luaopen_io);
//luabind::open(lua);
//luabind::module(lua)
//[
// luabind::class_<int3>("int3")
// //.def(luabind::constructor<>())
// //.def(luabind::constructor<const int&,const int&,const int&>())
// .def_readwrite("x", &int3::x)
// .def_readwrite("y", &int3::y)
// .def_readwrite("z", &int3::z)
//];
//luabind::module(lua)
//[
// luabind::def("powitanie",&piszpowitanie2)
//];
//int iErr = 0;
//lua_State *lua = lua_open (); // Open Lua
//LUA_OPEN_LIB(lua, luaopen_base);
//LUA_OPEN_LIB(lua, luaopen_io);
//if ((iErr = luaL_loadfile (lua, "scripts/lua/objects/0023_marletto_tower.lua")) == 0)
//{
// // Call main...
// if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
// {
// lua_pushstring (lua, "rightText");
// lua_gettable (lua, LUA_GLOBALSINDEX);
// lua_pcall (lua, 0, 0, 0);
// }
//}
//lua_close (lua);
if ((iErr = luaL_loadfile (lua, "scripts/lua/objects/0023_marletto_tower.lua")) == 0)
{
// Call main...
if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
{
//int ret = luabind::call_function<int>(lua, "helloWorld2");
//lua_pushstring (lua, "helloWorld2");
//lua_gettable (lua, LUA_GLOBALSINDEX);
//lua_pcall (lua, 0, 0, 0);
// Push the function name onto the stack
lua_pushstring (lua, "rightText");
lua_gettable (lua, LUA_GLOBALSINDEX);
lua_pcall (lua, 0, 0, 0);
}
}
lua_close (lua);
}
@ -82,10 +82,10 @@ std::vector<std::string> * CLuaHandler::searchForScripts(std::string fol)
#ifndef __GNUC__
throw new std::exception("No such folder!");
#else
throw std::exception();
throw new std::exception();
#endif
boost::filesystem::directory_iterator end_itr;
for
for
(
boost::filesystem::directory_iterator it(folder);
it!=end_itr;

1008
CMT.cpp

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,6 @@
#include "stdafx.h"
#include "CMessage.h"
#include "SDL_ttf.h"
#include "hch/CSemiDefHandler.h"
#include "hch/CDefHandler.h"
#include "CGameInfo.h"
#include "SDL_Extensions.h"
@ -10,12 +9,12 @@
#include <boost/algorithm/string/replace.hpp>
#include "CPlayerInterface.h"
#include "hch/CDefHandler.h"
#include "hch/CSemiDefHandler.h"
#include "CGameInfo.h"
#include "SDL_Extensions.h"
#include <sstream>
#include "CLua.h"
#include "hch/CGeneralTextHandler.h"
#include "client/Graphics.h"
SDL_Color tytulowy, tlo, zwykly ;
SDL_Rect genRect(int hh, int ww, int xx, int yy);
@ -51,7 +50,7 @@ void CMessage::init()
{
for (int i=0;i<PLAYER_LIMIT;i++)
{
CDefHandler * bluePieces = CGI->spriteh->giveDef("DIALGBOX.DEF");
CDefHandler * bluePieces = CDefHandler::giveDef("DIALGBOX.DEF");
std::vector<SDL_Surface *> n;
piecesOfBox.push_back(n);
if (i==1)
@ -63,15 +62,15 @@ void CMessage::init()
}
for (int j=0;j<bluePieces->ourImages.size();j++)
{
CSDL_Ext::blueToPlayersAdv(bluePieces->ourImages[j].bitmap,i);
graphics->blueToPlayersAdv(bluePieces->ourImages[j].bitmap,i);
piecesOfBox[i].push_back(bluePieces->ourImages[j].bitmap);
}
}
NMessage::background = CGI->bitmaph->loadBitmap("DIBOXBCK.BMP");
NMessage::background = BitmapHandler::loadBitmap("DIBOXBCK.BMP");
SDL_SetColorKey(background,SDL_SRCCOLORKEY,SDL_MapRGB(background->format,0,255,255));
}
ok = CGI->spriteh->giveDef("IOKAY.DEF");
cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
ok = CDefHandler::giveDef("IOKAY.DEF");
cancel = CDefHandler::giveDef("ICANCEL.DEF");
}

View File

@ -5,6 +5,7 @@
#include "hch/CAmbarCendamo.h"
#include "mapHandler.h"
#include "CGameState.h"
#include "hch/CObjectHandler.h"
using namespace std;
@ -41,14 +42,14 @@ vector<Coordinate>* CPathfinder::GetPath(const CGHeroInstance* hero)
int3 hpos = Hero->getPosition(false);
if (!Hero->canWalkOnSea())
{
if (CGI->mh->ttiles[hpos.x][hpos.y][hpos.z].terType==water)
if (CGI->mh->ttiles[hpos.x][hpos.y][hpos.z].tileInfo->tertype==water)
blockLandSea=false;
else
blockLandSea=true;
}
else
{
blockLandSea = indeterminate;
blockLandSea = boost::logic::indeterminate;
}
CalcG(&Start);
@ -191,11 +192,11 @@ void CPathfinder::CalcH(Coordinate* node)
* If there is fog of war on the node.
* => Impossible to move there.
*/
if( (CGI->mh->ttiles[node->x][node->y][node->z].blocked && !(node->x==End.x && node->y==End.y && CGI->mh->ttiles[node->x][node->y][node->z].visitable)) ||
(CGI->mh->ttiles[node->x][node->y][node->z].terType==rock) ||
((blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].terType==water)) ||
if( (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->blocked && !(node->x==End.x && node->y==End.y && CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->visitable)) ||
(CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype==rock) ||
((blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype==water)) ||
(!CGI->state->players[Hero->tempOwner].fogOfWarMap[node->x][node->y][node->z]) ||
((!blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].terType!=water)))
((!blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype!=water)))
{
//Impossible.
@ -206,13 +207,13 @@ void CPathfinder::CalcH(Coordinate* node)
int ret=-1;
int x = node->x;
int y = node->y;
if(node->x>=CGI->mh->reader->map.width)
x = CGI->mh->reader->map.width-1;
if(node->y>=CGI->mh->reader->map.height)
y = CGI->mh->reader->map.height-1;
if(node->x>=CGI->mh->map->width)
x = CGI->mh->map->width-1;
if(node->y>=CGI->mh->map->height)
y = CGI->mh->map->height-1;
//Get the movement cost.
ret = Hero->getTileCost(CGI->mh->ttiles[x][y][node->z].terType, CGI->mh->reader->map.terrain[x][y].malle,CGI->mh->reader->map.terrain[x][y].nuine);
ret = Hero->getTileCost(CGI->mh->ttiles[x][y][node->z].tileInfo->tertype, CGI->mh->map->terrain[x][y][node->z].malle,CGI->mh->map->terrain[x][y][node->z].nuine);
node->h = ret;
}

View File

@ -1,17 +1,18 @@
#include "stdafx.h"
#include <queue>
#include "CPlayerInterface.h"
#include "CAdvmapInterface.h"
#include "CMessage.h"
#include "mapHandler.h"
#include "SDL_Extensions.h"
#include "SDL_framerate.h"
#include "CScreenHandler.h"
#include "CCursorHandler.h"
#include "CCallback.h"
#include "SDL_Extensions.h"
#include "hch/CLodHandler.h"
#include "CPathfinder.h"
#include <sstream>
#include "hch/CAbilityHandler.h"
#include "hch/CHeroHandler.h"
#include "hch/CTownHandler.h"
#include "SDL_framerate.h"
@ -19,21 +20,33 @@
#include "CCastleInterface.h"
#include "CHeroWindow.h"
#include "timeHandler.h"
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "hch/CPreGameTextHandler.h"
#include "hch/CObjectHandler.h"
#include "CBattleInterface.h"
#include "CGameInfo.h"
#include "CLua.h"
#include <cmath>
#include "client/CCreatureAnimation.h"
#include "client/Graphics.h"
#include "map.h"
#include "lib/NetPacks.h"
#include "lib/CondSh.h"
using namespace CSDL_Ext;
extern TTF_Font * GEOR16;
extern bool continueReadingConsole;
CPlayerInterface * LOCPLINT;
extern std::queue<SDL_Event> events;
extern boost::mutex eventsM;
class OCM_HLP_CGIN
{
public:
bool operator ()(const std::pair<CGObjectInstance*,SDL_Rect> & a, const std::pair<CGObjectInstance*,SDL_Rect> & b) const
bool operator ()(const std::pair<const CGObjectInstance*,SDL_Rect> & a, const std::pair<const CGObjectInstance*,SDL_Rect> & b) const
{
return (*a.first)<(*b.first);
}
@ -228,10 +241,10 @@ void CGarrisonSlot::show()
{
char* buf = new char[15];
SDL_itoa(count,buf,10);
blitAt(CGI->creh->bigImgs[creature->idNumber],pos);
blitAt(graphics->bigImgs[creature->idNumber],pos);
printTo(buf,pos.x+56,pos.y+62,GEOR16,zwykly);
if(owner->highlighted==this)
blitAt(CGI->creh->bigImgs[-1],pos);
blitAt(graphics->bigImgs[-1],pos);
if(owner->update)
updateRect(&pos,screen);
delete [] buf;
@ -241,7 +254,7 @@ void CGarrisonSlot::show()
SDL_Rect jakis1 = genRect(pos.h,pos.w,owner->offx+ID*(pos.w+owner->interx),owner->offy+upg*(pos.h+owner->intery)), jakis2 = pos;
SDL_BlitSurface(owner->sur,&jakis1,screen,&jakis2);
if(owner->splitting)
blitAt(CGI->creh->bigImgs[-1],pos);
blitAt(graphics->bigImgs[-1],pos);
if(owner->update)
SDL_UpdateRect(screen,pos.x,pos.y,pos.w,pos.h);
}
@ -329,11 +342,11 @@ void CGarrisonInt::createSlots()
{
sup = new std::vector<CGarrisonSlot*>(7,(CGarrisonSlot *)(NULL));
for
(std::map<int,std::pair<CCreature*,int> >::const_iterator i=set1->slots.begin();
(std::map<si32,std::pair<ui32,si32> >::const_iterator i=set1->slots.begin();
i!=set1->slots.end(); i++)
{
(*sup)[i->first] =
new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y,i->first, 0, i->second.first,i->second.second);
new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y,i->first, 0, &CGI->creh->creatures[i->second.first],i->second.second);
}
for(int i=0; i<sup->size(); i++)
if((*sup)[i] == NULL)
@ -343,11 +356,11 @@ void CGarrisonInt::createSlots()
{
sdown = new std::vector<CGarrisonSlot*>(7,(CGarrisonSlot *)(NULL));
for
(std::map<int,std::pair<CCreature*,int> >::const_iterator i=set2->slots.begin();
(std::map<si32,std::pair<ui32,si32> >::const_iterator i=set2->slots.begin();
i!=set2->slots.end(); i++)
{
(*sdown)[i->first] =
new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y + 64 + intery,i->first,1, i->second.first,i->second.second);
new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y + 64 + intery,i->first,1, &CGI->creh->creatures[i->second.first],i->second.second);
}
for(int i=0; i<sup->size(); i++)
if((*sdown)[i] == NULL)
@ -517,7 +530,7 @@ void CInfoPopup::show(SDL_Surface * to)
blitAt(bitmap,pos.x,pos.y,(to)?(to):(screen));
}
SComponent::SComponent(Etype Type, int Subtype, int Val)
void SComponent::init(Etype Type, int Subtype, int Val)
{
std::ostringstream oss;
switch (Type)
@ -545,22 +558,40 @@ SComponent::SComponent(Etype Type, int Subtype, int Val)
pos.w = temp->w;
pos.h = temp->h;
}
SComponent::SComponent(Etype Type, int Subtype, int Val)
{
init(Type,Subtype,Val);
}
SComponent::SComponent(const Component &c)
{
if(c.id==0 && c.subtype==4)
init(experience,0,c.val);
else
init((Etype)c.id,c.subtype,c.val);
switch(c.id)
{
case resource:
if(c.when == -1)
subtitle += CGI->generaltexth->allTexts[3].substr(2,CGI->generaltexth->allTexts[3].length()-2);
break;
}
}
SDL_Surface * SComponent::getImg()
{
switch (type)
{
case primskill:
return CGI->heroh->pskillsb->ourImages[subtype].bitmap;
return graphics->pskillsb->ourImages[subtype].bitmap;
break;
case secskill:
return CGI->abilh->abils82->ourImages[subtype*3 + 3 + val].bitmap;
break;
case resource:
return CGI->heroh->resources->ourImages[subtype].bitmap;
return graphics->resources->ourImages[subtype].bitmap;
break;
case experience:
return CGI->heroh->pskillsb->ourImages[4].bitmap;
return graphics->pskillsb->ourImages[4].bitmap;
break;
}
return NULL;
@ -888,58 +919,38 @@ void TimeInterested::deactivate()
}
CPlayerInterface::CPlayerInterface(int Player, int serial)
{
LOCPLINT = this;
playerID=Player;
serialID=serial;
CGI->localPlayer = playerID;
human=true;
hInfo = CGI->bitmaph->loadBitmap("HEROQVBK.bmp");
SDL_SetColorKey(hInfo,SDL_SRCCOLORKEY,SDL_MapRGB(hInfo->format,0,255,255));
tInfo = CGI->bitmaph->loadBitmap("TOWNQVBK.bmp");
SDL_SetColorKey(tInfo,SDL_SRCCOLORKEY,SDL_MapRGB(tInfo->format,0,255,255));
slotsPos.push_back(std::pair<int,int>(44,82));
slotsPos.push_back(std::pair<int,int>(80,82));
slotsPos.push_back(std::pair<int,int>(116,82));
slotsPos.push_back(std::pair<int,int>(26,131));
slotsPos.push_back(std::pair<int,int>(62,131));
slotsPos.push_back(std::pair<int,int>(98,131));
slotsPos.push_back(std::pair<int,int>(134,131));
luck22 = CGI->spriteh->giveDefEss("ILCK22.DEF");
luck30 = CGI->spriteh->giveDefEss("ILCK30.DEF");
luck42 = CGI->spriteh->giveDefEss("ILCK42.DEF");
luck82 = CGI->spriteh->giveDefEss("ILCK82.DEF");
morale22 = CGI->spriteh->giveDefEss("IMRL22.DEF");
morale30 = CGI->spriteh->giveDefEss("IMRL30.DEF");
morale42 = CGI->spriteh->giveDefEss("IMRL42.DEF");
morale82 = CGI->spriteh->giveDefEss("IMRL82.DEF");
halls = CGI->spriteh->giveDefEss("ITMTLS.DEF");
forts = CGI->spriteh->giveDefEss("ITMCLS.DEF");
bigTownPic = CGI->spriteh->giveDefEss("ITPT.DEF");
pim = new boost::mutex;
}
CPlayerInterface::~CPlayerInterface()
{
delete pim;
}
void CPlayerInterface::init(ICallback * CB)
{
cb = dynamic_cast<CCallback*>(CB);
CGI->localPlayer = serialID;
adventureInt = new CAdvMapInt(playerID);
castleInt = NULL;
std::vector <const CGHeroInstance *> hh = cb->getHeroesInfo(false);
for(int i=0;i<hh.size();i++)
{
SDL_Surface * pom = infoWin(hh[i]);
heroWins.insert(std::pair<int,SDL_Surface*>(hh[i]->subID,pom));
graphics->heroWins.insert(std::pair<int,SDL_Surface*>(hh[i]->subID,pom));
}
std::vector<const CGTownInstance*> tt = cb->getTownsInfo(false);
for(int i=0;i<tt.size();i++)
{
SDL_Surface * pom = infoWin(tt[i]);
townWins.insert(std::pair<int,SDL_Surface*>(tt[i]->identifier,pom));
graphics->townWins.insert(std::pair<int,SDL_Surface*>(tt[i]->identifier,pom));
}
}
void CPlayerInterface::yourTurn()
{
LOCPLINT = this;
makingTurn = true;
CGI->localPlayer = serialID;
unsigned char & animVal = LOCPLINT->adventureInt->anim; //for animations handling
unsigned char & heroAnimVal = LOCPLINT->adventureInt->heroAnim;
adventureInt->infoBar.newDay(cb->getDate(1));
@ -949,7 +960,7 @@ void CPlayerInterface::yourTurn()
//initializing framerate keeper
mainFPSmng = new FPSmanager;
SDL_initFramerate(mainFPSmng);
SDL_setFramerate(mainFPSmng, 24);
SDL_setFramerate(mainFPSmng, 48);
SDL_Event sEvent;
//framerate keeper initialized
timeHandler th;
@ -985,7 +996,10 @@ void CPlayerInterface::yourTurn()
// }
//}
//water tiles updated
CGI->screenh->updateScreen();
//CGI->screenh->updateScreen();
pim->lock();
int tv = th.getDif();
for (int i=0;i<timeinterested.size();i++)
{
@ -995,14 +1009,17 @@ void CPlayerInterface::yourTurn()
timeinterested[i]->tick();
}
LOCPLINT->adventureInt->updateScreen = false;
while (SDL_PollEvent(&sEvent)) //wait for event...
eventsM.lock();
while(!events.empty())
{
handleEvent(&sEvent);
handleEvent(&events.front());
events.pop();
}
eventsM.unlock();
if (!castleInt) //stuff for advMapInt
{
++LOCPLINT->adventureInt->animValHitCount; //for animations
if(LOCPLINT->adventureInt->animValHitCount == 4)
if(LOCPLINT->adventureInt->animValHitCount == 8)
{
LOCPLINT->adventureInt->animValHitCount = 0;
++animVal;
@ -1021,7 +1038,7 @@ void CPlayerInterface::yourTurn()
}
if(LOCPLINT->adventureInt->scrollingRight)
{
if(LOCPLINT->adventureInt->position.x<CGI->ac->map.width-19+4)
if(LOCPLINT->adventureInt->position.x<CGI->mh->map->width-19+4)
{
LOCPLINT->adventureInt->position.x++;
LOCPLINT->adventureInt->updateScreen = true;
@ -1039,7 +1056,7 @@ void CPlayerInterface::yourTurn()
}
if(LOCPLINT->adventureInt->scrollingDown)
{
if(LOCPLINT->adventureInt->position.y<CGI->ac->map.height-18+4)
if(LOCPLINT->adventureInt->position.y<CGI->mh->map->height-18+4)
{
LOCPLINT->adventureInt->position.y++;
LOCPLINT->adventureInt->updateScreen = true;
@ -1059,12 +1076,14 @@ void CPlayerInterface::yourTurn()
}
for(int i=0;i<objsToBlit.size();i++)
objsToBlit[i]->show();
//SDL_Flip(screen);
pim->unlock();
CGI->curh->draw1();
CSDL_Ext::update(screen);
SDL_Delay(5); //give time for other apps
CGI->curh->draw2();
SDL_framerateDelay(mainFPSmng);
}
adventureInt->hide();
cb->endTurn();
}
inline void subRect(const int & x, const int & y, const int & z, const SDL_Rect & r, const int & hid)
@ -1127,6 +1146,7 @@ int getDir(int3 src, int3 dst)
}
void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
{
boost::unique_lock<boost::mutex> un(*pim);
//initializing objects and performing first step of move
CGHeroInstance * ho = details.ho; //object representing this hero
int3 hp = details.src;
@ -1469,10 +1489,10 @@ void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
}
LOCPLINT->adventureInt->update(); //updating screen
CSDL_Ext::update(screen);
CGI->screenh->updateScreen();
//CGI->screenh->updateScreen();
++LOCPLINT->adventureInt->animValHitCount; //for animations
if(LOCPLINT->adventureInt->animValHitCount == 4)
if(LOCPLINT->adventureInt->animValHitCount == 8)
{
LOCPLINT->adventureInt->animValHitCount = 0;
++LOCPLINT->adventureInt->anim;
@ -1553,83 +1573,15 @@ void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
}
void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
{
heroWins.erase(hero->ID);
boost::unique_lock<boost::mutex> un(*pim);
graphics->heroWins.erase(hero->ID);
adventureInt->heroList.updateHList();
}
void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
{
if(heroWins.find(hero->subID)==heroWins.end())
heroWins.insert(std::pair<int,SDL_Surface*>(hero->subID,infoWin(hero)));
if(graphics->heroWins.find(hero->subID)==graphics->heroWins.end())
graphics->heroWins.insert(std::pair<int,SDL_Surface*>(hero->subID,infoWin(hero)));
}
SDL_Surface * CPlayerInterface::drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from, int to)
{
char * buf = new char[10];
for (int i=from;i<to;i++)
{
SDL_itoa(curh->primSkills[i],buf,10);
printAtMiddle(buf,84+28*i,68,GEOR13,zwykly,ret);
}
delete[] buf;
return ret;
}
SDL_Surface * CPlayerInterface::drawHeroInfoWin(const CGHeroInstance * curh)
{
char * buf = new char[10];
blueToPlayersAdv(hInfo,playerID,1);
SDL_Surface * ret = SDL_DisplayFormat(hInfo);
SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
printAt(curh->name,75,15,GEOR13,zwykly,ret);
drawPrimarySkill(curh, ret);
for (std::map<int,std::pair<CCreature*,int> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
{
blitAt(CGI->creh->smallImgs[(*i).second.first->idNumber],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
SDL_itoa((*i).second.second,buf,10);
printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
}
blitAt(CGI->heroh->largePortraits[curh->portrait],11,12,ret);
SDL_itoa(curh->mana,buf,10);
printAtMiddle(buf,166,109,GEORM,zwykly,ret); //mana points
delete[] buf;
blitAt(morale22->ourImages[curh->getCurrentMorale()+3].bitmap,14,84,ret);
blitAt(luck22->ourImages[curh->getCurrentLuck()+3].bitmap,14,101,ret);
//SDL_SaveBMP(ret,"inf1.bmp");
return ret;
}
SDL_Surface * CPlayerInterface::drawTownInfoWin(const CGTownInstance * curh)
{
char * buf = new char[10];
blueToPlayersAdv(tInfo,playerID,1);
SDL_Surface * ret = SDL_DisplayFormat(tInfo);
SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
printAt(curh->name,75,15,GEOR13,zwykly,ret);
int pom = curh->fortLevel() - 1; if(pom<0) pom = 3;
blitAt(forts->ourImages[pom].bitmap,115,42,ret);
if((pom=curh->hallLevel())>=0)
blitAt(halls->ourImages[pom].bitmap,77,42,ret);
SDL_itoa(curh->dailyIncome(),buf,10);
printAtMiddle(buf,167,70,GEORM,zwykly,ret);
for (std::map<int,std::pair<CCreature*,int> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
{
if(!i->second.first)
continue;
blitAt(CGI->creh->smallImgs[(*i).second.first->idNumber],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
SDL_itoa((*i).second.second,buf,10);
printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
}
//blit town icon
pom = curh->subID*2;
if (!curh->hasFort())
pom += F_NUMBER*2;
if(curh->builded >= MAX_BUILDING_PER_TURN)
pom++;
blitAt(bigTownPic->ourImages[pom].bitmap,13,13,ret);
delete[] buf;
return ret;
}
void CPlayerInterface::openTownWindow(const CGTownInstance * town)
{
adventureInt->hide();
@ -1646,10 +1598,10 @@ SDL_Surface * CPlayerInterface::infoWin(const CGObjectInstance * specific) //spe
switch (specific->ID)
{
case 34:
return drawHeroInfoWin(dynamic_cast<const CGHeroInstance*>(specific));
return graphics->drawHeroInfoWin(dynamic_cast<const CGHeroInstance*>(specific));
break;
case 98:
return drawTownInfoWin(dynamic_cast<const CGTownInstance*>(specific));
return graphics->drawTownInfoWin(dynamic_cast<const CGTownInstance*>(specific));
break;
default:
return NULL;
@ -1663,11 +1615,11 @@ SDL_Surface * CPlayerInterface::infoWin(const CGObjectInstance * specific) //spe
case HEROI_TYPE:
{
const CGHeroInstance * curh = (const CGHeroInstance *)adventureInt->selection.selected;
return drawHeroInfoWin(curh);
return graphics->drawHeroInfoWin(curh);
}
case TOWNI_TYPE:
{
return drawTownInfoWin((const CGTownInstance *)adventureInt->selection.selected);
return graphics->drawTownInfoWin((const CGTownInstance *)adventureInt->selection.selected);
}
default:
return NULL;
@ -1844,7 +1796,6 @@ void CPlayerInterface::handleEvent(SDL_Event *sEvent)
else if ((sEvent->type==SDL_MOUSEBUTTONDOWN) && (sEvent->button.button == SDL_BUTTON_LEFT))
{
LOGE("Left mouse button down1");
for(int i=0; i<lclickable.size();i++)
{
if (isItIn(&lclickable[i]->pos,sEvent->motion.x,sEvent->motion.y))
@ -1897,16 +1848,17 @@ int3 CPlayerInterface::repairScreenPos(int3 pos)
pos.x = -Woff+1;
if(pos.y<=-Hoff)
pos.y = -Hoff+1;
if(pos.x>CGI->mh->reader->map.width - this->adventureInt->terrain.tilesw + Woff)
pos.x = CGI->mh->reader->map.width - this->adventureInt->terrain.tilesw + Woff;
if(pos.y>CGI->mh->reader->map.height - this->adventureInt->terrain.tilesh + Hoff)
pos.y = CGI->mh->reader->map.height - this->adventureInt->terrain.tilesh + Hoff;
if(pos.x>CGI->mh->map->width - this->adventureInt->terrain.tilesw + Woff)
pos.x = CGI->mh->map->width - this->adventureInt->terrain.tilesw + Woff;
if(pos.y>CGI->mh->map->height - this->adventureInt->terrain.tilesh + Hoff)
pos.y = CGI->mh->map->height - this->adventureInt->terrain.tilesh + Hoff;
return pos;
}
void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, int val)
{
SDL_FreeSurface(heroWins[hero->subID]);//TODO: moznaby zmieniac jedynie fragment bitmapy zwiazany z dana umiejetnoscia
heroWins[hero->subID] = infoWin(hero); //a nie przerysowywac calosc. Troche roboty, obecnie chyba nie wartej swieczki.
boost::unique_lock<boost::mutex> un(*pim);
SDL_FreeSurface(graphics->heroWins[hero->subID]);//TODO: moznaby zmieniac jedynie fragment bitmapy zwiazany z dana umiejetnoscia
graphics->heroWins[hero->subID] = infoWin(hero); //a nie przerysowywac calosc. Troche roboty, obecnie chyba nie wartej swieczki.
if (adventureInt->selection.selected == hero)
adventureInt->infoBar.draw();
return;
@ -1942,13 +1894,14 @@ void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownIn
}
void CPlayerInterface::garrisonChanged(const CGObjectInstance * obj)
{
boost::unique_lock<boost::mutex> un(*pim);
if(obj->ID == 34) //hero
{
const CGHeroInstance * hh;
if(hh = dynamic_cast<const CGHeroInstance*>(obj))
{
SDL_FreeSurface(heroWins[hh->subID]);
heroWins[hh->subID] = infoWin(hh);
SDL_FreeSurface(graphics->heroWins[hh->subID]);
graphics->heroWins[hh->subID] = infoWin(hh);
}
CHeroWindow * hw = dynamic_cast<CHeroWindow *>(curint);
if(hw)
@ -1968,8 +1921,8 @@ void CPlayerInterface::garrisonChanged(const CGObjectInstance * obj)
const CGTownInstance * tt;
if(tt = dynamic_cast<const CGTownInstance*>(obj))
{
SDL_FreeSurface(townWins[tt->identifier]);
townWins[tt->identifier] = infoWin(tt);
SDL_FreeSurface(graphics->townWins[tt->identifier]);
graphics->townWins[tt->identifier] = infoWin(tt);
}
const CCastleInterface *ci = dynamic_cast<CCastleInterface*>(curint);
@ -1986,6 +1939,7 @@ void CPlayerInterface::buildChanged(const CGTownInstance *town, int buildingID,
return;
if(castleInt->town!=town)
return;
boost::unique_lock<boost::mutex> un(*pim);
switch(what)
{
case 1:
@ -1997,8 +1951,9 @@ void CPlayerInterface::buildChanged(const CGTownInstance *town, int buildingID,
}
}
void CPlayerInterface::battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, tribool side) //called by engine when battle starts; side=0 - left, side=1 - right
void CPlayerInterface::battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side) //called by engine when battle starts; side=0 - left, side=1 - right
{
boost::unique_lock<boost::mutex> un(*pim);
curint->deactivate();
curint = new CBattleInterface(army1,army2,hero1,hero2);
curint->activate();
@ -2025,45 +1980,28 @@ void CPlayerInterface::actionFinished(BattleAction action)//occurs AFTER every a
BattleAction CPlayerInterface::activeStack(int stackID) //called when it's turn of that stack
{
unsigned char showCount = 0;
dynamic_cast<CBattleInterface*>(curint)->stackActivated(stackID);
while(!dynamic_cast<CBattleInterface*>(curint)->givenCommand) //while current unit can perform an action
CBattleInterface *b = dynamic_cast<CBattleInterface*>(curint);
{
++showCount;
SDL_Event sEvent;
while (SDL_PollEvent(&sEvent)) //wait for event...
{
LOCPLINT->handleEvent(&sEvent);
}
if(showCount%2==0)
for(int i=0;i<objsToBlit.size();i++)
objsToBlit[i]->show();
//SDL_Flip(screen);
CSDL_Ext::update(screen);
/*timeHandler th;
th.getDif();
int tv = th.getDif();
for (int i=0;i<((CBattleInterface*)this->curint)->timeinterested.size();i++)
{
if (timeinterested[i]->toNextTick>=0)
timeinterested[i]->toNextTick-=tv;
if (timeinterested[i]->toNextTick<0)
timeinterested[i]->tick();
}*/
SDL_Delay(1); //give time for other apps
SDL_framerateDelay(mainFPSmng);
boost::unique_lock<boost::mutex> un(*pim);
b->stackActivated(stackID);
}
BattleAction ret = *(dynamic_cast<CBattleInterface*>(curint)->givenCommand);
delete dynamic_cast<CBattleInterface*>(curint)->givenCommand;
dynamic_cast<CBattleInterface*>(curint)->givenCommand = NULL;
dynamic_cast<CBattleInterface*>(curint)->myTurn = false;
//wait till BattleInterface sets its command
boost::unique_lock<boost::mutex> lock(b->givenCommand->mx);
while(!b->givenCommand->data)
b->givenCommand->cond.wait(lock);
//tidy up
BattleAction ret = *(b->givenCommand->data);
delete b->givenCommand->data;
b->givenCommand->data = NULL;
//return command
return ret;
}
void CPlayerInterface::battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner)
void CPlayerInterface::battleEnd(BattleResult *br)
{
boost::unique_lock<boost::mutex> un(*pim);
dynamic_cast<CBattleInterface*>(curint)->deactivate();
LOCPLINT->objsToBlit.erase(std::find(LOCPLINT->objsToBlit.begin(),LOCPLINT->objsToBlit.end(),dynamic_cast<IShowable*>(curint)));
delete dynamic_cast<CBattleInterface*>(curint);
@ -2073,6 +2011,7 @@ void CPlayerInterface::battleEnd(CCreatureSet * army1, CCreatureSet * army2, CAr
void CPlayerInterface::battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)
{
boost::unique_lock<boost::mutex> un(*pim);
dynamic_cast<CBattleInterface*>(curint)->stackMoved(ID, dest, startMoving, endMoving);
}
@ -2098,9 +2037,30 @@ void CPlayerInterface::battleStackIsShooting(int ID, int dest)
void CPlayerInterface::showComp(SComponent comp)
{
boost::unique_lock<boost::mutex> un(*pim);
adventureInt->infoBar.showComp(&comp,4000);
}
void CPlayerInterface::showInfoDialog(std::string text, std::vector<Component*> &components)
{
curint->deactivate(); //dezaktywacja starego interfejsu
std::vector<SComponent*> intComps;
for(int i=0;i<components.size();i++)
intComps.push_back(new SComponent(*components[i]));
CInfoWindow * temp = CMessage::genIWindow(text,LOCPLINT->playerID,32,intComps);
LOCPLINT->objsToBlit.push_back(temp);
temp->pos.x=300-(temp->pos.w/2);
temp->pos.y=300-(temp->pos.h/2);
temp->okb.pos.x = temp->okb.posr.x + temp->pos.x;
temp->okb.pos.y = temp->okb.posr.y + temp->pos.y;
temp->okb.activate();
for (int i=0;i<temp->components.size();i++)
{
temp->components[i]->activate();
temp->components[i]->pos.x += temp->pos.x;
temp->components[i]->pos.y += temp->pos.y;
}
}
void CPlayerInterface::showInfoDialog(std::string text, std::vector<SComponent*> & components)
{
curint->deactivate(); //dezaktywacja starego interfejsu
@ -2141,12 +2101,12 @@ void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
}
CStatusBar::CStatusBar(int x, int y, std::string name, int maxw)
{
bg=CGI->bitmaph->loadBitmap(name);
bg=BitmapHandler::loadBitmap(name);
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
pos.x=x;
pos.y=y;
if(maxw >= 0)
pos.w = std::min(bg->w,maxw);
pos.w = min(bg->w,maxw);
else
pos.w=bg->w;
pos.h=bg->h;
@ -2218,12 +2178,12 @@ CHeroList::CHeroList(int Size)
posmanx = 666;
posmany = 213;
arrup = CGI->spriteh->giveDef("IAM012.DEF");
arrdo = CGI->spriteh->giveDef("IAM013.DEF");
mobile = CGI->spriteh->giveDef("IMOBIL.DEF");
mana = CGI->spriteh->giveDef("IMANA.DEF");
empty = CGI->bitmaph->loadBitmap("HPSXXX.bmp");
selection = CGI->bitmaph->loadBitmap("HPSYYY.bmp");
arrup = CDefHandler::giveDef("IAM012.DEF");
arrdo = CDefHandler::giveDef("IAM013.DEF");
mobile = CDefHandler::giveDef("IMOBIL.DEF");
mana = CDefHandler::giveDef("IMANA.DEF");
empty = BitmapHandler::loadBitmap("HPSXXX.bmp");
selection = BitmapHandler::loadBitmap("HPSYYY.bmp");
SDL_SetColorKey(selection,SDL_SRCCOLORKEY,SDL_MapRGB(selection->format,0,255,255));
from = 0;
pressed = indeterminate;
@ -2382,7 +2342,7 @@ void CHeroList::clickRight(tribool down)
}
//show popup
CInfoPopup * ip = new CInfoPopup(LOCPLINT->heroWins[items[from+ny].first->subID],LOCPLINT->current->motion.x-LOCPLINT->heroWins[items[from+ny].first->subID]->w,LOCPLINT->current->motion.y-LOCPLINT->heroWins[items[from+ny].first->subID]->h,false);
CInfoPopup * ip = new CInfoPopup(graphics->heroWins[items[from+ny].first->subID],LOCPLINT->current->motion.x-graphics->heroWins[items[from+ny].first->subID]->w,LOCPLINT->current->motion.y-graphics->heroWins[items[from+ny].first->subID]->h,false);
ip->activate();
}
else
@ -2435,7 +2395,7 @@ void CHeroList::draw()
if (pom>25) pom=25;
if (pom<0) pom=0;
blitAt(mana->ourImages[pom].bitmap,posmanx,posmany+i*32); //mana
SDL_Surface * temp = CGI->heroh->smallPortraits[LOCPLINT->cb->getHeroInfo(LOCPLINT->playerID,iT,0)->portrait];
SDL_Surface * temp = graphics->portraitSmall[LOCPLINT->cb->getHeroInfo(LOCPLINT->playerID,iT,0)->portrait];
blitAt(temp,posporx,pospory+i*32);
if ((selected == iT) && (LOCPLINT->adventureInt->selection.type == HEROI_TYPE))
{
@ -2466,8 +2426,8 @@ CTownList::CTownList(int Size, SDL_Rect * Pos, int arupx, int arupy, int ardox,
:CList(Size)
{
pos = *Pos;
arrup = CGI->spriteh->giveDef("IAM014.DEF");
arrdo = CGI->spriteh->giveDef("IAM015.DEF");
arrup = CDefHandler::giveDef("IAM014.DEF");
arrdo = CDefHandler::giveDef("IAM015.DEF");
arrupp.x=arupx;
arrupp.y=arupy;
@ -2532,7 +2492,7 @@ void CTownList::mouseMoved (SDL_MouseMotionEvent & sEvent)
LOCPLINT->statusbar->clear();
return;
};
LOCPLINT->statusbar->print(items[from+ny]->state->hoverText(const_cast<CGTownInstance*>(items[from+ny])));
LOCPLINT->statusbar->print(items[from+ny]->name);
}
void CTownList::clickLeft(tribool down)
@ -2622,7 +2582,7 @@ void CTownList::clickRight(tribool down)
}
//show popup
CInfoPopup * ip = new CInfoPopup(LOCPLINT->townWins[items[from+ny]->identifier],LOCPLINT->current->motion.x-LOCPLINT->townWins[items[from+ny]->identifier]->w,LOCPLINT->current->motion.y-LOCPLINT->townWins[items[from+ny]->identifier]->h,false);
CInfoPopup * ip = new CInfoPopup(graphics->townWins[items[from+ny]->identifier],LOCPLINT->current->motion.x-graphics->townWins[items[from+ny]->identifier]->w,LOCPLINT->current->motion.y-graphics->townWins[items[from+ny]->identifier]->h,false);
ip->activate();
}
else
@ -2647,15 +2607,15 @@ void CTownList::draw()
int i = iT-from;
if (iT>=items.size())
{
blitAt(CGI->townh->getPic(-1),posporx,pospory+i*32);
blitAt(graphics->getPic(-1),posporx,pospory+i*32);
continue;
}
blitAt(CGI->townh->getPic(items[iT]->subID,items[iT]->hasFort(),items[iT]->builded),posporx,pospory+i*32);
blitAt(graphics->getPic(items[iT]->subID,items[iT]->hasFort(),items[iT]->builded),posporx,pospory+i*32);
if ((selected == iT) && (LOCPLINT->adventureInt->selection.type == TOWNI_TYPE))
{
blitAt(CGI->townh->getPic(-2),posporx,pospory+i*32);
blitAt(graphics->getPic(-2),posporx,pospory+i*32);
}
}
if (from>0)
@ -2681,7 +2641,7 @@ CCreaturePic::~CCreaturePic()
}
int CCreaturePic::blitPic(SDL_Surface *to, int x, int y, bool nextFrame)
{
blitAt(CGI->creh->backgrounds[c->faction],x,y);//curx-50,pos.y+130-65);
blitAt(graphics->backgrounds[c->faction],x,y);//curx-50,pos.y+130-65);
SDL_Rect dst = genRect(130,100,x,y);
if(c->isDoubleWide())
x-=15;
@ -2725,7 +2685,7 @@ void CRecrutationWindow::clickLeft(tribool down)
if(isItIn(&genRect(132,102,pos.x+curx,pos.y+64),LOCPLINT->current->motion.x,LOCPLINT->current->motion.y))
{
which = i;
int newAmount = std::min(amounts[i],creatures[i].amount);
int newAmount = min(amounts[i],creatures[i].amount);
slider->amount = newAmount;
if(slider->value > newAmount)
slider->moveTo(newAmount);
@ -2780,8 +2740,8 @@ void CRecrutationWindow::show(SDL_Surface * to)
int curx = pos.x+115-creatures[which].res.size()*16;
for(int i=0;i<creatures[which].res.size();i++)
{
blitAt(CGI->townh->resources->ourImages[creatures[which].res[i].first].bitmap,curx,pos.y+243,screen);
blitAt(CGI->townh->resources->ourImages[creatures[which].res[i].first].bitmap,curx+258,pos.y+243,screen);
blitAt(graphics->resources32->ourImages[creatures[which].res[i].first].bitmap,curx,pos.y+243,screen);
blitAt(graphics->resources32->ourImages[creatures[which].res[i].first].bitmap,curx+258,pos.y+243,screen);
SDL_itoa(creatures[which].res[i].second,pom,10);
printAtMiddle(pom,curx+12,pos.y+286,GEOR13,zwykly,screen);
SDL_itoa(creatures[which].res[i].second * slider->value,pom,10);
@ -2813,8 +2773,8 @@ CRecrutationWindow::CRecrutationWindow(const std::vector<std::pair<int,int> > &C
creatures[i].pic = new CCreaturePic(&CGI->creh->creatures[Creatures[i].first]);
amounts[i] = CGI->creh->creatures[Creatures[i].first].maxAmount(LOCPLINT->cb->getResourceAmount());
}
SDL_Surface *hhlp = CGI->bitmaph->loadBitmap("TPRCRT.bmp");
blueToPlayersAdv(hhlp,LOCPLINT->playerID);
SDL_Surface *hhlp = BitmapHandler::loadBitmap("TPRCRT.bmp");
graphics->blueToPlayersAdv(hhlp,LOCPLINT->playerID);
bitmap = SDL_ConvertSurface(hhlp,screen->format,0); //na 8bitowej mapie by sie psulo
SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
SDL_FreeSurface(hhlp);
@ -2822,7 +2782,7 @@ CRecrutationWindow::CRecrutationWindow(const std::vector<std::pair<int,int> > &C
pos.y = screen->h/2 - bitmap->h/2;
pos.w = bitmap->w;
pos.h = bitmap->h;
slider = new CSlider(pos.x+176,pos.y+279,135,boost::bind(&CRecrutationWindow::sliderMoved,this, _1),1,std::min(amounts[0],creatures[0].amount),0,true);
slider = new CSlider(pos.x+176,pos.y+279,135,boost::bind(&CRecrutationWindow::sliderMoved,this, _1),1,min(amounts[0],creatures[0].amount),0,true);
std::string pom;
printAtMiddle(CGI->generaltexth->allTexts[346],113,231,GEOR13,zwykly,bitmap); //cost per troop t
printAtMiddle(CGI->generaltexth->allTexts[465],205,231,GEOR13,zwykly,bitmap); //available t
@ -2876,7 +2836,7 @@ CSplitWindow::CSplitWindow(int cid, int max, CGarrisonInt *Owner)
c=cid;
slider = NULL;
gar = Owner;
bitmap = CGI->bitmaph->loadBitmap("GPUCRDIV.bmp");
bitmap = BitmapHandler::loadBitmap("GPUCRDIV.bmp");
SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
pos.x = screen->w/2 - bitmap->w/2;
pos.y = screen->h/2 - bitmap->h/2;
@ -2976,12 +2936,12 @@ CCreInfoWindow::CCreInfoWindow
:ok(0),dismiss(0),upgrade(0),type(Type),dsm(Dsm)
{
c = &CGI->creh->creatures[Cid];
bitmap = CGI->bitmaph->loadBitmap("CRSTKPU.bmp");
bitmap = BitmapHandler::loadBitmap("CRSTKPU.bmp");
pos.x = screen->w/2 - bitmap->w/2;
pos.y = screen->h/2 - bitmap->h/2;
pos.w = bitmap->w;
pos.h = bitmap->h;
blueToPlayersAdv(bitmap,LOCPLINT->playerID);
graphics->blueToPlayersAdv(bitmap,LOCPLINT->playerID);
SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
anim = new CCreaturePic(c);
if(!type) anim->anim->setType(1);
@ -3045,8 +3005,8 @@ CCreInfoWindow::CCreInfoWindow
//luck and morale
blitAt(LOCPLINT->morale42->ourImages[(State)?(State->morale+3):(3)].bitmap,24,189,bitmap);
blitAt(LOCPLINT->luck42->ourImages[(State)?(State->luck+3):(3)].bitmap,77,189,bitmap);
blitAt(graphics->morale42->ourImages[(State)?(State->morale+3):(3)].bitmap,24,189,bitmap);
blitAt(graphics->luck42->ourImages[(State)?(State->luck+3):(3)].bitmap,77,189,bitmap);
//print abilities text - if r-click popup
if(type)

View File

@ -25,6 +25,11 @@ class CCreatureSet;
class CGObjectInstance;
class CSlider;
namespace boost
{
class mutex;
};
class IShowable
{
public:
@ -154,7 +159,7 @@ public:
};
class CInfoWindow : public CSimpleWindow //text + comp. + ok button
{ //okno usuwa swoje komponenty w chwili zamkniecia
{ //window deletes its components when closed
public:
CSCButton<CInfoWindow> okb;
std::vector<SComponent*> components;
@ -207,8 +212,9 @@ public:
std::string description; //r-click
std::string subtitle;
void init(Etype Type, int Subtype, int Val);
SComponent(Etype Type, int Subtype, int Val);
//SComponent(const & SComponent r);
SComponent(const Component &c);
void clickRight (boost::logic::tribool down);
virtual SDL_Surface * getImg();
@ -290,17 +296,20 @@ public:
class CPlayerInterface : public CGameInterface
{
public:
//minor interfaces
boost::mutex *pim;
bool makingTurn;
SDL_Event * current;
SDL_Event * current;
IActivable *curint;
CAdvMapInt * adventureInt;
CCastleInterface * castleInt;
FPSmanager * mainFPSmng;
IStatusBar *statusbar;
//TODO: town interace, battle interface, other interfaces
//to commucate with engine
CCallback * cb;
//GUI elements
std::vector<ClickableL*> lclickable;
std::vector<ClickableR*> rclickable;
std::vector<Hoverable*> hoverable;
@ -309,15 +318,7 @@ public:
std::vector<TimeInterested*> timeinterested;
std::vector<IShowable*> objsToBlit;
SDL_Surface * hInfo, *tInfo;
std::vector<std::pair<int, int> > slotsPos;
CDefEssential *luck22, *luck30, *luck42, *luck82,
*morale22, *morale30, *morale42, *morale82,
*halls, *forts, *bigTownPic;
std::map<int,SDL_Surface*> heroWins;
std::map<int,SDL_Surface*> townWins;
//overloaded funcs from Interface
//overloaded funcs from CGameInterface
void yourTurn();
void heroMoved(const HeroMoveDetails & details);
void tileRevealed(int3 pos);
@ -326,19 +327,19 @@ public:
void heroCreated(const CGHeroInstance* hero);
void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, int val);
void receivedResource(int type, int val);
void showInfoDialog(std::string text, std::vector<Component*> &components);
void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID);
void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town);
void garrisonChanged(const CGObjectInstance * obj);
void buildChanged(const CGTownInstance *town, int buildingID, int what); //what: 1 - built, 2 - demolished
//battles
void battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::logic::tribool side); //called by engine when battle starts; side=0 - left, side=1 - right
//for battles
void battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side); //called by engine when battle starts; side=0 - left, side=1 - right
void battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles); //called when battlefield is prepared, prior the battle beginning
void battleNewRound(int round); //called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
void actionStarted(BattleAction action);//occurs BEFORE every action taken by any stack or by the hero
void actionFinished(BattleAction action);//occurs AFTER every action taken by any stack or by the hero
BattleAction activeStack(int stackID); //called when it's turn of that stack
void battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner);
void battleEnd(BattleResult *br);
void battleStackMoved(int ID, int dest, bool startMoving, bool endMoving);
void battleStackAttacking(int ID, int dest);
void battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting);
@ -349,7 +350,6 @@ public:
//-------------//
void showComp(SComponent comp);
void openTownWindow(const CGTownInstance * town); //shows townscreen
void openHeroWindow(const CGHeroInstance * hero); //shows hero window with given hero
SDL_Surface * infoWin(const CGObjectInstance * specific); //specific=0 => draws info about selected town/hero //TODO - gdy sie dorobi sensowna hierarchie klas ins. to wywalic tego brzydkiego void*
@ -359,14 +359,11 @@ public:
void handleMouseMotion(SDL_Event *sEvent);
void init(ICallback * CB);
int3 repairScreenPos(int3 pos);
void removeObjToBlit(IShowable* obj);
void showInfoDialog(std::string text, std::vector<SComponent*> & components);
void removeObjToBlit(IShowable* obj);
SDL_Surface * drawHeroInfoWin(const CGHeroInstance * curh);
SDL_Surface * drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from=0, int to=PRIMARY_SKILLS);
SDL_Surface * drawTownInfoWin(const CGTownInstance * curh);
CPlayerInterface(int Player, int serial);
CPlayerInterface(int Player, int serial);//c-tor
~CPlayerInterface();//d-tor
};
class CStatusBar
: public CIntObject, public IStatusBar
@ -537,4 +534,6 @@ public:
void show(SDL_Surface * to = NULL);
};
extern CPlayerInterface * LOCPLINT;
#endif //CPLAYERINTERFACE_H

View File

@ -1,5 +1,6 @@
#include "stdafx.h"
#include "CPreGame.h"
#include "hch/CDefHandler.h"
#include "SDL.h"
#include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations
#include "boost/algorithm/string.hpp"
@ -11,16 +12,22 @@
#include "CGameInfo.h"
#include "hch/CGeneralTextHandler.h"
#include "CCursorHandler.h"
#include "CScreenHandler.h"
#include "hch/CLodHandler.h"
#include "hch/CTownHandler.h"
#include "hch/CHeroHandler.h"
#include <cmath>
#include "client/Graphics.h"
#include <boost/thread.hpp>
#include <boost/bind.hpp>
extern SDL_Surface * screen;
extern SDL_Color tytulowy, tlo, zwykly ;
extern TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX, *GEORM;
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
SDL_Rect genRect(int hh, int ww, int xx, int yy);
SDL_Color genRGB(int r, int g, int b, int a=0);
//void printAt(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen);
@ -162,16 +169,16 @@ Slider::Slider(int x, int y, int h, int amnt, int cap, bool ver)
if (ver)
{
pos = genRect(h,16,x,y);
down = Button(genRect(16,16,x,y+h-16),boost::bind(&Slider::moveDown,this),CGI->spriteh->giveDef("SCNRBDN.DEF"),false);
up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CGI->spriteh->giveDef("SCNRBUP.DEF"),false);
slider = Button(genRect(16,16,x,y+16),boost::function<void()>(),CGI->spriteh->giveDef("SCNRBSL.DEF"),false);
down = Button(genRect(16,16,x,y+h-16),boost::bind(&Slider::moveDown,this),CDefHandler::giveDef("SCNRBDN.DEF"),false);
up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CDefHandler::giveDef("SCNRBUP.DEF"),false);
slider = Button(genRect(16,16,x,y+16),boost::function<void()>(),CDefHandler::giveDef("SCNRBSL.DEF"),false);
}
else
{
pos = genRect(16,h,x,y);
down = Button(genRect(16,16,x+h-16,y),boost::bind(&Slider::moveDown,this),CGI->spriteh->giveDef("SCNRBRT.DEF"),false);
up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CGI->spriteh->giveDef("SCNRBLF.DEF"),false);
slider = Button(genRect(16,16,x+16,y),boost::function<void()>(),CGI->spriteh->giveDef("SCNRBSL.DEF"),false);
down = Button(genRect(16,16,x+h-16,y),boost::bind(&Slider::moveDown,this),CDefHandler::giveDef("SCNRBRT.DEF"),false);
up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CDefHandler::giveDef("SCNRBLF.DEF"),false);
slider = Button(genRect(16,16,x+16,y),boost::function<void()>(),CDefHandler::giveDef("SCNRBSL.DEF"),false);
}
moving = false;
whereAreWe=0;
@ -447,7 +454,7 @@ void Options::OptionSwitch::press(bool down)
for (;;)
{
ourOpt->castle+=dir;
if (((int)pow((double)2,ourOpt->castle))&ourInf->allowedFactions)
if (((int)pow((double)2,(int)ourOpt->castle))&ourInf->allowedFactions)
{
break;
}
@ -585,7 +592,7 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
int pom=ourOpt->castle;
if (ourOpt->castle<F_NUMBER && ourOpt->castle>=0)
{
blitAtWR(CGI->townh->getPic(ourOpt->castle,true,false),176,130+50*se);
blitAtWR(graphics->getPic(ourOpt->castle,true,false),176,130+50*se);
}
else if (ourOpt->castle==-1)
{
@ -608,7 +615,8 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
{
if(ourOpt->heroPortrait>=0)
{
blitAtWR(CGI->heroh->smallPortraits[ourOpt->heroPortrait],252,130+50*se);
//TODO: restore drawing hero portrait
//blitAtWR(CGI->heroh->heroes[ourOpt->heroPortrait]->portraitSmall,252,130+50*se);
}
else
{
@ -617,7 +625,8 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
}
else
{
blitAtWR(CGI->heroh->smallPortraits[pom],252,130+50*se);
//TODO: restore drawing hero portrait
//blitAtWR(CGI->heroh->heroes[pom]->portraitSmall,252,130+50*se);
}
break;
}
@ -664,35 +673,35 @@ Options::~Options()
void Options::init()
{
inited=true;
bg = CGI->bitmaph->loadBitmap("ADVOPTBK.bmp");
bg = BitmapHandler::loadBitmap("ADVOPTBK.bmp");
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
left = CGI->spriteh->giveDef("ADOPLFA.DEF");
right = CGI->spriteh->giveDef("ADOPRTA.DEF");
bonuses = CGI->spriteh->giveDef("SCNRSTAR.DEF");
rHero = CGI->bitmaph->loadBitmap("HPSRAND1.bmp");
rCastle = CGI->bitmaph->loadBitmap("HPSRAND0.bmp");
nHero = CGI->bitmaph->loadBitmap("HPSRAND6.bmp");
nCastle = CGI->bitmaph->loadBitmap("HPSRAND5.bmp");
left = CDefHandler::giveDef("ADOPLFA.DEF");
right = CDefHandler::giveDef("ADOPRTA.DEF");
bonuses = CDefHandler::giveDef("SCNRSTAR.DEF");
rHero = BitmapHandler::loadBitmap("HPSRAND1.bmp");
rCastle = BitmapHandler::loadBitmap("HPSRAND0.bmp");
nHero = BitmapHandler::loadBitmap("HPSRAND6.bmp");
nCastle = BitmapHandler::loadBitmap("HPSRAND5.bmp");
turnLength = new Slider(57,557,195,11,1,false);
turnLength->fun=boost::bind(&CPreGame::setTurnLength,CPG,_1);
flags.push_back(CGI->spriteh->giveDef("AOFLGBR.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBB.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBY.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBG.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBO.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBP.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBT.DEF"));
flags.push_back(CGI->spriteh->giveDef("AOFLGBS.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBR.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBB.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBY.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBG.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBO.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBP.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBT.DEF"));
flags.push_back(CDefHandler::giveDef("AOFLGBS.DEF"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPRPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPBPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPYPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPGPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPOPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPPPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPTPNL.bmp"));
bgs.push_back(CGI->bitmaph->loadBitmap("ADOPSPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPRPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPBPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPYPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPGPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPOPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPPPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPTPNL.bmp"));
bgs.push_back(BitmapHandler::loadBitmap("ADOPSPNL.bmp"));
}
void Options::show()
{
@ -970,73 +979,50 @@ void MapSel::show()
//SDL_Flip(screen);
CSDL_Ext::update(screen);
}
boost::mutex mx;
void MapSel::processMaps(std::vector<std::string> &pliczkiTemp, int &index)
{
bool areMaps=true;
int pom=-1;
while(areMaps)
{
mx.lock();
if(index>=pliczkiTemp.size())
{
mx.unlock();
break;
}
else
{
pom = index++;
mx.unlock();
}
gzFile tempf = gzopen(pliczkiTemp[pom].c_str(),"rb");
unsigned char * sss = new unsigned char[1000];
int iii=0;
while(true)
{
if (iii>=1000) break;
int z = gzgetc (tempf);
if (z>=0)
{
sss[iii++] = (unsigned char)z;
}
else break;
}
gzclose(tempf);
if(iii<50) {std::cout<<"\t\tWarning: corrupted map file: "<<pliczkiTemp[pom]<<std::endl; continue;}
if (!sss[4]) continue; //nie ma graczy? mapa niegrywalna //ju¿ to kiedyœ komentowa³em- - to bzdura //tu calkiem pasuje...
CMapInfo mi(pliczkiTemp[pom],sss);
mx.lock();
ourMaps.push_back(mi);
mx.unlock();
delete[] sss;
}
}
void MapSel::init()
{
bg = CGI->bitmaph->loadBitmap("SCSELBCK.bmp");
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
small.imgs = CGI->spriteh->giveDef("SCSMBUT.DEF");
small.fun = NULL;
small.pos = genRect(small.imgs->ourImages[0].bitmap->h,small.imgs->ourImages[0].bitmap->w,161,52);
small.ourGroup=NULL;
medium.imgs = CGI->spriteh->giveDef("SCMDBUT.DEF");
medium.fun = NULL;
medium.pos = genRect(medium.imgs->ourImages[0].bitmap->h,medium.imgs->ourImages[0].bitmap->w,208,52);
medium.ourGroup=NULL;
large.imgs = CGI->spriteh->giveDef("SCLGBUT.DEF");
large.fun = NULL;
large.pos = genRect(large.imgs->ourImages[0].bitmap->h,large.imgs->ourImages[0].bitmap->w,255,52);
large.ourGroup=NULL;
xlarge.imgs = CGI->spriteh->giveDef("SCXLBUT.DEF");
xlarge.fun = NULL;
xlarge.pos = genRect(xlarge.imgs->ourImages[0].bitmap->h,xlarge.imgs->ourImages[0].bitmap->w,302,52);
xlarge.ourGroup=NULL;
all.imgs = CGI->spriteh->giveDef("SCALBUT.DEF");
all.fun = NULL;
all.pos = genRect(all.imgs->ourImages[0].bitmap->h,all.imgs->ourImages[0].bitmap->w,349,52);
all.ourGroup=NULL;
all.selectable=xlarge.selectable=large.selectable=medium.selectable=small.selectable=false;
small.what=medium.what=large.what=xlarge.what=all.what=&sizeFilter;
small.key=36;medium.key=72;large.key=108;xlarge.key=144;all.key=0;
//Button<> nrplayer, mapsize, type, name, viccon, loscon;
nrplayer.imgs = CGI->spriteh->giveDef("SCBUTT1.DEF");
nrplayer.fun = NULL;
nrplayer.pos = genRect(nrplayer.imgs->ourImages[0].bitmap->h,nrplayer.imgs->ourImages[0].bitmap->w,26,92);
nrplayer.key=_playerAm;
mapsize.imgs = CGI->spriteh->giveDef("SCBUTT2.DEF");
mapsize.fun = NULL;
mapsize.pos = genRect(mapsize.imgs->ourImages[0].bitmap->h,mapsize.imgs->ourImages[0].bitmap->w,58,92);
mapsize.key=_size;
type.imgs = CGI->spriteh->giveDef("SCBUTCP.DEF");
type.fun = NULL;
type.pos = genRect(type.imgs->ourImages[0].bitmap->h,type.imgs->ourImages[0].bitmap->w,91,92);
type.key=_format;
name.imgs = CGI->spriteh->giveDef("SCBUTT3.DEF");
name.fun = NULL;
name.pos = genRect(name.imgs->ourImages[0].bitmap->h,name.imgs->ourImages[0].bitmap->w,124,92);
name.key=_name;
viccon.imgs = CGI->spriteh->giveDef("SCBUTT4.DEF");
viccon.fun = NULL;
viccon.pos = genRect(viccon.imgs->ourImages[0].bitmap->h,viccon.imgs->ourImages[0].bitmap->w,309,92);
viccon.key=_viccon;
loscon.imgs = CGI->spriteh->giveDef("SCBUTT5.DEF");
loscon.fun = NULL;
loscon.pos = genRect(loscon.imgs->ourImages[0].bitmap->h,loscon.imgs->ourImages[0].bitmap->w,342,92);
loscon.key=_loscon;
nrplayer.poin=mapsize.poin=type.poin=name.poin=viccon.poin=loscon.poin=(int*)(&sortBy);
nrplayer.fun=mapsize.fun=type.fun=name.fun=viccon.fun=loscon.fun=boost::bind(&CPreGame::sortMaps,CPG);
Dtypes = CGI->spriteh->giveDef("SCSELC.DEF");
Dvic = CGI->spriteh->giveDef("SCNRVICT.DEF");
Dloss = CGI->spriteh->giveDef("SCNRLOSS.DEF");
//Dsizes = CPG->slh->giveDef("SCNRMPSZ.DEF");
Dsizes = CGI->spriteh->giveDef("SCNRMPSZ.DEF");
sFlags = CGI->spriteh->giveDef("ITGFLAGS.DEF");
//get map files names
std::vector<std::string> pliczkiTemp;
fs::path tie( (fs::initial_path<fs::path>())/"/maps" );
@ -1049,31 +1035,79 @@ void MapSel::init()
pliczkiTemp.push_back("Maps/"+(dir->path().leaf()));
}
}
for (int i=0; i<pliczkiTemp.size();i++)
{
gzFile tempf = gzopen(pliczkiTemp[i].c_str(),"rb");
std::string sss;
int iii=0;
while(++iii)
{
if (iii>4000) break;
int z = gzgetc (tempf);
if (z>=0)
{
sss+=(unsigned char)z;
}
else break;
}
gzclose(tempf);
//if (sss[0]<28) continue; //zly format
if(iii<5) {std::cout<<"\t\tWarning: corrupted map file: "<<pliczkiTemp[i]<<std::endl; continue;}
if (!sss[4]) continue; //nie ma graczy? mapa niegrywalna //ju? to kiedy? komentowa?em- - to bzdura //tu calkiem pasuje...
unsigned char* file2 = new unsigned char[sss.length()];
for (int j=0;j<sss.length();j++)
file2[j]=sss[j];
ourMaps.push_back(CMapInfo(pliczkiTemp[i],file2));
delete[] file2;
}
int mapInd=0;
boost::thread_group group;
int cores = std::max((unsigned int)1,boost::thread::hardware_concurrency());
for(int ti=0;ti<cores;ti++)
group.create_thread(boost::bind(&MapSel::processMaps,this,boost::ref(pliczkiTemp),boost::ref(mapInd)));
bg = BitmapHandler::loadBitmap("SCSELBCK.bmp");
SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
small.imgs = CDefHandler::giveDef("SCSMBUT.DEF");
small.fun = NULL;
small.pos = genRect(small.imgs->ourImages[0].bitmap->h,small.imgs->ourImages[0].bitmap->w,161,52);
small.ourGroup=NULL;
medium.imgs = CDefHandler::giveDef("SCMDBUT.DEF");
medium.fun = NULL;
medium.pos = genRect(medium.imgs->ourImages[0].bitmap->h,medium.imgs->ourImages[0].bitmap->w,208,52);
medium.ourGroup=NULL;
large.imgs = CDefHandler::giveDef("SCLGBUT.DEF");
large.fun = NULL;
large.pos = genRect(large.imgs->ourImages[0].bitmap->h,large.imgs->ourImages[0].bitmap->w,255,52);
large.ourGroup=NULL;
xlarge.imgs = CDefHandler::giveDef("SCXLBUT.DEF");
xlarge.fun = NULL;
xlarge.pos = genRect(xlarge.imgs->ourImages[0].bitmap->h,xlarge.imgs->ourImages[0].bitmap->w,302,52);
xlarge.ourGroup=NULL;
all.imgs = CDefHandler::giveDef("SCALBUT.DEF");
all.fun = NULL;
all.pos = genRect(all.imgs->ourImages[0].bitmap->h,all.imgs->ourImages[0].bitmap->w,349,52);
all.ourGroup=NULL;
all.selectable=xlarge.selectable=large.selectable=medium.selectable=small.selectable=false;
small.what=medium.what=large.what=xlarge.what=all.what=&sizeFilter;
small.key=36;medium.key=72;large.key=108;xlarge.key=144;all.key=0;
//Button<> nrplayer, mapsize, type, name, viccon, loscon;
nrplayer.imgs = CDefHandler::giveDef("SCBUTT1.DEF");
nrplayer.fun = NULL;
nrplayer.pos = genRect(nrplayer.imgs->ourImages[0].bitmap->h,nrplayer.imgs->ourImages[0].bitmap->w,26,92);
nrplayer.key=_playerAm;
mapsize.imgs = CDefHandler::giveDef("SCBUTT2.DEF");
mapsize.fun = NULL;
mapsize.pos = genRect(mapsize.imgs->ourImages[0].bitmap->h,mapsize.imgs->ourImages[0].bitmap->w,58,92);
mapsize.key=_size;
type.imgs = CDefHandler::giveDef("SCBUTCP.DEF");
type.fun = NULL;
type.pos = genRect(type.imgs->ourImages[0].bitmap->h,type.imgs->ourImages[0].bitmap->w,91,92);
type.key=_format;
name.imgs = CDefHandler::giveDef("SCBUTT3.DEF");
name.fun = NULL;
name.pos = genRect(name.imgs->ourImages[0].bitmap->h,name.imgs->ourImages[0].bitmap->w,124,92);
name.key=_name;
viccon.imgs = CDefHandler::giveDef("SCBUTT4.DEF");
viccon.fun = NULL;
viccon.pos = genRect(viccon.imgs->ourImages[0].bitmap->h,viccon.imgs->ourImages[0].bitmap->w,309,92);
viccon.key=_viccon;
loscon.imgs = CDefHandler::giveDef("SCBUTT5.DEF");
loscon.fun = NULL;
loscon.pos = genRect(loscon.imgs->ourImages[0].bitmap->h,loscon.imgs->ourImages[0].bitmap->w,342,92);
loscon.key=_loscon;
nrplayer.poin=mapsize.poin=type.poin=name.poin=viccon.poin=loscon.poin=(int*)(&sortBy);
nrplayer.fun=mapsize.fun=type.fun=name.fun=viccon.fun=loscon.fun=boost::bind(&CPreGame::sortMaps,CPG);
Dtypes = CDefHandler::giveDef("SCSELC.DEF");
Dvic = CDefHandler::giveDef("SCNRVICT.DEF");
Dloss = CDefHandler::giveDef("SCNRLOSS.DEF");
//Dsizes = CPG->slh->giveDef("SCNRMPSZ.DEF");
Dsizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
group.join_all();
std::sort(ourMaps.begin(),ourMaps.end(),mapSorter(_name));
slid = new Slider(375,92,480,ourMaps.size(),18,true);
slid->fun = boost::bind(&CPreGame::printMapsFrom,CPG,_1);
@ -1105,6 +1139,7 @@ void MapSel::select(int which, bool updateMapsList, bool forceSettingsUpdate)
{
bool dontSaveSettings = ((selected!=which) || (CPG->ret.playerInfos.size()==0) || forceSettingsUpdate);
selected = which;
CPG->ret.mapname = ourMaps[selected].filename;
if(updateMapsList)
printMaps(slid->whereAreWe,18,0,true);
int serialC=0;
@ -1385,14 +1420,14 @@ void CPreGame::initScenSel()
{
ourScenSel = new ScenSel();
ourScenSel->listShowed=false;
if (rand()%2) ourScenSel->background=CGI->bitmaph->loadBitmap("ZPIC1000.bmp");
else ourScenSel->background=CGI->bitmaph->loadBitmap("ZPIC1001.bmp");
if (rand()%2) ourScenSel->background=BitmapHandler::loadBitmap("ZPIC1000.bmp");
else ourScenSel->background=BitmapHandler::loadBitmap("ZPIC1001.bmp");
ourScenSel->pressed=NULL;
ourScenSel->scenInf=CGI->bitmaph->loadBitmap("GSELPOP1.bmp");//SDL_LoadBMP("h3bitmap.lod\\GSELPOP1.bmp");
ourScenSel->randMap=CGI->bitmaph->loadBitmap("RANMAPBK.bmp");
ourScenSel->options=CGI->bitmaph->loadBitmap("ADVOPTBK.bmp");
ourScenSel->scenInf=BitmapHandler::loadBitmap("GSELPOP1.bmp");//SDL_LoadBMP("h3bitmap.lod\\GSELPOP1.bmp");
ourScenSel->randMap=BitmapHandler::loadBitmap("RANMAPBK.bmp");
ourScenSel->options=BitmapHandler::loadBitmap("ADVOPTBK.bmp");
SDL_SetColorKey(ourScenSel->scenInf,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->scenInf->format,0,255,255));
//SDL_SetColorKey(ourScenSel->scenList,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->scenList->format,0,255,255));
SDL_SetColorKey(ourScenSel->randMap,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->randMap->format,0,255,255));
@ -1402,22 +1437,22 @@ void CPreGame::initScenSel()
ourScenSel->difficulty->type=1;
ourScenSel->selectedDiff=-77;
ourScenSel->difficulty->gdzie = &ourScenSel->selectedDiff;
ourScenSel->bEasy = IntSelBut(genRect(0,0,506,456),NULL,CGI->spriteh->giveDef("GSPBUT3.DEF"),true,ourScenSel->difficulty,0);
ourScenSel->bNormal = IntSelBut(genRect(0,0,538,456),NULL,CGI->spriteh->giveDef("GSPBUT4.DEF"),true,ourScenSel->difficulty,1);
ourScenSel->bHard = IntSelBut(genRect(0,0,570,456),NULL,CGI->spriteh->giveDef("GSPBUT5.DEF"),true,ourScenSel->difficulty,2);
ourScenSel->bExpert = IntSelBut(genRect(0,0,602,456),NULL,CGI->spriteh->giveDef("GSPBUT6.DEF"),true,ourScenSel->difficulty,3);
ourScenSel->bImpossible = IntSelBut(genRect(0,0,634,456),NULL,CGI->spriteh->giveDef("GSPBUT7.DEF"),true,ourScenSel->difficulty,4);
ourScenSel->bEasy = IntSelBut(genRect(0,0,506,456),NULL,CDefHandler::giveDef("GSPBUT3.DEF"),true,ourScenSel->difficulty,0);
ourScenSel->bNormal = IntSelBut(genRect(0,0,538,456),NULL,CDefHandler::giveDef("GSPBUT4.DEF"),true,ourScenSel->difficulty,1);
ourScenSel->bHard = IntSelBut(genRect(0,0,570,456),NULL,CDefHandler::giveDef("GSPBUT5.DEF"),true,ourScenSel->difficulty,2);
ourScenSel->bExpert = IntSelBut(genRect(0,0,602,456),NULL,CDefHandler::giveDef("GSPBUT6.DEF"),true,ourScenSel->difficulty,3);
ourScenSel->bImpossible = IntSelBut(genRect(0,0,634,456),NULL,CDefHandler::giveDef("GSPBUT7.DEF"),true,ourScenSel->difficulty,4);
ourScenSel->bBack = Button(genRect(0,0,584,535),boost::bind(&CPreGame::showNewMenu,this),CGI->spriteh->giveDef("SCNRBACK.DEF"));
ourScenSel->bBegin = Button(genRect(0,0,414,535),boost::bind(&CPreGame::begin,this),CGI->spriteh->giveDef("SCNRBEG.DEF"));
ourScenSel->bBack = Button(genRect(0,0,584,535),boost::bind(&CPreGame::showNewMenu,this),CDefHandler::giveDef("SCNRBACK.DEF"));
ourScenSel->bBegin = Button(genRect(0,0,414,535),boost::bind(&CPreGame::begin,this),CDefHandler::giveDef("SCNRBEG.DEF"));
ourScenSel->bScens = Button(genRect(0,0,414,81),boost::bind(&CPreGame::showScenList,this),CDefHandler::giveDef("GSPBUTT.DEF"));
ourScenSel->bScens = Button(genRect(0,0,414,81),boost::bind(&CPreGame::showScenList,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
for (int i=0; i<ourScenSel->bScens.imgs->ourImages.size(); i++)
CSDL_Ext::printAt(CGI->generaltexth->allTexts[500],25+i,2+i,GEOR13,zwykly,ourScenSel->bScens.imgs->ourImages[i].bitmap); //"Show Available Scenarios"
ourScenSel->bRandom = Button(genRect(0,0,414,105),boost::bind(&CPreGame::showScenList,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
ourScenSel->bRandom = Button(genRect(0,0,414,105),boost::bind(&CPreGame::showScenList,this),CDefHandler::giveDef("GSPBUTT.DEF"));
for (int i=0; i<ourScenSel->bRandom.imgs->ourImages.size(); i++)
CSDL_Ext::printAt(CGI->generaltexth->allTexts[740],25+i,2+i,GEOR13,zwykly,ourScenSel->bRandom.imgs->ourImages[i].bitmap);
ourScenSel->bOptions = Button(genRect(0,0,414,509),boost::bind(&CPreGame::showOptions,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
ourScenSel->bOptions = Button(genRect(0,0,414,509),boost::bind(&CPreGame::showOptions,this),CDefHandler::giveDef("GSPBUTT.DEF"));
for (int i=0; i<ourScenSel->bOptions.imgs->ourImages.size(); i++)
CSDL_Ext::printAt(CGI->generaltexth->allTexts[501],25+i,2+i,GEOR13,zwykly,ourScenSel->bOptions.imgs->ourImages[i].bitmap); //"Show Advanced Options"
@ -1510,17 +1545,17 @@ void CPreGame::showOptions()
void CPreGame::initNewMenu()
{
ourNewMenu = new menuItems();
ourNewMenu->bgAd = CGI->bitmaph->loadBitmap("ZNEWGAM.bmp");
ourNewMenu->background = CGI->bitmaph->loadBitmap("ZPIC1005.bmp");
ourNewMenu->bgAd = BitmapHandler::loadBitmap("ZNEWGAM.bmp");
ourNewMenu->background = BitmapHandler::loadBitmap("ZPIC1005.bmp");
blitAt(ourNewMenu->bgAd,114,312,ourNewMenu->background);
//loading menu buttons
ourNewMenu->newGame = CGI->spriteh->giveDef("ZTSINGL.DEF");
ourNewMenu->loadGame = CGI->spriteh->giveDef("ZTMULTI.DEF");
ourNewMenu->highScores = CGI->spriteh->giveDef("ZTCAMPN.DEF");
ourNewMenu->credits = CGI->spriteh->giveDef("ZTTUTOR.DEF");
ourNewMenu->quit = CGI->spriteh->giveDef("ZTBACK.DEF");
ok = CGI->spriteh->giveDef("IOKAY.DEF");
cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
ourNewMenu->newGame = CDefHandler::giveDef("ZTSINGL.DEF");
ourNewMenu->loadGame = CDefHandler::giveDef("ZTMULTI.DEF");
ourNewMenu->highScores = CDefHandler::giveDef("ZTCAMPN.DEF");
ourNewMenu->credits = CDefHandler::giveDef("ZTTUTOR.DEF");
ourNewMenu->quit = CDefHandler::giveDef("ZTBACK.DEF");
ok = CDefHandler::giveDef("IOKAY.DEF");
cancel = CDefHandler::giveDef("ICANCEL.DEF");
// single scenario
ourNewMenu->lNewGame.h=ourNewMenu->newGame->ourImages[0].bitmap->h;
ourNewMenu->lNewGame.w=ourNewMenu->newGame->ourImages[0].bitmap->w;
@ -1572,15 +1607,15 @@ void CPreGame::showNewMenu()
void CPreGame::initMainMenu()
{
ourMainMenu = new menuItems();
ourMainMenu->background = CGI->bitmaph->loadBitmap("ZPIC1005.bmp"); //SDL_LoadBMP("h3bitmap.lod\\ZPIC1005.bmp");
ourMainMenu->background = BitmapHandler::loadBitmap("ZPIC1005.bmp"); //SDL_LoadBMP("h3bitmap.lod\\ZPIC1005.bmp");
//loading menu buttons
ourMainMenu->newGame = CGI->spriteh->giveDef("ZMENUNG.DEF");
ourMainMenu->loadGame = CGI->spriteh->giveDef("ZMENULG.DEF");
ourMainMenu->highScores = CGI->spriteh->giveDef("ZMENUHS.DEF");
ourMainMenu->credits = CGI->spriteh->giveDef("ZMENUCR.DEF");
ourMainMenu->quit = CGI->spriteh->giveDef("ZMENUQT.DEF");
ok = CGI->spriteh->giveDef("IOKAY.DEF");
cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
ourMainMenu->newGame = CDefHandler::giveDef("ZMENUNG.DEF");
ourMainMenu->loadGame = CDefHandler::giveDef("ZMENULG.DEF");
ourMainMenu->highScores = CDefHandler::giveDef("ZMENUHS.DEF");
ourMainMenu->credits = CDefHandler::giveDef("ZMENUCR.DEF");
ourMainMenu->quit = CDefHandler::giveDef("ZMENUQT.DEF");
ok = CDefHandler::giveDef("IOKAY.DEF");
cancel = CDefHandler::giveDef("ICANCEL.DEF");
// new game button location
ourMainMenu->lNewGame.h=ourMainMenu->newGame->ourImages[0].bitmap->h;
ourMainMenu->lNewGame.w=ourMainMenu->newGame->ourImages[0].bitmap->w;
@ -1820,7 +1855,6 @@ StartInfo CPreGame::runLoop()
SDL_Event sEvent;
while(run)
{
CGI->screenh->updateScreen();
try
{
if(SDL_PollEvent(&sEvent)) //wait for event...
@ -2077,8 +2111,10 @@ StartInfo CPreGame::runLoop()
}
catch(...)
{ continue; }
SDL_Delay(1); //give time for other apps
CGI->curh->draw1();
SDL_Flip(screen);
CGI->curh->draw2();
SDL_Delay(20); //give time for other apps
}
return ret;
}

View File

@ -4,16 +4,15 @@
#include <set>
#include "SDL.h"
#include "StartInfo.h"
#include "hch/CSemiDefHandler.h"
#include "hch/CSemiLodHandler.h"
#include "hch/CPreGameTextHandler.h"
#include "hch/CPreGameTextHandler.h"
#include "CMessage.h"
#include "map.h"
#include "hch/CMusicHandler.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
class CPreGame;
extern class CPreGame *CPG;
class CDefHandler;
extern CPreGame * CPG;
typedef void(CPreGame::*ttt)();
class CGroup;
@ -204,6 +203,7 @@ public:
void moveByOne(bool up);
void printSelectedInfo();
void printFlags();
void processMaps(std::vector<std::string> &pliczkiTemp, int &index);
MapSel();
~MapSel();
};

View File

@ -1,45 +0,0 @@
#include "stdafx.h"
#include "CScreenHandler.h"
#include "SDL.h"
#include "SDL_thread.h"
#include "SDL_framerate.h"
#include "SDL_Extensions.h"
#include "CCursorHandler.h"
#include "CGameInfo.h"
#include "hch/CDefHandler.h"
extern SDL_Surface * screen, * screen2;
void CScreenHandler::initScreen()
{
//myth = SDL_CreateThread(&internalScreenFunc, this);
}
void CScreenHandler::updateScreen()
{
/*blitAt(screen, 0, 0, screen2);
switch(CGI->curh->mode)
{
case 0:
{
blitAt(CGI->curh->adventure->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
break;
}
case 1:
{
blitAt(CGI->curh->combat->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
break;
}
case 2:
{
blitAt(CGI->curh->deflt->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
break;
}
case 3:
{
blitAt(CGI->curh->spell->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
break;
}
}
CSDL_Ext::update(screen2);*/
}

View File

@ -1,17 +0,0 @@
#ifndef CSCREENHANDLER_H
#define CSCREENHANDLER_H
struct SDL_Thread;
class CScreenHandler
{
private:
SDL_Thread * myth;
public:
void initScreen();
void updateScreen();
};
#endif //CSCREENHANDLER_H

View File

@ -1 +0,0 @@

Binary file not shown.

View File

@ -1,40 +1,48 @@
ACLOCAL_AMFLAGS = -I aclocal/m4
EXTRA_DIST = aclocal/m4
bin_PROGRAMS = vcmi
vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB)
#bin_PROGRAMS = vcmi
#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
AM_CXXFLAGS = $(BOOST_CPPFLAGS)
vcmi_SOURCES = \
AdventureMapButton.cpp CGameState.cpp CScreenHandler.h \
AdventureMapButton.h CGameState.h global.h \
AI_Base.h CHeroWindow.cpp int3.h \
CAdvmapInterface.cpp CHeroWindow.h map.cpp \
CAdvmapInterface.h CLua.cpp map.h \
CBattleInterface.cpp CLua.h mapHandler.cpp \
CBattleInterface.h CLuaHandler.cpp mapHandler.h \
CCallback.cpp CLuaHandler.h nodrze.h \
CCallback.h CMessage.cpp SDL_Extensions.cpp \
CCastleInterface.cpp CMessage.h SDL_Extensions.h \
CCastleInterface.h CMT.cpp SDL_framerate.cpp \
CConsoleHandler.cpp SDL_framerate.h \
CConsoleHandler.h CPathfinder.cpp SDL_rotozoom.cpp \
CCursorHandler.cpp CPathfinder.h SDL_rotozoom.h \
CCursorHandler.h CPlayerInterface.cpp StartInfo.h \
CGameInfo.cpp CPlayerInterface.h stdafx.cpp \
CGameInfo.h CPreGame.cpp stdafx.h \
CGameInterface.cpp CPreGame.h tchar_amigaos4.h \
CGameInterface.h CScreenHandler.cpp timeHandler.h \
hch/CAbilityHandler.cpp hch/CDefObjInfoHandler.cpp hch/CSemiDefHandler.cpp \
hch/CAbilityHandler.h hch/CDefObjInfoHandler.h hch/CSemiDefHandler.h \
hch/CAmbarCendamo.cpp hch/CGeneralTextHandler.cpp hch/CSemiLodHandler.cpp \
hch/CAmbarCendamo.h hch/CGeneralTextHandler.h hch/CSemiLodHandler.h \
hch/CArtHandler.cpp hch/CHeroHandler.cpp hch/CSndHandler.cpp \
hch/CArtHandler.h hch/CHeroHandler.h hch/CSndHandler.h \
hch/CBuildingHandler.cpp hch/CLodHandler.cpp hch/CSpellHandler.cpp \
hch/CBuildingHandler.h hch/CLodHandler.h hch/CSpellHandler.h \
hch/CCastleHandler.cpp hch/CMusicHandler.cpp hch/CTownHandler.cpp \
hch/CCastleHandler.h hch/CMusicHandler.h hch/CTownHandler.h \
hch/CCreatureHandler.cpp hch/CObjectHandler.cpp hch/CVideoHandler.cpp \
hch/CCreatureHandler.h hch/CObjectHandler.h hch/CVideoHandler.h \
hch/CDefHandler.cpp hch/CPreGameTextHandler.cpp \
hch/CDefHandler.h hch/CPreGameTextHandler.h
SUBDIRS = lib client server
#vcmi_SOURCES = \
# AdventureMapButton.cpp CGameState.cpp \
# AdventureMapButton.h CGameState.h global.h \
# AI_Base.h CHeroWindow.cpp int3.h \
# CAdvmapInterface.cpp CHeroWindow.h map.cpp \
# CAdvmapInterface.h CLua.cpp map.h \
# CBattleInterface.cpp CLua.h mapHandler.cpp \
# CBattleInterface.h CLuaHandler.cpp mapHandler.h \
# CCallback.cpp CLuaHandler.h nodrze.h \
# CCallback.h CMessage.cpp SDL_Extensions.cpp \
# CCastleInterface.cpp CMessage.h SDL_Extensions.h \
# CCastleInterface.h CMT.cpp SDL_framerate.cpp \
# CConsoleHandler.cpp SDL_framerate.h \
# CConsoleHandler.h CPathfinder.cpp \
# CCursorHandler.cpp CPathfinder.h \
# CCursorHandler.h CPlayerInterface.cpp StartInfo.h \
# CGameInfo.cpp CPlayerInterface.h stdafx.cpp \
# CGameInfo.h CPreGame.cpp stdafx.h \
# CGameInterface.cpp CPreGame.h tchar_amigaos4.h \
# CGameInterface.h timeHandler.h \
# hch/CAbilityHandler.cpp hch/CDefObjInfoHandler.cpp \
# hch/CAbilityHandler.h hch/CDefObjInfoHandler.h \
# hch/CAmbarCendamo.cpp hch/CGeneralTextHandler.cpp \
# hch/CAmbarCendamo.h hch/CGeneralTextHandler.h \
# hch/CArtHandler.cpp hch/CHeroHandler.cpp hch/CSndHandler.cpp \
# hch/CArtHandler.h hch/CHeroHandler.h hch/CSndHandler.h \
# hch/CBuildingHandler.cpp hch/CLodHandler.cpp hch/CSpellHandler.cpp \
# hch/CBuildingHandler.h hch/CLodHandler.h hch/CSpellHandler.h \
# hch/CMusicHandler.cpp hch/CTownHandler.cpp \
# hch/CMusicHandler.h hch/CTownHandler.h \
# hch/CCreatureHandler.cpp hch/CObjectHandler.cpp hch/CVideoHandler.cpp \
# hch/CCreatureHandler.h hch/CObjectHandler.h hch/CVideoHandler.h \
# hch/CDefHandler.cpp hch/CPreGameTextHandler.cpp \
# hch/CDefHandler.h hch/CPreGameTextHandler.h \
#client/CBitmapHandler.cpp client/CCreatureAnimation.cpp client/Client.cpp client/Graphics.cpp \
#client/CBitmapHandler.h client/CCreatureAnimation.h client/Client.h client/Graphics.h \
#lib/VCMI_Lib.h lib/VCMI_Lib.cpp \
# server/CScriptCallback.h server/CScriptCallback.cpp \
# lib/Connection.cpp lib/Connection.h \
# CThreadHelper.cpp CThreadHelper.h
#
#

1
NEWS
View File

@ -1 +0,0 @@

Binary file not shown.

1
README
View File

@ -1 +0,0 @@

View File

@ -9,8 +9,7 @@
#include <boost/algorithm/string.hpp>
#include "hch/CDefHandler.h"
#include <map>
extern SDL_Color playerColorPalette[256];
#include "client/Graphics.h"
SDL_Surface * CSDL_Ext::newSurface(int w, int h, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given
{
@ -416,45 +415,6 @@ SDL_Surface * CSDL_Ext::rotate03(SDL_Surface * toRot)
}
return ret;
}
//converts surface to cursor
SDL_Cursor * CSDL_Ext::SurfaceToCursor(SDL_Surface *image, int hx, int hy)
{
int w, x, y;
Uint8 *data, *mask, *d, *m, r, g, b;
Uint32 color;
SDL_Cursor *cursor;
w = (image->w + 7) / 8;
data = (Uint8 *)alloca(w * image->h * 2);
if (data == NULL)
return NULL;
memset(data, 0, w * image->h * 2);
mask = data + w * image->h;
if (SDL_MUSTLOCK(image))
SDL_LockSurface(image);
for (y = 0; y < image->h; y++)
{
d = data + y * w;
m = mask + y * w;
for (x = 0; x < image->w; x++)
{
color = CSDL_Ext::SDL_GetPixel(image, x, y);
if ((image->flags & SDL_SRCCOLORKEY) == 0 || color != image->format->colorkey)
{
SDL_GetRGB(color, image->format, &r, &g, &b);
color = (r + g + b) / 3;
m[x / 8] |= 128 >> (x & 7);
if (color < 128)
d[x / 8] |= 128 >> (x & 7);
}
}
}
if (SDL_MUSTLOCK(image))
SDL_UnlockSurface(image);
cursor = SDL_CreateCursor(data, mask, w, image->h, hx, hy);
return cursor;
}
Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte)
{
int bpp = surface->format->BytesPerPixel;
@ -486,7 +446,7 @@ Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y
return *(Uint32 *)p;
default:
return 0; /* shouldn't happen, but avoids warnings */
return 0; // shouldn't happen, but avoids warnings
}
}
@ -545,11 +505,6 @@ SDL_Surface * CSDL_Ext::alphaTransform(SDL_Surface *src)
return src;
}
SDL_Surface * CSDL_Ext::secondAlphaTransform(SDL_Surface * src, SDL_Surface * alpha)
{
return copySurface(src);
}
int CSDL_Ext::blit8bppAlphaTo24bpp(SDL_Surface * src, SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect)
{
static std::map<Uint8, int> st;
@ -747,132 +702,6 @@ void CSDL_Ext::update(SDL_Surface * what)
if(what)
SDL_UpdateRect(what, 0, 0, what->w, what->h);
}
void CSDL_Ext::blueToPlayers(SDL_Surface * sur, int player)
{
if(sur->format->BitsPerPixel == 8)
{
for(int i=0; i<sur->format->palette->ncolors; ++i)
{
SDL_Color * cc = sur->format->palette->colors+i;
if(cc->r==0 && cc->g==0 && cc->b==255)
{
cc->r = CGameInfo::mainObj->playerColors[player].r;
cc->g = CGameInfo::mainObj->playerColors[player].g;
cc->b = CGameInfo::mainObj->playerColors[player].b;
}
}
}
else if(sur->format->BitsPerPixel == 24)
{
for(int y=0; y<sur->h; ++y)
{
for(int x=0; x<sur->w; ++x)
{
Uint8* cp = (Uint8*)sur->pixels + y+sur->pitch + x*3;
/*
if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
if(cp[0]==0 && cp[1]==0 && cp[2]==255)
{
cp[0] = CGameInfo::mainObj->playerColors[player].r;
cp[1] = CGameInfo::mainObj->playerColors[player].g;
cp[2] = CGameInfo::mainObj->playerColors[player].b;
}
}
else
{
*/
if(cp[0]==255 && cp[1]==0 && cp[2]==0)
{
cp[0] = CGameInfo::mainObj->playerColors[player].b;
cp[1] = CGameInfo::mainObj->playerColors[player].g;
cp[2] = CGameInfo::mainObj->playerColors[player].r;
}
// }
}
}
}
}
void CSDL_Ext::blueToPlayersAdv(SDL_Surface * sur, int player, int mode, void* additionalInfo)
{
if(player==1) //it is actually blue...
return;
if(sur->format->BitsPerPixel == 8)
{
for(int i=0; i<32; ++i)
{
sur->format->palette->colors[224+i] = playerColorPalette[32*player+i];
}
}
else if(sur->format->BitsPerPixel == 24) //should never happen in general
{
for(int y=0; y<sur->h; ++y)
{
for(int x=0; x<sur->w; ++x)
{
Uint8* cp = (Uint8*)sur->pixels + y*sur->pitch + x*3;
/*
if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
if(cp[2]>cp[1] && cp[2]>cp[0])
{
std::vector<long long int> sort1;
sort1.push_back(cp[0]);
sort1.push_back(cp[1]);
sort1.push_back(cp[2]);
std::vector< std::pair<long long int, Uint8*> > sort2;
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].r, &(cp[0])));
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].g, &(cp[1])));
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].b, &(cp[2])));
std::sort(sort1.begin(), sort1.end());
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
if(sort2[1].first>sort2[2].first)
std::swap(sort2[1], sort2[2]);
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
for(int hh=0; hh<3; ++hh)
{
(*sort2[hh].second) = (sort1[hh] + sort2[hh].first)/2.2;
}
}
}
else
*/
{
if(
((mode==0) && (cp[0]>cp[1]) && (cp[0]>cp[2])) ||
((mode==1) && (cp[2]<45) && (cp[0]>80) && (cp[1]<70) && ((cp[0]-cp[1])>40))
)
{
std::vector<long long int> sort1;
sort1.push_back(cp[2]);
sort1.push_back(cp[1]);
sort1.push_back(cp[0]);
std::vector< std::pair<long long int, Uint8*> > sort2;
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].r, &(cp[2])));
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].g, &(cp[1])));
sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].b, &(cp[0])));
std::sort(sort1.begin(), sort1.end());
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
if(sort2[1].first>sort2[2].first)
std::swap(sort2[1], sort2[2]);
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
for(int hh=0; hh<3; ++hh)
{
(*sort2[hh].second) = (sort1[hh]*0.8 + sort2[hh].first)/2;
}
}
}
}
}
}
}
void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, int3 color)
{
for(int i=0;i<w;i++)
@ -893,9 +722,9 @@ void CSDL_Ext::setPlayerColor(SDL_Surface * sur, unsigned char player)
if(sur->format->BitsPerPixel==8)
{
if(player != 255)
*(sur->format->palette->colors+5) = CGameInfo::mainObj->playerColors[player];
*(sur->format->palette->colors+5) = graphics->playerColors[player];
else
*(sur->format->palette->colors+5) = CGameInfo::mainObj->neutralColor;
*(sur->format->palette->colors+5) = *graphics->neutralColor;
}
}
int readNormalNr (std::istream &in, int bytCon)
@ -916,15 +745,6 @@ int readNormalNr (std::istream &in, int bytCon)
return ret;
}
//void CSDL_Ext::fullAlphaTransform(SDL_Surface *& src)
//{
// src = alphaTransform(src);
// //SDL_Surface * hlp2;
// //hlp2 = secondAlphaTransform(src, std32bppSurface);
// //SDL_FreeSurface(src);
// //src = hlp2;
//}
std::string CSDL_Ext::processStr(std::string str, std::vector<std::string> & tor)
{
for (int i=0;(i<tor.size())&&(boost::find_first(str,"%s"));i++)

View File

@ -34,9 +34,7 @@ namespace CSDL_Ext
Uint32 SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte = false);
SDL_Color SDL_GetPixelColor(SDL_Surface *surface, int x, int y);
SDL_Surface * alphaTransform(SDL_Surface * src); //adds transparency and shadows (partial handling only; see examples of using for details)
SDL_Surface * secondAlphaTransform(SDL_Surface * src, SDL_Surface * alpha); //alpha is a surface we want to blit src to
int blit8bppAlphaTo24bpp(SDL_Surface * src, SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
//void fullAlphaTransform(SDL_Surface *& src); //performs first and second alpha transform
Uint32 colorToUint32(const SDL_Color * color); //little endian only
void printTo(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2);// quality: 0 - lowest, 1 - medium, 2 - highest; prints at right bottom corner of specific area. position of corner indicated by (x, y)
void printToWR(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2);// quality: 0 - lowest, 1 - medium, 2 - highest; prints at right bottom corner of specific area. position of corner indicated by (x, y)
@ -45,10 +43,6 @@ namespace CSDL_Ext
void printAtWB(std::string text, int x, int y, TTF_Font * font, int charpr, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen);
void printAt(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2); // quality: 0 - lowest, 1 - medium, 2 - highest
void update(SDL_Surface * what = screen); //updates whole surface (default - main screen)
void blueToPlayers(SDL_Surface * sur, int player); //simple color substitution
void blueToPlayersAdv(SDL_Surface * sur, int player, int mode=0, void* additionalInfo=NULL); //substitute blue color by another one, makes it nicer keeping nuances
//mode 1 is calibrated for hero infobox
//mode 2 is calibrated for resbar and gets in additionalInfo a pointer to the set of (SDL_Color) which shouldn't be replaced
void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, int3 color);
void setPlayerColor(SDL_Surface * sur, unsigned char player); //sets correct color of flags; -1 for neutral
std::string processStr(std::string str, std::vector<std::string> & tor); //replaces %s in string

File diff suppressed because it is too large Load Diff

View File

@ -1,117 +0,0 @@
/*
SDL_rotozoom - rotozoomer
LGPL (c) A. Schiffler
*/
#ifndef _SDL_rotozoom_h
#define _SDL_rotozoom_h
#include <math.h>
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef M_PI
#define M_PI 3.141592654
#endif
#include "SDL.h"
/* ---- Defines */
#define SMOOTHING_OFF 0
#define SMOOTHING_ON 1
/* ---- Structures */
typedef struct tColorRGBA {
Uint8 r;
Uint8 g;
Uint8 b;
Uint8 a;
} tColorRGBA;
typedef struct tColorY {
Uint8 y;
} tColorY;
/* ---- Prototypes */
#ifdef WIN32
#ifdef BUILD_DLL
#define DLLINTERFACE __declspec(dllexport)
#else
#define DLLINTERFACE __declspec(dllimport)
#endif
#else
#define DLLINTERFACE
#endif
/*
rotozoomSurface()
Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'angle' is the rotation in degrees. 'zoom' a scaling factor. If 'smooth' is 1
then the destination 32bit surface is anti-aliased. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
*/
SDL_Surface *rotozoomSurface(SDL_Surface * src, double angle, double zoom, int smooth);
SDL_Surface *rotozoomSurfaceXY
(SDL_Surface * src, double angle, double zoomx, double zoomy, int smooth);
/* Returns the size of the target surface for a rotozoomSurface() call */
void rotozoomSurfaceSize(int width, int height, double angle, double zoom, int *dstwidth,
int *dstheight);
void rotozoomSurfaceSizeXY
(int width, int height, double angle, double zoomx, double zoomy,
int *dstwidth, int *dstheight);
/*
zoomSurface()
Zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is 1
then the destination 32bit surface is anti-aliased. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
*/
SDL_Surface *zoomSurface(SDL_Surface * src, double zoomx, double zoomy, int smooth);
/* Returns the size of the target surface for a zoomSurface() call */
void zoomSurfaceSize(int width, int height, double zoomx, double zoomy, int *dstwidth, int *dstheight);
/*
shrinkSurface()
Shrinks a 32bit or 8bit 'src' surface ti a newly created 'dst' surface.
'factorx' and 'factory' are the shrinking ratios (i.e. 2=1/2 the size,
3=1/3 the size, etc.) The destination surface is antialiased by averaging
the source box RGBA or Y information. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
*/
SDL_Surface *shrinkSurface(SDL_Surface * src, int factorx, int factory);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#endif /* _SDL_rotozoom_h */

View File

@ -10,22 +10,36 @@ struct StartInfo
{
struct PlayerSettings
{
int castle, hero, //ID, if -1 then random, if -2 then none
si32 castle, hero, //ID, if -1 then random, if -2 then none
heroPortrait; //-1 if default, else ID
std::string heroName;
Ebonus bonus;
Ecolor color; //from 0 -
int serial;
int handicap;//0-no, 1-mild, 2-severe
si8 bonus; //usees enum type Ebonus
ui8 color; //from 0 -
ui8 serial;
ui8 handicap;//0-no, 1-mild, 2-severe
std::string name;
bool human;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & castle;
h & hero;
h & heroPortrait;
h & heroName;
h & bonus;
h & color;
h & serial;
h & handicap;
h & name;
h & human;
}
};
int difficulty; //0=easy; 4=impossible
si32 difficulty; //0=easy; 4=impossible
std::vector<PlayerSettings> playerInfos;
int turnTime; //in minutes, 0=unlimited
ui8 turnTime; //in minutes, 0=unlimited
std::string mapname;
PlayerSettings & getIthPlayersSettings(int no)
{
for(int i=0; i<playerInfos.size(); ++i)
for(unsigned int i=0; i<playerInfos.size(); ++i)
if(playerInfos[i].color == no)
return playerInfos[i];
#ifndef __GNUC__
@ -34,6 +48,13 @@ struct StartInfo
throw new std::exception();
#endif
}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & difficulty;
h & playerInfos;
h & turnTime;
h & mapname;
}
};
#endif

1
aclocal.m4 vendored
View File

@ -851,3 +851,4 @@ AC_SUBST([am__untar])
m4_include([aclocal/m4/ax_boost_base.m4])
m4_include([aclocal/m4/ax_boost_filesystem.m4])
m4_include([aclocal/m4/ax_boost_system.m4])
m4_include([aclocal/m4/ax_boost_thread.m4])

View File

@ -0,0 +1,147 @@
# ===========================================================================
# http://autoconf-archive.cryp.to/ax_boost_thread.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_BOOST_THREAD
#
# DESCRIPTION
#
# Test for Thread library from the Boost C++ libraries. The macro requires
# a preceding call to AX_BOOST_BASE. Further documentation is available at
# <http://randspringer.de/boost/index.html>.
#
# This macro calls:
#
# AC_SUBST(BOOST_THREAD_LIB)
#
# And sets:
#
# HAVE_BOOST_THREAD
#
# LAST MODIFICATION
#
# 2008-04-12
#
# COPYLEFT
#
# Copyright (c) 2008 Thomas Porschberg <thomas@randspringer.de>
# Copyright (c) 2008 Michael Tindal
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved.
AC_DEFUN([AX_BOOST_THREAD],
[
AC_ARG_WITH([boost-thread],
AS_HELP_STRING([--with-boost-thread@<:@=special-lib@:>@],
[use the Thread library from boost - it is possible to specify a certain library for the linker
e.g. --with-boost-thread=boost_thread-gcc-mt ]),
[
if test "$withval" = "no"; then
want_boost="no"
elif test "$withval" = "yes"; then
want_boost="yes"
ax_boost_user_thread_lib=""
else
want_boost="yes"
ax_boost_user_thread_lib="$withval"
fi
],
[want_boost="yes"]
)
if test "x$want_boost" = "xyes"; then
AC_REQUIRE([AC_PROG_CC])
AC_REQUIRE([AC_CANONICAL_BUILD])
CPPFLAGS_SAVED="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
export CPPFLAGS
LDFLAGS_SAVED="$LDFLAGS"
LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
export LDFLAGS
AC_CACHE_CHECK(whether the Boost::Thread library is available,
ax_cv_boost_thread,
[AC_LANG_PUSH([C++])
CXXFLAGS_SAVE=$CXXFLAGS
if test "x$build_os" = "xsolaris" ; then
CXXFLAGS="-pthreads $CXXFLAGS"
elif test "x$build_os" = "xming32" ; then
CXXFLAGS="-mthreads $CXXFLAGS"
else
CXXFLAGS="-pthread $CXXFLAGS"
fi
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([[@%:@include <boost/thread/thread.hpp>]],
[[boost::thread_group thrds;
return 0;]]),
ax_cv_boost_thread=yes, ax_cv_boost_thread=no)
CXXFLAGS=$CXXFLAGS_SAVE
AC_LANG_POP([C++])
])
if test "x$ax_cv_boost_thread" = "xyes"; then
if test "x$build_os" = "xsolaris" ; then
BOOST_CPPFLAGS="-pthreads $BOOST_CPPFLAGS"
elif test "x$build_os" = "xming32" ; then
BOOST_CPPFLAGS="-mthreads $BOOST_CPPFLAGS"
else
BOOST_CPPFLAGS="-pthread $BOOST_CPPFLAGS"
fi
AC_SUBST(BOOST_CPPFLAGS)
AC_DEFINE(HAVE_BOOST_THREAD,,[define if the Boost::Thread library is available])
BOOSTLIBDIR=`echo $BOOST_LDFLAGS | sed -e 's/@<:@^\/@:>@*//'`
LDFLAGS_SAVE=$LDFLAGS
case "x$build_os" in
*bsd* )
LDFLAGS="-pthread $LDFLAGS"
break;
;;
esac
if test "x$ax_boost_user_thread_lib" = "x"; then
for libextension in `ls $BOOSTLIBDIR/libboost_thread*.{so,a}* 2>/dev/null | sed 's,.*/,,' | sed -e 's;^lib\(boost_thread.*\)\.so.*$;\1;' -e 's;^lib\(boost_thread.*\)\.a*$;\1;'` ; do
ax_lib=${libextension}
AC_CHECK_LIB($ax_lib, exit,
[BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
[link_thread="no"])
done
if test "x$link_thread" != "xyes"; then
for libextension in `ls $BOOSTLIBDIR/boost_thread*.{dll,a}* 2>/dev/null | sed 's,.*/,,' | sed -e 's;^\(boost_thread.*\)\.dll.*$;\1;' -e 's;^\(boost_thread.*\)\.a*$;\1;'` ; do
ax_lib=${libextension}
AC_CHECK_LIB($ax_lib, exit,
[BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
[link_thread="no"])
done
fi
else
for ax_lib in $ax_boost_user_thread_lib boost_thread-$ax_boost_user_thread_lib; do
AC_CHECK_LIB($ax_lib, exit,
[BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
[link_thread="no"])
done
fi
if test "x$link_thread" = "xno"; then
AC_MSG_ERROR(Could not link against $ax_lib !)
else
case "x$build_os" in
*bsd* )
BOOST_LDFLAGS="-pthread $BOOST_LDFLAGS"
break;
;;
esac
fi
fi
CPPFLAGS="$CPPFLAGS_SAVED"
LDFLAGS="$LDFLAGS_SAVED"
fi
])

352
client/CBitmapHandler.cpp Normal file
View File

@ -0,0 +1,352 @@
#include "../stdafx.h"
#include "SDL.h"
#include "SDL_image.h"
#include "CBitmapHandler.h"
#include "../hch/CDefHandler.h"
#include "../hch/CLodHandler.h"
#include <sstream>
#include <boost/thread.hpp>
boost::mutex bitmap_handler_mx;
int readNormalNr (int pos, int bytCon, unsigned char * str);
CLodHandler * BitmapHandler::bitmaph = NULL;
void BMPHeader::print(std::ostream & out)
{
CDefHandler::print(out,fullSize,4);
CDefHandler::print(out,_h1,4);
CDefHandler::print(out,_c1,4);
CDefHandler::print(out,_c2,4);
CDefHandler::print(out,x,4);
CDefHandler::print(out,y,4);
CDefHandler::print(out,_c3,2);
CDefHandler::print(out,_c4,2);
CDefHandler::print(out,_h2,4);
CDefHandler::print(out,_h3,4);
CDefHandler::print(out,dataSize1,4);
CDefHandler::print(out,dataSize2,4);
for (int i=0;i<8;i++)
out << _c5[i];
out.flush();
}
void CPCXConv::openPCX(char * PCX, int len)
{
pcxs=len;
pcx=(unsigned char*)PCX;
}
void CPCXConv::fromFile(std::string path)
{
std::ifstream * is = new std::ifstream();
is -> open(path.c_str(),std::ios::binary);
is->seekg(0,std::ios::end); // to the end
pcxs = is->tellg(); // read length
is->seekg(0,std::ios::beg); // wracamy na poczatek
pcx = new unsigned char[pcxs]; // allocate memory
is->read((char*)pcx, pcxs); // read map file to buffer
is->close();
delete is;
}
void CPCXConv::saveBMP(std::string path)
{
std::ofstream os;
os.open(path.c_str(), std::ios::binary);
os.write((char*)bmp,bmps);
os.close();
}
void CPCXConv::convert()
{
BMPHeader bh;
BMPPalette pal[256];
Epcxformat format;
int fSize,i,y;
bool check1, check2;
unsigned char add;
int it=0;
std::stringstream out;
fSize = readNormalNr(it,4,pcx);it+=4;
bh.x = readNormalNr(it,4,pcx);it+=4;
bh.y = readNormalNr(it,4,pcx);it+=4;
if (fSize==bh.x*bh.y*3)
check1=true;
else
check1=false;
if (fSize==bh.x*bh.y)
check2=true;
else
check2=false;
if (check1)
format=PCX24B;
else if (check2)
format=PCX8B;
else
return;
add = 4 - bh.x%4;
if (add==4)
add=0;
bh._h3=bh.x*bh.y;
if (format==PCX8B)
{
bh._c1=0x436;
bh._c2=0x28;
bh._c3=1;
bh._c4=8;
//bh.dataSize2=bh.dataSize1=maxx*maxy;
bh.dataSize1=bh.x;
bh.dataSize2=bh.y;
bh.fullSize = bh.dataSize1+436;
}
else
{
bh._c1=0x36;
bh._c2=0x28;
bh._c3=1;
bh._c4=0x18;
//bh.dataSize2=bh.dataSize1=0xB12;
bh.dataSize1=bh.x;
bh.dataSize2=bh.y;
bh.fullSize=(bh.x+add)*bh.y*3+36+18;
bh._h3*=3;
}
if (format==PCX8B)
{
it = pcxs-256*3;
for (int i=0;i<256;i++)
{
pal[i].R=pcx[it++];
pal[i].G=pcx[it++];
pal[i].B=pcx[it++];
pal[i].F='\0';
}
}
out<<"BM";
bh.print(out);
if (format==PCX8B)
{
for (int i=0;i<256;i++)
{
out<<pal[i].B;
out<<pal[i].G;
out<<pal[i].R;
out<<pal[i].F;
}
for (y=bh.y;y>0;y--)
{
it=0xC+(y-1)*bh.x;
for (int j=0;j<bh.x;j++)
out<<pcx[it+j];
if (add>0)
{
for (int j=0;j<add;j++)
out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
}
}
}
else
{
for (y=bh.y; y>0; y--)
{
it=0xC+(y-1)*bh.x*3;
for (int j=0;j<bh.x*3;j++)
out<<pcx[it+j];
if (add>0)
{
for (int j=0;j<add*3;j++)
out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
}
}
}
std::string temp = out.str();
bmp = new unsigned char[temp.length()];
bmps=temp.length();
for (int a=0;a<temp.length();a++)
{
bmp[a]=temp[a];
}
}
SDL_Surface * CPCXConv::getSurface()
{
SDL_Surface * ret;
BMPHeader bh;
Epcxformat format;
int fSize,i,y;
bool check1, check2;
unsigned char add;
int it=0;
fSize = readNormalNr(it,4,pcx);it+=4;
bh.x = readNormalNr(it,4,pcx);it+=4;
bh.y = readNormalNr(it,4,pcx);it+=4;
if (fSize==bh.x*bh.y*3)
check1=true;
else
check1=false;
if (fSize==bh.x*bh.y)
check2=true;
else
check2=false;
if (check1)
format=PCX24B;
else if (check2)
format=PCX8B;
else
return NULL;
add = 4 - bh.x%4;
if (add==4)
add=0;
if (format==PCX8B)
{
ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 8, 0, 0, 0, 0);
}
else
{
#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
int bmask = 0xff0000;
int gmask = 0x00ff00;
int rmask = 0x0000ff;
#else
int bmask = 0x0000ff;
int gmask = 0x00ff00;
int rmask = 0xff0000;
#endif
ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 24, rmask, gmask, bmask, 0);
}
if (format==PCX8B)
{
it = pcxs-256*3;
for (int i=0;i<256;i++)
{
SDL_Color tp;
#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
tp.b = pcx[it++];
tp.g = pcx[it++];
tp.r = pcx[it++];
#else
tp.r = pcx[it++];
tp.g = pcx[it++];
tp.b = pcx[it++];
#endif
tp.unused = 0;
*(ret->format->palette->colors+i) = tp;
}
for (y=bh.y;y>0;y--)
{
it=0xC+(y-1)*bh.x;
for (int j=0;j<bh.x;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j];
}
if (add>0)
{
for (int j=0;j<add;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * (j+bh.x)) = 0;
}
}
}
}
else
{
for (y=bh.y; y>0; y--)
{
it=0xC+(y-1)*bh.x*3;
for (int j=0;j<bh.x*3;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + j) = pcx[it+j];
}
if (add>0)
{
for (int j=0;j<add*3;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + (j+bh.x*3)) = 0;
}
}
}
}
return ret;
}
SDL_Surface * BitmapHandler::loadBitmap(std::string fname, bool setKey)
{
if(!fname.size())
return NULL;
unsigned char * pcx;
std::transform(fname.begin(),fname.end(),fname.begin(),toupper);
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
Entry *e = bitmaph->entries.znajdz(fname);
if(!e)
{
std::cout<<"File "<<fname<<" not found"<<std::endl;
return NULL;
}
if(e->offset<0)
{
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".BMP");
fname = "Data/"+fname;
FILE * f = fopen(fname.c_str(),"r");
if(f)
{
fclose(f);
return SDL_LoadBMP(fname.c_str());
}
else //file .bmp not present, check .pcx
{
char sign[3];
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
f = fopen(fname.c_str(),"r");
if(!f)
return NULL;
fread(sign,1,3,f);
if(sign[0]=='B' && sign[1]=='M') //BMP named as PCX - people (eg. Kulex) sometimes use such files
{
fclose(f);
return SDL_LoadBMP(fname.c_str());
}
else //PCX - but we don't know which
{
if((sign[0]==10) && (sign[1]<6) && (sign[2]==1)) //ZSoft PCX
{
fclose(f);
return IMG_Load(fname.c_str());
}
else //H3-style PCX
{
CPCXConv cp;
pcx = new unsigned char[e->realSize];
memcpy(pcx,sign,3);
int res = fread((char*)pcx+3, 1, e->realSize-3, f);
fclose(f);
cp.openPCX((char*)pcx,e->realSize);
return cp.getSurface();
}
}
}
}
bitmap_handler_mx.lock();
fseek(bitmaph->FLOD, e->offset, 0);
if (e->size==0) //file is not compressed
{
pcx = new unsigned char[e->realSize];
fread((char*)pcx, 1, e->realSize, bitmaph->FLOD);
bitmap_handler_mx.unlock();
}
else
{
unsigned char * pcd = new unsigned char[e->size];
fread((char*)pcd, 1, e->size, bitmaph->FLOD);
bitmap_handler_mx.unlock();
int res=bitmaph->infs2(pcd,e->size,e->realSize,pcx);
if(res!=0)
{
std::cout<<"an error "<<res<<" occured while extracting file "<<fname<<std::endl;
}
delete [] pcd;
}
CPCXConv cp;
cp.openPCX((char*)pcx,e->realSize);
SDL_Surface * ret = cp.getSurface();
if(setKey)
SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
return ret;
}

39
client/CBitmapHandler.h Normal file
View File

@ -0,0 +1,39 @@
#pragma once
#include "../global.h"
struct SDL_Surface;
class CLodHandler;
enum Epcxformat {PCX8B, PCX24B};
struct BMPPalette
{
unsigned char R,G,B,F;
};
struct BMPHeader
{
int fullSize, _h1, _h2, _h3, _c1, _c2, _c3, _c4, x, y,
dataSize1, dataSize2; //DataSize=X*Y+2*Y
unsigned char _c5[8];
void print(std::ostream & out);
BMPHeader(){_h1=_h2=0;for(int i=0;i<8;i++)_c5[i]=0;};
};
class CPCXConv
{
public:
unsigned char * pcx, *bmp;
int pcxs, bmps;
void fromFile(std::string path);
void saveBMP(std::string path);
void openPCX(char * PCX, int len);
void openPCX();
void convert();
SDL_Surface * getSurface(); //for standard H3 PCX
//SDL_Surface * getSurfaceZ(); //for ZSoft PCX
CPCXConv(){pcx=bmp=NULL;pcxs=bmps=0;};
~CPCXConv(){if (pcxs) delete[] pcx; if(bmps) delete[] bmp;}
};
namespace BitmapHandler
{
extern CLodHandler *bitmaph;
SDL_Surface * loadBitmap(std::string fname, bool setKey=false);
};

View File

@ -0,0 +1,352 @@
#include "CCreatureAnimation.h"
#include "../hch/CLodHandler.h"
int CCreatureAnimation::getType() const
{
return type;
}
void CCreatureAnimation::setType(int type)
{
this->type = type;
curFrame = 0;
if(type!=-1)
{
if(SEntries[curFrame].group!=type) //rewind
{
int j=-1; //first frame in displayed group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group==type && j==-1)
{
j = g;
break;
}
}
if(curFrame!=-1)
curFrame = j;
}
}
else
{
if(curFrame>=frames)
curFrame = 0;
}
}
CCreatureAnimation::CCreatureAnimation(std::string name) : RLEntries(NULL), RWEntries(NULL)
{
FDef = CDefHandler::Spriteh->giveFile(name); //load main file
//init anim data
int i,j, totalInBlock;
char Buffer[13];
defName=name;
i = 0;
DEFType = readNormalNr(i,4); i+=4;
fullWidth = readNormalNr(i,4); i+=4;
fullHeight = readNormalNr(i,4); i+=4;
i=0xc;
totalBlocks = readNormalNr(i,4); i+=4;
i=0x10;
for (int it=0;it<256;it++)
{
palette[it].R = FDef[i++];
palette[it].G = FDef[i++];
palette[it].B = FDef[i++];
palette[it].F = 0;
}
i=0x310;
totalEntries=0;
for (int z=0; z<totalBlocks; z++)
{
int unknown1 = readNormalNr(i,4); i+=4;
totalInBlock = readNormalNr(i,4); i+=4;
for (j=SEntries.size(); j<totalEntries+totalInBlock; j++)
SEntries.push_back(SEntry());
int unknown2 = readNormalNr(i,4); i+=4;
int unknown3 = readNormalNr(i,4); i+=4;
for (j=0; j<totalInBlock; j++)
{
for (int k=0;k<13;k++) Buffer[k]=FDef[i+k];
i+=13;
SEntries[totalEntries+j].name=Buffer;
}
for (j=0; j<totalInBlock; j++)
{
SEntries[totalEntries+j].offset = readNormalNr(i,4);
int unknown4 = readNormalNr(i,4); i+=4;
}
//totalEntries+=totalInBlock;
for(int hh=0; hh<totalInBlock; ++hh)
{
SEntries[totalEntries].group = z;
++totalEntries;
}
}
for(j=0; j<SEntries.size(); ++j)
{
SEntries[j].name = SEntries[j].name.substr(0, SEntries[j].name.find('.')+4);
}
//init vars
curFrame = 0;
type = -1;
frames = totalEntries;
}
int CCreatureAnimation::readNormalNr (int pos, int bytCon, unsigned char * str, bool cyclic)
{
int ret=0;
int amp=1;
if (str)
{
for (int i=0; i<bytCon; i++)
{
ret+=str[pos+i]*amp;
amp*=256;
}
}
else
{
for (int i=0; i<bytCon; i++)
{
ret+=FDef[pos+i]*amp;
amp*=256;
}
}
if(cyclic && bytCon<4 && ret>=amp/2)
{
ret = ret-amp;
}
return ret;
}
int CCreatureAnimation::nextFrameMiddle(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
{
return nextFrame(dest,x-fullWidth/2,y-fullHeight/2,attacker,incrementFrame,yellowBorder,destRect);
}
int CCreatureAnimation::nextFrame(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
{
if(dest->format->BytesPerPixel<3)
return -1; //not enough depth
//increasing frame numer
int SIndex = -1;
if(incrementFrame)
{
SIndex = curFrame++;
if(type!=-1)
{
if(SEntries[curFrame].group!=type) //rewind
{
int j=-1; //first frame in displayed group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group==type && j==-1)
{
j = g;
break;
}
}
if(curFrame!=-1)
curFrame = j;
}
}
else
{
if(curFrame>=frames)
curFrame = 0;
}
}
else
{
SIndex = curFrame;
}
//frame number increased
long BaseOffset,
SpriteWidth, SpriteHeight, //sprite format
LeftMargin, RightMargin, TopMargin,BottomMargin,
i, add, FullHeight,FullWidth,
TotalRowLength, // length of read segment
RowAdd;
unsigned char SegmentType, SegmentLength;
i=BaseOffset=SEntries[SIndex].offset;
int prSize=readNormalNr(i,4,FDef);i+=4;
int defType2 = readNormalNr(i,4,FDef);i+=4;
FullWidth = readNormalNr(i,4,FDef);i+=4;
FullHeight = readNormalNr(i,4,FDef);i+=4;
SpriteWidth = readNormalNr(i,4,FDef);i+=4;
SpriteHeight = readNormalNr(i,4,FDef);i+=4;
LeftMargin = readNormalNr(i,4,FDef);i+=4;
TopMargin = readNormalNr(i,4,FDef);i+=4;
RightMargin = FullWidth - SpriteWidth - LeftMargin;
BottomMargin = FullHeight - SpriteHeight - TopMargin;
add = 4 - FullWidth%4;
int BaseOffsetor = BaseOffset = i;
int ftcp = 0;
if (defType2==1) //as it should be allways in creature animations
{
if (TopMargin>0)
{
for (int i=0;i<TopMargin;i++)
{
ftcp+=FullWidth+add;
}
}
RLEntries = new int[SpriteHeight];
for (int i=0;i<SpriteHeight;i++)
{
RLEntries[i]=readNormalNr(BaseOffset,4,FDef);BaseOffset+=4;
}
for (int i=0;i<SpriteHeight;i++)
{
BaseOffset=BaseOffsetor+RLEntries[i];
if (LeftMargin>0)
{
ftcp+=LeftMargin;
}
TotalRowLength=0;
do
{
SegmentType=FDef[BaseOffset++];
SegmentLength=FDef[BaseOffset++];
if (SegmentType==0xFF)
{
for (int k=0;k<=SegmentLength;k++)
{
int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
int yB = ftcp/(FullWidth+add) + y;
if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
{
if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
putPixel(dest, xB + yB*dest->w, palette[FDef[BaseOffset+k]], FDef[BaseOffset+k], yellowBorder);
}
ftcp++; //increment pos
if ((TotalRowLength+k+1)>=SpriteWidth)
break;
}
BaseOffset+=SegmentLength+1;////
TotalRowLength+=SegmentLength+1;
}
else
{
for (int k=0;k<SegmentLength+1;k++)
{
int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
int yB = ftcp/(FullWidth+add) + y;
if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
{
if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
putPixel(dest, xB + yB*dest->w, palette[SegmentType], SegmentType, yellowBorder);
}
ftcp++; //increment pos
}
TotalRowLength+=SegmentLength+1;
}
}while(TotalRowLength<SpriteWidth);
RowAdd=SpriteWidth-TotalRowLength;
if (RightMargin>0)
{
ftcp+=RightMargin;
}
if (add>0)
{
ftcp+=add+RowAdd;
}
}
delete [] RLEntries;
RLEntries = NULL;
if (BottomMargin>0)
{
ftcp += BottomMargin * (FullWidth+add);
}
}
//SDL_UpdateRect(dest, x, y, FullWidth+add, FullHeight);
return 0;
}
int CCreatureAnimation::framesInGroup(int group) const
{
int ret = 0; //number of frames in given group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group == group)
++ret;
}
return ret;
}
CCreatureAnimation::~CCreatureAnimation()
{
delete [] FDef;
if (RWEntries)
delete [] RWEntries;
if (RLEntries)
delete [] RLEntries;
}
void CCreatureAnimation::putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const
{
if(palc!=0)
{
Uint8 * p = (Uint8*)dest->pixels + ftcp*3;
if(palc > 7) //normal color
{
p[0] = color.B;
p[1] = color.G;
p[2] = color.R;
}
else if(yellowBorder && (palc == 6 || palc == 7)) //dark yellow border
{
p[0] = 0;
p[1] = 0xff;
p[2] = 0xff;
}
else if(yellowBorder && (palc == 5)) //yellow border
{
p[0] = color.B;
p[1] = color.G;
p[2] = color.R;
}
else if(palc < 5) //shadow
{
Uint16 alpha;
switch(color.G)
{
case 0:
alpha = 128;
break;
case 50:
alpha = 50+32;
break;
case 100:
alpha = 100+64;
break;
case 125:
alpha = 125+64;
break;
case 128:
alpha = 128+64;
break;
case 150:
alpha = 150+64;
break;
default:
alpha = 255;
break;
}
//alpha counted
p[0] = (p[0] * alpha)>>8;
p[1] = (p[1] * alpha)>>8;
p[2] = (p[2] * alpha)>>8;
}
}
}

View File

@ -0,0 +1,45 @@
#pragma once
#include "../global.h"
#include "../CPlayerInterface.h"
#include "../hch/CDefHandler.h"
class CCreatureAnimation : public CIntObject
{
private:
int totalEntries, DEFType, totalBlocks;
bool allowRepaint;
int length;
BMPPalette palette[256];
unsigned int * RWEntries;
int * RLEntries;
struct SEntry
{
std::string name;
int offset;
int group;
} ;
std::vector<SEntry> SEntries ;
char id[2];
std::string defName, curDir;
int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
void putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const;
////////////
unsigned char * FDef; //animation raw data
unsigned int curFrame; //number of currently displayed frame
unsigned int frames; //number of frames
int type; //type of animation being displayed (-1 - whole animation, >0 - specified part [default: -1])
public:
int fullWidth, fullHeight; //read-only, please!
CCreatureAnimation(std::string name); //c-tor
~CCreatureAnimation(); //d-tor
void setType(int type); //sets type of animation and cleares framecount
int getType() const; //returns type of animation
int nextFrame(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
int nextFrameMiddle(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
int framesInGroup(int group) const; //retirns number of fromes in given group
};

425
client/Client.cpp Normal file
View File

@ -0,0 +1,425 @@
#include "Client.h"
#include "../lib/Connection.h"
#include "../StartInfo.h"
#include "../map.h"
#include "../CGameState.h"
#include "../CGameInfo.h"
#include "../mapHandler.h"
#include "../CCallback.h"
#include "../CPlayerInterface.h"
#include "../CConsoleHandler.h"
#include "../lib/NetPacks.h"
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include "../hch/CObjectHandler.h"
#include "../hch/CGeneralTextHandler.h"
#include "../hch/CArtHandler.h"
#include <boost/thread/shared_mutex.hpp>
#include "../lib/VCMI_Lib.h"
CSharedCond<std::set<IPack*> > mess(new std::set<IPack*>);
std::string toString(MetaString &ms)
{
std::string ret;
for(int i=0;i<ms.message.size();i++)
{
if(ms.message[i]>0)
{
ret += ms.strings[ms.message[i]-1];
}
else
{
std::vector<std::string> *vec;
int type = ms.texts[-ms.message[i]-1].first,
ser = ms.texts[-ms.message[i]-1].second;
if(type == 5)
{
ret += CGI->arth->artifacts[ser].name;
continue;
}
else if(type == 7)
{
ret += CGI->creh->creatures[ser].namePl;
continue;
}
else if(type == 9)
{
ret += CGI->objh->mines[ser].first;
continue;
}
else if(type == 10)
{
ret += CGI->objh->mines[ser].second;
continue;
}
else
{
switch(type)
{
case 1:
vec = &CGI->generaltexth->allTexts;
break;
case 2:
vec = &CGI->objh->xtrainfo;
break;
case 3:
vec = &CGI->objh->names;
break;
case 4:
vec = &CGI->objh->restypes;
break;
case 6:
vec = &CGI->generaltexth->arraytxt;
break;
case 8:
vec = &CGI->objh->creGens;
break;
case 11:
vec = &CGI->objh->advobtxt;
}
ret += (*vec)[ser];
}
}
}
for(int i=0;i<ms.replacements.size();i++)
{
ret.replace(ret.find("%s"),2,ms.replacements[i]);
}
return ret;
}
CClient::CClient(void)
{
}
CClient::CClient(CConnection *con, StartInfo *si)
:serv(con)
{
timeHandler tmh;
CGI->state = new CGameState();
THC std::cout<<"\tGamestate: "<<tmh.getDif()<<std::endl;
CConnection &c(*con);
////////////////////////////////////////////////////
ui8 pom8;
c << ui8(2) << ui8(1); //new game; one client
c << *si;
c >> pom8;
if(pom8) throw "Server cannot open the map!";
c << ui8(si->playerInfos.size());
for(int i=0;i<si->playerInfos.size();i++)
c << ui8(si->playerInfos[i].color);
ui32 seed, sum;
std::string mapname;
c >> mapname >> sum >> seed;
THC std::cout<<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
Mapa * mapa = new Mapa(mapname);
THC std::cout<<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
std::cout << "\tServer checksum for "<<mapname <<": "<<sum << std::endl;
std::cout << "\tOur checksum for the map: "<< mapa->checksum << std::endl;
if(mapa->checksum != sum)
{
#ifndef __GNUC__
throw std::exception("Wrong checksum");
#else
throw std::exception();
#endif
exit(-1);
}
std::cout << "\tUsing random seed: "<<seed << std::endl;
gs = CGI->state;
gs->scenarioOps = si;
gs->init(si,mapa,seed);
CGI->mh = new CMapHandler();
THC std::cout<<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
CGI->mh->map = mapa;
THC std::cout<<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
CGI->mh->init();
THC std::cout<<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
for (int i=0; i<CGI->state->scenarioOps->playerInfos.size();i++) //initializing interfaces
{
ui8 color = gs->scenarioOps->playerInfos[i].color;
CCallback *cb = new CCallback(gs,color,this);
if(!gs->scenarioOps->playerInfos[i].human)
{
playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,"EmptyAI.dll"));
}
else
{
gs->currentPlayer = color;
playerint[color] = new CPlayerInterface(color,i);
playerint[color]->init(cb);
}
}
CGI->consoleh->cb = new CCallback(gs,-1,this);
}
CClient::~CClient(void)
{
}
void CClient::process(int what)
{
switch (what)
{
case 100: //one of our interaces has turn
{
ui8 player;
*serv >> player;//who?
std::cout << "It's turn of "<<(unsigned)player<<" player."<<std::endl;
boost::thread(boost::bind(&CGameInterface::yourTurn,playerint[player]));
break;
}
case 101:
{
NewTurn n;
*serv >> n;
std::cout << "New day: "<<(unsigned)n.day<<". Applying changes... ";
gs->apply(&n);
std::cout << "done!"<<std::endl;
break;
}
case 102: //set resource amount
{
SetResource sr;
*serv >> sr;
std::cout << "Set amount of "<<CGI->objh->restypes[sr.resid]
<< " of player "<<(unsigned)sr.player <<" to "<<sr.val<<std::endl;
gs->apply(&sr);
playerint[sr.player]->receivedResource(sr.resid,sr.val);
break;
}
case 103: //show info dialog
{
InfoWindow iw;
*serv >> iw;
std::vector<Component*> comps;
for(int i=0;i<iw.components.size();i++)
comps.push_back(&iw.components[i]);
playerint[iw.player]->showInfoDialog(toString(iw.text),comps);
break;
}
case 104:
{
SetResources sr;
*serv >> sr;
std::cout << "Set amount of resources of player "<<(unsigned)sr.player<<std::endl;
gs->apply(&sr);
playerint[sr.player]->receivedResource(-1,-1);
break;
}
case 105:
{
SetPrimSkill sps;
*serv >> sps;
std::cout << "Changing hero primary skill"<<std::endl;
gs->apply(&sps);
playerint[gs->getHero(sps.id)->tempOwner]->heroPrimarySkillChanged(gs->getHero(sps.id),sps.which,sps.val);
break;
}
case 107:
{
ShowInInfobox sii;
*serv >> sii;
SComponent sc(sii.c);
sc.description = toString(sii.text);
if(playerint[sii.player]->human)
static_cast<CPlayerInterface*>(playerint[sii.player])->showComp(sc);
break;
}
case 500:
{
RemoveHero rh;
*serv >> rh;
CGHeroInstance *h = static_cast<CGHeroInstance*>(gs->map->objects[rh.id]);
std::cout << "Removing hero with id = "<<(unsigned)rh.id<<std::endl;
CGI->mh->removeObject(h);
gs->apply(&rh);
playerint[h->tempOwner]->heroKilled(h);
break;
}
case 501: //hero movement response - we have to notify interfaces and callback
{
TryMoveHero *th = new TryMoveHero; //will be deleted by callback after processing
*serv >> *th;
std::cout << "HeroMove: id="<<th->id<<"\tResult: "<<(unsigned)th->result<<"\tPosition "<<th->end<<std::endl;
gs->apply(th);
int player = gs->map->objects[th->id]->getOwner();
if(playerint[player])
{
for(std::set<int3>::iterator i=th->fowRevealed.begin(); i != th->fowRevealed.end(); i++)
playerint[player]->tileRevealed(*i);
//std::for_each(th->fowRevealed.begin(),th->fowRevealed.end(),boost::bind(&CGameInterface::tileRevealed,playerint[player],_1));
}
//notify interfacesabout move
int nn=0; //number of interfece of currently browsed player
for(std::map<ui8, CGameInterface*>::iterator i=playerint.begin();i!=playerint.end();i++)
{
if(gs->players[i->first].fogOfWarMap[th->start.x-1][th->start.y][th->start.z] || gs->players[i->first].fogOfWarMap[th->end.x-1][th->end.y][th->end.z])
{
HeroMoveDetails hmd(th->start,th->end,static_cast<CGHeroInstance*>(gs->map->objects[th->id]));
hmd.successful = th->result;
i->second->heroMoved(hmd);
}
}
//add info for callback
mess.mx->lock();
mess.res->insert(th);
mess.mx->unlock();
mess.cv->notify_all();
break;
}
case 502:
{
SetGarrisons sg;
*serv >> sg;
gs->apply(&sg);
for(std::map<ui32,CCreatureSet>::iterator i = sg.garrs.begin(); i!=sg.garrs.end(); i++)
playerint[gs->map->objects[i->first]->tempOwner]->garrisonChanged(gs->map->objects[i->first]);
break;
}
case 503:
{
SetStrInfo ssi;
*serv >> ssi;
gs->apply(&ssi);
//TODO: notify interfaces
break;
}
case 504:
{
NewStructures ns;
*serv >> ns;
gs->apply(&ns);
BOOST_FOREACH(si32 bid, ns.bid)
playerint[gs->map->objects[ns.tid]->tempOwner]->buildChanged(static_cast<CGTownInstance*>(gs->map->objects[ns.tid]),bid,1);
break;
}
case 1001:
{
SetObjectProperty sop;
*serv >> sop;
std::cout << "Setting " << (unsigned)sop.what << " property of " << sop.id <<" object to "<<sop.val<<std::endl;
gs->apply(&sop);
break;
}
case 1002:
{
SetHoverName shn;
*serv >> shn;
std::cout << "Setting a name of " << shn.id <<" object to "<< toString(shn.name) <<std::endl;
gs->mx->lock();
gs->map->objects[shn.id]->hoverName = toString(shn.name);
gs->mx->unlock();
break;
}
case 3000:
{
BattleStart bs;
*serv >> bs; //uses new to allocate memory for battleInfo - must be deleted when battle is over
std::cout << "Starting battle!" <<std::endl;
gs->apply(&bs);
if(playerint.find(gs->curB->side1) != playerint.end())
playerint[gs->curB->side1]->battleStart(&gs->curB->army1, &gs->curB->army2, gs->curB->tile, gs->getHero(gs->curB->hero1), gs->getHero(gs->curB->hero2), 0);
if(playerint.find(gs->curB->side2) != playerint.end())
playerint[gs->curB->side2]->battleStart(&gs->curB->army1, &gs->curB->army2, gs->curB->tile, gs->getHero(gs->curB->hero1), gs->getHero(gs->curB->hero2), 1);
break;
}
case 3001:
{
BattleNextRound bnr;
*serv >> bnr;
std::cout << "Round nr " << bnr.round <<std::endl;
gs->apply(&bnr);
//tell players about next round
if(playerint.find(gs->curB->side1) != playerint.end())
playerint[gs->curB->side1]->battleNewRound(bnr.round);
if(playerint.find(gs->curB->side2) != playerint.end())
playerint[gs->curB->side2]->battleNewRound(bnr.round);
break;
}
case 3002:
{
BattleSetActiveStack sas;
*serv >> sas;
std::cout << "Active stack: " << sas.stack <<std::endl;
gs->apply(&sas);
int owner = gs->curB->getStack(sas.stack)->owner;
if(owner >= PLAYER_LIMIT) //ugly workaround to skip neutral creatures - should be replaced with AI
{
BattleAction ba;
ba.stackNumber = sas.stack;
ba.actionType = 3;
*serv << ui16(3002) << ba;
}
else
{
boost::thread(boost::bind(&CClient::waitForMoveAndSend,this,owner));
}
break;
}
case 3003:
{
BattleResult br;
*serv >> br;
std::cout << "Battle ends. Winner: " << (unsigned)br.winner<< ". Type of end: "<< (unsigned)br.result <<std::endl;
if(playerint.find(gs->curB->side1) != playerint.end())
playerint[gs->curB->side1]->battleEnd(&br);
if(playerint.find(gs->curB->side2) != playerint.end())
playerint[gs->curB->side2]->battleEnd(&br);
gs->apply(&br);
break;
}
case 3004:
{
BattleStackMoved br;
*serv >> br;
std::cout << "Stack "<<br.stack <<" moves to the tile "<<br.tile<<std::endl;
if(playerint.find(gs->curB->side1) != playerint.end())
playerint[gs->curB->side1]->battleStackMoved(br.stack,br.tile,br.flags&1,br.flags&2);
if(playerint.find(gs->curB->side2) != playerint.end())
playerint[gs->curB->side2]->battleStackMoved(br.stack,br.tile,br.flags&1,br.flags&2);
gs->apply(&br);
break;
}
case 9999:
break;
default:
#ifndef __GNUC__
throw std::exception("Not supported server message!");
#else
throw std::exception();
#endif
break;
}
}
void CClient::waitForMoveAndSend(int color)
{
BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
*serv << ui16(3002) << ba;
}
void CClient::run()
{
try
{
ui16 typ;
while(1)
{
*serv >> typ;
process(typ);
}
} HANDLE_EXCEPTION
}

53
client/Client.h Normal file
View File

@ -0,0 +1,53 @@
#pragma once
#include "../global.h"
#include <boost/thread.hpp>
struct StartInfo;
class CGameState;
class CGameInterface;
class CConnection;
class CCallback;
namespace boost
{
class mutex;
class condition_variable;
}
template <typename T>
struct CSharedCond
{
boost::mutex *mx;
boost::condition_variable *cv;
T *res;
CSharedCond(T*R)
{
res = R;
mx = new boost::mutex;
cv = new boost::condition_variable;
}
~CSharedCond()
{
delete res;
delete mx;
delete cv;
}
};
class CClient
{
CGameState *gs;
std::map<ui8,CGameInterface *> playerint;
CConnection *serv;
void waitForMoveAndSend(int color);
public:
CClient(void);
CClient(CConnection *con, StartInfo *si);
~CClient(void);
void process(int what);
void run();
friend class CCallback;
friend class CScriptCallback;
};

486
client/Graphics.cpp Normal file
View File

@ -0,0 +1,486 @@
#include "../stdafx.h"
#include "Graphics.h"
#include "../hch/CDefHandler.h"
#include "../hch/CObjectHandler.h"
#include "../SDL_Extensions.h"
#include <boost/assign/std/vector.hpp>
#include <sstream>
#include <iomanip>
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/assign/std/vector.hpp>
#include "../CThreadHelper.h"
#include "../CGameInfo.h"
#include "../hch/CLodHandler.h"
using namespace boost::assign;
using namespace CSDL_Ext;
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
Graphics * graphics = NULL;
SDL_Surface * Graphics::drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from, int to)
{
char * buf = new char[10];
for (int i=from;i<to;i++)
{
SDL_itoa(curh->primSkills[i],buf,10);
printAtMiddle(buf,84+28*i,68,GEOR13,zwykly,ret);
}
delete[] buf;
return ret;
}
SDL_Surface * Graphics::drawHeroInfoWin(const CGHeroInstance * curh)
{
char * buf = new char[10];
blueToPlayersAdv(hInfo,curh->tempOwner);
SDL_Surface * ret = SDL_DisplayFormat(hInfo);
SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
printAt(curh->name,75,15,GEOR13,zwykly,ret);
drawPrimarySkill(curh, ret);
for (std::map<si32,std::pair<ui32,si32> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
{
blitAt(graphics->smallImgs[(*i).second.first],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
SDL_itoa((*i).second.second,buf,10);
printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
}
blitAt(graphics->portraitLarge[curh->portrait],11,12,ret);
SDL_itoa(curh->mana,buf,10);
printAtMiddle(buf,166,109,GEORM,zwykly,ret); //mana points
delete[] buf;
blitAt(morale22->ourImages[curh->getCurrentMorale()+3].bitmap,14,84,ret);
blitAt(luck22->ourImages[curh->getCurrentLuck()+3].bitmap,14,101,ret);
return ret;
}
SDL_Surface * Graphics::drawTownInfoWin(const CGTownInstance * curh)
{
char * buf = new char[10];
blueToPlayersAdv(tInfo,curh->tempOwner);
SDL_Surface * ret = SDL_DisplayFormat(tInfo);
SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
printAt(curh->name,75,15,GEOR13,zwykly,ret);
int pom = curh->fortLevel() - 1; if(pom<0) pom = 3;
blitAt(forts->ourImages[pom].bitmap,115,42,ret);
if((pom=curh->hallLevel())>=0)
blitAt(halls->ourImages[pom].bitmap,77,42,ret);
SDL_itoa(curh->dailyIncome(),buf,10);
printAtMiddle(buf,167,70,GEORM,zwykly,ret);
for (std::map<si32,std::pair<ui32,si32> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
{
if(!i->second.first)
continue;
blitAt(graphics->smallImgs[(*i).second.first],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
SDL_itoa((*i).second.second,buf,10);
printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
}
//blit town icon
pom = curh->subID*2;
if (!curh->hasFort())
pom += F_NUMBER*2;
if(curh->builded >= MAX_BUILDING_PER_TURN)
pom++;
blitAt(bigTownPic->ourImages[pom].bitmap,13,13,ret);
delete[] buf;
return ret;
}
void Graphics::loadPaletteAndColors()
{
std::string pals = CGI->bitmaph->getTextFile("PLAYERS.PAL");
playerColorPalette = new SDL_Color[256];
neutralColor = new SDL_Color;
playerColors = new SDL_Color[PLAYER_LIMIT];
int startPoint = 24; //beginning byte; used to read
for(int i=0; i<256; ++i)
{
SDL_Color col;
col.r = pals[startPoint++];
col.g = pals[startPoint++];
col.b = pals[startPoint++];
col.unused = pals[startPoint++];
playerColorPalette[i] = col;
}
//colors initialization
int3 kolory[] = {int3(0xff,0,0),int3(0x31,0x52,0xff),int3(0x9c,0x73,0x52),int3(0x42,0x94,0x29),
int3(0xff,0x84,0x0),int3(0x8c,0x29,0xa5),int3(0x09,0x9c,0xa5),int3(0xc6,0x7b,0x8c)};
for(int i=0;i<8;i++)
{
playerColors[i].r = kolory[i].x;
playerColors[i].g = kolory[i].y;
playerColors[i].b = kolory[i].z;
playerColors[i].unused = 0;
}
neutralColor->r = 0x84; neutralColor->g = 0x84; neutralColor->b = 0x84;//gray
}
void Graphics::initializeBattleGraphics()
{
std::ifstream bback("config/battleBack.txt");
battleBacks.resize(9);
for(int i=0; i<9; ++i) //9 - number of terrains battle can be fought on
{
int am;
bback>>am;
battleBacks[i].resize(am);
for(int f=0; f<am; ++f)
{
bback>>battleBacks[i][f];
}
}
//initializing battle hero animation
std::ifstream bher("config/battleHeroes.txt");
int numberofh;
bher>>numberofh;
battleHeroes.resize(numberofh);
for(int i=0; i<numberofh; ++i) //9 - number of terrains battle can be fought on
{
bher>>battleHeroes[i];
}
}
Graphics::Graphics()
{
slotsPos.push_back(std::pair<int,int>(44,82));
slotsPos.push_back(std::pair<int,int>(80,82));
slotsPos.push_back(std::pair<int,int>(116,82));
slotsPos.push_back(std::pair<int,int>(26,131));
slotsPos.push_back(std::pair<int,int>(62,131));
slotsPos.push_back(std::pair<int,int>(98,131));
slotsPos.push_back(std::pair<int,int>(134,131));
CDefHandler *smi, *smi2;
std::vector<Task> tasks; //preparing list of graphics to load
tasks += boost::bind(&Graphics::loadPaletteAndColors,this);
tasks += boost::bind(&Graphics::loadHeroFlags,this);
tasks += boost::bind(&Graphics::loadHeroPortraits,this);
tasks += boost::bind(&Graphics::initializeBattleGraphics,this);
tasks += GET_SURFACE(hInfo,"HEROQVBK.bmp");
tasks += GET_SURFACE(tInfo,"TOWNQVBK.bmp");
tasks += GET_DEF(artDefs,"ARTIFACT.DEF");
tasks += GET_DEF_ESS(forts,"ITMCLS.DEF");
tasks += GET_DEF_ESS(luck22,"ILCK22.DEF");
tasks += GET_DEF_ESS(luck30,"ILCK30.DEF");
tasks += GET_DEF_ESS(luck42,"ILCK42.DEF");
tasks += GET_DEF_ESS(luck82,"ILCK82.DEF");
tasks += GET_DEF_ESS(morale22,"IMRL22.DEF");
tasks += GET_DEF_ESS(morale30,"IMRL30.DEF");
tasks += GET_DEF_ESS(morale42,"IMRL42.DEF");
tasks += GET_DEF_ESS(morale82,"IMRL82.DEF");
tasks += GET_DEF_ESS(halls,"ITMTLS.DEF");
tasks += GET_DEF_ESS(bigTownPic,"ITPT.DEF");
tasks += GET_DEF(pskillsb,"PSKILL.DEF");
tasks += GET_DEF(resources,"RESOUR82.DEF");
tasks += GET_DEF(un44,"UN44.DEF");
tasks += GET_DEF(smallIcons,"ITPA.DEF");
tasks += GET_DEF(resources32,"RESOURCE.DEF");
tasks += GET_DEF(smi,"CPRSMALL.DEF");
tasks += GET_DEF(smi2,"TWCRPORT.DEF");
std::ifstream ifs("config/cr_bgs.txt");
int id;
std::string name;
while(!ifs.eof())
{
ifs >> id >> name;
tasks += GET_SURFACE(backgrounds[id],name);
}
CThreadHelper th(&tasks,std::max((unsigned int)1,boost::thread::hardware_concurrency()));
th.run();
//handling 32x32px imgs
smi->notFreeImgs = true;
for (int i=0; i<smi->ourImages.size(); i++)
{
smallImgs[i-2] = smi->ourImages[i].bitmap;
}
delete smi;
smi2->notFreeImgs = true;
for (int i=0; i<smi2->ourImages.size(); i++)
{
bigImgs[i-2] = smi2->ourImages[i].bitmap;
}
delete smi2;
}
void Graphics::loadHeroPortraits()
{
std::ifstream of("config/portrety.txt");
int numberOfPortraits;
of>>numberOfPortraits;
for (int j=0; j<numberOfPortraits; j++)
{
int ID;
of>>ID;
std::string path;
of>>path;
portraitSmall.push_back(BitmapHandler::loadBitmap(path));
for(int ff=0; ff<path.size(); ++ff) //size letter is usually third one, but there are exceptions an it should fix the problem
{
if(path[ff]=='S')
{
path[ff]='L';
break;
}
}
portraitLarge.push_back(BitmapHandler::loadBitmap(path));
SDL_SetColorKey(portraitLarge[portraitLarge.size()-1],SDL_SRCCOLORKEY,SDL_MapRGB(portraitLarge[portraitLarge.size()-1]->format,0,255,255));
}
of.close();
}
void Graphics::loadHeroAnim(std::vector<CDefHandler **> & anims)
{
std::vector<std::pair<int,int> > rotations; //first - group number to be rotated1, second - group number after rotation1
rotations += std::make_pair(6,10), std::make_pair(7,11), std::make_pair(8,12), std::make_pair(1,13),
std::make_pair(2,14), std::make_pair(3,15);
for(int i=0; i<anims.size();i++)
{
std::stringstream nm;
nm << "AH" << std::setw(2) << std::setfill('0') << i << "_.DEF";
std::string name = nm.str();
(*anims[i]) = CDefHandler::giveDef(name);
int pom = 0; //how many groups has been rotated
for(int o=7; pom<6; ++o)
{
for(int p=0;p<6;p++)
{
if((*anims[i])->ourImages[o].groupNumber==rotations[p].first)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01((*anims[i])->ourImages[o+e].bitmap);
nci.groupNumber = rotations[p].second;
nci.imName = std::string();
(*anims[i])->ourImages.push_back(nci);
if(pom>2) //we need only one frame for groups 13/14/15
break;
}
if(pom<3) //there are eight frames of animtion of groups 6/7/8 so for speed we'll skip them
o+=8;
else //there is only one frame of 1/2/3
o+=1;
++pom;
if(p==2 && pom<4) //group1 starts at index 1
o = 1;
}
}
}
for(int ff=0; ff<(*anims[i])->ourImages.size(); ++ff)
{
CSDL_Ext::alphaTransform((*anims[i])->ourImages[ff].bitmap);
}
(*anims[i])->alphaTransformed = true;
}
}
void Graphics::loadHeroFlags(std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > &pr, bool mode)
{
for(int i=0;i<8;i++)
(this->*pr.first).push_back(CDefHandler::giveDef(pr.second[i]));
std::vector<std::pair<int,int> > rotations; //first - group number to be rotated1, second - group number after rotation1
rotations += std::make_pair(6,10), std::make_pair(7,11), std::make_pair(8,12);
for(int q=0; q<8; ++q)
{
for(int o=0; o<(this->*pr.first)[q]->ourImages.size(); ++o)
{
for(int p=0;p<rotations.size();p++)
{
if((this->*pr.first)[q]->ourImages[o].groupNumber==rotations[p].first)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01((this->*pr.first)[q]->ourImages[o+e].bitmap);
nci.groupNumber = rotations[p].second;
nci.imName = std::string();
(this->*pr.first)[q]->ourImages.push_back(nci);
}
o+=8;
}
}
}
if (mode)
{
for(int o=0; o<flags4[q]->ourImages.size(); ++o)
{
if(flags4[q]->ourImages[o].groupNumber==1)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
nci.groupNumber = 13;
nci.imName = std::string();
flags4[q]->ourImages.push_back(nci);
}
o+=8;
}
if(flags4[q]->ourImages[o].groupNumber==2)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
nci.groupNumber = 14;
nci.imName = std::string();
flags4[q]->ourImages.push_back(nci);
}
o+=8;
}
if(flags4[q]->ourImages[o].groupNumber==3)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
nci.groupNumber = 15;
nci.imName = std::string();
flags4[q]->ourImages.push_back(nci);
}
o+=8;
}
}
}
for(int ff=0; ff<(this->*pr.first)[q]->ourImages.size(); ++ff)
{
SDL_SetColorKey((this->*pr.first)[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
SDL_MapRGB((this->*pr.first)[q]->ourImages[ff].bitmap->format, 0, 255, 255)
);
}
(this->*pr.first)[q]->alphaTransformed = true;
}
}
void Graphics::loadHeroFlags()
{
using namespace boost::assign;
timeHandler th;
std::vector<CDefHandler *> Graphics::*point;
std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > pr[4];
pr[0].first = &Graphics::flags1;
pr[0].second+=("ABF01L.DEF"),("ABF01G.DEF"),("ABF01R.DEF"),("ABF01D.DEF"),("ABF01B.DEF"),
("ABF01P.DEF"),("ABF01W.DEF"),("ABF01K.DEF");
pr[1].first = &Graphics::flags2;
pr[1].second+=("ABF02L.DEF"),("ABF02G.DEF"),("ABF02R.DEF"),("ABF02D.DEF"),("ABF02B.DEF"),
("ABF02P.DEF"),("ABF02W.DEF"),("ABF02K.DEF");
pr[2].first = &Graphics::flags3;
pr[2].second+=("ABF03L.DEF"),("ABF03G.DEF"),("ABF03R.DEF"),("ABF03D.DEF"),("ABF03B.DEF"),
("ABF03P.DEF"),("ABF03W.DEF"),("ABF03K.DEF");
pr[3].first = &Graphics::flags4;
pr[3].second+=("AF00.DEF"),("AF01.DEF"),("AF02.DEF"),("AF03.DEF"),("AF04.DEF"),
("AF05.DEF"),("AF06.DEF"),("AF07.DEF");
boost::thread_group grupa;
grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[3]),true));
grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[2]),false));
grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[1]),false));
grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[0]),false));
grupa.join_all();
std::cout << "Loading and transforming heroes' flags: "<<th.getDif()<<std::endl;
}
SDL_Surface * Graphics::getPic(int ID, bool fort, bool builded)
{
if (ID==-1)
return smallIcons->ourImages[0].bitmap;
else if (ID==-2)
return smallIcons->ourImages[1].bitmap;
else if (ID==-3)
return smallIcons->ourImages[2+F_NUMBER*4].bitmap;
else if (ID>F_NUMBER || ID<-3)
#ifndef __GNUC__
throw new std::exception("Invalid ID");
#else
throw new std::exception();
#endif
else
{
int pom = 3;
if(!fort)
pom+=F_NUMBER*2;
pom += ID*2;
if (!builded)
pom--;
return smallIcons->ourImages[pom].bitmap;
}
}
void Graphics::blueToPlayersAdv(SDL_Surface * sur, int player)
{
if(player==1) //it is actually blue...
return;
if(sur->format->BitsPerPixel == 8)
{
for(int i=0; i<32; ++i)
{
sur->format->palette->colors[224+i] = playerColorPalette[32*player+i];
}
}
else if(sur->format->BitsPerPixel == 24) //should never happen in general
{
for(int y=0; y<sur->h; ++y)
{
for(int x=0; x<sur->w; ++x)
{
Uint8* cp = (Uint8*)sur->pixels + y*sur->pitch + x*3;
if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
if(cp[2]>cp[1] && cp[2]>cp[0])
{
std::vector<long long int> sort1;
sort1.push_back(cp[0]);
sort1.push_back(cp[1]);
sort1.push_back(cp[2]);
std::vector< std::pair<long long int, Uint8*> > sort2;
sort2.push_back(std::make_pair(graphics->playerColors[player].r, &(cp[0])));
sort2.push_back(std::make_pair(graphics->playerColors[player].g, &(cp[1])));
sort2.push_back(std::make_pair(graphics->playerColors[player].b, &(cp[2])));
std::sort(sort1.begin(), sort1.end());
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
if(sort2[1].first>sort2[2].first)
std::swap(sort2[1], sort2[2]);
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
for(int hh=0; hh<3; ++hh)
{
(*sort2[hh].second) = (sort1[hh] + sort2[hh].first)/2.2;
}
}
}
else
{
if(
(/*(mode==0) && (cp[0]>cp[1]) && (cp[0]>cp[2])) ||
((mode==1) &&*/ (cp[2]<45) && (cp[0]>80) && (cp[1]<70) && ((cp[0]-cp[1])>40))
)
{
std::vector<long long int> sort1;
sort1.push_back(cp[2]);
sort1.push_back(cp[1]);
sort1.push_back(cp[0]);
std::vector< std::pair<long long int, Uint8*> > sort2;
sort2.push_back(std::make_pair(graphics->playerColors[player].r, &(cp[2])));
sort2.push_back(std::make_pair(graphics->playerColors[player].g, &(cp[1])));
sort2.push_back(std::make_pair(graphics->playerColors[player].b, &(cp[0])));
std::sort(sort1.begin(), sort1.end());
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
if(sort2[1].first>sort2[2].first)
std::swap(sort2[1], sort2[2]);
if(sort2[0].first>sort2[1].first)
std::swap(sort2[0], sort2[1]);
for(int hh=0; hh<3; ++hh)
{
(*sort2[hh].second) = (sort1[hh]*0.8 + sort2[hh].first)/2;
}
}
}
}
}
}
}

53
client/Graphics.h Normal file
View File

@ -0,0 +1,53 @@
#pragma once
#include "../global.h"
class CDefEssential;
struct SDL_Surface;
class CGHeroInstance;
class CGTownInstance;
class CDefHandler;
class CHeroClass;
struct SDL_Color;
class Graphics
{
public:
//various graphics
SDL_Color * playerColors; //array [8]
SDL_Color * neutralColor;
SDL_Color * playerColorPalette; //palette to make interface colors good - array of size [256]
SDL_Surface * hInfo, *tInfo; //hero and town infobox bgs
std::vector<std::pair<int, int> > slotsPos; //creature slot positions in infoboxes
CDefEssential *luck22, *luck30, *luck42, *luck82,
*morale22, *morale30, *morale42, *morale82,
*halls, *forts, *bigTownPic;
std::map<int,SDL_Surface*> heroWins; //hero_ID => infobox
std::map<int,SDL_Surface*> townWins; //town_ID => infobox
CDefHandler * artDefs; //artifacts
std::vector<SDL_Surface *> portraitSmall; //48x32 px portraits of heroes
std::vector<SDL_Surface *> portraitLarge; //58x64 px portraits of heroes
std::vector<CDefHandler *> flags1, flags2, flags3, flags4; //flags blitted on heroes when ,
CDefHandler * pskillsb, *resources; //82x93
CDefHandler * un44; //many things
CDefHandler * smallIcons, *resources32; //resources 32x32
//creatures
std::map<int,SDL_Surface*> smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border
std::map<int,SDL_Surface*> bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border
std::map<int,SDL_Surface*> backgrounds; //castle ID -> 100x130 background creature image // -1 is for neutral
//for battles
std::vector< std::vector< std::string > > battleBacks; //battleBacks[terType] - vector of possible names for certain terrain type
std::vector< std::string > battleHeroes; //battleHeroes[hero type] - name of def that has hero animation for battle
//functions
Graphics();
void initializeBattleGraphics();
void loadPaletteAndColors();
void loadHeroFlags();
void loadHeroFlags(std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > &pr, bool mode);
void loadHeroAnim(std::vector<CDefHandler **> & anims);
void loadHeroPortraits();
SDL_Surface * drawHeroInfoWin(const CGHeroInstance * curh);
SDL_Surface * drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from=0, int to=PRIMARY_SKILLS);
SDL_Surface * drawTownInfoWin(const CGTownInstance * curh);
SDL_Surface * getPic(int ID, bool fort=true, bool builded=false); //returns small picture of town: ID=-1 - blank; -2 - border; -3 - random
void blueToPlayersAdv(SDL_Surface * sur, int player); //replaces blue interface colour with a color of player
};
extern Graphics * graphics;

83
client/Makefile.am Normal file
View File

@ -0,0 +1,83 @@
AUTOMAKE_OPTIONS=foreign
bin_PROGRAMS = vcmiclient
#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
#AM_CXXFLAGS = $(BOOST_CPPFLAGS)
vcmiclient_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
#vcmiclient_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
vcmiclient_LDFLAGS = -L$(top_builddir)/lib
vcmiclient_LDADD += -lvcmi
vcmiclient_SOURCES = \
../AdventureMapButton.cpp \
../hch/CAbilityHandler.cpp \
../CAdvmapInterface.cpp \
../CBattleInterface.cpp \
./CBitmapHandler.cpp \
../CCallback.cpp \
../CCastleInterface.cpp \
../CConsoleHandler.cpp \
./CCreatureAnimation.cpp \
../CCursorHandler.cpp \
../hch/CDefHandler.cpp \
../CGameInfo.cpp \
../CGameInterface.cpp \
../hch/CGeneralTextHandler.cpp \
../CHeroWindow.cpp \
./Client.cpp \
../CLuaHandler.cpp \
../CMessage.cpp \
../CMT.cpp \
../hch/CMusicHandler.cpp \
../CPathfinder.cpp \
../CPlayerInterface.cpp \
../CPreGame.cpp \
../hch/CPreGameTextHandler.cpp \
../hch/CSndHandler.cpp \
../hch/CSpellHandler.cpp \
../CThreadHelper.cpp \
./Graphics.cpp \
../mapHandler.cpp \
../SDL_Extensions.cpp \
../SDL_framerate.cpp \
../AdventureMapButton.h \
../AI_Base.h \
../hch/CAbilityHandler.h \
../CAdvmapInterface.h \
../hch/CAmbarCendamo.h \
../hch/CArtHandler.h \
../CBattleInterface.h \
./CBitmapHandler.h \
../hch/CBuildingHandler.h \
../CCallback.h \
../CCastleInterface.h \
../CConsoleHandler.h \
./CCreatureAnimation.h \
../hch/CCreatureHandler.h \
../CCursorHandler.h \
../hch/CDefHandler.h \
../CGameInfo.h \
../CGameInterface.h \
../hch/CGeneralTextHandler.h \
../hch/CHeroHandler.h \
../CHeroWindow.h \
./Client.h \
../CLuaHandler.h \
../CMessage.h \
../hch/CMusicHandler.h \
../hch/CObjectHandler.h \
../CPathfinder.h \
../CPlayerInterface.h \
../CPreGame.h \
../hch/CPreGameTextHandler.h \
../hch/CSndHandler.h \
../hch/CSpellHandler.h \
../CThreadHelper.h \
../global.h \
./Graphics.h \
../int3.h \
../map.h \
../mapHandler.h \
../nodrze.h \
../SDL_framerate.h \
../StartInfo.h \
../stdafx.h \
../timeHandler.h

570
client/VCMI_client.vcproj Normal file
View File

@ -0,0 +1,570 @@
<?xml version="1.0" encoding="windows-1250"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="VCMI_client"
ProjectGUID="{8355EBA8-65C2-44A4-BC2D-78053E1BF2D6}"
RootNamespace="VCMI_client"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="G:\vcmt\repa\include"
GeneratePreprocessedFile="0"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
WarningLevel="1"
DebugInformationFormat="4"
DisableSpecificWarnings="4251"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
ShowProgress="0"
AdditionalLibraryDirectories="G:\vcmt\repa\libs"
GenerateDebugInformation="true"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
EnableFiberSafeOptimizations="true"
WholeProgramOptimization="true"
AdditionalIncludeDirectories="G:\vcmt\repa\include"
StringPooling="true"
BasicRuntimeChecks="0"
RuntimeLibrary="2"
EnableFunctionLevelLinking="false"
EnableEnhancedInstructionSet="0"
WarningLevel="3"
DebugInformationFormat="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
AdditionalLibraryDirectories="G:\vcmt\repa\libs"
GenerateDebugInformation="false"
Driver="0"
OptimizeReferences="2"
EnableCOMDATFolding="2"
LinkTimeCodeGeneration="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="RD|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
EnableFiberSafeOptimizations="true"
WholeProgramOptimization="true"
AdditionalIncludeDirectories="G:\vcmt\repa\include"
StringPooling="true"
BasicRuntimeChecks="0"
RuntimeLibrary="2"
EnableFunctionLevelLinking="false"
EnableEnhancedInstructionSet="0"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
AdditionalLibraryDirectories="G:\vcmt\repa\libs"
GenerateDebugInformation="true"
Driver="0"
OptimizeReferences="2"
EnableCOMDATFolding="2"
LinkTimeCodeGeneration="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\AdventureMapButton.cpp"
>
</File>
<File
RelativePath="..\hch\CAbilityHandler.cpp"
>
</File>
<File
RelativePath="..\CAdvmapInterface.cpp"
>
</File>
<File
RelativePath="..\CBattleInterface.cpp"
>
</File>
<File
RelativePath=".\CBitmapHandler.cpp"
>
</File>
<File
RelativePath="..\CCallback.cpp"
>
</File>
<File
RelativePath="..\CCastleInterface.cpp"
>
</File>
<File
RelativePath="..\CConsoleHandler.cpp"
>
</File>
<File
RelativePath=".\CCreatureAnimation.cpp"
>
</File>
<File
RelativePath="..\CCursorHandler.cpp"
>
</File>
<File
RelativePath="..\hch\CDefHandler.cpp"
>
</File>
<File
RelativePath="..\CGameInfo.cpp"
>
</File>
<File
RelativePath="..\CGameInterface.cpp"
>
</File>
<File
RelativePath="..\hch\CGeneralTextHandler.cpp"
>
</File>
<File
RelativePath="..\CHeroWindow.cpp"
>
</File>
<File
RelativePath=".\Client.cpp"
>
</File>
<File
RelativePath="..\CLuaHandler.cpp"
>
</File>
<File
RelativePath="..\CMessage.cpp"
>
</File>
<File
RelativePath="..\CMT.cpp"
>
</File>
<File
RelativePath="..\hch\CMusicHandler.cpp"
>
</File>
<File
RelativePath="..\CPathfinder.cpp"
>
</File>
<File
RelativePath="..\CPlayerInterface.cpp"
>
</File>
<File
RelativePath="..\CPreGame.cpp"
>
</File>
<File
RelativePath="..\hch\CPreGameTextHandler.cpp"
>
</File>
<File
RelativePath="..\hch\CSndHandler.cpp"
>
</File>
<File
RelativePath="..\hch\CSpellHandler.cpp"
>
</File>
<File
RelativePath="..\CThreadHelper.cpp"
>
</File>
<File
RelativePath=".\Graphics.cpp"
>
</File>
<File
RelativePath="..\mapHandler.cpp"
>
</File>
<File
RelativePath="..\SDL_Extensions.cpp"
>
</File>
<File
RelativePath="..\SDL_framerate.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath="..\AdventureMapButton.h"
>
</File>
<File
RelativePath="..\AI_Base.h"
>
</File>
<File
RelativePath="..\hch\CAbilityHandler.h"
>
</File>
<File
RelativePath="..\CAdvmapInterface.h"
>
</File>
<File
RelativePath="..\hch\CAmbarCendamo.h"
>
</File>
<File
RelativePath="..\hch\CArtHandler.h"
>
</File>
<File
RelativePath="..\CBattleInterface.h"
>
</File>
<File
RelativePath=".\CBitmapHandler.h"
>
</File>
<File
RelativePath="..\hch\CBuildingHandler.h"
>
</File>
<File
RelativePath="..\CCallback.h"
>
</File>
<File
RelativePath="..\CCastleInterface.h"
>
</File>
<File
RelativePath="..\CConsoleHandler.h"
>
</File>
<File
RelativePath=".\CCreatureAnimation.h"
>
</File>
<File
RelativePath="..\hch\CCreatureHandler.h"
>
</File>
<File
RelativePath="..\CCursorHandler.h"
>
</File>
<File
RelativePath="..\hch\CDefHandler.h"
>
</File>
<File
RelativePath="..\CGameInfo.h"
>
</File>
<File
RelativePath="..\CGameInterface.h"
>
</File>
<File
RelativePath="..\hch\CGeneralTextHandler.h"
>
</File>
<File
RelativePath="..\hch\CHeroHandler.h"
>
</File>
<File
RelativePath="..\CHeroWindow.h"
>
</File>
<File
RelativePath=".\Client.h"
>
</File>
<File
RelativePath="..\CLuaHandler.h"
>
</File>
<File
RelativePath="..\CMessage.h"
>
</File>
<File
RelativePath="..\hch\CMusicHandler.h"
>
</File>
<File
RelativePath="..\hch\CObjectHandler.h"
>
</File>
<File
RelativePath="..\CPathfinder.h"
>
</File>
<File
RelativePath="..\CPlayerInterface.h"
>
</File>
<File
RelativePath="..\CPreGame.h"
>
</File>
<File
RelativePath="..\hch\CPreGameTextHandler.h"
>
</File>
<File
RelativePath="..\hch\CSndHandler.h"
>
</File>
<File
RelativePath="..\hch\CSpellHandler.h"
>
</File>
<File
RelativePath="..\CThreadHelper.h"
>
</File>
<File
RelativePath="..\global.h"
>
</File>
<File
RelativePath=".\Graphics.h"
>
</File>
<File
RelativePath="..\int3.h"
>
</File>
<File
RelativePath="..\map.h"
>
</File>
<File
RelativePath="..\mapHandler.h"
>
</File>
<File
RelativePath="..\nodrze.h"
>
</File>
<File
RelativePath="..\SDL_framerate.h"
>
</File>
<File
RelativePath="..\StartInfo.h"
>
</File>
<File
RelativePath="..\stdafx.h"
>
</File>
<File
RelativePath="..\timeHandler.h"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -54,6 +54,9 @@
/* define if the Boost::System library is available */
#undef HAVE_BOOST_SYSTEM
/* define if the Boost::Thread library is available */
#undef HAVE_BOOST_THREAD
/* Define to 1 if you have the <fcntl.h> header file. */
#undef HAVE_FCNTL_H

View File

@ -11,6 +11,7 @@ AC_PROG_CXX
AX_BOOST_BASE([1.33])
AX_BOOST_SYSTEM
AX_BOOST_FILESYSTEM
AX_BOOST_THREAD
AC_PROG_CC
AC_PROG_CPP
AC_PROG_RANLIB
@ -74,4 +75,4 @@ AC_FUNC_SELECT_ARGTYPES
AC_CHECK_FUNCS([lua_pushhstring lua_calchash],, AC_MSG_ERROR([Lua required fuctions not found]))
AC_CHECK_FUNCS([atexit memset pow select sqrt])
AC_OUTPUT(Makefile hch/Makefile)
AC_OUTPUT(Makefile lib/Makefile client/Makefile server/Makefile)

View File

@ -1,22 +1,30 @@
#ifndef GLOBAL_H
#define GLOBAL_H
#include <iostream>
#include <boost/logic/tribool.hpp>
#include <boost/cstdint.hpp>
typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
typedef boost::int8_t si8; //signed int 8 bits (1 byte)
#include "int3.h"
#define CHECKTIME 1
#if CHECKTIME
#include "timeHandler.h"
#include <boost/logic/tribool.hpp>
#include <iostream>
#include "int3.h"
#define THC
#else
#define THC //
#endif
#ifdef WIN32
#define NAME_VER ("VCMI \"Altanatse\" 0.7")
#ifdef _WIN32
#define PATHSEPARATOR "\\"
#define DATADIR ""
#define DATA_DIR ""
#else
#define PATHSEPARATOR "/"
#define DATADIR "/progdir/"
#define DATA_DIR "/progdir/"
#endif
enum Ecolor {RED, BLUE, TAN, GREEN, ORANGE, PURPLE, TEAL, PINK}; //player's colors
@ -30,31 +38,12 @@ enum ElossCon {lossCastle, lossHero, timeExpires, lossStandard=255};
enum EHeroClasses {HERO_KNIGHT, HERO_CLERIC, HERO_RANGER, HERO_DRUID, HERO_ALCHEMIST, HERO_WIZARD,
HERO_DEMONIAC, HERO_HERETIC, HERO_DEATHKNIGHT, HERO_NECROMANCER, HERO_WARLOCK, HERO_OVERLORD,
HERO_BARBARIAN, HERO_BATTLEMAGE, HERO_BEASTMASTER, HERO_WITCH, HERO_PLANESWALKER, HERO_ELEMENTALIST};
#ifdef _DEBUG
class CGameInfo;
extern CGameInfo* CGI;
#else
#define CGI (CGameInfo::mainObj)
#endif
#define CURPLINT (((CPlayerInterface*)((CGameInfo::mainObj)->playerint[(CGameInfo::mainObj)->state->currentPlayer])))
#define LOCPLINT (((CPlayerInterface*)((CGameInfo::mainObj)->playerint[(CGameInfo::mainObj)->localPlayer])))
//CURPLINT gives pointer to the interface of human player which is currently making turn,
//LOCPLINT gives pointer to the interface which is currently showed (on this machine)
#define HEROI_TYPE (0)
#define TOWNI_TYPE (1)
//#define LOGUJ
#ifdef LOGUJ
#define LOG(x) std::cout<<x;
#define LOGE(x) std::cout<<x<<std::endl;
#else
#define LOG(x) ;
#define LOGE(x) ;
#endif
const int F_NUMBER = 9; //factions (town types) quantity
const int PLAYER_LIMIT = 8; //player limit per map
const int HEROES_PER_TYPE=8; //amount of heroes of each type
@ -62,6 +51,7 @@ const int SKILL_QUANTITY=28;
const int SKILL_PER_HERO=8;
const int ARTIFACTS_QUANTITY=171;
const int HEROES_QUANTITY=156;
const int SPELLS_QUANTITY=70;
const int RESOURCE_QUANTITY=8;
const int TERRAIN_TYPES=10;
const int PRIMARY_SKILLS=4;
@ -75,6 +65,19 @@ const int MAX_BUILDING_PER_TURN = 1;
#define DEFBYPASS
#ifdef _WIN32
#ifdef VCMI_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#if defined(__GNUC__) && __GNUC__ >= 4
#define DLL_EXPORT __attribute__ ((visibility("default")))
#else
#define DLL_EXPORT
#endif
#endif
#define HANDLE_EXCEPTION \
catch (const std::exception& e) { \

View File

@ -7,33 +7,33 @@
void CAbilityHandler::loadAbilities()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("SSTRAITS.TXT");
std::string buf = CGI->bitmaph->getTextFile("SSTRAITS.TXT");
int it=0;
std::string dump;
for(int i=0; i<2; ++i)
{
CGeneralTextHandler::loadToIt(dump,buf,it,3);
loadToIt(dump,buf,it,3);
}
for (int i=0; i<SKILL_QUANTITY; i++)
{
CAbility * nab = new CAbility; //new skill, that will be read
CGeneralTextHandler::loadToIt(nab->name,buf,it,4);
CGeneralTextHandler::loadToIt(nab->basicText,buf,it,4);
CGeneralTextHandler::loadToIt(nab->advText,buf,it,4);
CGeneralTextHandler::loadToIt(nab->expText,buf,it,3);
loadToIt(nab->name,buf,it,4);
loadToIt(nab->basicText,buf,it,4);
loadToIt(nab->advText,buf,it,4);
loadToIt(nab->expText,buf,it,3);
nab->idNumber = abilities.size();
abilities.push_back(nab);
}
abils32 = CGI->spriteh->giveDef("SECSK32.DEF");
abils44 = CGI->spriteh->giveDef("SECSKILL.DEF");
abils82 = CGI->spriteh->giveDef("SECSK82.DEF");
abils32 = CDefHandler::giveDef("SECSK32.DEF");
abils44 = CDefHandler::giveDef("SECSKILL.DEF");
abils82 = CDefHandler::giveDef("SECSK82.DEF");
buf = CGameInfo::mainObj->bitmaph->getTextFile("SKILLLEV.TXT");
buf = CGI->bitmaph->getTextFile("SKILLLEV.TXT");
it=0;
for(int i=0; i<6; ++i)
{
std::string buffo;
CGeneralTextHandler::loadToIt(buffo,buf,it,3);
loadToIt(buffo,buf,it,3);
levels.push_back(buffo);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,40 +1,19 @@
#ifndef CAMBARCENDAMO_H
#define CAMBARCENDAMO_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "../global.h"
#include "SDL.h"
#include "../map.h"
#include "CSemiDefHandler.h"
#include "CDefHandler.h"
#include "CCreatureHandler.h"
enum EDefType {TOWN_DEF, HERO_DEF, CREATURES_DEF, SEERHUT_DEF, RESOURCE_DEF, TERRAINOBJ_DEF, EVENTOBJ_DEF, SIGN_DEF, GARRISON_DEF, ARTIFACT_DEF, WITCHHUT_DEF, SCHOLAR_DEF, PLAYERONLY_DEF, SHRINE_DEF, SPELLSCROLL_DEF, PANDORA_DEF, GRAIL_DEF, CREGEN_DEF, CREGEN2_DEF, CREGEN3_DEF, BORDERGUARD_DEF, HEROPLACEHOLDER_DEF};
class CAmbarCendamo
class DLL_EXPORT CAmbarCendamo
{
public:
/////////////////member variables
Mapa map;
std::ifstream * is; // stream used to read map file
int andame; // length of map file
unsigned char * bufor; // here we store map bytecode
std::vector<CDefHandler*> defs;
/////////////////member functions
CAmbarCendamo (const char * tie); // c-tor; tie is the path of the map file
CAmbarCendamo (unsigned char * map); // c-tor; map is pointer to array containing map; it is not copied, so don't delete
~CAmbarCendamo (); // d-tor
int readNormalNr (int pos, int bytCon=4, bool cyclic = false); //read number from bytCon bytes starting from pos position in buffer ; if cyclic is true, number is treated as it were signed number with bytCon bytes
void teceDef (); // create files with info about defs
void deh3m(); // decode file, results are stored in map
void processMap(std::vector<std::string> & defsToUnpack); //choose castles, creatures, resources, artifacts...
////
std::vector<std::string> resDefNames;
////
void loadDefs();
EDefType getDefType(CGDefInfo * a); //returns type of object in def
CCreatureSet readCreatureSet(int pos, int number = 7); //reads creature set in most recently encountered format; reades number units (default is 7)
//Mapa* map;
//CAmbarCendamo (unsigned char * data); // c-tor; data is pointer to decompressed h3m data
//~CAmbarCendamo (); // d-tor
};
#endif //CAMBARCENDAMO_H

View File

@ -1,146 +1,47 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "CArtHandler.h"
#include "../CGameInfo.h"
#include "CGeneralTextHandler.h"
#include "CLodHandler.h"
#include <boost/assign/std/vector.hpp>
#include <boost/assign/list_of.hpp>
#include "../lib/VCMI_Lib.h"
void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
extern CLodHandler *bitmaph;
using namespace boost::assign;
CArtHandler::CArtHandler()
{
VLC->arth = this;
}
void CArtHandler::loadArtifacts()
{
artDefs = CGI->spriteh->giveDef("ARTIFACT.DEF");
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("ARTRAITS.TXT");
std::vector<bool CArtifact::*> slots;
slots += &CArtifact::spellBook, &CArtifact::warMachine4, &CArtifact::warMachine3, &CArtifact::warMachine2,
&CArtifact::warMachine1, &CArtifact::misc5, &CArtifact::misc4, &CArtifact::misc3, &CArtifact::misc2,
&CArtifact::misc1, &CArtifact::feet, &CArtifact::lRing, &CArtifact::rRing, &CArtifact::torso,
&CArtifact::lHand, &CArtifact::rHand, &CArtifact::neck, &CArtifact::shoulders, &CArtifact::head;
std::map<char,EartClass> classes =
map_list_of('S',SartClass)('T',TartClass)('N',NartClass)('J',JartClass)('R',RartClass);
std::string buf = bitmaph->getTextFile("ARTRAITS.TXT"), dump, pom;
int it=0;
std::string dump;
for(int i=0; i<2; ++i)
{
CGeneralTextHandler::loadToIt(dump,buf,it,3);
loadToIt(dump,buf,it,3);
}
for (int i=0; i<ARTIFACTS_QUANTITY; i++)
{
CArtifact nart;
std::string pom;
CGeneralTextHandler::loadToIt(nart.name,buf,it,4);
CGeneralTextHandler::loadToIt(pom,buf,it,4);
loadToIt(nart.name,buf,it,4);
loadToIt(pom,buf,it,4);
nart.price=atoi(pom.c_str());
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.spellBook=true;
else
nart.spellBook = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.warMachine4=true;
else
nart.warMachine4 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.warMachine3=true;
else
nart.warMachine3 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.warMachine2=true;
else
nart.warMachine2 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.warMachine1=true;
else
nart.warMachine1 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.misc5=true;
else
nart.misc5 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.misc4=true;
else
nart.misc4 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.misc3=true;
else
nart.misc3 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.misc2=true;
else
nart.misc2 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.misc1=true;
else
nart.misc1 = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.feet=true;
else
nart.feet = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.lRing=true;
else
nart.lRing = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.rRing=true;
else
nart.rRing = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.torso=true;
else
nart.torso = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.lHand=true;
else
nart.lHand = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.rHand=true;
else
nart.rHand = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.neck=true;
else
nart.neck = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.shoulders=true;
else
nart.shoulders = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
if (pom[0]=='x')
nart.head=true;
else
nart.head = false;
CGeneralTextHandler::loadToIt(pom,buf,it,4);
switch (pom[0])
for(int j=0;j<slots.size();j++)
{
case 'S':
nart.aClass=SartClass;
break;
case 'T':
nart.aClass=TartClass;
break;
case 'N':
nart.aClass=NartClass;
break;
case 'J':
nart.aClass=JartClass;
break;
case 'R':
nart.aClass=RartClass;
break;
loadToIt(pom,buf,it,4);
nart.*slots[j] = (pom[0]=='x');
}
CGeneralTextHandler::loadToIt(nart.description,buf,it,3);
nart.id=artifacts.size();
loadToIt(pom,buf,it,4);
nart.aClass = classes[pom[0]];
loadToIt(nart.description,buf,it,3);
nart.id=i;
artifacts.push_back(nart);
}
for(int i=0;i<144;i++) //do 144, bo nie chcemy bzdurek

View File

@ -1,13 +1,13 @@
#ifndef CARTHANDLER_H
#define CARTHANDLER_H
#include "../global.h"
#include <string>
#include <vector>
enum EartClass {SartClass=0, TartClass, NartClass, JartClass, RartClass}; //artifact class (relict, treasure, strong, weak etc.)
class CDefHandler;
class CArtifact //container for artifacts
class DLL_EXPORT CArtifact //container for artifacts
{
public:
bool isAllowed; //true if we can use this artifact (map information)
@ -21,14 +21,14 @@ public:
int id;
};
class CArtHandler //handles artifacts
class DLL_EXPORT CArtHandler //handles artifacts
{
public:
CDefHandler * artDefs;
std::vector<CArtifact*> treasures, minors, majors, relics;
std::vector<CArtifact> artifacts;
void loadArtifacts();
bool loadArtEvents();
CArtHandler();
};
#endif // CARTHANDLER_H

View File

@ -1,9 +1,10 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "../CGameInfo.h"
#include "CBuildingHandler.h"
#include "CLodHandler.h"
#include <sstream>
#include <fstream>
extern CLodHandler * bitmaph;
std::string readTo(std::string &in, unsigned int &it, char end)
{
int pom = it;
@ -31,6 +32,7 @@ unsigned int readNr(std::string &in, unsigned int &it)
CBuilding * readBg(std::string &buf, unsigned int& it)
{
CBuilding * nb = new CBuilding();
nb->resources.resize(RESOURCE_QUANTITY);
for(int res=0;res<7;res++)
nb->resources[res] = readNr(buf,it);
nb->refName = readTo(buf,it,'\n');
@ -38,7 +40,7 @@ CBuilding * readBg(std::string &buf, unsigned int& it)
}
void CBuildingHandler::loadBuildings()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("BUILDING.TXT"), temp;
std::string buf = bitmaph->getTextFile("BUILDING.TXT"), temp;
unsigned int andame = buf.size(), it=0; //buf iterator
temp = readTo(buf,it,'\n');temp = readTo(buf,it,'\n');//read 2 lines of file info
@ -79,7 +81,7 @@ void CBuildingHandler::loadBuildings()
}
/////done reading BUILDING.TXT*****************************
buf = CGameInfo::mainObj->bitmaph->getTextFile("BLDGNEUT.TXT");
buf = bitmaph->getTextFile("BLDGNEUT.TXT");
andame = buf.size(), it=0;
for(int b=0;b<15;b++)
@ -109,7 +111,7 @@ void CBuildingHandler::loadBuildings()
}
/////done reading "BLDGNEUT.TXT"******************************
buf = CGameInfo::mainObj->bitmaph->getTextFile("BLDGSPEC.TXT");
buf = bitmaph->getTextFile("BLDGSPEC.TXT");
andame = buf.size(), it=0;
for(int f=0;f<F_NUMBER;f++)
{
@ -126,7 +128,7 @@ void CBuildingHandler::loadBuildings()
}
/////done reading BLDGSPEC.TXT*********************************
buf = CGameInfo::mainObj->bitmaph->getTextFile("DWELLING.TXT");
buf = bitmaph->getTextFile("DWELLING.TXT");
andame = buf.size(), it=0;
for(int f=0;f<F_NUMBER;f++)
{

View File

@ -2,19 +2,20 @@
#define CBUILDINGHANDLER_H
#include "../global.h"
#include <map>
#include <vector>
//enum EbuildingType {NEUTRAL=-1, CASTLE, RAMPART, TOWER, INFERNO, NECROPOLIS, DUNGEON, STRONGHOLD, FORTRESS, CONFLUX};
class CBuilding //a typical building encountered in every castle ;]
class DLL_EXPORT CBuilding //a typical building encountered in every castle ;]
{
public:
std::string name;
std::string refName; //reference name, for identification
int resources[7];
std::vector<int> resources;
std::string description;
//EbuildingType type; //type of building (occures in many castles or is specific for one castle)
//bool isDwelling; //true, if this building is a dwelling
};
class CBuildingHandler
class DLL_EXPORT CBuildingHandler
{
public:
std::map<int, std::map<int, CBuilding*> > buildings; ///< first int is the castle ID, second the building ID (in ERM-U format)

View File

@ -1,2 +0,0 @@
#include "../stdafx.h"
#include "CCastleHandler.h"

View File

@ -1,51 +0,0 @@
#ifndef CCASTLEHANDLER_H
#define CCASTLEHANDLER_H
#include "CBuildingHandler.h"
#include "CHeroHandler.h"
#include "CObjectHandler.h"
#include "CCreatureHandler.h"
class CCastleEvent
{
public:
std::string name, message;
int wood, mercury, ore, sulfur, crystal, gems, gold; //gain / loss of resources
unsigned char players; //players for whom this event can be applied
bool forHuman, forComputer;
int firstShow; //postpone of first encounter time in days
int forEvery; //every n days this event will occure
unsigned char bytes[6]; //build specific buildings (raw format, similar to town's)
int gen[7]; //additional creatures in i-th level dwelling
};
class CCastleObjInfo : public CSpecObjInfo //castle class
{
public:
int x, y, z; //posiotion
std::vector<CBuilding> buildings; //buildings we can build in this castle
std::vector<bool> isBuild; //isBuild[i] is true, when building buildings[i] has been built
std::vector<bool> isLocked; //isLocked[i] is true, when building buildings[i] canot be built
bool unusualBuildins; //if true, intrepret bytes below
unsigned char buildingSettings[12]; //raw format for two vectors above (greatly depends on town type)
bool hasFort; //used only if unusualBuildings is false
CHero * visitingHero;
CHero * garnisonHero;
unsigned char bytes[4]; //identifying bytes
unsigned char player; //255 - nobody, players 0 - 7
std::string name; //town name
CCreatureSet garrison;
std::vector<CSpell *> possibleSpells;
std::vector<CSpell *> obligatorySpells;
std::vector<CSpell *> availableSpells;
std::vector<CCastleEvent> events;
unsigned char alignment; //255 - same as owner/random, 0 - same as red, 1 - same as blue, etc
};
#endif //CCASTLEHANDLER_H

View File

@ -1,6 +1,5 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "../CGameInfo.h"
#include "CDefHandler.h"
#include "CCreatureHandler.h"
#include "CLodHandler.h"
#include <sstream>
@ -8,8 +7,12 @@
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "../SDL_Extensions.h"
#include "../lib/VCMI_Lib.h"
extern CLodHandler * bitmaph;
CCreatureHandler::CCreatureHandler()
{
VLC->creh = this;
}
int CCreature::getQuantityID(int quantity)
{
if (quantity<5)
@ -42,25 +45,23 @@ bool CCreature::isFlying()
{
return boost::algorithm::find_first(abilityRefs, "FLYING_ARMY");
}
bool CCreature::isShooting()
{
return boost::algorithm::find_first(abilityRefs, "SHOOTING_ARMY");
}
int CCreature::maxAmount(const std::vector<int> &res) const //how many creatures can be bought
si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
{
int ret = 2147483645;
int resAmnt = std::min(res.size(),cost.size());
for(int i=0;i<resAmnt;i++)
if(cost[i])
ret = std::min(ret,res[i]/cost[i]);
ret = std::min(ret,(int)(res[i]/cost[i]));
return ret;
}
void CCreatureHandler::loadCreatures()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("ZCRTRAIT.TXT");
std::string buf = bitmaph->getTextFile("ZCRTRAIT.TXT");
int andame = buf.size();
int i=0; //buf iterator
int hmcr=0;
@ -352,19 +353,6 @@ void CCreatureHandler::loadCreatures()
ifs.close();
ifs.clear();
ifs.open("config/cr_bgs.txt");
while(!ifs.eof())
{
int id;
std::string name;
ifs >> id >> name;
backgrounds[id]=CGI->bitmaph->loadBitmap(name);
}
ifs.close();
ifs.clear();
ifs.open("config/cr_factions.txt");
while(!ifs.eof())
{
@ -385,23 +373,6 @@ void CCreatureHandler::loadCreatures()
ifs.close();
ifs.clear();
//loading 32x32px imgs
CDefHandler *smi = CGI->spriteh->giveDef("CPRSMALL.DEF");
smi->notFreeImgs = true;
for (int i=0; i<smi->ourImages.size(); i++)
{
boost::assign::insert(smallImgs)(i-2,smi->ourImages[i].bitmap);
}
delete smi;
smi = CGI->spriteh->giveDef("TWCRPORT.DEF");
smi->notFreeImgs = true;
for (int i=0; i<smi->ourImages.size(); i++)
{
boost::assign::insert(bigImgs)(i-2,smi->ourImages[i].bitmap);
}
delete smi;
//
//loading unit animation def names
std::ifstream inp("config/CREDEFS.TXT", std::ios::in | std::ios::binary); //this file is not in lod
inp.seekg(0,std::ios::end); // na koniec
@ -472,7 +443,7 @@ void CCreatureHandler::loadCreatures()
void CCreatureHandler::loadAnimationInfo()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("CRANIM.TXT");
std::string buf = bitmaph->getTextFile("CRANIM.TXT");
int andame = buf.size();
int i=0; //buf iterator
int hmcr=0;
@ -642,421 +613,3 @@ void CCreatureHandler::loadUnitAnimInfo(CCreature & unit, std::string & src, int
}
i+=2;
}
void CCreatureHandler::loadUnitAnimations()
{
//std::ifstream inp("config/CREDEFS.TXT", std::ios::in | std::ios::binary); //this file is not in lod
//inp.seekg(0,std::ios::end); // na koniec
//int andame = inp.tellg(); // read length
//inp.seekg(0,std::ios::beg); // wracamy na poczatek
//char * bufor = new char[andame]; // allocate memory
//inp.read((char*)bufor, andame); // read map file to buffer
//inp.close();
//std::string buf = std::string(bufor);
//delete [andame] bufor;
//int i = 0; //buf iterator
//int hmcr = 0;
//for(i; i<andame; ++i) //omitting rubbish
//{
// if(buf[i]=='\r')
// break;
//}
//i+=2;
//for(int s=0; s<creatures.size(); ++s)
//{
// int befi=i;
// std::string rub;
// for(i; i<andame; ++i)
// {
// if(buf[i]==' ')
// break;
// }
// rub = buf.substr(befi, i-befi);
// ++i;
// befi=i;
// for(i; i<andame; ++i)
// {
// if(buf[i]=='\r')
// break;
// }
// std::string defName = buf.substr(befi, i-befi);
// if(defName != std::string("x"))
// creatures[s].battleAnimation = CGameInfo::mainObj->spriteh->giveDef(defName);
// else
// creatures[s].battleAnimation = NULL;
// i+=2;
//}
}
int CCreatureAnimation::getType() const
{
return type;
}
void CCreatureAnimation::setType(int type)
{
this->type = type;
curFrame = 0;
if(type!=-1)
{
if(SEntries[curFrame].group!=type) //rewind
{
int j=-1; //first frame in displayed group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group==type && j==-1)
{
j = g;
break;
}
}
if(curFrame!=-1)
curFrame = j;
}
}
else
{
if(curFrame>=frames)
curFrame = 0;
}
}
CCreatureAnimation::CCreatureAnimation(std::string name) : RLEntries(NULL), RWEntries(NULL)
{
//load main file
std::string data2 = CGI->spriteh->getTextFile(name);
if(data2.size()==0)
throw new std::string("no such def!");
FDef = new unsigned char[data2.size()];
for(int g=0; g<data2.size(); ++g)
{
FDef[g] = data2[g];
}
//init anim data
int i,j, totalInBlock;
char Buffer[13];
defName=name;
int andame = data2.size();
i = 0;
DEFType = readNormalNr(i,4); i+=4;
fullWidth = readNormalNr(i,4); i+=4;
fullHeight = readNormalNr(i,4); i+=4;
i=0xc;
totalBlocks = readNormalNr(i,4); i+=4;
i=0x10;
for (int it=0;it<256;it++)
{
palette[it].R = FDef[i++];
palette[it].G = FDef[i++];
palette[it].B = FDef[i++];
palette[it].F = 0;
}
i=0x310;
totalEntries=0;
for (int z=0; z<totalBlocks; z++)
{
int unknown1 = readNormalNr(i,4); i+=4;
totalInBlock = readNormalNr(i,4); i+=4;
for (j=SEntries.size(); j<totalEntries+totalInBlock; j++)
SEntries.push_back(SEntry());
int unknown2 = readNormalNr(i,4); i+=4;
int unknown3 = readNormalNr(i,4); i+=4;
for (j=0; j<totalInBlock; j++)
{
for (int k=0;k<13;k++) Buffer[k]=FDef[i+k];
i+=13;
SEntries[totalEntries+j].name=Buffer;
}
for (j=0; j<totalInBlock; j++)
{
SEntries[totalEntries+j].offset = readNormalNr(i,4);
int unknown4 = readNormalNr(i,4); i+=4;
}
//totalEntries+=totalInBlock;
for(int hh=0; hh<totalInBlock; ++hh)
{
SEntries[totalEntries].group = z;
++totalEntries;
}
}
for(j=0; j<SEntries.size(); ++j)
{
SEntries[j].name = SEntries[j].name.substr(0, SEntries[j].name.find('.')+4);
}
//pictures don't have to be readed here
//for(int i=0; i<SEntries.size(); ++i)
//{
// Cimage nimg;
// nimg.bitmap = getSprite(i);
// nimg.imName = SEntries[i].name;
// nimg.groupNumber = SEntries[i].group;
// ourImages.push_back(nimg);
//}
//delete FDef;
//FDef = NULL;
//init vars
curFrame = 0;
type = -1;
frames = totalEntries;
}
int CCreatureAnimation::readNormalNr (int pos, int bytCon, unsigned char * str, bool cyclic)
{
int ret=0;
int amp=1;
if (str)
{
for (int i=0; i<bytCon; i++)
{
ret+=str[pos+i]*amp;
amp*=256;
}
}
else
{
for (int i=0; i<bytCon; i++)
{
ret+=FDef[pos+i]*amp;
amp*=256;
}
}
if(cyclic && bytCon<4 && ret>=amp/2)
{
ret = ret-amp;
}
return ret;
}
int CCreatureAnimation::nextFrameMiddle(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
{
return nextFrame(dest,x-fullWidth/2,y-fullHeight/2,attacker,incrementFrame,yellowBorder,destRect);
}
int CCreatureAnimation::nextFrame(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
{
if(dest->format->BytesPerPixel<3)
return -1; //not enough depth
//increasing frame numer
int SIndex = -1;
if(incrementFrame)
{
SIndex = curFrame++;
if(type!=-1)
{
if(SEntries[curFrame].group!=type) //rewind
{
int j=-1; //first frame in displayed group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group==type && j==-1)
{
j = g;
break;
}
}
if(curFrame!=-1)
curFrame = j;
}
}
else
{
if(curFrame>=frames)
curFrame = 0;
}
}
else
{
SIndex = curFrame;
}
//frame number increased
long BaseOffset,
SpriteWidth, SpriteHeight, //sprite format
LeftMargin, RightMargin, TopMargin,BottomMargin,
i, add, FullHeight,FullWidth,
TotalRowLength, // length of read segment
RowAdd;
unsigned char SegmentType, SegmentLength;
i=BaseOffset=SEntries[SIndex].offset;
int prSize=readNormalNr(i,4,FDef);i+=4;
int defType2 = readNormalNr(i,4,FDef);i+=4;
FullWidth = readNormalNr(i,4,FDef);i+=4;
FullHeight = readNormalNr(i,4,FDef);i+=4;
SpriteWidth = readNormalNr(i,4,FDef);i+=4;
SpriteHeight = readNormalNr(i,4,FDef);i+=4;
LeftMargin = readNormalNr(i,4,FDef);i+=4;
TopMargin = readNormalNr(i,4,FDef);i+=4;
RightMargin = FullWidth - SpriteWidth - LeftMargin;
BottomMargin = FullHeight - SpriteHeight - TopMargin;
add = 4 - FullWidth%4;
int BaseOffsetor = BaseOffset = i;
int ftcp = 0;
if (defType2==1) //as it should be allways in creature animations
{
if (TopMargin>0)
{
for (int i=0;i<TopMargin;i++)
{
ftcp+=FullWidth+add;
}
}
RLEntries = new int[SpriteHeight];
for (int i=0;i<SpriteHeight;i++)
{
RLEntries[i]=readNormalNr(BaseOffset,4,FDef);BaseOffset+=4;
}
for (int i=0;i<SpriteHeight;i++)
{
BaseOffset=BaseOffsetor+RLEntries[i];
if (LeftMargin>0)
{
ftcp+=LeftMargin;
}
TotalRowLength=0;
do
{
SegmentType=FDef[BaseOffset++];
SegmentLength=FDef[BaseOffset++];
if (SegmentType==0xFF)
{
for (int k=0;k<=SegmentLength;k++)
{
int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
int yB = ftcp/(FullWidth+add) + y;
if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
{
if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
putPixel(dest, xB + yB*dest->w, palette[FDef[BaseOffset+k]], FDef[BaseOffset+k], yellowBorder);
}
ftcp++; //increment pos
if ((TotalRowLength+k+1)>=SpriteWidth)
break;
}
BaseOffset+=SegmentLength+1;////
TotalRowLength+=SegmentLength+1;
}
else
{
for (int k=0;k<SegmentLength+1;k++)
{
int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
int yB = ftcp/(FullWidth+add) + y;
if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
{
if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
putPixel(dest, xB + yB*dest->w, palette[SegmentType], SegmentType, yellowBorder);
}
ftcp++; //increment pos
}
TotalRowLength+=SegmentLength+1;
}
}while(TotalRowLength<SpriteWidth);
RowAdd=SpriteWidth-TotalRowLength;
if (RightMargin>0)
{
ftcp+=RightMargin;
}
if (add>0)
{
ftcp+=add+RowAdd;
}
}
delete [] RLEntries;
RLEntries = NULL;
if (BottomMargin>0)
{
ftcp += BottomMargin * (FullWidth+add);
}
}
//SDL_UpdateRect(dest, x, y, FullWidth+add, FullHeight);
return 0;
}
int CCreatureAnimation::framesInGroup(int group) const
{
int ret = 0; //number of frames in given group
for(int g=0; g<SEntries.size(); ++g)
{
if(SEntries[g].group == group)
++ret;
}
return ret;
}
CCreatureAnimation::~CCreatureAnimation()
{
delete [] FDef;
if (RWEntries)
delete [] RWEntries;
if (RLEntries)
delete [] RLEntries;
}
void CCreatureAnimation::putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const
{
if(palc!=0)
{
Uint8 * p = (Uint8*)dest->pixels + ftcp*3;
if(palc > 7) //normal color
{
p[0] = color.B;
p[1] = color.G;
p[2] = color.R;
}
else if(yellowBorder && (palc == 6 || palc == 7)) //dark yellow border
{
p[0] = 0;
p[1] = 0xff;
p[2] = 0xff;
}
else if(yellowBorder && (palc == 5)) //yellow border
{
p[0] = color.B;
p[1] = color.G;
p[2] = color.R;
}
else if(palc < 5) //shadow
{
Uint16 alpha;
switch(color.G)
{
case 0:
alpha = 128;
break;
case 50:
alpha = 50+32;
break;
case 100:
alpha = 100+64;
break;
case 125:
alpha = 125+64;
break;
case 128:
alpha = 128+64;
break;
case 150:
alpha = 150+64;
break;
default:
alpha = 255;
break;
}
//alpha counted
p[0] = (p[0] * alpha)>>8;
p[1] = (p[1] * alpha)>>8;
p[2] = (p[2] * alpha)>>8;
}
}
}

View File

@ -1,16 +1,14 @@
#ifndef CCREATUREHANDLER_H
#define CCREATUREHANDLER_H
#include "../CPlayerInterface.h"
#include "../global.h"
#include <string>
#include <vector>
#include <map>
#include "CDefHandler.h"
#include <set>
class CDefHandler;
struct SDL_Surface;
class CLodHandler;
class CCreature
class DLL_EXPORT CCreature
{
public:
std::string namePl, nameSing, nameRef; //name in singular and plural form; and reference name
@ -23,7 +21,7 @@ public:
std::string abilityText; //description of abilities
std::string abilityRefs; //references to abilities, in textformat
std::string animDefName;
int idNumber;
ui32 idNumber;
int faction; //-1 = neutral
///animation info
@ -37,32 +35,20 @@ public:
bool isDefinite; //if the creature type is wotn dependent, it should be true
int indefLevel; //only if indefinite
bool indefUpgraded; //onlu if inddefinite
//end
//CDefHandler * battleAnimation;
//TODO - zdolnoœci - na typie wyliczeniowym czy czymœ
static int getQuantityID(int quantity); //0 - a few, 1 - several, 2 - pack, 3 - lots, 4 - horde, 5 - throng, 6 - swarm, 7 - zounds, 8 - legion
//TODO - zdolnoœci (abilities) - na typie wyliczeniowym czy czymœ - albo lepiej secie czegoœ
bool isDoubleWide(); //returns true if unit is double wide on battlefield
bool isFlying(); //returns true if it is a flying unit
bool isShooting(); //returns true if unit can shoot
int maxAmount(const std::vector<int> &res) const; //how many creatures can be bought
si32 maxAmount(const std::vector<si32> &res) const; //how many creatures can be bought
static int getQuantityID(int quantity); //0 - a few, 1 - several, 2 - pack, 3 - lots, 4 - horde, 5 - throng, 6 - swarm, 7 - zounds, 8 - legion
};
class CCreatureSet //seven combined creatures
{
public:
std::map<int,std::pair<CCreature*,int> > slots;
//CCreature * slot1, * slot2, * slot3, * slot4, * slot5, * slot6, * slot7; //types of creatures on each slot
//unsigned int s1, s2, s3, s4, s5, s6, s7; //amounts of units in slots
bool formation; //false - wide, true - tight
};
class CCreatureHandler
class DLL_EXPORT CCreatureHandler
{
public:
std::map<int,SDL_Surface*> smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border
std::map<int,SDL_Surface*> bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border
std::map<int,SDL_Surface*> backgrounds; //castle ID -> 100x130 background creature image // -1 is for neutral
std::vector<CCreature> creatures; //creature ID -> creature info
std::map<int,std::vector<CCreature*> > levelCreatures; //level -> list of creatures
std::map<std::string,int> nameToID;
@ -71,48 +57,6 @@ public:
void loadCreatures();
void loadAnimationInfo();
void loadUnitAnimInfo(CCreature & unit, std::string & src, int & i);
void loadUnitAnimations();
CCreatureHandler();
};
class CCreatureAnimation : public CIntObject
{
private:
int totalEntries, DEFType, totalBlocks;
bool allowRepaint;
int length;
BMPPalette palette[256];
unsigned int * RWEntries;
int * RLEntries;
struct SEntry
{
std::string name;
int offset;
int group;
} ;
std::vector<SEntry> SEntries ;
char id[2];
std::string defName, curDir;
int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
void putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const;
////////////
unsigned char * FDef; //animation raw data
unsigned int curFrame; //number of currently displayed frame
unsigned int frames; //number of frames
int type; //type of animation being displayed (-1 - whole animation, >0 - specified part [default: -1])
public:
int fullWidth, fullHeight; //read-only, please!
CCreatureAnimation(std::string name); //c-tor
~CCreatureAnimation(); //d-tor
void setType(int type); //sets type of animation and cleares framecount
int getType() const; //returns type of animation
int nextFrame(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
int nextFrameMiddle(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
int framesInGroup(int group) const; //retirns number of fromes in given group
};
#endif //CCREATUREHANDLER_H

View File

@ -1,7 +1,9 @@
#include "../stdafx.h"
#include "SDL.h"
#include "CDefHandler.h"
#include <sstream>
#include "CLodHandler.h"
CLodHandler* CDefHandler::Spriteh = NULL;
long long pow(long long a, int b)
{
if (!b) return 1;
@ -10,24 +12,6 @@ long long pow(long long a, int b)
a*=c;
return a;
}
void BMPHeader::print(std::ostream & out)
{
CDefHandler::print(out,fullSize,4);
CDefHandler::print(out,_h1,4);
CDefHandler::print(out,_c1,4);
CDefHandler::print(out,_c2,4);
CDefHandler::print(out,x,4);
CDefHandler::print(out,y,4);
CDefHandler::print(out,_c3,2);
CDefHandler::print(out,_c4,2);
CDefHandler::print(out,_h2,4);
CDefHandler::print(out,_h3,4);
CDefHandler::print(out,dataSize1,4);
CDefHandler::print(out,dataSize2,4);
for (int i=0;i<8;i++)
out << _c5[i];
out.flush();
}
CDefHandler::CDefHandler()
{
//FDef = NULL;
@ -133,12 +117,11 @@ void CDefHandler::openDef(std::string name)
FDef = NULL;
}
void CDefHandler::openFromMemory(unsigned char *table, int size, std::string name)
void CDefHandler::openFromMemory(unsigned char *table, std::string name)
{
int i,j, totalInBlock;
char Buffer[13];
defName=name;
int andame = size;
i = 0;
DEFType = readNormalNr(i,4,table); i+=4;
fullWidth = readNormalNr(i,4,table); i+=4;
@ -576,3 +559,23 @@ CDefEssential * CDefHandler::essentialize()
notFreeImgs = true;
return ret;
}
CDefHandler * CDefHandler::giveDef(std::string defName, CLodHandler * spriteh)
{
if(!spriteh) spriteh=Spriteh;
unsigned char * data = spriteh->giveFile(defName);
CDefHandler * nh = new CDefHandler();
nh->openFromMemory(data, defName);
nh->alphaTransformed = false;
delete [] data;
return nh;
}
CDefEssential * CDefHandler::giveDefEss(std::string defName, CLodHandler * spriteh)
{
CDefEssential * ret;
CDefHandler * temp = giveDef(defName,spriteh);
ret = temp->essentialize();
delete temp;
return ret;
}

View File

@ -1,76 +1,63 @@
#ifndef CDEFHANDLER_H
#define CDEFHANDLER_H
#include "SDL.h"
#include "CSemiDefHandler.h"
class CDefEssential;
struct BMPHeader
{
int fullSize, _h1, _h2, _h3, _c1, _c2, _c3, _c4, x, y,
dataSize1, dataSize2; //DataSize=X*Y+2*Y
unsigned char _c5[8];
void print(std::ostream & out);
BMPHeader(){_h1=_h2=0;for(int i=0;i<8;i++)_c5[i]=0;};
};/*
struct DEFHeader
{
int type, width, height, groups;
unsigned char palette[767];
};
struct DEFGroup
{
int ID, items, unknown1, unknown2;
};*/
struct BMPPalette
{
unsigned char R,G,B,F;
};
class CDefHandler
{
private:
int totalEntries, DEFType, totalBlocks, fullWidth, fullHeight;
bool allowRepaint;
int length;
BMPPalette palette[256];
unsigned int * RWEntries;
int * RLEntries;
struct SEntry
{
std::string name;
int offset;
int group;
} ;
std::vector<SEntry> SEntries ;
char id[2];
public:
std::string defName, curDir;
std::vector<Cimage> ourImages;
bool alphaTransformed;
bool notFreeImgs;
CDefHandler();
~CDefHandler();
static void print (std::ostream & stream, int nr, int bytcon);
int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
static unsigned char *writeNormalNr (int nr, int bytCon);
SDL_Surface * getSprite (int SIndex, unsigned char * FDef); //zapisuje klatke o zadanym numerze do "testtt.bmp"
void openDef(std::string name);
void expand(unsigned char N,unsigned char & BL, unsigned char & BR);
void openFromMemory(unsigned char * table, int size, std::string name);
CDefEssential * essentialize();
};
class CDefEssential //DefHandler with images only
{
public:
std::vector<Cimage> ourImages;
~CDefEssential();
};
#endif // CDEFHANDLER_H
#ifndef CDEFHANDLER_H
#define CDEFHANDLER_H
#include "../client/CBitmapHandler.h"
struct SDL_Surface;
class CDefEssential;
class CLodHandler;
struct Cimage
{
int groupNumber;
std::string imName; //name without extension
SDL_Surface * bitmap;
};
class CDefHandler
{
private:
int totalEntries, DEFType, totalBlocks, fullWidth, fullHeight;
bool allowRepaint;
int length;
BMPPalette palette[256];
unsigned int * RWEntries;
int * RLEntries;
struct SEntry
{
std::string name;
int offset;
int group;
} ;
std::vector<SEntry> SEntries ;
char id[2];
public:
static CLodHandler * Spriteh;
std::string defName, curDir;
std::vector<Cimage> ourImages;
bool alphaTransformed;
bool notFreeImgs;
CDefHandler();
~CDefHandler();
static void print (std::ostream & stream, int nr, int bytcon);
int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
static unsigned char *writeNormalNr (int nr, int bytCon);
SDL_Surface * getSprite (int SIndex, unsigned char * FDef); //zapisuje klatke o zadanym numerze do "testtt.bmp"
void openDef(std::string name);
void expand(unsigned char N,unsigned char & BL, unsigned char & BR);
void openFromMemory(unsigned char * table, std::string name);
CDefEssential * essentialize();
static CDefHandler * giveDef(std::string defName, CLodHandler * spriteh=NULL);
static CDefEssential * giveDefEss(std::string defName, CLodHandler * spriteh=NULL);
};
class CDefEssential //DefHandler with images only
{
public:
std::vector<Cimage> ourImages;
~CDefEssential();
};
#endif // CDEFHANDLER_H

View File

@ -1,9 +1,11 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "CDefObjInfoHandler.h"
#include "../CGameInfo.h"
#include "CLodHandler.h"
#include <sstream>
#include "../lib/VCMI_Lib.h"
extern CLodHandler * bitmaph;
bool CGDefInfo::isVisitable()
{
for (int i=0; i<6; i++)
@ -17,15 +19,11 @@ CGDefInfo::CGDefInfo()
{
visitDir = (8|16|32|64|128); //4,5,6,7,8 - any not-from-up direction
}
bool DefObjInfo::operator==(const std::string & por) const
{
return this->defName == por;
}
void CDefObjInfoHandler::load()
{
VLC->dobjinfo = this;
nodrze<int> ideki;
std::istringstream inp(CGameInfo::mainObj->bitmaph->getTextFile("ZOBJCTS.TXT"));
std::istringstream inp(bitmaph->getTextFile("ZOBJCTS.TXT"));
int objNumber;
inp>>objNumber;
for(int hh=0; hh<objNumber; ++hh)
@ -62,8 +60,8 @@ void CDefObjInfoHandler::load()
}
}
for(int yy=0; yy<2; ++yy)
inp>>dump;
for(int yy=0; yy<2; ++yy) //first - on which types of terrain object can be placed;
inp>>dump; //second -in which terrains' menus object in the editor will be available (?)
inp>>nobj->id;
inp>>nobj->subid;
inp>>nobj->type;
@ -72,14 +70,4 @@ void CDefObjInfoHandler::load()
if(nobj->id==98)
castles[nobj->subid]=nobj;
}
}
bool DefObjInfo::isVisitable() const
{
for(int g=0; g<6; ++g)
{
if(visitMap[g]!=0)
return true;
}
return false;
}
}

View File

@ -2,8 +2,10 @@
#define COBJINFOECTHANDLER_H
#include <vector>
#include <map>
#include "../global.h"
class CDefHandler;
class CGDefInfo
class CLodHandler;
class DLL_EXPORT CGDefInfo
{
public:
std::string name;
@ -14,7 +16,8 @@ public:
int id, subid; //of object described by this defInfo
int terrainAllowed, //on which terrain it is possible to place object
terrainMenu; //in which menus in map editor object will be showed
int type; //(0- ground, 1- towns, 2-creatures, 3- heroes, 4-artifacts, 5- resources)
int width, height; //tiles
int type; //(0- ground, 1- towns, 2-creatures, 3- heroes, 4-artifacts, 5- resources)
CDefHandler * handler;
int printPriority;
bool isVisitable();
@ -27,19 +30,7 @@ public:
}
CGDefInfo();
};
struct DefObjInfo
{
std::string defName;
int priority;
int type, subtype;
int objType;
unsigned char visitMap[6];
unsigned char blockMap[6];
bool operator==(const std::string & por) const;
bool isVisitable() const;
};
class CDefObjInfoHandler
class DLL_EXPORT CDefObjInfoHandler
{
public:
std::map<int,std::map<int,CGDefInfo*> > gobjs;

View File

@ -6,7 +6,7 @@
void CGeneralTextHandler::load()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("GENRLTXT.TXT");
std::string buf = CGI->bitmaph->getTextFile("GENRLTXT.TXT");
int andame = buf.size();
int i=0; //buf iterator
for(i; i<andame; ++i)
@ -29,7 +29,7 @@ void CGeneralTextHandler::load()
while(itr<strs.length()-1)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
loadToIt(tmp, strs, itr, 3);
arraytxt.push_back(tmp);
}
@ -38,7 +38,7 @@ void CGeneralTextHandler::load()
for(int hh=0; hh<4; ++hh)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strin, itr, 3);
loadToIt(tmp, strin, itr, 3);
primarySkillNames.push_back(tmp);
}
@ -47,7 +47,7 @@ void CGeneralTextHandler::load()
for(int hh=0; hh<45; ++hh)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strin2, itr, 3);
loadToIt(tmp, strin2, itr, 3);
jktexts.push_back(tmp);
}
@ -56,116 +56,7 @@ void CGeneralTextHandler::load()
for(int hh=0; hh<33; ++hh)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strin3, itr, 3);
loadToIt(tmp, strin3, itr, 3);
heroscrn.push_back(tmp);
}
}
void CGeneralTextHandler::loadToIt(std::string &dest, std::string &src, int &iter, int mode)
{
switch(mode)
{
case 0:
{
int hmcr = 0;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\t')
++hmcr;
if(hmcr==1)
break;
}
++iter;
int befi=iter;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\t')
break;
}
dest = src.substr(befi, iter-befi);
++iter;
hmcr = 0;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\r')
++hmcr;
if(hmcr==1)
break;
}
iter+=2;
break;
}
case 1:
{
int hmcr = 0;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\t')
++hmcr;
if(hmcr==1)
break;
}
++iter;
int befi=iter;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\r')
break;
}
dest = src.substr(befi, iter-befi);
iter+=2;
break;
}
case 2:
{
int befi=iter;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\t')
break;
}
dest = src.substr(befi, iter-befi);
++iter;
int hmcr = 0;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\r')
++hmcr;
if(hmcr==1)
break;
}
iter+=2;
break;
}
case 3:
{
int befi=iter;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\r')
break;
}
dest = src.substr(befi, iter-befi);
iter+=2;
break;
}
case 4:
{
int befi=iter;
for(iter; iter<src.size(); ++iter)
{
if(src[iter]=='\t')
break;
}
dest = src.substr(befi, iter-befi);
iter++;
break;
}
}
}
}

View File

@ -1,9 +1,9 @@
#ifndef CGENERALTEXTHANDLER_H
#define CGENERALTEXTHANDLER_H
#include "../global.h"
#include <string>
#include <vector>
DLL_EXPORT void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
class CGeneralTextHandler //Handles general texts
{
public:
@ -13,21 +13,6 @@ public:
std::vector<std::string> primarySkillNames;
std::vector<std::string> jktexts;
std::vector<std::string> heroscrn;
/*std::string cantAddManager, experienceLimitScenarioReached, heroExperienceInfo, perDay, or, somethingVanquished, lastTownLostInfo, heroesAbandonedYou, heroesAbandonedHim;
std::string couldNotSaveGame, errorOpeningFile, newgameUppercase, sureToDismissArmy, playersTurn, errorReceivingDataKeepTrying, somethingTheSomething, recruit, noRoomInGarrision, numberOFAdventuringHeroes, heroWithoutCreatures;
std::string videoQuality, itemCantBeTraded, sureDismissHero, selectSpellTarget, invalidTeleportDestination, teleportHere, castSomething, castSomethingOnSomething, sureRetreat, notEnoughGold, capturedEnemyArtifact, none;
std::string surrenderProposal, highMoraleNextAttack, lowMoraleFreeze, makeRoomInArmyForSomething, attackSomethingSomethingDamage, shootSomethingOneShootLeftSomethingDamage;
std::string campaignDescription, somethingIsActive, sessionName, userName, creature, creatures, badLuckOnSomething, goodLuckOnSomething, treasure, somethingSomethingsUnderAttack, town, hero, townScreen, cannotBuildBoat, requires, systemUppercase;
std::string worldMapHelp, sureEndTurnHeroMayMove, diggingArtifactWholeDay, noRoomForArtifact, heroUncoveredThe, diggingNothing, tryLookingOnLand, unchartedTerritory;
std::string month, week, day, enemyViewTip, pingInfo, sureToRestart, sureToStartNewGame, sureQuit, dimensionDoorFiled, chooseBonus, ping, pingSomething, pingEveryone, score, autosaveUppercase;
std::string startingHeroB, heroSpecialityB, associatedCreaturesB, townAlignmentB, errorSendingDataKeepTrying, tooFewPalyersForMultiGame, artifactBonusB, goldBonusB, resourceBonusB, randomBonusB;
std::string fiveHundredToOneThousand, armageddonDamages, woodOreBonus, randomlyChoosenArtifact, disruptingRayReducesDefence, goldStartingBonus, woodOreStartingBonus, randomStartingBonus;
std::string youEliminatedFormGame, scoreToHallOfFame, trySearchingOnClearGround, sendingData, receivingData, chaosMp2, randomHeroB, randomStartingHeroInfo, randomTownB, randomStartingTownInfo, somethingSurrendersInfo;
std::string heroesCDNotFound, autosaving, playerexitUppercase, statusWindowTip, border, somethingAbsorbsMana, somethingsAbsorbMana, unableChangeHeroesDirectory, unableFindHeoresDataFiles, victoryAchievementText;
std::string somethingsRiseFromDeath, somethingRisesFormDeath, somethingDiesUnderGaze, somethingsDieUnderGaze, somethingTakesDefensiveStance, somethingsTakeDefensiveStance, somethingExp, nearestTownOccupied, noAvailableTown, heroTooTiredSpell, townGateCannotBeUsed, youHaveNoHeroes, heroHasCastSpell;
std::string doYouWishToSaveSomethingsArmy, problemsWithInputDevices, problemsWithSound, problemsWithMouse, problemsWithWindows, abandonedShipyard, spellFailed, somethingPauses, somethingsPause, somethingLevelSomething, somethingStudiedMagic, learnsSpeced, andSpaced, fromSomethingSpaced;*/
static void loadToIt(std::string & dest, std::string & src, int & iter, int mode = 0); //mode 0 - dump to tab, dest to tab, dump to eol //mode 1 - dump to tab, src to eol //mode 2 - copy to tab, dump to eol //mode 3 - copy to eol //mode 4 - copy to tab
void load();
};

View File

@ -1,81 +1,60 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "CHeroHandler.h"
#include "../CGameInfo.h"
#include <sstream>
#include "../CGameInfo.h"
#include "CGeneralTextHandler.h"
#include "CLodHandler.h"
#include "CAbilityHandler.h"
#include "../SDL_Extensions.h"
#include <cmath>
#include <iomanip>
#include "../lib/VCMI_Lib.h"
extern CLodHandler * bitmaph;
void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
CHeroHandler::~CHeroHandler()
CHeroClass::CHeroClass()
{
for (int j=0;j<heroes.size();j++)
skillLimit = 8;
}
CHeroClass::~CHeroClass()
{
}
int CHeroClass::chooseSecSkill(std::set<int> possibles) //picks secondary skill out from given possibilities
{
if(possibles.size()==1)
return *possibles.begin();
int totalProb = 0;
for(std::set<int>::iterator i=possibles.begin(); i!=possibles.end(); i++)
{
delete heroes[j];
totalProb += proSec[*i];
}
for(std::map<int, SDL_Surface*>::iterator it = smallPortraits.begin(); it!=smallPortraits.end(); ++it)
int ran = rand()%totalProb;
for(std::set<int>::iterator i=possibles.begin(); i!=possibles.end(); i++)
{
delete it->second;
}
for(std::map<int, SDL_Surface*>::iterator it = largePortraits.begin(); it!=largePortraits.end(); ++it)
{
delete it->second;
ran -= proSec[*i];
if(ran<0)
return *i;
}
}
CHeroHandler::~CHeroHandler()
{}
void CHeroHandler::loadPortraits()
{
std::ifstream of("config/portrety.txt");
int numberOfPortraits;
of>>numberOfPortraits;
for (int j=0; j<numberOfPortraits; j++)
{
int ID;
of>>ID;
std::string path;
of>>path;
smallPortraits[ID] = CGI->bitmaph->loadBitmap(path);
if (!smallPortraits[ID])
std::cout<<"Can't read small portrait for "<<ID<<" ("<<path<<")\n";
for(int ff=0; ff<path.size(); ++ff) //size letter is usually third one, but there are exceptions an it should fix the problem
{
if(path[ff]=='S')
{
path[ff]='L';
break;
}
}
largePortraits[ID] = CGI->bitmaph->loadBitmap(path);
if (!largePortraits[ID])
std::cout<<"Can't read large portrait for "<<ID<<" ("<<path<<")\n";
SDL_SetColorKey(largePortraits[ID],SDL_SRCCOLORKEY,SDL_MapRGB(largePortraits[ID]->format,0,255,255));
}
of.close();
pskillsb = CGI->spriteh->giveDef("PSKILL.DEF");
resources = CGI->spriteh->giveDef("RESOUR82.DEF");
un44 = CGI->spriteh->giveDef("UN44.DEF");
std::string strs = CGI->bitmaph->getTextFile("PRISKILL.TXT");
std::string strs = bitmaph->getTextFile("PRISKILL.TXT");
int itr=0;
for (int i=0; i<PRIMARY_SKILLS; i++)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
loadToIt(tmp, strs, itr, 3);
pskillsn.push_back(tmp);
}
}
void CHeroHandler::loadHeroes()
{
VLC->heroh = this;
int ID=0;
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HOTRAITS.TXT");
std::string buf = bitmaph->getTextFile("HOTRAITS.TXT");
int it=0;
std::string dump;
for(int i=0; i<2; ++i)
{
CGeneralTextHandler::loadToIt(dump,buf,it,3);
loadToIt(dump,buf,it,3);
}
int numberOfCurrentClassHeroes = 0;
@ -115,15 +94,15 @@ void CHeroHandler::loadHeroes()
}
std::string pom ;
CGeneralTextHandler::loadToIt(nher->name,buf,it,4);
loadToIt(nher->name,buf,it,4);
for(int x=0;x<3;x++)
{
CGeneralTextHandler::loadToIt(pom,buf,it,4);
loadToIt(pom,buf,it,4);
nher->lowStack[x] = atoi(pom.c_str());
CGeneralTextHandler::loadToIt(pom,buf,it,4);
loadToIt(pom,buf,it,4);
nher->highStack[x] = atoi(pom.c_str());
CGeneralTextHandler::loadToIt(nher->refTypeStack[x],buf,it,(x==2) ? (3) : (4));
loadToIt(nher->refTypeStack[x],buf,it,(x==2) ? (3) : (4));
int hlp = nher->refTypeStack[x].find_first_of(' ',0);
if(hlp>=0)
nher->refTypeStack[x].replace(hlp,1,"");
@ -156,34 +135,34 @@ void CHeroHandler::loadHeroes()
}
void CHeroHandler::loadSpecialAbilities()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HEROSPEC.TXT");
std::string buf = bitmaph->getTextFile("HEROSPEC.TXT");
int it=0;
std::string dump;
for(int i=0; i<2; ++i)
{
CGeneralTextHandler::loadToIt(dump,buf,it,3);
loadToIt(dump,buf,it,3);
}
for (int i=0;i<heroes.size();i++)
{
CGeneralTextHandler::loadToIt(heroes[i]->bonusName,buf,it,4);
CGeneralTextHandler::loadToIt(heroes[i]->shortBonus,buf,it,4);
CGeneralTextHandler::loadToIt(heroes[i]->longBonus,buf,it,3);
loadToIt(heroes[i]->bonusName,buf,it,4);
loadToIt(heroes[i]->shortBonus,buf,it,4);
loadToIt(heroes[i]->longBonus,buf,it,3);
}
}
void CHeroHandler::loadBiographies()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HEROBIOS.TXT");
std::string buf = bitmaph->getTextFile("HEROBIOS.TXT");
int it=0;
for (int i=0;i<heroes.size();i++)
{
CGeneralTextHandler::loadToIt(heroes[i]->biography,buf,it,3);
loadToIt(heroes[i]->biography,buf,it,3);
}
}
void CHeroHandler::loadHeroClasses()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HCTRAITS.TXT");
std::string buf = bitmaph->getTextFile("HCTRAITS.TXT");
int andame = buf.size();
for(int y=0; y<andame; ++y)
if(buf[y]==',')
@ -281,7 +260,7 @@ void CHeroHandler::loadHeroClasses()
//CHero kkk = heroes[0];
for(int dd=0; dd<CGameInfo::mainObj->abilh->abilities.size(); ++dd)
for(int dd=0; dd<SKILL_QUANTITY; ++dd)
{
befi=i;
for(i; i<andame; ++i)
@ -306,89 +285,6 @@ void CHeroHandler::loadHeroClasses()
++i;
}
++i;
std::stringstream nm;
nm<<"AH";
nm<<std::setw(2);
nm<<std::setfill('0');
nm<<heroClasses.size();
nm<<"_.DEF";
hc->moveAnim = CGI->spriteh->giveDef(nm.str());
for(int o=0; o<hc->moveAnim->ourImages.size(); ++o)
{
if(hc->moveAnim->ourImages[o].groupNumber==6)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
nci.groupNumber = 10;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
}
o+=8;
}
if(hc->moveAnim->ourImages[o].groupNumber==7)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
nci.groupNumber = 11;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
}
o+=8;
}
if(hc->moveAnim->ourImages[o].groupNumber==8)
{
for(int e=0; e<8; ++e)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
nci.groupNumber = 12;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
}
o+=8;
}
}
for(int o=0; o<hc->moveAnim->ourImages.size(); ++o)
{
if(hc->moveAnim->ourImages[o].groupNumber==1)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
nci.groupNumber = 13;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
//o+=1;
}
if(hc->moveAnim->ourImages[o].groupNumber==2)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
nci.groupNumber = 14;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
//o+=1;
}
if(hc->moveAnim->ourImages[o].groupNumber==3)
{
Cimage nci;
nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
nci.groupNumber = 15;
nci.imName = std::string();
hc->moveAnim->ourImages.push_back(nci);
//o+=1;
}
}
for(int ff=0; ff<hc->moveAnim->ourImages.size(); ++ff)
{
CSDL_Ext::alphaTransform(hc->moveAnim->ourImages[ff].bitmap);
}
hc->moveAnim->alphaTransformed = true;
heroClasses.push_back(hc);
}
}

View File

@ -1,19 +1,14 @@
#ifndef CHEROHANDLER_H
#define CHEROHANDLER_H
#include "../global.h"
#include <string>
#include <vector>
#include "CCreatureHandler.h"
#include "SDL.h"
#include "../int3.h"
#include "CAmbarCendamo.h"
#include "../CGameInterface.h"
#include <set>
class CHeroClass;
class CDefHandler;
class CGameInfo;
class CGHeroInstance;
class CHero
class DLL_EXPORT CHero
{
public:
std::string name;
@ -28,9 +23,10 @@ public:
//bool operator<(CHero& drugi){if (ID < drugi.ID) return true; else return false;}
};
class CHeroClass
class DLL_EXPORT CHeroClass
{
public:
ui32 skillLimit; //how many secondary skills can hero learn
std::string name;
float aggression;
int initialAttack, initialDefence, initialPower, initialKnowledge;
@ -39,18 +35,16 @@ public:
int selectionProbability[9]; //probability of selection in towns
std::vector<int> terrCosts; //default costs of going through terrains: dirt, sand, grass, snow, swamp, rough, subterrain, lava, water, rock; -1 means terrain is imapassable
CDefHandler * moveAnim; //added group 10: up - left, 11 - left and 12 - left down // 13 - up-left standing; 14 - left standing; 15 - left down standing
int chooseSecSkill(std::set<int> possibles); //picks secondary skill out from given possibilities
CHeroClass();
~CHeroClass();
};
class CHeroHandler
class DLL_EXPORT CHeroHandler
{
public:
std::vector<CGHeroInstance *> heroInstances;
std::vector<CHero*> heroes; //by³o nodrze
std::vector<CHeroClass *> heroClasses;
std::vector<CDefHandler *> flags1, flags2, flags3, flags4; //flags blitted on heroes when ,
std::map<int, SDL_Surface *> smallPortraits, largePortraits; //there are more portraits than playable heroes! ; small - 48x32 px ; large - 58x64 px
CDefHandler * pskillsb, *resources; //82x93
CDefHandler * un44; //many things
std::vector<std::string> pskillsn;
std::vector<int> expPerLevel; //expPerLEvel[i] is amount of exp needed to reach level i; if it is not in this vector, multiplicate last value by 1,2 to get next value
unsigned int level(unsigned int experience);
@ -59,17 +53,9 @@ public:
void loadSpecialAbilities();
void loadBiographies();
void loadHeroClasses();
void loadPortraits(); //loads also imgs and names of primary skills
void loadPortraits(); //loads names of primary skills
void initHeroClasses();
~CHeroHandler();
void initTerrainCosts();
friend void CAmbarCendamo::deh3m();
friend void initGameState(CGameInfo * cgi);
//friend class CConsoleHandler;
//friend void CPlayerInterface::heroMoved(const HeroMoveDetails & details); //TODO: wywalic, wstretne!!!
};
#endif //CHEROHANDLER_H

View File

@ -1,14 +1,16 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "zlib.h"
#include "CLodHandler.h"
#include "../SDL_Extensions.h"
#include "CDefHandler.h"
#include <sstream>
#include <algorithm>
#include <cctype>
#include <cstring>
#include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations
#include "SDL_image.h"
int readNormalNr (int pos, int bytCon, unsigned char * str)
#include "boost/filesystem/operations.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
DLL_EXPORT int readNormalNr (int pos, int bytCon, unsigned char * str)
{
int ret=0;
int amp=1;
@ -23,505 +25,50 @@ int readNormalNr (int pos, int bytCon, unsigned char * str)
else return -1;
return ret;
}
void CPCXConv::openPCX(char * PCX, int len)
{
pcxs=len;
pcx=(unsigned char*)PCX;
/*pcx = new unsigned char[len];
for (int i=0;i<len;i++)
pcx[i]=PCX[i];*/
}
void CPCXConv::fromFile(std::string path)
{
std::ifstream * is = new std::ifstream();
is -> open(path.c_str(),std::ios::binary);
is->seekg(0,std::ios::end); // to the end
pcxs = is->tellg(); // read length
is->seekg(0,std::ios::beg); // wracamy na poczatek
pcx = new unsigned char[pcxs]; // allocate memory
is->read((char*)pcx, pcxs); // read map file to buffer
is->close();
delete is;
}
void CPCXConv::saveBMP(std::string path)
{
std::ofstream os;
os.open(path.c_str(), std::ios::binary);
os.write((char*)bmp,bmps);
os.close();
}
void CPCXConv::convert()
{
BMPHeader bh;
BMPPalette pal[256];
Epcxformat format;
int fSize,i,y;
bool check1, check2;
unsigned char add;
int it=0;
std::stringstream out;
fSize = readNormalNr(it,4,pcx);it+=4;
bh.x = readNormalNr(it,4,pcx);it+=4;
bh.y = readNormalNr(it,4,pcx);it+=4;
if (fSize==bh.x*bh.y*3)
check1=true;
else
check1=false;
if (fSize==bh.x*bh.y)
check2=true;
else
check2=false;
if (check1)
format=PCX24B;
else if (check2)
format=PCX8B;
else
return;
add = 4 - bh.x%4;
if (add==4)
add=0;
bh._h3=bh.x*bh.y;
if (format==PCX8B)
{
bh._c1=0x436;
bh._c2=0x28;
bh._c3=1;
bh._c4=8;
//bh.dataSize2=bh.dataSize1=maxx*maxy;
bh.dataSize1=bh.x;
bh.dataSize2=bh.y;
bh.fullSize = bh.dataSize1+436;
}
else
{
bh._c1=0x36;
bh._c2=0x28;
bh._c3=1;
bh._c4=0x18;
//bh.dataSize2=bh.dataSize1=0xB12;
bh.dataSize1=bh.x;
bh.dataSize2=bh.y;
bh.fullSize=(bh.x+add)*bh.y*3+36+18;
bh._h3*=3;
}
if (format==PCX8B)
{
it = pcxs-256*3;
for (int i=0;i<256;i++)
{
pal[i].R=pcx[it++];
pal[i].G=pcx[it++];
pal[i].B=pcx[it++];
pal[i].F='\0';
}
}
out<<"BM";
bh.print(out);
if (format==PCX8B)
{
for (int i=0;i<256;i++)
{
out<<pal[i].B;
out<<pal[i].G;
out<<pal[i].R;
out<<pal[i].F;
}
for (y=bh.y;y>0;y--)
{
it=0xC+(y-1)*bh.x;
for (int j=0;j<bh.x;j++)
out<<pcx[it+j];
if (add>0)
{
for (int j=0;j<add;j++)
out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
}
}
}
else
{
for (y=bh.y; y>0; y--)
{
it=0xC+(y-1)*bh.x*3;
for (int j=0;j<bh.x*3;j++)
out<<pcx[it+j];
if (add>0)
{
for (int j=0;j<add*3;j++)
out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
}
}
}
std::string temp = out.str();
bmp = new unsigned char[temp.length()];
bmps=temp.length();
for (int a=0;a<temp.length();a++)
{
bmp[a]=temp[a];
}
}
SDL_Surface * CPCXConv::getSurface()
{
SDL_Surface * ret;
BMPHeader bh;
Epcxformat format;
int fSize,i,y;
bool check1, check2;
unsigned char add;
int it=0;
fSize = readNormalNr(it,4,pcx);it+=4;
bh.x = readNormalNr(it,4,pcx);it+=4;
bh.y = readNormalNr(it,4,pcx);it+=4;
if (fSize==bh.x*bh.y*3)
check1=true;
else
check1=false;
if (fSize==bh.x*bh.y)
check2=true;
else
check2=false;
if (check1)
format=PCX24B;
else if (check2)
format=PCX8B;
else
return NULL;
add = 4 - bh.x%4;
if (add==4)
add=0;
if (format==PCX8B)
{
ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 8, 0, 0, 0, 0);
}
else
{
#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
int bmask = 0xff0000;
int gmask = 0x00ff00;
int rmask = 0x0000ff;
#else
int bmask = 0x0000ff;
int gmask = 0x00ff00;
int rmask = 0xff0000;
#endif
ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 24, rmask, gmask, bmask, 0);
}
if (format==PCX8B)
{
it = pcxs-256*3;
for (int i=0;i<256;i++)
{
SDL_Color tp;
#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
tp.b = pcx[it++];
tp.g = pcx[it++];
tp.r = pcx[it++];
#else
tp.r = pcx[it++];
tp.g = pcx[it++];
tp.b = pcx[it++];
#endif
tp.unused = 0;
*(ret->format->palette->colors+i) = tp;
}
for (y=bh.y;y>0;y--)
{
it=0xC+(y-1)*bh.x;
for (int j=0;j<bh.x;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j];
}
if (add>0)
{
for (int j=0;j<add;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * (j+bh.x)) = 0;
}
}
}
}
else
{
for (y=bh.y; y>0; y--)
{
it=0xC+(y-1)*bh.x*3;
for (int j=0;j<bh.x*3;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + j) = pcx[it+j];
}
if (add>0)
{
for (int j=0;j<add*3;j++)
{
*((char*)ret->pixels + ret->pitch * (y-1) + (j+bh.x*3)) = 0;
}
}
}
}
return ret;
}
SDL_Surface * CLodHandler::loadBitmap(std::string fname)
{
if(!fname.size())
return NULL;
unsigned char * pcx;
std::transform(fname.begin(),fname.end(),fname.begin(),toupper);
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
Entry *e = entries.znajdz(fname);
if(!e)
{
std::cout<<"File "<<fname<<" not found"<<std::endl;
return NULL;
}
if(e->offset<0)
{
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".BMP");
fname = "Data/"+fname;
FILE * f = fopen(fname.c_str(),"r");
if(f)
{
fclose(f);
return SDL_LoadBMP(fname.c_str());
}
else //file .bmp not present, check .pcx
{
char sign[3];
fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
f = fopen(fname.c_str(),"r");
if(!f)
return NULL;
fread(sign,1,3,f);
if(sign[0]=='B' && sign[1]=='M') //BMP named as PCX - people (eg. Kulex) sometimes use such files
{
fclose(f);
return SDL_LoadBMP(fname.c_str());
}
else //PCX - but we don't know which
{
if((sign[0]==10) && (sign[1]<6) && (sign[2]==1)) //ZSoft PCX
{
fclose(f);
return IMG_Load(fname.c_str());
}
else //H3-style PCX
{
CPCXConv cp;
pcx = new unsigned char[e->realSize];
memcpy(pcx,sign,3);
int res = fread((char*)pcx+3, 1, e->realSize-3, f);
fclose(f);
cp.openPCX((char*)pcx,e->realSize);
return cp.getSurface();
}
}
}
}
fseek(FLOD, e->offset, 0);
if (e->size==0) //file is not compressed
{
pcx = new unsigned char[e->realSize];
fread((char*)pcx, 1, e->realSize, FLOD);
}
else
{
unsigned char * pcd = new unsigned char[e->size];
fread((char*)pcd, 1, e->size, FLOD);
int res=infs2(pcd,e->size,e->realSize,pcx);
if(res!=0)
{
std::cout<<"an error "<<res<<" occured while extracting file "<<fname<<std::endl;
}
delete [] pcd;
}
CPCXConv cp;
cp.openPCX((char*)pcx,e->realSize);
return cp.getSurface();
}
int CLodHandler::decompress (unsigned char * source, int size, int realSize, std::string & dest)
{
std::ofstream lb;
lb.open(DATADIR "lodbuf" PATHSEPARATOR "buf.gz", std::ios::out|std::ios::binary);
for(int i=0; i<size; ++i)
{
lb<<source[i];
}
lb.close();
FILE * inputf = fopen(DATADIR "lodbuf" PATHSEPARATOR "buf.gz", "rb+");
FILE * outputf = fopen(dest.c_str(), "wb+");
int ret = infm(inputf, outputf);
fclose(inputf);
fclose(outputf);
return ret;
}
int CLodHandler::infm(FILE *source, FILE *dest, int wBits)
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[NLoadHandlerHelp::fCHUNK];
unsigned char out[NLoadHandlerHelp::fCHUNK];
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, wBits);
if (ret != Z_OK)
return ret;
/* decompress until deflate stream ends or end of file */
do
{
strm.avail_in = fread(in, 1, NLoadHandlerHelp::fCHUNK, source);
if (ferror(source)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
/* run inflate() on input until output buffer not full */
do
{
strm.avail_out = NLoadHandlerHelp::fCHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
//assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret)
{
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = NLoadHandlerHelp::fCHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest))
{
(void)inflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/* clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
CDefHandler * CLodHandler::giveDef(std::string defName)
unsigned char * CLodHandler::giveFile(std::string defName, int * length)
{
std::transform(defName.begin(), defName.end(), defName.begin(), (int(*)(int))toupper);
Entry * ourEntry = entries.znajdz(Entry(defName));
if(!ourEntry) //nothing's been found
{
std::cerr<<"No def: "<<defName;
throw(std::string("Bad def name!"));
std::cerr<<"Cannot find file: "<<defName;
return NULL;
}
CDefHandler * ret;
if(length) *length = ourEntry->realSize;
mutex->lock();
fseek(FLOD, ourEntry->offset, 0);
unsigned char * outp;
if (ourEntry->offset<0) //file in the sprites/ folder
if (ourEntry->offset<0) //file is in the sprites/ folder; no compression
{
char * outp = new char[ourEntry->realSize];
char name[120];for(int i=0;i<120;i++) name[i]='\0';
unsigned char * outp = new unsigned char[ourEntry->realSize];
char name[30];memset(name,0,30);
strcat(name,"Sprites/");
strcat(name,(char*)ourEntry->name);
FILE * f = fopen(name,"rb");
int result = fread(outp,1,ourEntry->realSize,f);
mutex->unlock();
if(result<0) {std::cout<<"Error in file reading: "<<name<<std::endl;delete[] outp; return NULL;}
CDefHandler * nh = new CDefHandler();
nh->openFromMemory((unsigned char*)outp, ourEntry->realSize, std::string((char*)ourEntry->name));
nh->alphaTransformed = false;
ret = nh;
delete[] outp;
else
return outp;
}
else if (ourEntry->size==0) //file is not compressed
{
outp = new unsigned char[ourEntry->realSize];
fread((char*)outp, 1, ourEntry->realSize, FLOD);
CDefHandler * nh = new CDefHandler();
nh->openFromMemory(outp, ourEntry->realSize, std::string((char*)ourEntry->name));
nh->alphaTransformed = false;
ret = nh;
delete[] outp;
mutex->unlock();
return outp;
}
else //we will decompress file
{
outp = new unsigned char[ourEntry->size];
fread((char*)outp, 1, ourEntry->size, FLOD);
fseek(FLOD, 0, 0);
mutex->unlock();
unsigned char * decomp = NULL;
int decRes = infs2(outp, ourEntry->size, ourEntry->realSize, decomp);
CDefHandler * nh = new CDefHandler();
nh->openFromMemory(decomp, ourEntry->realSize, std::string((char*)ourEntry->name));
nh->alphaTransformed = false;
ret = nh;
delete[] decomp;
delete[] outp;
return decomp;
}
return ret;
}
CDefEssential * CLodHandler::giveDefEss(std::string defName)
{
CDefEssential * ret;
CDefHandler * temp = giveDef(defName);
ret = temp->essentialize();
delete temp;
return ret;
}
std::vector<CDefHandler *> CLodHandler::extractManyFiles(std::vector<std::string> defNamesIn)
{
std::vector<CDefHandler *> ret(defNamesIn.size());
for(int hh=0; hh<defNamesIn.size(); ++hh)
{
//std::transform(defNamesIn[hh].begin(), defNamesIn[hh].end(), defNamesIn[hh].begin(), (int(*)(int))toupper);
Entry * e = entries.znajdz(defNamesIn[hh]);
if(!e)
continue;
fseek(FLOD, e->offset, 0);
unsigned char * outp;
if (e->size==0) //file is not compressed
{
outp = new unsigned char[e->realSize];
fread((char*)outp, 1, e->realSize, FLOD);
CDefHandler * nh = new CDefHandler;
nh->openFromMemory(outp, e->realSize, std::string((char*)e->name));
nh->alphaTransformed = false;
ret[hh] = nh;
}
else //we will decompressing file
{
outp = new unsigned char[e->size];
fread((char*)outp, 1, e->size, FLOD);
fseek(FLOD, 0, 0);
unsigned char * decomp = NULL;
int decRes = infs2(outp, e->size, e->realSize, decomp);
CDefHandler * nh = new CDefHandler;
nh->openFromMemory(decomp, e->realSize, std::string((char*)e->name));
nh->alphaTransformed = false;
delete [] decomp;
ret[hh] = nh;
}
delete[] outp;
}
return ret;
return NULL;
}
int CLodHandler::infs(unsigned char * in, int size, int realSize, std::ofstream & out, int wBits)
{
@ -599,7 +146,7 @@ int CLodHandler::infs(unsigned char * in, int size, int realSize, std::ofstream
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
DLL_EXPORT int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
{
int ret;
unsigned have;
@ -629,12 +176,6 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
}
++chunkNumber;
strm.avail_in = readBytes;
//strm.avail_in = fread(inx, 1, NLoadHandlerHelp::fCHUNK, source);
/*if (in.bad())
{
(void)inflateEnd(&strm);
return Z_ERRNO;
}*/
if (strm.avail_in == 0)
break;
strm.next_in = inx;
@ -656,22 +197,11 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
return ret;
}
have = NLoadHandlerHelp::fCHUNK - strm.avail_out;
/*if (fwrite(out, 1, have, dest) != have || ferror(dest))
{
(void)inflateEnd(&strm);
return Z_ERRNO;
}*/
//out.write((char*)outx, have);
for(int oo=0; oo<have; ++oo)
{
out[latPosOut] = outx[oo];
++latPosOut;
}
/*if(out.bad())
{
(void)inflateEnd(&strm);
return Z_ERRNO;
}*/
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
@ -684,15 +214,11 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
void CLodHandler::extract(std::string FName)
{
std::ofstream FOut;
int i;
//std::cout<<" done\n";
for (int i=0;i<totalFiles;i++)
{
fseek(FLOD, entries[i].offset, 0);
std::string bufff = (DATADIR + FName.substr(0, FName.size()-4) + PATHSEPARATOR + (char*)entries[i].name);
std::string bufff = (DATA_DIR + FName.substr(0, FName.size()-4) + PATHSEPARATOR + (char*)entries[i].name);
unsigned char * outp;
if (entries[i].size==0) //file is not compressed
{
@ -799,8 +325,9 @@ int CLodHandler::readNormalNr (unsigned char* bufor, int bytCon, bool cyclic)
return ret;
}
void CLodHandler::init(std::string lodFile)
void CLodHandler::init(std::string lodFile, std::string dirName)
{
mutex = new boost::mutex;
std::string Ts;
FLOD = fopen(lodFile.c_str(), "rb");
fseek(FLOD, 8, 0);
@ -844,56 +371,36 @@ void CLodHandler::init(std::string lodFile)
}
entries.push_back(entry);
}
boost::filesystem::directory_iterator enddir;
if(boost::filesystem::exists(dirName))
{
for (boost::filesystem::directory_iterator dir(dirName);dir!=enddir;dir++)
{
if(boost::filesystem::is_regular(dir->status()))
{
std::string name = dir->path().leaf();
std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
boost::algorithm::replace_all(name,".BMP",".PCX");
Entry * e = entries.znajdz(name);
if(e)
{
e->offset = -1;
e->realSize = e->size = boost::filesystem::file_size(dir->path());
}
}
}
}
else
std::cout<<"Warning: No "+dirName+"/ folder!"<<std::endl;
}
std::string CLodHandler::getTextFile(std::string name)
{
std::string ret0;
std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
Entry *e;
e = entries.znajdz(name);
if(!e)
{
std::cout << "Error: cannot load "<<name<<" from the .lod file!"<<std::endl;
return ret0;
}
if(e->offset<0)
{
char * outp = new char[e->realSize];
char name[120];for(int i=0;i<120;i++) name[i]='\0';
strcat(name,"Data/");
strcat(name,(char*)e->name);
FILE * f = fopen(name,"rb");
int result = fread(outp,1,e->realSize,f);
if(result<0) {std::cout<<"Error in file reading: "<<name<<std::endl;return ret0;}
for (int itr=0;itr<e->realSize;itr++)
ret0+= *(outp+itr);
delete[] outp;
return ret0;
}
fseek(FLOD, e->offset, 0);
unsigned char * outp;
if (e->size==0) //file is not compressed
{
outp = new unsigned char[e->realSize];
fread((char*)outp, 1, e->realSize, FLOD);
std::string ret = std::string((char*)outp);
delete[] outp;
return ret;
}
else //we will decompressing file
{
outp = new unsigned char[e->size];
fread((char*)outp, 1, e->size, FLOD);
fseek(FLOD, 0, 0);
unsigned char * decomp = NULL;
int decRes = infs2(outp, e->size, e->realSize, decomp);
std::string ret;
for (int itr=0;itr<e->realSize;itr++)
ret+= *((char*)decomp+itr);
delete[] outp;
delete[] decomp;
return ret;
}
return ret0;
int length=-1;
unsigned char* data = giveFile(name,&length);
std::string ret;
ret.reserve(length);
for(int i=0;i<length;i++)
ret+=data[i];
delete [] data;
return ret;
}

View File

@ -1,20 +1,16 @@
#ifndef CLODHANDLER_H
#define CLODHANDLER_H
#include <iostream>
#include "../global.h"
#include <fstream>
#include <vector>
#include <string>
#include "zlib.h"
#include "../nodrze.h"
#include "SDL.h"
struct SDL_Surface;
class CDefHandler;
class CDefEssential;
enum Epcxformat {PCX8B, PCX24B};
namespace boost
{class mutex;};
namespace NLoadHandlerHelp
{
const int dmHelp=0, dmNoExtractingMask=1;
@ -43,43 +39,22 @@ struct Entry
//Entry(unsigned char ): nameStr(con){};
Entry(){};
};
class CPCXConv
class DLL_EXPORT CLodHandler
{
public:
unsigned char * pcx, *bmp;
int pcxs, bmps;
void fromFile(std::string path);
void saveBMP(std::string path);
void openPCX(char * PCX, int len);
void openPCX();
void convert();
SDL_Surface * getSurface(); //for standard H3 PCX
//SDL_Surface * getSurfaceZ(); //for ZSoft PCX
CPCXConv(){pcx=bmp=NULL;pcxs=bmps=0;};
~CPCXConv(){if (pcxs) delete[] pcx; if(bmps) delete[] bmp;}
};
class CLodHandler
{
private:
FILE* FLOD;
public:
nodrze<Entry> entries;
unsigned int totalFiles;
boost::mutex *mutex;
int readNormalNr (unsigned char* bufor, int bytCon, bool cyclic=false); //lod header reading helper
int decompress (unsigned char * source, int size, int realSize, std::ofstream & dest); //main decompression function
int decompress (unsigned char * source, int size, int realSize, std::string & dest); //main decompression function
int infm(FILE *source, FILE *dest, int wBits = 15); //zlib handler
int infs(unsigned char * in, int size, int realSize, std::ofstream & out, int wBits=15); //zlib fast handler
int infs2(unsigned char * in, int size, int realSize, unsigned char*& out, int wBits=15); //zlib fast handler
std::vector<CDefHandler *> extractManyFiles(std::vector<std::string> defNamesIn); //extrats given files (defs only)
CDefHandler * giveDef(std::string defName);
CDefEssential * giveDefEss(std::string defName);
unsigned char * giveFile(std::string defName, int * length=NULL); //returns pointer to the decompressed data - it must be deleted when no longer needed!
std::string getTextFile(std::string name); //extracts one file
void extract(std::string FName);
void extractFile(std::string FName, std::string name); //extracts a specific file
void init(std::string lodFile);
SDL_Surface * loadBitmap(std::string fname);
void init(std::string lodFile, std::string dirName);
};
#endif //CLODHANDLER_H

View File

@ -12,53 +12,53 @@ void CMusicHandler::initMusics()
}
atexit(Mix_CloseAudio);
AITheme0 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITheme0.mp3");
AITheme1 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITHEME1.mp3");
AITheme2 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITHEME2.mp3");
buildTown = Mix_LoadWAV("MP3" PATHSEPARATOR "BUILDTWN.wav");
combat1 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT01.mp3");
combat2 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT02.mp3");
combat3 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT03.mp3");
combat4 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT04.mp3");
castleTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "CstleTown.mp3");
defendCastle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Defend Castle.mp3");
dirt = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "DIRT.mp3");
dungeon = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "DUNGEON.mp3");
elemTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "ElemTown.mp3");
evilTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "EvilTheme.mp3");
fortressTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "FortressTown.mp3");
goodTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "GoodTheme.mp3");
grass = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "GRASS.mp3");
infernoTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "InfernoTown.mp3");
lava = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LAVA.mp3");
loopLepr = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoopLepr.mp3");
loseCampain = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Lose Campain.mp3");
loseCastle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoseCastle.mp3");
loseCombat = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoseCombat.mp3");
mainMenu = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "MAINMENU.mp3");
mainMenuWoG = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "MainMenuWoG.mp3");
necroTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "necroTown.mp3");
neutralTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "NeutralTheme.mp3");
rampart = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "RAMPART.mp3");
retreatBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Retreat Battle.mp3");
rough = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "ROUGH.mp3");
sand = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SAND.mp3");
secretTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SecretTheme.mp3");
snow = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SNOW.mp3");
stronghold = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "StrongHold.mp3");
surrenderBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Surrender Battle.mp3");
swamp = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SWAMP.mp3");
towerTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "TowerTown.mp3");
ultimateLose = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "UltimateLose.mp3");
underground = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Underground.mp3");
water = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "WATER.mp3");
winBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Win Battle.mp3");
winScenario = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Win Scenario.mp3");
//AITheme0 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITheme0.mp3");
//AITheme1 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITHEME1.mp3");
//AITheme2 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITHEME2.mp3");
//buildTown = Mix_LoadWAV("MP3" PATHSEPARATOR "BUILDTWN.wav");
//combat1 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT01.mp3");
//combat2 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT02.mp3");
//combat3 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT03.mp3");
//combat4 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT04.mp3");
//castleTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "CstleTown.mp3");
//defendCastle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Defend Castle.mp3");
//dirt = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "DIRT.mp3");
//dungeon = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "DUNGEON.mp3");
//elemTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "ElemTown.mp3");
//evilTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "EvilTheme.mp3");
//fortressTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "FortressTown.mp3");
//goodTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "GoodTheme.mp3");
//grass = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "GRASS.mp3");
//infernoTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "InfernoTown.mp3");
//lava = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LAVA.mp3");
//loopLepr = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoopLepr.mp3");
//loseCampain = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Lose Campain.mp3");
//loseCastle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoseCastle.mp3");
//loseCombat = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoseCombat.mp3");
//mainMenu = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "MAINMENU.mp3");
//mainMenuWoG = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "MainMenuWoG.mp3");
//necroTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "necroTown.mp3");
//neutralTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "NeutralTheme.mp3");
//rampart = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "RAMPART.mp3");
//retreatBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Retreat Battle.mp3");
//rough = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "ROUGH.mp3");
//sand = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SAND.mp3");
//secretTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SecretTheme.mp3");
//snow = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SNOW.mp3");
//stronghold = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "StrongHold.mp3");
//surrenderBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Surrender Battle.mp3");
//swamp = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SWAMP.mp3");
//towerTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "TowerTown.mp3");
//ultimateLose = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "UltimateLose.mp3");
//underground = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Underground.mp3");
//water = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "WATER.mp3");
//winBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Win Battle.mp3");
//winScenario = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Win Scenario.mp3");
click = Mix_LoadWAV(DATADIR "MP3" PATHSEPARATOR "snd1.wav");
click = Mix_LoadWAV(DATA_DIR "MP3" PATHSEPARATOR "snd1.wav");
click->volume = 30;
this->sndh = new CSndHandler(std::string(DATADIR "Data" PATHSEPARATOR "Heroes3.snd"));
this->sndh = new CSndHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "Heroes3.snd"));
}
void CMusicHandler::playClick()
@ -90,7 +90,7 @@ void CMusicHandler::playLodSnd(std::string sndname)
channel = Mix_PlayChannel(-1, chunk, 0);
if(channel == -1)
{
fprintf(stderr, "Unable to play WAV file("DATADIR "Data" PATHSEPARATOR "Heroes3.wav::%s): %s\n",
fprintf(stderr, "Unable to play WAV file("DATA_DIR "Data" PATHSEPARATOR "Heroes3.wav::%s): %s\n",
sndname.c_str(),Mix_GetError());
}
ops->close(ops);

View File

@ -1,72 +1,74 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "CObjectHandler.h"
#include "../CGameInfo.h"
#include "CGeneralTextHandler.h"
#include "CLodHandler.h"
#include "CAmbarCendamo.h"
#include "../mapHandler.h"
#include "CDefObjInfoHandler.h"
#include "../CLua.h"
#include "CLodHandler.h"
#include "CDefObjInfoHandler.h"
#include "CHeroHandler.h"
#include <boost/algorithm/string/replace.hpp>
#include "CTownHandler.h"
#include "CArtHandler.h"
#include "../lib/VCMI_Lib.h"
DLL_EXPORT void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
extern CLodHandler * bitmaph;
void CObjectHandler::loadObjects()
{
VLC->objh = this;
int ID=0;
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("OBJNAMES.TXT");
std::string buf = bitmaph->getTextFile("OBJNAMES.TXT");
int it=0;
while (it<buf.length()-1)
{
CObject nobj;
CGeneralTextHandler::loadToIt(nobj.name,buf,it,3);
if(nobj.name.size() && (nobj.name[nobj.name.size()-1]==(char)10 || nobj.name[nobj.name.size()-1]==(char)13 || nobj.name[nobj.name.size()-1]==(char)9))
nobj.name = nobj.name.substr(0, nobj.name.size()-1);
objects.push_back(nobj);
std::string nobj;
loadToIt(nobj,buf,it,3);
if(nobj.size() && (nobj[nobj.size()-1]==(char)10 || nobj[nobj.size()-1]==(char)13 || nobj[nobj.size()-1]==(char)9))
nobj = nobj.substr(0, nobj.size()-1);
names.push_back(nobj);
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("ADVEVENT.TXT");
buf = bitmaph->getTextFile("ADVEVENT.TXT");
it=0;
std::string temp;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
if (temp[0]=='\"')
temp = temp.substr(1,temp.length()-2);
boost::algorithm::replace_all(temp,"\"\"","\"");
advobtxt.push_back(temp);
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("XTRAINFO.TXT");
buf = bitmaph->getTextFile("XTRAINFO.TXT");
it=0;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
xtrainfo.push_back(temp);
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("MINENAME.TXT");
buf = bitmaph->getTextFile("MINENAME.TXT");
it=0;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
mines.push_back(std::pair<std::string,std::string>(temp,""));
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("MINEEVNT.TXT");
buf = bitmaph->getTextFile("MINEEVNT.TXT");
it=0;
int i=0;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
temp = temp.substr(1,temp.length()-2);
mines[i++].second = temp;
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("RESTYPES.TXT");
buf = bitmaph->getTextFile("RESTYPES.TXT");
it=0;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
restypes.push_back(temp);
}
@ -82,11 +84,11 @@ void CObjectHandler::loadObjects()
}
ifs.close();
ifs.clear();
buf = CGameInfo::mainObj->bitmaph->getTextFile("ZCRGN1.TXT");
buf = bitmaph->getTextFile("ZCRGN1.TXT");
it=0;
while (it<buf.length()-1)
{
CGeneralTextHandler::loadToIt(temp,buf,it,3);
loadToIt(temp,buf,it,3);
creGens.push_back(temp);
}
@ -113,11 +115,11 @@ void CGObjectInstance::setOwner(int ow)
}
int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
{
return defInfo->handler->ourImages[0].bitmap->w/32;
return defInfo->width;
}
int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
{
return defInfo->handler->ourImages[0].bitmap->h/32;
return defInfo->width;
}
bool CGObjectInstance::visitableAt(int x, int y) const //returns true if ibject is visitable at location (x, y) form left top tile of image (x, y in tiles)
{
@ -145,10 +147,6 @@ bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const //screen p
return true;
if(!cmp.defInfo->isVisitable() && defInfo->isVisitable())
return false;
//if(defInfo->isOnDefList && !(cmp.defInfo->isOnDefList))
// return true;
//if(cmp.defInfo->isOnDefList && !(defInfo->isOnDefList))
// return false;
if(this->pos.x<cmp.pos.x)
return true;
return false;
@ -181,8 +179,8 @@ unsigned int CGHeroInstance::getLowestCreatureSpeed()
unsigned int sl = 100;
for(int h=0; h<army.slots.size(); ++h)
{
if(army.slots[h].first->speed<sl)
sl = army.slots[h].first->speed;
if(VLC->creh->creatures[army.slots[h].first].speed<sl)
sl = VLC->creh->creatures[army.slots[h].first].speed;
}
return sl;
}
@ -239,7 +237,13 @@ int CGHeroInstance::getSecSkillLevel(const int & ID) const
return secSkills[i].second;
return -1;
}
const CArtifact * CGHeroInstance::getArt(int pos)
{
if(artifWorn.find(pos)!=artifWorn.end())
return &VLC->arth->artifacts[artifWorn[pos]];
else
return NULL;
}
int CGTownInstance::getSightDistance() const //returns sight distance
{
@ -277,7 +281,7 @@ int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns
}
int CGTownInstance::creatureGrowth(const int & level) const
{
int ret = CGI->creh->creatures[town->basicCreatures[level]].growth;
int ret = VLC->creh->creatures[town->basicCreatures[level]].growth;
switch(fortLevel())
{
case 3:
@ -286,13 +290,13 @@ int CGTownInstance::creatureGrowth(const int & level) const
ret*=(1.5); break;
}
if(builtBuildings.find(26)!=builtBuildings.end()) //grail
ret+=CGI->creh->creatures[town->basicCreatures[level]].growth;
ret+=VLC->creh->creatures[town->basicCreatures[level]].growth;
if(getHordeLevel(0)==level)
if((builtBuildings.find(18)!=builtBuildings.end()) || (builtBuildings.find(19)!=builtBuildings.end()))
ret+=CGI->creh->creatures[town->basicCreatures[level]].hordeGrowth;
ret+=VLC->creh->creatures[town->basicCreatures[level]].hordeGrowth;
if(getHordeLevel(1)==level)
if((builtBuildings.find(24)!=builtBuildings.end()) || (builtBuildings.find(25)!=builtBuildings.end()))
ret+=CGI->creh->creatures[town->basicCreatures[level]].hordeGrowth;
ret+=VLC->creh->creatures[town->basicCreatures[level]].hordeGrowth;
return ret;
}
int CGTownInstance::dailyIncome() const
@ -324,9 +328,7 @@ CGTownInstance::CGTownInstance()
builded=-1;
destroyed=-1;
garrisonHero=NULL;
//state->owner=-1;
town=NULL;
income = 500;
visitingHero = NULL;
}
@ -334,7 +336,7 @@ CGObjectInstance::CGObjectInstance(): animPhaseShift(rand()%0xff)
{
//std::cout << "Tworze obiekt "<<this<<std::endl;
//state = new CLuaObjectScript();
//state = NULL;
state = NULL;
tempOwner = 254;
blockVisit = false;
}
@ -347,11 +349,12 @@ CGObjectInstance::~CGObjectInstance()
}
CGHeroInstance::CGHeroInstance()
{
level = exp = -1;
portrait = level = exp = -1;
isStanding = true;
moveDir = 4;
mana = 0;
visitedTown = NULL;
type = NULL;
}
CGHeroInstance::~CGHeroInstance()

View File

@ -1,13 +1,12 @@
#ifndef COBJECTHANDLER_H
#define COBJECTHANDLER_H
#include "../global.h"
#include <string>
#include <vector>
#include <set>
#include <map>
#include "CCreatureHandler.h"
#include "CArtHandler.h"
#include "CAbilityHandler.h"
#include "CSpellHandler.h"
//#include "CHeroHandler.h"
using boost::logic::tribool;
class CCPPObjectScript;
class CGObjectInstance;
@ -18,301 +17,45 @@ class CTown;
class CHero;
class CBuilding;
class CSpell;
class CSpecObjInfo //class with object - specific info (eg. different information for creatures and heroes); use inheritance to make object - specific classes
{
};
class CEventObjInfo : public CSpecObjInfo
{
public:
bool areGuarders; //true if there are
CCreatureSet guarders;
bool isMessage; //true if there is a message
std::string message;
unsigned int gainedExp;
int manaDiff; //amount of gained / lost mana
int moraleDiff; //morale modifier
int luckDiff; //luck modifier
int wood, mercury, ore, sulfur, crystal, gems, gold; //gained / lost resources
unsigned int attack; //added attack points
unsigned int defence; //added defence points
unsigned int power; //added power points
unsigned int knowledge; //added knowledge points
std::vector<CAbility *> abilities; //gained abilities
std::vector<int> abilityLevels; //levels of gained abilities
std::vector<CArtifact *> artifacts; //gained artifacts
std::vector<CSpell *> spells; //gained spells
CCreatureSet creatures; //gained creatures
unsigned char availableFor; //players whom this event is available for
bool computerActivate; //true if computre player can activate this event
bool humanActivate; //true if human player can activate this event
};
class CHeroObjInfo : public CSpecObjInfo
{
public:
unsigned char bytes[4]; //mysterius bytes identifying hero in a strange way
int player;
CHero * type;
std::string name; //if nonstandard
bool standardGarrison; //true if hero has standard garrison
CCreatureSet garrison; //hero's army
std::vector<CArtifact *> artifacts; //hero's artifacts from bag
//CArtifact * artHead, * artLRing, * artRRing, * artLHand, * artRhand, * artFeet, * artSpellBook, * artMach1, * artMach2, * artMach3, * artMach4, * artMisc1, * artMisc2, * artMisc3, * artMisc4, * artMisc5, * artTorso, * artNeck, * artShoulders; //working artifactsstd::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
std::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
bool isGuarding;
int guardRange; //range of hero's guard
std::string biography; //if nonstandard
bool sex; //if true, reverse hero's sex
std::vector<CSpell *> spells; //hero's spells
int attack, defence, power, knowledge; //main hero's attributes
unsigned int experience; //hero's experience points
std::vector<CAbility *> abilities; //hero's abilities
std::vector<int> abilityLevels; //hero ability levels
bool defaultMainStats; //if true attack, defence, power and knowledge are typical
CGHeroInstance * myInstance; //pointer to appropriate hero instance
};
class CCreatureObjInfo : public CSpecObjInfo
{
public:
unsigned char bytes[4]; //mysterious bytes identifying creature
unsigned int number; //number of units (0 - random)
unsigned char character; //chracter of this set of creatures (0 - the most friendly, 4 - the most hostile)
std::string message; //message printed for attacking hero
int wood, mercury, ore, sulfur, crytal, gems, gold; //resources gained to hero that has won with monsters
CArtifact * gainedArtifact; //artifact gained to hero
bool neverFlees; //if true, the troops will never flee
bool notGrowingTeam; //if true, number of units won't grow
};
class CSignObjInfo : public CSpecObjInfo
{
public:
std::string message; //message
};
class CSeerHutObjInfo : public CSpecObjInfo
{
public:
unsigned char missionType; //type of mission: 0 - no mission; 1 - reach level; 2 - reach main statistics values; 3 - win with a certain hero; 4 - win with a certain creature; 5 - collect some atifacts; 6 - have certain troops in army; 7 - collect resources; 8 - be a certain hero; 9 - be a certain player
bool isDayLimit; //if true, there is a day limit
int lastDay; //after this day (first day is 0) mission cannot be completed
//for mission 1
int m1level;
//for mission 2
int m2attack, m2defence, m2power, m2knowledge;
//for mission 3
unsigned char m3bytes[4];
//for mission 4
unsigned char m4bytes[4];
//for mission 5
std::vector<CArtifact *> m5arts;
//for mission 6
std::vector<CCreature *> m6cre;
std::vector<int> m6number;
//for mission 7
int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold;
//for mission 8
CHero * m8hero;
//for mission 9
int m9player; //number; from 0 to 7
std::string firstVisitText, nextVisitText, completedText;
char rewardType; //type of reward: 0 - no reward; 1 - experience; 2 - mana points; 3 - morale bonus; 4 - luck bonus; 5 - resources; 6 - main ability bonus (attak, defence etd.); 7 - secondary ability gain; 8 - artifact; 9 - spell; 10 - creature
//for reward 1
int r1exp;
//for reward 2
int r2mana;
//for reward 3
int r3morale;
//for reward 4
int r4luck;
//for reward 5
unsigned char r5type; //0 - wood, 1 - mercury, 2 - ore, 3 - sulfur, 4 - crystal, 5 - gems, 6 - gold
int r5amount;
//for reward 6
unsigned char r6type; //0 - attack, 1 - defence, 2 - power, 3 - knowledge
int r6amount;
//for reward 7
CAbility * r7ability;
unsigned char r7level; //1 - basic, 2 - advanced, 3 - expert
//for reward 8
CArtifact * r8art;
//for reward 9
CSpell * r9spell;
//for reward 10
CCreature * r10creature;
int r10amount;
};
class CWitchHutObjInfo : public CSpecObjInfo
{
public:
std::vector<CAbility *> allowedAbilities;
};
class CScholarObjInfo : public CSpecObjInfo
{
public:
unsigned char bonusType; //255 - random, 0 - primary skill, 1 - secondary skill, 2 - spell
unsigned char r0type;
CAbility * r1;
CSpell * r2;
};
class CGarrisonObjInfo : public CSpecObjInfo
{
public:
unsigned char player; //255 - nobody; 0 - 7 - players
CCreatureSet units;
bool movableUnits; //if true, units can be moved
};
class CArtifactObjInfo : public CSpecObjInfo
{
public:
bool areGuards;
std::string message;
CCreatureSet guards;
};
class CResourceObjInfo : public CSpecObjInfo
{
public:
bool randomAmount;
int amount; //if not random
bool areGuards;
CCreatureSet guards;
std::string message;
};
class CPlayerOnlyObjInfo : public CSpecObjInfo
{
public:
unsigned char player; //FF - nobody, 0 - 7
};
class CShrineObjInfo : public CSpecObjInfo
{
public:
unsigned char spell; //number of spell or 255
};
class CSpellScrollObjinfo : public CSpecObjInfo
{
public:
std::string message;
CSpell * spell;
bool areGuarders;
CCreatureSet guarders;
};
class CPandorasBoxObjInfo : public CSpecObjInfo
{
public:
std::string message;
bool areGuarders;
CCreatureSet guarders;
//gained things:
unsigned int gainedExp;
int manaDiff;
int moraleDiff;
int luckDiff;
int wood, mercury, ore, sulfur, crystal, gems, gold;
int attack, defence, power, knowledge;
std::vector<CAbility *> abilities;
std::vector<int> abilityLevels;
std::vector<CArtifact *> artifacts;
std::vector<CSpell *> spells;
CCreatureSet creatures;
};
class CGrailObjInfo : public CSpecObjInfo
{
public:
int radius; //place grail at the distance lesser or equal radius from this place
};
class CCreGenObjInfo : public CSpecObjInfo
{
public:
unsigned char player; //owner
bool asCastle;
int identifier;
unsigned char castles[2]; //allowed castles
};
class CCreGen2ObjInfo : public CSpecObjInfo
{
public:
unsigned char player; //owner
bool asCastle;
int identifier;
unsigned char castles[2]; //allowed castles
unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6>
};
class CCreGen3ObjInfo : public CSpecObjInfo
{
public:
unsigned char player; //owner
unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6>
};
class CBorderGuardObjInfo : public CSpecObjInfo //copied form seer huts, seems to be similar
{
public:
char missionType; //type of mission: 0 - no mission; 1 - reach level; 2 - reach main statistics values; 3 - win with a certain hero; 4 - win with a certain creature; 5 - collect some atifacts; 6 - have certain troops in army; 7 - collect resources; 8 - be a certain hero; 9 - be a certain player
bool isDayLimit; //if true, there is a day limit
int lastDay; //after this day (first day is 0) mission cannot be completed
//for mission 1
int m1level;
//for mission 2
int m2attack, m2defence, m2power, m2knowledge;
//for mission 3
unsigned char m3bytes[4];
//for mission 4
unsigned char m4bytes[4];
//for mission 5
std::vector<CArtifact *> m5arts;
//for mission 6
std::vector<CCreature *> m6cre;
std::vector<int> m6number;
//for mission 7
int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold;
//for mission 8
CHero * m8hero;
//for mission 9
int m9player; //number; from 0 to 7
std::string firstVisitText, nextVisitText, completedText;
};
class CObject //typical object that can be encountered on a map
{
public:
std::string name; //object's name
};
class CGTownInstance;
class CArtifact;
class CGDefInfo;
class CSpecObjInfo;
class CGObjectInstance
class DLL_EXPORT CCastleEvent
{
public:
std::string name, message;
int wood, mercury, ore, sulfur, crystal, gems, gold; //gain / loss of resources
unsigned char players; //players for whom this event can be applied
bool forHuman, forComputer;
int firstShow; //postpone of first encounter time in days
int forEvery; //every n days this event will occure
unsigned char bytes[6]; //build specific buildings (raw format, similar to town's)
int gen[7]; //additional creatures in i-th level dwelling
bool operator<(const CCastleEvent &drugie) const
{
return firstShow<drugie.firstShow;
}
};
class DLL_EXPORT CGObjectInstance
{
public:
int3 pos; //h3m pos
int ID, subID; //normal ID (this one from OH3 maps ;]) - eg. town=98; hero=34
int id;//number of object in CObjectHandler's vector
si32 id;//number of object in CObjectHandler's vector
CGDefInfo * defInfo;
CCPPObjectScript * state;
CSpecObjInfo * info;
unsigned char animPhaseShift;
std::string hoverName;
int tempOwner; //uzywane dla szybkosci, skrypt ma obowiazek aktualizowac te zmienna
bool blockVisit;
int blockVisit; //if non-zero then blocks the tile but is visitable from neighbouring tile
virtual bool isHero() const;
int getOwner() const;
@ -327,22 +70,21 @@ public:
CGObjectInstance& operator=(const CGObjectInstance & right);
};
class CArmedInstance: public CGObjectInstance
class DLL_EXPORT CArmedInstance: public CGObjectInstance
{
public:
CCreatureSet army; //army
};
class CGHeroInstance : public CArmedInstance
class DLL_EXPORT CGHeroInstance : public CArmedInstance
{
public:
int moveDir; //format: 123
// 8 4
// 765
bool isStanding;
bool flagPrinted;
CHero * type;
int exp; //experience point
ui32 exp; //experience point
int level; //current level of hero
std::string name; //may be custom
std::string biography; //may be custom
@ -351,12 +93,23 @@ public:
std::vector<int> primSkills; //0-attack, 1-defence, 2-spell power, 3-knowledge
std::vector<std::pair<int,int> > secSkills; //first - ID of skill, second - level of skill (0 - basic, 1 - adv., 2 - expert)
int movement; //remaining movement points
int identifier; //from the map file
bool sex;
bool inTownGarrison; // if hero is in town garrison
struct DLL_EXPORT Patrol
{
Patrol(){patrolling=false;patrolRadious=-1;};
bool patrolling;
int patrolRadious;
} patrol;
bool inTownGarrison; // if hero is in town garrison
CGTownInstance * visitedTown; //set if hero is visiting town or in the town garrison
std::vector<CArtifact *> artifacts; //hero's artifacts from bag
std::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
std::vector<int> artifacts; //hero's artifacts from bag
std::map<int,int> artifWorn; //map<position,artifact_id>; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
std::set<int> spells; //known spells (spell IDs)
virtual bool isHero() const;
unsigned int getTileCost(const EterrainType & ttype, const Eroad & rdtype, const Eriver & rvtype) const;
@ -372,41 +125,42 @@ public:
int getCurrentLuck() const;
int getCurrentMorale() const;
int getSecSkillLevel(const int & ID) const; //-1 - no skill
const CArtifact * getArt(int pos);
CGHeroInstance();
virtual ~CGHeroInstance();
};
class CGTownInstance : public CArmedInstance
class DLL_EXPORT CGTownInstance : public CArmedInstance
{
public:
CTown * town;
std::string name; // name of town
int builded; //how many buildings has been built this turn
int destroyed; //how many buildings has been destroyed this turn
int identifier;
int income;
const CGHeroInstance * garrisonHero, *visitingHero;
int identifier; //special identifier from h3m (only > RoE maps)
int alignment;
std::set<si32> forbiddenBuildings, builtBuildings;
std::vector<int> possibleSpells, obligatorySpells, availableSpells;
struct StrInfo
{
public:
std::map<int,int> creatures; //level - available amount
std::map<si32,ui32> creatures; //level - available amount
template <typename Handler> void serialize(Handler &h, const int version)
{
h & creatures;
}
} strInfo;
std::set<CCastleEvent> events;
std::set<int> forbiddenBuildings, builtBuildings, h3mbuildings;
const CGHeroInstance * garrisonHero, *visitingHero;
std::vector<CSpell *> possibleSpells, obligatorySpells, availableSpells;
int getSightDistance() const; //returns sight distance
int fortLevel() const; //0 - none, 1 - fort, 2 - citadel, 3 - castle
int hallLevel() const; // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
bool creatureDwelling(const int & level, bool upgraded=false) const;
int getHordeLevel(const int & HID) const; //HID - 0 or 1; returns creature level or -1 if that horde structure is not present
int creatureGrowth(const int & level) const;
bool hasFort() const;
bool hasCapitol() const;
int dailyIncome() const;
@ -415,11 +169,10 @@ public:
virtual ~CGTownInstance();
};
class CObjectHandler
class DLL_EXPORT CObjectHandler
{
public:
std::vector<CObject> objects; //vector of objects; i-th object in vector has subnumber i
std::vector<CGObjectInstance*> objInstances; //vector with objects on map
std::vector<std::string> names; //vector of objects; i-th object in vector has subnumber i
std::vector<int> cregens; //type 17. dwelling subid -> creature ID
void loadObjects();

View File

@ -25,7 +25,7 @@ std::string CPreGameTextHandler::getDescr(std::string text)
}
void CPreGameTextHandler::loadTexts()
{
std::string buf1 = CGameInfo::mainObj->bitmaph->getTextFile("ZELP.TXT");
std::string buf1 = CGI->bitmaph->getTextFile("ZELP.TXT");
int itr=0, eol=-1, eolnext=-1, pom;
eolnext = buf1.find_first_of('\r',itr);
while(itr<buf1.size())
@ -48,7 +48,7 @@ void CPreGameTextHandler::loadTexts()
}
itr=eol+2;
}
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("VCDESC.TXT");
std::string buf = CGI->bitmaph->getTextFile("VCDESC.TXT");
int andame = buf.size();
int i=0; //buf iterator
for(int gg=0; gg<14; ++gg)
@ -62,7 +62,7 @@ void CPreGameTextHandler::loadTexts()
victoryConditions[gg] = buf.substr(befi, i-befi);
i+=2;
}
buf = CGameInfo::mainObj->bitmaph->getTextFile("LCDESC.TXT");
buf = CGI->bitmaph->getTextFile("LCDESC.TXT");
andame = buf.size();
i=0; //buf iterator
for(int gg=0; gg<4; ++gg)

View File

@ -1,148 +0,0 @@
#include "../stdafx.h"
#include "CSemiDefHandler.h"
#include <fstream>
#include "SDL_image.h"
extern SDL_Surface * screen;
std::string CSemiDefHandler::nameFromType (EterrainType typ)
{
switch(typ)
{
case dirt:
{
return std::string("DIRTTL.DEF");
break;
}
case sand:
{
return std::string("SANDTL.DEF");
break;
}
case grass:
{
return std::string("GRASTL.DEF");
break;
}
case snow:
{
return std::string("SNOWTL.DEF");
break;
}
case swamp:
{
return std::string("SWMPTL.DEF");
break;
}
case rough:
{
return std::string("ROUGTL.DEF");
break;
}
case subterranean:
{
return std::string("SUBBTL.DEF");
break;
}
case lava:
{
return std::string("LAVATL.DEF");
break;
}
case water:
{
return std::string("WATRTL.DEF");
break;
}
case rock:
{
return std::string("ROCKTL.DEF");
break;
}
}
return std::string();
}
void CSemiDefHandler::openDef(std::string name, std::string lodName, int dist)
{
std::ifstream * is = new std::ifstream();
is -> open((lodName+"\\"+name).c_str(),std::ios::binary);
is->seekg(0,std::ios::end); // na koniec
int andame = is->tellg(); // read length
is->seekg(0,std::ios::beg); // wracamy na poczatek
buforD = new unsigned char[andame]; // allocate memory
is->read((char*)buforD, andame); // read map file to buffer
defName = name;
int gdzie = defName.find_last_of("\\");
defName = defName.substr(gdzie+1, gdzie-defName.length());
delete is;
readFileList(dist);
loadImages(lodName);
}
CSemiDefHandler::~CSemiDefHandler()
{
for (int i=0;i<ourImages.size();i++)
SDL_FreeSurface(ourImages[i].bitmap);
}
void CSemiDefHandler::readFileList(int dist)
{
howManyImgs = buforD[788];
int i = 800;
for (int pom=0;pom<howManyImgs;pom++)
{
std::string temp;
while (buforD[i]!=0)
{
temp+=buforD[i++];
}
i+=dist; //by³o zwiêkszenie tylko o jedno
if (temp!="")
{
temp = temp.substr(0,temp.length()-4) + ".BMP";
namesOfImgs.push_back(temp);
}
else pom--;
}
delete buforD;
}
void CSemiDefHandler::loadImages(std::string path)
{
for (int i=0; i<namesOfImgs.size(); i++)
{
openImg((path+"\\_"+defName+"\\"+namesOfImgs[i]).c_str());
}
}
void SDL_DisplayBitmap(const char *file, SDL_Surface *ekran, int x, int y)
{
SDL_Surface *image;
SDL_Rect dest;
image = SDL_LoadBMP(file);
if ( image == NULL )
{
fprintf(stderr, "Nie mo¿na wczytaæ %s: %s\n", file, SDL_GetError());
return;
}
dest.x = x;
dest.y = y;
dest.w = image->w;
dest.h = image->h;
SDL_BlitSurface(image, NULL, ekran, &dest);
SDL_UpdateRects(ekran, 1, &dest);
SDL_FreeSurface(image);
}
void CSemiDefHandler::openImg(const char *name)
{
SDL_Surface *image;
image=IMG_Load(name);
//SDL_DisplayBitmap(name,image, 0,0);
if(!image)
{
printf("IMG_Load: %s\n", IMG_GetError());
return;
// handle error
}
Cimage vinya;
vinya.bitmap = image;
SDL_SetColorKey(vinya.bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(vinya.bitmap->format,0,255,255));
vinya.imName = name;
ourImages.push_back(vinya);
}

View File

@ -1,31 +0,0 @@
#ifndef SEMIDEF_H
#define SEMIDEF_H
#include "../global.h"
#include <string>
#include "SDL.h"
//#include "SDL_image.h"
#include <vector>
struct Cimage
{
int groupNumber;
std::string imName; //name without extension
SDL_Surface * bitmap;
};
class CSemiDefHandler
{
public:
int howManyImgs;
std::string defName;
std::vector<Cimage> ourImages;
std::vector<std::string> namesOfImgs;
unsigned char * buforD;
static std::string nameFromType(EterrainType typ);
void openImg(const char *name);
void openDef(std::string name, std::string lodName, int dist=1);
void readFileList(int dist = 1);
void loadImages(std::string path);
~CSemiDefHandler();
};
#endif // SEMIDEF_H

View File

@ -1,12 +0,0 @@
#include "../stdafx.h"
#include "CSemiLodHandler.h"
void CSemiLodHandler::openLod(std::string path)
{
ourName = path;
};
CSemiDefHandler * CSemiLodHandler::giveDef(std::string name, int dist)
{
CSemiDefHandler * ret = new CSemiDefHandler();
ret->openDef(name, ourName, dist);
return ret;
};

View File

@ -1,13 +0,0 @@
#ifndef CSEMILODHANDLER_H
#define CSEMILODHANDLER_H
#include "CSemiDefHandler.h"
class CSemiLodHandler
{
public:
std::string ourName; // name of our lod
void openLod(std::string path);
CSemiDefHandler * giveDef(std::string name, int dist=1); //loads def from our lod
};
#endif //CSEMILODHANDLER_H

View File

@ -1,11 +1,11 @@
#include "../stdafx.h"
#include "../stdafx.h"
#include "CSpellHandler.h"
#include "../CGameInfo.h"
#include "CLodHandler.h"
void CSpellHandler::loadSpells()
{
std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("SPTRAITS.TXT");
std::string buf = CGI->bitmaph->getTextFile("SPTRAITS.TXT");
int andame = buf.size();
int i=0; //buf iterator
int hmcr=0;

View File

@ -1,24 +1,22 @@
#define VCMI_DLL
#include "../stdafx.h"
#include "CTownHandler.h"
#include "../CGameInfo.h"
#include "CLodHandler.h"
#include <sstream>
#include "CGeneralTextHandler.h"
#include "../lib/VCMI_Lib.h"
extern CLodHandler * bitmaph;
void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
CTownHandler::CTownHandler()
{
smallIcons = CGI->spriteh->giveDef("ITPA.DEF");
resources = CGI->spriteh->giveDef("RESOURCE.DEF");
VLC->townh = this;
}
CTownHandler::~CTownHandler()
{
delete smallIcons;
//todo - delete structures info
}
{}
void CTownHandler::loadNames()
{
std::istringstream ins, names;
ins.str(CGI->bitmaph->getTextFile("TOWNTYPE.TXT"));
names.str(CGI->bitmaph->getTextFile("TOWNNAME.TXT"));
ins.str(bitmaph->getTextFile("TOWNTYPE.TXT"));
names.str(bitmaph->getTextFile("TOWNNAME.TXT"));
int si=0;
char bufname[75];
while (!ins.eof())
@ -40,21 +38,21 @@ void CTownHandler::loadNames()
towns.push_back(town);
}
std::string strs = CGI->bitmaph->getTextFile("TCOMMAND.TXT");
std::string strs = bitmaph->getTextFile("TCOMMAND.TXT");
int itr=0;
while(itr<strs.length()-1)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
loadToIt(tmp, strs, itr, 3);
tcommands.push_back(tmp);
}
strs = CGI->bitmaph->getTextFile("HALLINFO.TXT");
strs = bitmaph->getTextFile("HALLINFO.TXT");
itr=0;
while(itr<strs.length()-1)
{
std::string tmp;
CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
loadToIt(tmp, strs, itr, 3);
hcommands.push_back(tmp);
}
@ -277,35 +275,3 @@ void CTownHandler::loadNames()
of.clear();
}
}
SDL_Surface * CTownHandler::getPic(int ID, bool fort, bool builded)
{
if (ID==-1)
return smallIcons->ourImages[0].bitmap;
else if (ID==-2)
return smallIcons->ourImages[1].bitmap;
else if (ID==-3)
return smallIcons->ourImages[2+F_NUMBER*4].bitmap;
else if (ID>F_NUMBER || ID<-3)
#ifndef __GNUC__
throw new std::exception("Invalid ID");
#else
throw new std::exception();
#endif
else
{
int pom = 3;
if(!fort)
pom+=F_NUMBER*2;
pom += ID*2;
if (!builded)
pom--;
return smallIcons->ourImages[pom].bitmap;
}
}
int CTownHandler::getTypeByDefName(std::string name)
{
//TODO
return 0;
}

View File

@ -1,18 +1,12 @@
#ifndef CTOWNHANDLER_H
#define CTOWNHANDLER_H
#include "CDefHandler.h"
#include "CCreatureHandler.h"
#include "SDL.h"
#include "../int3.h"
#include <string>
#include <vector>
#include "../global.h"
#include <set>
class CBuilding;
class CSpell;
class CHero;
class CGTownInstance;
class CTown
class DLL_EXPORT CTown
{
public:
std::string name; //name of type
@ -24,7 +18,7 @@ public:
int typeID;
};
struct Structure
struct DLL_EXPORT Structure
{
int ID;
int3 pos;
@ -39,23 +33,17 @@ struct Structure
}
};
class CTownHandler
class DLL_EXPORT CTownHandler
{
public:
CDefHandler * smallIcons, *resources; //resources 32x32
CTownHandler();
~CTownHandler();
std::vector<CTown> towns;
std::vector<std::string> tcommands, hcommands;
void loadNames();
SDL_Surface * getPic(int ID, bool fort=true, bool builded=false); //ID=-1 - blank; -2 - border; -3 - random
static int getTypeByDefName(std::string name);
std::map<int,std::map<int, Structure*> > structures; // <town ID, <structure ID, structure>>
std::map<int, std::map<int,std::set<int> > > requirements; //requirements[town_id][structure_id] -> set of required buildings
std::vector<CGTownInstance *> townInstances;
CTownHandler();
~CTownHandler();
void loadNames();
};
#endif //CTOWNHANDLER_H

32
int3.h
View File

@ -1,22 +1,34 @@
#ifndef INT3_H
#define INT3_H
#include <map>
class CCreature;
class CCreatureSet //seven combined creatures
{
public:
std::map<si32,std::pair<ui32,si32> > slots; //slots[slot_id]=> pair(creature_id,creature_quantity)
bool formation; //false - wide, true - tight
template <typename Handler> void serialize(Handler &h, const int version)
{
h & slots & formation;
}
};
class int3
{
public:
int x,y,z;
si32 x,y,z;
inline int3():x(0),y(0),z(0){}; //c-tor, x/y/z initialized to 0
inline int3(const int & X, const int & Y, const int & Z):x(X),y(Y),z(Z){}; //c-tor
inline int3(const si32 & X, const si32 & Y, const si32 & Z):x(X),y(Y),z(Z){}; //c-tor
inline ~int3(){} // d-tor - does nothing
inline int3 operator+(const int3 & i) const
{return int3(x+i.x,y+i.y,z+i.z);}
inline int3 operator+(const int i) const //increases all components by int
inline int3 operator+(const si32 i) const //increases all components by si32
{return int3(x+i,y+i,z+i);}
inline int3 operator-(const int3 & i) const
{return int3(x-i.x,y-i.y,z-i.z);}
inline int3 operator-(const int i) const
inline int3 operator-(const si32 i) const
{return int3(x-i,y-i,z-i);}
inline int3 operator-() const //increases all components by int
inline int3 operator-() const //increases all components by si32
{return int3(-x,-y,-z);}
inline void operator+=(const int3 & i)
{
@ -24,7 +36,7 @@ public:
y+=i.y;
z+=i.z;
}
inline void operator+=(const int & i)
inline void operator+=(const si32 & i)
{
x+=i;
y+=i;
@ -36,7 +48,7 @@ public:
y-=i.y;
z-=i.z;
}
inline void operator-=(const int & i)
inline void operator-=(const si32 & i)
{
x+=i;
y+=i;
@ -62,13 +74,17 @@ public:
return false;
return false;
}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & x & y & z;
}
};
inline std::istream & operator>>(std::istream & str, int3 & dest)
{
str>>dest.x>>dest.y>>dest.z;
return str;
}
inline std::ostream & operator<<(std::ostream & str, int3 & sth)
inline std::ostream & operator<<(std::ostream & str, const int3 & sth)
{
return str<<sth.x<<' '<<sth.y<<' '<<sth.z;
}

13
lib/BattleAction.h Normal file
View File

@ -0,0 +1,13 @@
#pragma once
struct BattleAction
{
ui8 side; //who made this action: false - left, true - right player
ui32 stackNumber;//stack ID, -1 left hero, -2 right hero,
ui8 actionType; // 0 = Cancel BattleAction 1 = Hero cast a spell 2 = Walk 3 = Defend 4 = Retreat from the battle 5 = Surrender 6 = Walk and Attack 7 = Shoot 8 = Wait 9 = Catapult 10 = Monster casts a spell (i.e. Faerie Dragons)
ui16 destinationTile;
si32 additionalInfo; // e.g. spell number if type is 1 || 10
template <typename Handler> void serialize(Handler &h, const int version)
{
h & side & stackNumber & actionType & destinationTile & additionalInfo;
}
};

13
lib/CondSh.h Normal file
View File

@ -0,0 +1,13 @@
#pragma once
#include <boost/thread.hpp>
template <typename T> struct CondSh
{
T data;
boost::condition_variable cond;
boost::mutex mx;
CondSh(){};
CondSh(T t){data = t;};
void set(T t){mx.lock();data=t;mx.unlock();}; //set data
void setn(T t){mx.lock();data=t;mx.unlock();cond.notify_all();}; //set data and notify
T get(){boost::unique_lock<boost::mutex> lock(mx); return data;};
};

104
lib/Connection.cpp Normal file
View File

@ -0,0 +1,104 @@
#define VCMI_DLL
#pragma warning(disable:4355)
#include "Connection.h"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using namespace boost;
using namespace boost::asio::ip;
#define LOG(a) \
if(logging)\
out << a
#if defined(__hppa__) || \
defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
(defined(__MIPS__) && defined(__MISPEB__)) || \
defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
defined(__sparc__)
#define BIG_ENDIAN
#else
#define LIL_ENDIAN
#endif
void CConnection::init()
{
#ifdef LIL_ENDIAN
myEndianess = true;
#else
myEndianess = false;
#endif
connected = true;
std::string pom;
//we got connection
(*this) << std::string("Aiya!\n") << name << myEndianess; //identify ourselves
(*this) >> pom >> pom >> contactEndianess;
out << "Established connection with "<<pom<<std::endl;
wmx = new boost::mutex;
rmx = new boost::mutex;
}
CConnection::CConnection(std::string host, std::string port, std::string Name, std::ostream & Out)
:io_service(new asio::io_service), name(Name), out(Out)//, send(this), rec(this)
{
boost::system::error_code error = asio::error::host_not_found;
socket = new tcp::socket(*io_service);
tcp::resolver resolver(*io_service);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(tcp::resolver::query(host,port));
socket->connect(*endpoint_iterator, error);
if (error){ delete socket; throw "Can't establish connection :("; }
init();
}
CConnection::CConnection(
boost::asio::basic_stream_socket<boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp> > * Socket,
std::string Name,
std::ostream & Out )
:socket(Socket),io_service(&Socket->io_service()), out(Out), name(Name)//, send(this), rec(this)
{
init();
}
CConnection::CConnection(boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > * acceptor, boost::asio::io_service *Io_service, std::string Name, std::ostream & Out)
: out(Out), name(Name)//, send(this), rec(this)
{
boost::system::error_code error = asio::error::host_not_found;
socket = new tcp::socket(*io_service);
acceptor->accept(*socket,error);
if (error){ delete socket; throw "Can't establish connection :("; }
init();
}
int CConnection::write(const void * data, unsigned size)
{
LOG("Sending " << size << " byte(s) of data" <<std::endl);
int ret;
ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size)));
return ret;
}
int CConnection::read(void * data, unsigned size)
{
LOG("Receiving " << size << " byte(s) of data" <<std::endl);
int ret = asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size)));
return ret;
}
CConnection::~CConnection(void)
{
if(socket)
socket->close();
delete socket;
delete io_service;
delete wmx;
delete rmx;
}
template <>
void CConnection::saveSerializable<std::string>(const std::string &data)
{
*this << ui32(data.size());
write(data.c_str(),data.size());
}
template <>
void CConnection::loadSerializable<std::string>(std::string &data)
{
ui32 l;
*this >> l;
data.resize(l);
read((void*)data.c_str(),l);
}

382
lib/Connection.h Normal file
View File

@ -0,0 +1,382 @@
#pragma once
#include "../global.h"
#include <string>
#include <vector>
#include <set>
#include <boost/type_traits/is_fundamental.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/identity.hpp>
const int version = 63;
class CConnection;
namespace mpl = boost::mpl;
namespace boost
{
namespace asio
{
namespace ip
{
class tcp;
}
class io_service;
template <typename Protocol> class stream_socket_service;
template <typename Protocol,typename StreamSocketService>
class basic_stream_socket;
template <typename Protocol> class socket_acceptor_service;
template <typename Protocol,typename SocketAcceptorService>
class basic_socket_acceptor;
}
class mutex;
};
enum SerializationLvl
{
Wrong=0,
Primitive,
Pointer,
Serializable
};
template<typename T>
struct SerializationLevel
{
typedef mpl::integral_c_tag tag;
typedef
typename mpl::eval_if<
boost::is_fundamental<T>,
mpl::int_<Primitive>,
//else
typename mpl::eval_if<
boost::is_class<T>,
mpl::int_<Serializable>,
//else
typename mpl::eval_if<
boost::is_array<T>,
mpl::int_<Primitive>,
//else
typename mpl::eval_if<
boost::is_pointer<T>,
mpl::int_<Pointer>,
//else
typename mpl::eval_if<
boost::is_enum<T>,
mpl::int_<Primitive>,
//else
mpl::int_<Wrong>
>
>
>
>
>::type type;
static const int value = SerializationLevel::type::value;
};
template <typename Serializer> class DLL_EXPORT COSer
{
public:
bool saving;
COSer(){saving=true;};
Serializer * This()
{
return static_cast<Serializer*>(this);
}
template<class T>
Serializer & operator<<(const T &t)
{
this->This()->save(t);
return * this->This();
}
template<class T>
COSer & operator&(T & t){
return * this->This() << t;
}
};
template <typename Serializer> class DLL_EXPORT CISer
{
public:
bool saving;
CISer(){saving = false;};
Serializer * This()
{
return static_cast<Serializer*>(this);
}
template<class T>
Serializer & operator>>(T &t)
{
this->This()->load(t);
return * this->This();
}
template<class T>
CISer & operator&(T & t){
return * this->This() >> t;
}
};
template<typename Ser,typename T>
struct SavePrimitive
{
static void invoke(Ser &s, const T &data)
{
s.savePrimitive(data);
}
};
template<typename Ser,typename T>
struct SaveSerializable
{
static void invoke(Ser &s, const T &data)
{
s.saveSerializable(data);
}
};
template<typename Ser,typename T>
struct LoadPrimitive
{
static void invoke(Ser &s, T &data)
{
s.loadPrimitive(data);
}
};
template<typename Ser,typename T>
struct SavePointer
{
static void invoke(Ser &s, const T &data)
{
s.savePointer(data);
}
};
template<typename Ser,typename T>
struct LoadPointer
{
static void invoke(Ser &s, T &data)
{
s.loadPointer(data);
}
};
template<typename Ser,typename T>
struct LoadSerializable
{
static void invoke(Ser &s, T &data)
{
s.loadSerializable(data);
}
};
template<typename Ser,typename T>
struct SaveWrong
{
static void invoke(Ser &s, const T &data)
{
throw std::exception("Wrong save serialization call!");
}
};
template<typename Ser,typename T>
struct LoadWrong
{
static void invoke(Ser &s, const T &data)
{
throw std::exception("Wrong load serialization call!");
}
};
class DLL_EXPORT CConnection
:public CISer<CConnection>, public COSer<CConnection>
{
std::ostream &out;
CConnection(void);
void init();
public:
boost::mutex *rmx, *wmx; // read/write mutexes
template <typename T>
void savePrimitive(const T &data)
{
write(&data,sizeof(data));
}
template <typename T>
void loadPrimitive(T &data)
{
read(&data,sizeof(data));
}
template <typename T>
void saveSerializable(const T &data)
{
const_cast<T&>(data).serialize(*static_cast<COSer<CConnection>*>(this),version);
}
template <typename T>
void loadSerializable(T &data)
{
data.serialize(*static_cast<CISer<CConnection>*>(this),version);
}
template <typename T>
void savePointer(const T &data)
{
*this << *data;
}
template <typename T>
void loadPointer(T &data)
{
std::cout<<"Allocating memory for pointer!"<<std::endl;
typedef typename boost::remove_pointer<T>::type npT;
data = new npT;
*this >> *data;
}
template <typename T>
void saveSerializable(const std::vector<T> &data)
{
boost::uint32_t length = data.size();
*this << length;
for(ui32 i=0;i<length;i++)
*this << data[i];
}
template <typename T>
void loadSerializable(std::vector<T> &data)
{
boost::uint32_t length;
*this >> length;
data.resize(length);
for(ui32 i=0;i<length;i++)
*this >> data[i];
}
template <typename T>
void saveSerializable(const std::set<T> &data)
{
std::set<T> &d = const_cast<std::set<T> &>(data);
boost::uint32_t length = d.size();
*this << length;
for(typename std::set<T>::iterator i=d.begin();i!=d.end();i++)
*this << *i;
}
template <typename T>
void loadSerializable(std::set<T> &data)
{
boost::uint32_t length;
*this >> length;
T ins;
for(ui32 i=0;i<length;i++)
{
*this >> ins;
data.insert(ins);
}
}
template <typename T1, typename T2>
void saveSerializable(const std::pair<T1,T2> &data)
{
*this << data.first << data.second;
}
template <typename T1, typename T2>
void loadSerializable(std::pair<T1,T2> &data)
{
*this >> data.first >> data.second;
}
template <typename T1, typename T2>
void saveSerializable(const std::map<T1,T2> &data)
{
*this << ui32(data.size());
for(typename std::map<T1,T2>::const_iterator i=data.begin();i!=data.end();i++)
*this << i->first << i->second;
}
template <typename T1, typename T2>
void loadSerializable(std::map<T1,T2> &data)
{
ui32 length;
*this >> length;
T1 t;
for(int i=0;i<length;i++)
{
*this >> t;
*this >> data[t];
}
}
template <typename T>
void save(const T &data)
{
typedef
//if
typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
mpl::identity<SavePrimitive<CConnection,T> >,
//else if
typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
mpl::identity<SavePointer<CConnection,T> >,
//else if
typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
mpl::identity<SaveSerializable<CConnection,T> >,
//else
mpl::identity<SaveWrong<CConnection,T> >
>
>
>::type typex;
typex::invoke(*this, data);
}
template <typename T>
void load(T &data)
{
typedef
//if
typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
mpl::identity<LoadPrimitive<CConnection,T> >,
//else if
typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
mpl::identity<LoadPointer<CConnection,T> >,
//else if
typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
mpl::identity<LoadSerializable<CConnection,T> >,
//else
mpl::identity<LoadWrong<CConnection,T> >
>
>
>::type typex;
typex::invoke(*this, data);
}
boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp> > * socket;
bool logging;
bool connected;
bool myEndianess, contactEndianess; //true if little endian, if ednianess is different we'll have to revert recieved multi-byte vars
boost::asio::io_service *io_service;
std::string name; //who uses this connection
CConnection
(std::string host, std::string port, std::string Name, std::ostream & Out);
CConnection
(boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > * acceptor,
boost::asio::io_service *Io_service, std::string Name, std::ostream & Out);
CConnection
(boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp> > * Socket,
std::string Name, std::ostream & Out); //use immediately after accepting connection into socket
int write(const void * data, unsigned size);
int read(void * data, unsigned size);
int readLine(void * data, unsigned maxSize);
~CConnection(void);
};
template<> DLL_EXPORT
void CConnection::saveSerializable<std::string>(const std::string &data);
template <>DLL_EXPORT
void CConnection::loadSerializable<std::string>(std::string &data);

32
lib/Makefile.am Normal file
View File

@ -0,0 +1,32 @@
noinst_LIBRARIES = libvcmi.a
#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
#AM_CXXFLAGS = $(BOOST_CPPFLAGS)
libvcmi_a_SOURCES = \
../hch/CAmbarCendamo.cpp \
../hch/CArtHandler.cpp \
../hch/CBuildingHandler.cpp \
../hch/CCreatureHandler.cpp \
../hch/CDefObjInfoHandler.cpp \
../CGameState.cpp \
../hch/CHeroHandler.cpp \
../hch/CLodHandler.cpp \
../hch/CObjectHandler.cpp \
./Connection.cpp \
../hch/CTownHandler.cpp \
../map.cpp \
../stdafx.cpp \
./VCMI_Lib.cpp \
../hch/CAmbarCendamo.h \
../hch/CArtHandler.h \
../hch/CBuildingHandler.h \
../hch/CCreatureHandler.h \
../hch/CDefObjInfoHandler.h \
../CGameState.h \
../hch/CHeroHandler.h \
../hch/CLodHandler.h \
../hch/CObjectHandler.h \
./Connection.h \
../hch/CTownHandler.h \
../map.h \
./NetPacks.h \
./VCMI_Lib.h

337
lib/NetPacks.h Normal file
View File

@ -0,0 +1,337 @@
#include "../global.h"
struct IPack
{
virtual ui16 getType()const = 0 ;
//template<ui16 Type>
//static bool isType(const IPack * ip)
//{
// return Type == ip->getType();
//}
template<ui16 Type>
static bool isType(IPack * ip)
{
return Type == ip->getType();
}
//template<ui16 Type>
//static bool isType(const IPack & ip)
//{
// return Type == ip.getType();
//}
};
template <typename T> struct CPack
:public IPack
{
ui16 type;
ui16 getType() const{return type;}
T* This(){return static_cast<T*>(this);};
};
struct NewTurn : public CPack<NewTurn> //101
{
struct Hero
{
ui32 id, move, mana; //id is a general serial id
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & move & mana;
}
bool operator<(const Hero&h)const{return id < h.id;}
};
struct Resources
{
ui8 player;
si32 resources[RESOURCE_QUANTITY];
template <typename Handler> void serialize(Handler &h, const int version)
{
h & player & resources;
}
bool operator<(const Resources&h)const{return player < h.player;}
};
std::set<Hero> heroes; //updates movement and mana points
std::set<Resources> res;//resource list
ui32 day;
bool resetBuilded;
NewTurn(){type = 101;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & heroes & res & day & resetBuilded;
}
};
struct SetResource : public CPack<SetResource> //102
{
SetResource(){type = 102;};
ui8 player, resid;
si32 val;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & player & resid & val;
}
};
struct SetResources : public CPack<SetResources> //104
{
SetResources(){type = 104;};
ui8 player;
std::vector<si32> res; //res[resid] => res amount
template <typename Handler> void serialize(Handler &h, const int version)
{
h & player & res;
}
};
struct SetPrimSkill : public CPack<SetPrimSkill> //105
{
SetPrimSkill(){type = 105;};
ui8 abs; //0 - changes by value; 1 - sets to value
si32 id;
ui16 which, val;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & abs & id & which & val;
}
};
struct RemoveHero : public CPack<RemoveHero> //500
{
RemoveHero(){type = 500;};
RemoveHero(si32 ID){id = ID;type = 500;};
si32 id;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id;
}
};
struct TryMoveHero : public CPack<TryMoveHero> //501
{
TryMoveHero(){type = 501;};
ui32 id, movePoints;
ui8 result;
int3 start, end;
std::set<int3> fowRevealed; //revealed tiles
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & result & start & end & movePoints & fowRevealed;
}
};
struct SetGarrisons : public CPack<SetGarrisons> //502
{
SetGarrisons(){type = 502;};
std::map<ui32,CCreatureSet> garrs;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & garrs;
}
};
struct SetStrInfo : public CPack<SetStrInfo> //503
{
SetStrInfo(){type = 503;};
si32 tid;
std::map<si32,ui32> cres;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & tid & cres;
}
};
struct NewStructures : public CPack<NewStructures> //504
{
NewStructures(){type = 504;};
si32 tid;
std::set<si32> bid;
si16 builded;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & tid & bid & builded;
}
};
struct MetaString : public CPack<MetaString> //2001 helper for object scrips
{
std::vector<std::string> strings;
std::vector<std::pair<ui8,ui32> > texts; //pairs<text handler type, text number>; types: 1 - generaltexthandler->all; 2 - objh->xtrainfo; 3 - objh->names; 4 - objh->restypes; 5 - arth->artifacts[id].name; 6 - generaltexth->arraytxt; 7 - creh->creatures[os->subID].namePl; 8 - objh->creGens; 9 - objh->mines[ID].first; 10 - objh->mines[ID].second; 11 - objh->advobtxt
std::vector<si32> message;
std::vector<std::string> replacements;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & strings & texts & message & replacements;
}
MetaString& operator<<(const std::pair<ui8,ui32> &txt)
{
message.push_back(-((si32)texts.size())-1);
texts.push_back(txt);
return *this;
}
MetaString& operator<<(const std::string &txt)
{
message.push_back(strings.size()+1);
strings.push_back(txt);
return *this;
}
void clear()
{
strings.clear();
texts.clear();
message.clear();
}
MetaString(){type = 2001;};
};
struct Component : public CPack<Component> //2002 helper for object scrips informations
{
ui16 id, subtype; //ids: 0 - primskill; 1 - secskill; 2 - resource; 3 - creature; 4 - artifact; 5 - experience
si32 val; // + give; - take
si16 when; // 0 - now; +x - within x days; -x - per x days
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & subtype & val & when;
}
Component(){type = 2002;};
Component(ui16 Type, ui16 Subtype, si32 Val, si16 When):id(Type),subtype(Subtype),val(Val),when(When){type = 2002;};
};
struct InfoWindow : public CPack<InfoWindow> //103 - displays simple info window
{
MetaString text;
std::vector<Component> components;
ui8 player;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & text & components & player;
}
InfoWindow(){type = 103;};
};
struct SetObjectProperty : public CPack<SetObjectProperty>//1001
{
ui32 id;
ui8 what; //1 - owner; 2 - blockvis
ui32 val;
SetObjectProperty(){type = 1001;};
SetObjectProperty(ui32 ID, ui8 What, ui32 Val):id(ID),what(What),val(Val){type = 1001;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & what & val;
}
};
struct SetHoverName : public CPack<SetHoverName>//1002
{
ui32 id;
MetaString name;
SetHoverName(){type = 1002;};
SetHoverName(ui32 ID, MetaString& Name):id(ID),name(Name){type = 1002;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & name;
}
};
struct HeroLevelUp : public CPack<HeroLevelUp>//2000
{
si32 id;
ui8 primskill, level;
std::set<ui16> skills;
HeroLevelUp(){type = 2000;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & id & primskill & level & skills;
}
};
struct BattleInfo;
struct BattleStart : public CPack<BattleStart>//3000
{
BattleInfo * info;
BattleStart(){type = 3000;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & info;
}
};
struct BattleNextRound : public CPack<BattleNextRound>//3001
{
si32 round;
BattleNextRound(){type = 3001;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & round;
}
};
struct BattleSetActiveStack : public CPack<BattleSetActiveStack>//3002
{
ui32 stack;
BattleSetActiveStack(){type = 3002;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & stack;
}
};
struct BattleResult : public CPack<BattleResult>//3003
{
ui8 result; //0 - normal victory; 1 - escape; 2 - surrender
ui8 winner; //0 - attacker, 1 - defender, [2 - draw (should be possible?)]
std::set<std::pair<ui32,si32> > s1, s2; //first => casualties of attackers - set of pairs crid<>number
ui32 exp[2]; //exp for attacker and defender
std::set<ui32> artifacts; //artifacts taken from loser to winner
BattleResult(){type = 3003;};
template <typename Handler> void serialize(Handler &h, const int version)
{
h & result & winner & s1 & s2 & exp & artifacts;
}
};
struct BattleStackMoved : public CPack<BattleStackMoved>//3004
{
ui32 stack, tile;
ui8 flags;
BattleStackMoved(){flags = 0; type = 3004;};
bool startMoving()
{
return flags & 1;
}
bool endMoving()
{
return flags & 2;
}
template <typename Handler> void serialize(Handler &h, const int version)
{
h & stack & tile & flags;
}
};
struct ShowInInfobox : public CPack<ShowInInfobox> //107
{
ShowInInfobox(){type = 107;};
ui8 player;
Component c;
MetaString text;
template <typename Handler> void serialize(Handler &h, const int version)
{
h & player & c & text;
}
};

Some files were not shown because too many files have changed in this diff Show More