CPreGame.cpp 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662
  1. #include "StdInc.h"
  2. #include "CPreGame.h"
  3. #include <zlib.h>
  4. #include "../lib/CStopWatch.h"
  5. #include "UIFramework/SDL_Extensions.h"
  6. #include "CGameInfo.h"
  7. #include "UIFramework/CCursorHandler.h"
  8. #include "CAnimation.h"
  9. #include "CDefHandler.h"
  10. #include "../lib/CDefObjInfoHandler.h"
  11. #include "../lib/CGeneralTextHandler.h"
  12. #include "../lib/CLodHandler.h"
  13. #include "../lib/CTownHandler.h"
  14. #include "../lib/CHeroHandler.h"
  15. #include "../lib/CObjectHandler.h"
  16. #include "../lib/CCampaignHandler.h"
  17. #include "../lib/CCreatureHandler.h"
  18. #include "../lib/JsonNode.h"
  19. #include "CMusicHandler.h"
  20. #include "CVideoHandler.h"
  21. #include "Graphics.h"
  22. #include "../lib/Connection.h"
  23. #include "../lib/VCMIDirs.h"
  24. #include "../lib/map.h"
  25. #include "GUIClasses.h"
  26. #include "CPlayerInterface.h"
  27. #include "../CCallback.h"
  28. #include "CMessage.h"
  29. #include "../lib/CSpellHandler.h" /*for campaign bonuses*/
  30. #include "../lib/CArtHandler.h" /*for campaign bonuses*/
  31. #include "../lib/CBuildingHandler.h" /*for campaign bonuses*/
  32. #include "CBitmapHandler.h"
  33. #include "Client.h"
  34. #include "../lib/NetPacks.h"
  35. #include "../lib/RegisterTypes.h"
  36. #include "../lib/CThreadHelper.h"
  37. #include "CConfigHandler.h"
  38. #include "../lib/CFileUtility.h"
  39. #include "../lib/GameConstants.h"
  40. #include "UIFramework/CGuiHandler.h"
  41. #include "UIFramework/CIntObjectClasses.h"
  42. /*
  43. * CPreGame.cpp, part of VCMI engine
  44. *
  45. * Authors: listed in file AUTHORS in main folder
  46. *
  47. * License: GNU General Public License v2.0 or later
  48. * Full text of license available in license.txt file, in main folder
  49. *
  50. */
  51. namespace fs = boost::filesystem;
  52. using boost::bind;
  53. using boost::ref;
  54. #if _MSC_VER >= 1600
  55. //#define bind boost::bind
  56. //#define ref boost::ref
  57. #endif
  58. void startGame(StartInfo * options, CConnection *serv = NULL);
  59. CGPreGame * CGP = nullptr;
  60. ISelectionScreenInfo *SEL;
  61. static int playerColor; //if more than one player - applies to the first
  62. static std::string selectedName; //set when game is started/loaded
  63. struct EvilHlpStruct
  64. {
  65. CConnection *serv;
  66. StartInfo *sInfo;
  67. void reset(bool strong = true)
  68. {
  69. if(strong)
  70. {
  71. vstd::clear_pointer(serv);
  72. vstd::clear_pointer(sInfo);
  73. }
  74. else
  75. {
  76. serv = NULL;
  77. sInfo = NULL;
  78. }
  79. }
  80. } startingInfo;
  81. static void do_quit()
  82. {
  83. SDL_Event event;
  84. event.quit.type = SDL_QUIT;
  85. SDL_PushEvent(&event);
  86. }
  87. static CMapInfo *mapInfoFromGame()
  88. {
  89. CMapInfo *ret = new CMapInfo();
  90. CMapHeader *headerCopy = new CMapHeader(*LOCPLINT->cb->getMapHeader()); //will be deleted by CMapInfo d-tor
  91. ret->setHeader(headerCopy);
  92. return ret;
  93. }
  94. static void setPlayersFromGame()
  95. {
  96. playerColor = LOCPLINT->playerID;
  97. }
  98. static void swapPlayers(PlayerSettings &a, PlayerSettings &b)
  99. {
  100. std::swap(a.human, b.human);
  101. std::swap(a.name, b.name);
  102. if(a.human == 1)
  103. playerColor = a.color;
  104. else if(b.human == 1)
  105. playerColor = b.color;
  106. }
  107. void setPlayer(PlayerSettings &pset, unsigned player, const std::map<ui32, std::string> &playerNames)
  108. {
  109. if(vstd::contains(playerNames, player))
  110. pset.name = playerNames.find(player)->second;
  111. else
  112. pset.name = CGI->generaltexth->allTexts[468];//Computer
  113. pset.human = player;
  114. if(player == playerNames.begin()->first)
  115. playerColor = pset.color;
  116. }
  117. void updateStartInfo(std::string filename, StartInfo & sInfo, const CMapHeader * mapHeader, const std::map<ui32, std::string> &playerNames)
  118. {
  119. sInfo.playerInfos.clear();
  120. if(!filename.size())
  121. return;
  122. /*sInfo.playerInfos.resize(to->playerAmnt);*/
  123. sInfo.mapname = filename;
  124. playerColor = -1;
  125. std::map<ui32, std::string>::const_iterator namesIt = playerNames.begin();
  126. for (int i = 0; i < GameConstants::PLAYER_LIMIT; i++)
  127. {
  128. const PlayerInfo &pinfo = mapHeader->players[i];
  129. //neither computer nor human can play - no player
  130. if (!(pinfo.canComputerPlay || pinfo.canComputerPlay))
  131. continue;
  132. PlayerSettings &pset = sInfo.playerInfos[i];
  133. pset.color = i;
  134. if(pinfo.canHumanPlay && namesIt != playerNames.end())
  135. setPlayer(pset, namesIt++->first, playerNames);
  136. else
  137. setPlayer(pset, 0, playerNames);
  138. pset.castle = pinfo.defaultCastle();
  139. pset.hero = pinfo.defaultHero();
  140. if(pinfo.mainHeroName.length())
  141. {
  142. pset.heroName = pinfo.mainHeroName;
  143. if((pset.heroPortrait = pinfo.mainHeroPortrait) == 255)
  144. pset.heroPortrait = pinfo.p9;
  145. }
  146. pset.handicap = 0;
  147. }
  148. }
  149. template <typename T> class CApplyOnPG;
  150. class CBaseForPGApply
  151. {
  152. public:
  153. virtual void applyOnPG(CSelectionScreen *selScr, void *pack) const =0;
  154. virtual ~CBaseForPGApply(){};
  155. template<typename U> static CBaseForPGApply *getApplier(const U * t=NULL)
  156. {
  157. return new CApplyOnPG<U>;
  158. }
  159. };
  160. template <typename T> class CApplyOnPG : public CBaseForPGApply
  161. {
  162. public:
  163. void applyOnPG(CSelectionScreen *selScr, void *pack) const
  164. {
  165. T *ptr = static_cast<T*>(pack);
  166. ptr->apply(selScr);
  167. }
  168. };
  169. static CApplier<CBaseForPGApply> *applier = NULL;
  170. static CPicture* createPicture(const JsonNode& config)
  171. {
  172. return new CPicture(config["name"].String(), config["x"].Float(), config["y"].Float());
  173. }
  174. CMenuScreen::CMenuScreen(const JsonNode& configNode):
  175. config(configNode)
  176. {
  177. OBJ_CONSTRUCTION_CAPTURING_ALL;
  178. background = new CPicture(config["background"].String());
  179. if (config["scalable"].Bool())
  180. {
  181. if (background->bg->format->palette)
  182. background->convertToScreenBPP();
  183. background->scaleTo(Point(screen->w, screen->h));
  184. }
  185. pos = background->center();
  186. BOOST_FOREACH(const JsonNode& node, config["items"].Vector())
  187. menuNameToEntry.push_back(node["name"].String());
  188. BOOST_FOREACH(const JsonNode& node, config["images"].Vector())
  189. images.push_back(createPicture(node));
  190. //Hardcoded entry
  191. menuNameToEntry.push_back("credits");
  192. tabs = new CTabbedInt(boost::bind(&CMenuScreen::createTab, this, _1), CTabbedInt::DestroyFunc());
  193. tabs->type |= REDRAW_PARENT;
  194. }
  195. CIntObject * CMenuScreen::createTab(size_t index)
  196. {
  197. if (config["items"].Vector().size() == index)
  198. return new CreditsScreen();
  199. return new CMenuEntry(this, config["items"].Vector()[index]);
  200. }
  201. void CMenuScreen::showAll(SDL_Surface * to)
  202. {
  203. CIntObject::showAll(to);
  204. if (pos.h != to->h || pos.w != to->w)
  205. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  206. }
  207. void CMenuScreen::show(SDL_Surface * to)
  208. {
  209. if (!config["video"].isNull())
  210. CCS->videoh->update(config["video"]["x"].Float() + pos.x, config["video"]["y"].Float() + pos.y, to, true, false);
  211. CIntObject::show(to);
  212. }
  213. void CMenuScreen::activate()
  214. {
  215. CCS->musich->playMusic(musicBase::mainMenu, -1);
  216. if (!config["video"].isNull())
  217. CCS->videoh->open(config["video"]["name"].String());
  218. CIntObject::activate();
  219. }
  220. void CMenuScreen::deactivate()
  221. {
  222. if (!config["video"].isNull())
  223. CCS->videoh->close();
  224. CIntObject::deactivate();
  225. }
  226. void CMenuScreen::switchToTab(size_t index)
  227. {
  228. tabs->setActive(index);
  229. }
  230. //funciton for std::string -> boost::function conversion for main menu
  231. static boost::function<void()> genCommand(CMenuScreen* menu, std::vector<std::string> menuType, const std::string &string)
  232. {
  233. static const std::vector<std::string> commandType = boost::assign::list_of
  234. ("to")("campaigns")("start")("load")("exit")("highscores");
  235. static const std::vector<std::string> gameType = boost::assign::list_of
  236. ("single")("multi")("campaign")("tutorial");
  237. std::list<std::string> commands;
  238. boost::split(commands, string, boost::is_any_of("\t "));
  239. if (!commands.empty())
  240. {
  241. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  242. commands.pop_front();
  243. if (index > 3 || !commands.empty())
  244. {
  245. switch (index)
  246. {
  247. break; case 0://to - switch to another tab, if such tab exists
  248. {
  249. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  250. if ( index2 != menuType.size())
  251. return boost::bind(&CMenuScreen::switchToTab, menu, index2);
  252. }
  253. break; case 1://open campaign selection window
  254. {
  255. return boost::bind(&CGPreGame::openCampaignScreen, CGP, commands.front());
  256. }
  257. break; case 2://start
  258. {
  259. switch (std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  260. {
  261. case 0: return bind(&CGPreGame::openSel, CGP, CMenuScreen::newGame, CMenuScreen::SINGLE_PLAYER);
  262. case 1: return &pushIntT<CMultiMode>;
  263. case 2: return boost::bind(&CGPreGame::openSel, CGP, CMenuScreen::campaignList, CMenuScreen::SINGLE_PLAYER);
  264. case 3: return boost::function<void()>();//TODO: start tutorial
  265. }
  266. }
  267. break; case 3://load
  268. {
  269. switch (std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  270. {
  271. case 0: return boost::bind(&CGPreGame::openSel, CGP, CMenuScreen::loadGame, CMenuScreen::SINGLE_PLAYER);
  272. case 1: return boost::bind(&CGPreGame::openSel, CGP, CMenuScreen::loadGame, CMenuScreen::MULTI_HOT_SEAT);
  273. case 2: return boost::function<void()>();//TODO: load campaign
  274. case 3: return boost::function<void()>();//TODO: load tutorial
  275. }
  276. }
  277. break; case 4://exit
  278. {
  279. return boost::bind(CInfoWindow::showYesNoDialog, boost::ref(CGI->generaltexth->allTexts[69]), (const std::vector<CComponent*>*)0, do_quit, 0, false, 1);
  280. }
  281. break; case 5://highscores
  282. {
  283. return boost::function<void()>(); //TODO: high scores &pushIntT<CHighScores>;
  284. }
  285. }
  286. }
  287. }
  288. tlog0<<"Failed to parse command: "<<string<<"\n";
  289. return boost::function<void()>();
  290. }
  291. CAdventureMapButton* CMenuEntry::createButton(CMenuScreen* parent, const JsonNode& button)
  292. {
  293. boost::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  294. std::pair<std::string, std::string> help;
  295. if (!button["help"].isNull() && button["help"].Float() > 0)
  296. help = CGI->generaltexth->zelp[button["help"].Float()];
  297. int posx = button["x"].Float();
  298. if (posx < 0)
  299. posx = pos.w + posx;
  300. int posy = button["y"].Float();
  301. if (posy < 0)
  302. posy = pos.h + posy;
  303. return new CAdventureMapButton(help, command, posx, posy, button["name"].String(), button["hotkey"].Float());
  304. }
  305. CMenuEntry::CMenuEntry(CMenuScreen* parent, const JsonNode &config)
  306. {
  307. OBJ_CONSTRUCTION_CAPTURING_ALL;
  308. type |= REDRAW_PARENT;
  309. pos = parent->pos;
  310. BOOST_FOREACH(const JsonNode& node, config["images"].Vector())
  311. images.push_back(createPicture(node));
  312. BOOST_FOREACH(const JsonNode& node, config["buttons"].Vector())
  313. {
  314. buttons.push_back(createButton(parent, node));
  315. buttons.back()->hoverable = true;
  316. buttons.back()->type |= REDRAW_PARENT;
  317. }
  318. }
  319. CreditsScreen::CreditsScreen()
  320. {
  321. addUsedEvents(LCLICK | RCLICK);
  322. type |= REDRAW_PARENT;
  323. OBJ_CONSTRUCTION_CAPTURING_ALL;
  324. pos.w = CGP->menu->pos.w;
  325. pos.h = CGP->menu->pos.h;
  326. std::string text = bitmaph->getTextFile("CREDITS");
  327. size_t firstQuote = text.find('\"')+1;
  328. text = text.substr(firstQuote, text.find('\"', firstQuote) - firstQuote );
  329. credits = new CTextBox(text, Rect(pos.w - 350, 600, 350, 32000), 0, FONT_CREDITS, CENTER, Colors::Cornsilk);
  330. credits->pos.h = credits->maxH;
  331. }
  332. void CreditsScreen::showAll(SDL_Surface * to)
  333. {
  334. //Do not draw anything
  335. }
  336. void CreditsScreen::show(SDL_Surface * to)
  337. {
  338. static int count = 0;
  339. count++;
  340. if (count == 2)
  341. {
  342. credits->pos.y--;
  343. count = 0;
  344. }
  345. Rect creditsArea = credits->pos & pos;
  346. SDL_SetClipRect(screenBuf, &creditsArea);
  347. SDL_SetClipRect(screen, &creditsArea);
  348. redraw();
  349. CIntObject::showAll(to);
  350. SDL_SetClipRect(screen, NULL);
  351. SDL_SetClipRect(screenBuf, NULL);
  352. //end of credits, close this screen
  353. if (credits->pos.y + credits->pos.h < 0)
  354. clickRight(false, false);
  355. }
  356. void CreditsScreen::clickLeft(tribool down, bool previousState)
  357. {
  358. clickRight(down, previousState);
  359. }
  360. void CreditsScreen::clickRight(tribool down, bool previousState)
  361. {
  362. CTabbedInt* menu = dynamic_cast<CTabbedInt*>(parent);
  363. assert(menu);
  364. menu->setActive(0);
  365. }
  366. CGPreGame::CGPreGame():
  367. pregameConfig(new JsonNode(GameConstants::DATA_DIR + "/config/mainmenu.json"))
  368. {
  369. //OBJ_CONSTRUCTION_CAPTURING_ALL;
  370. GH.defActionsDef = 63;
  371. CGP = this;
  372. menu = new CMenuScreen((*pregameConfig)["window"]);
  373. loadGraphics();
  374. }
  375. CGPreGame::~CGPreGame()
  376. {
  377. disposeGraphics();
  378. }
  379. void CGPreGame::openSel(CMenuScreen::EState screenType, CMenuScreen::EMultiMode multi /*= CMenuScreen::SINGLE_PLAYER*/)
  380. {
  381. GH.pushInt(new CSelectionScreen(screenType, multi));
  382. }
  383. void CGPreGame::loadGraphics()
  384. {
  385. background = BitmapHandler::loadBitmap("DIBOXBCK");
  386. victory = CDefHandler::giveDef("SCNRVICT.DEF");
  387. loss = CDefHandler::giveDef("SCNRLOSS.DEF");
  388. bonuses = CDefHandler::giveDef("SCNRSTAR.DEF");
  389. rHero = BitmapHandler::loadBitmap("HPSRAND1.bmp");
  390. rTown = BitmapHandler::loadBitmap("HPSRAND0.bmp");
  391. nHero = BitmapHandler::loadBitmap("HPSRAND6.bmp");
  392. nTown = BitmapHandler::loadBitmap("HPSRAND5.bmp");
  393. }
  394. void CGPreGame::disposeGraphics()
  395. {
  396. delete victory;
  397. delete loss;
  398. SDL_FreeSurface(background);
  399. SDL_FreeSurface(rHero);
  400. SDL_FreeSurface(nHero);
  401. SDL_FreeSurface(rTown);
  402. SDL_FreeSurface(nTown);
  403. }
  404. void CGPreGame::update()
  405. {
  406. if (GH.listInt.empty())
  407. {
  408. GH.pushInt(this);
  409. GH.pushInt(menu);
  410. menu->switchToTab(0);
  411. }
  412. if(SEL)
  413. SEL->update();
  414. // Handles mouse and key input
  415. GH.updateTime();
  416. GH.handleEvents();
  417. if (GH.curInt == NULL) // no redraw, when a new game was created
  418. return;
  419. GH.topInt()->show(screen);
  420. if (settings["general"]["showfps"].Bool())
  421. GH.drawFPSCounter();
  422. // draw the mouse cursor and update the screen
  423. CCS->curh->draw1();
  424. CSDL_Ext::update(screen);
  425. CCS->curh->draw2();
  426. }
  427. void CGPreGame::showAll(SDL_Surface *to)
  428. {
  429. //fill screen with background texture
  430. for (int y=0; y<to->h; y+=background->h)
  431. {
  432. for (int x=0; x<to->w; x+=background->w)
  433. {
  434. blitAt(background, x, y, to);
  435. }
  436. }
  437. }
  438. void CGPreGame::openCampaignScreen(std::string name)
  439. {
  440. BOOST_FOREACH(const JsonNode& node, (*pregameConfig)["campaignsset"].Vector())
  441. {
  442. if (node["name"].String() == name)
  443. {
  444. GH.pushInt(new CCampaignScreen(node));
  445. return;
  446. }
  447. }
  448. tlog1<<"Unknown campaign set: "<<name<<"\n";
  449. }
  450. CGPreGame *CGPreGame::create()
  451. {
  452. if(!CGP)
  453. CGP = new CGPreGame();
  454. return CGP;
  455. }
  456. void CGPreGame::removeFromGui()
  457. {
  458. //remove everything but main menu and background
  459. GH.popInts(GH.listInt.size() - 2);
  460. GH.popInt(GH.topInt()); //remove main menu
  461. GH.popInt(GH.topInt()); //remove background
  462. }
  463. CSelectionScreen::CSelectionScreen(CMenuScreen::EState Type, CMenuScreen::EMultiMode MultiPlayer /*= CMenuScreen::SINGLE_PLAYER*/, const std::map<ui32, std::string> *Names /*= NULL*/)
  464. : ISelectionScreenInfo(Names), serverHandlingThread(NULL), mx(new boost::recursive_mutex),
  465. serv(NULL), ongoingClosing(false), myNameID(255)
  466. {
  467. CGPreGame::create(); //we depend on its graphics
  468. screenType = Type;
  469. multiPlayer = MultiPlayer;
  470. OBJ_CONSTRUCTION_CAPTURING_ALL;
  471. bool network = (MultiPlayer == CMenuScreen::MULTI_NETWORK_GUEST || MultiPlayer == CMenuScreen::MULTI_NETWORK_HOST);
  472. CServerHandler *sh = NULL;
  473. if(multiPlayer == CMenuScreen::MULTI_NETWORK_HOST)
  474. {
  475. sh = new CServerHandler;
  476. sh->startServer();
  477. }
  478. IShowActivatable::type = BLOCK_ADV_HOTKEYS;
  479. pos.w = 762;
  480. pos.h = 584;
  481. if(Type == CMenuScreen::saveGame)
  482. {
  483. bordered = false;
  484. center(pos);
  485. }
  486. else if(Type == CMenuScreen::campaignList)
  487. {
  488. bordered = false;
  489. bg = new CPicture(BitmapHandler::loadBitmap("CamCust.bmp"), 0, 0, true);
  490. pos = bg->center();
  491. }
  492. else
  493. {
  494. bordered = true;
  495. bg = new CPicture(BitmapHandler::loadBitmap(rand()%2 ? "ZPIC1000.bmp" : "ZPIC1001.bmp"), 0, 0, true);
  496. pos = bg->center();
  497. }
  498. sInfo.difficulty = 1;
  499. current = NULL;
  500. sInfo.mode = (Type == CMenuScreen::newGame ? StartInfo::NEW_GAME : StartInfo::LOAD_GAME);
  501. sInfo.turnTime = 0;
  502. curTab = NULL;
  503. card = new InfoCard(network); //right info card
  504. if (screenType == CMenuScreen::campaignList)
  505. {
  506. opt = NULL;
  507. }
  508. else
  509. {
  510. opt = new OptionsTab(); //scenario options tab
  511. opt->recActions = DISPOSE;
  512. }
  513. sel = new SelectionTab(screenType, bind(&CSelectionScreen::changeSelection, this, _1), multiPlayer); //scenario selection tab
  514. sel->recActions = DISPOSE;
  515. switch(screenType)
  516. {
  517. case CMenuScreen::newGame:
  518. {
  519. card->difficulty->onChange = bind(&CSelectionScreen::difficultyChange, this, _1);
  520. card->difficulty->select(1, 0);
  521. CAdventureMapButton *select = new CAdventureMapButton(CGI->generaltexth->zelp[45], bind(&CSelectionScreen::toggleTab, this, sel), 411, 80, "GSPBUTT.DEF", SDLK_s);
  522. select->addTextOverlay(CGI->generaltexth->allTexts[500], FONT_SMALL);
  523. CAdventureMapButton *opts = new CAdventureMapButton(CGI->generaltexth->zelp[46], bind(&CSelectionScreen::toggleTab, this, opt), 411, 510, "GSPBUTT.DEF", SDLK_a);
  524. opts->addTextOverlay(CGI->generaltexth->allTexts[501], FONT_SMALL);
  525. CAdventureMapButton *random = new CAdventureMapButton(CGI->generaltexth->zelp[47], bind(&CSelectionScreen::toggleTab, this, sel), 411, 105, "GSPBUTT.DEF", SDLK_r);
  526. random->addTextOverlay(CGI->generaltexth->allTexts[740], FONT_SMALL);
  527. start = new CAdventureMapButton(CGI->generaltexth->zelp[103], bind(&CSelectionScreen::startGame, this), 411, 535, "SCNRBEG.DEF", SDLK_b);
  528. if(network)
  529. {
  530. CAdventureMapButton *hideChat = new CAdventureMapButton(CGI->generaltexth->zelp[48], bind(&InfoCard::toggleChat, card), 619, 83, "GSPBUT2.DEF", SDLK_h);
  531. hideChat->addTextOverlay(CGI->generaltexth->allTexts[531], FONT_SMALL);
  532. if(multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  533. {
  534. SDL_Color orange = {232, 184, 32, 0};
  535. select->text->color = opts->text->color = random->text->color = orange;
  536. select->block(true);
  537. opts->block(true);
  538. random->block(true);
  539. start->block(true);
  540. }
  541. }
  542. }
  543. break;
  544. case CMenuScreen::loadGame:
  545. sel->recActions = 255;
  546. start = new CAdventureMapButton(CGI->generaltexth->zelp[103], bind(&CSelectionScreen::startGame, this), 411, 535, "SCNRLOD.DEF", SDLK_l);
  547. break;
  548. case CMenuScreen::saveGame:
  549. sel->recActions = 255;
  550. start = new CAdventureMapButton("", CGI->generaltexth->zelp[103].second, bind(&CSelectionScreen::startGame, this), 411, 535, "SCNRSAV.DEF");
  551. break;
  552. case CMenuScreen::campaignList:
  553. sel->recActions = 255;
  554. start = new CAdventureMapButton(std::pair<std::string, std::string>(), bind(&CSelectionScreen::startCampaign, this), 411, 535, "SCNRLOD.DEF", SDLK_b);
  555. break;
  556. }
  557. start->assignedKeys.insert(SDLK_RETURN);
  558. std::string backName;
  559. if(Type == CMenuScreen::campaignList)
  560. {
  561. backName = "SCNRBACK.DEF";
  562. }
  563. else
  564. {
  565. backName = "SCNRBACK.DEF";
  566. }
  567. back = new CAdventureMapButton("", CGI->generaltexth->zelp[105].second, bind(&CGuiHandler::popIntTotally, &GH, this), 581, 535, backName, SDLK_ESCAPE);
  568. if(network)
  569. {
  570. if(multiPlayer == CMenuScreen::MULTI_NETWORK_HOST)
  571. {
  572. assert(playerNames.size() == 1 && vstd::contains(playerNames, 1)); //TODO hot-seat/network combo
  573. serv = sh->connectToServer();
  574. *serv << (ui8) 4;
  575. myNameID = 1;
  576. }
  577. else
  578. {
  579. serv = CServerHandler::justConnectToServer();
  580. }
  581. *serv << playerNames.begin()->second;
  582. if(multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  583. {
  584. const CMapInfo *map;
  585. *serv >> myNameID >> map;
  586. serv->connectionID = myNameID;
  587. changeSelection(map);
  588. }
  589. else //host
  590. {
  591. if(current)
  592. {
  593. SelectMap sm(*current);
  594. *serv << &sm;
  595. UpdateStartOptions uso(sInfo);
  596. *serv << &uso;
  597. }
  598. }
  599. applier = new CApplier<CBaseForPGApply>;
  600. registerTypes4(*applier);
  601. serverHandlingThread = new boost::thread(&CSelectionScreen::handleConnection, this);
  602. }
  603. delete sh;
  604. }
  605. CSelectionScreen::~CSelectionScreen()
  606. {
  607. ongoingClosing = true;
  608. if(serv)
  609. {
  610. assert(serverHandlingThread);
  611. QuitMenuWithoutStarting qmws;
  612. *serv << &qmws;
  613. // while(!serverHandlingThread->timed_join(boost::posix_time::milliseconds(50)))
  614. // processPacks();
  615. serverHandlingThread->join();
  616. delete serverHandlingThread;
  617. }
  618. playerColor = -1;
  619. playerNames.clear();
  620. assert(!serv);
  621. vstd::clear_pointer(applier);
  622. delete mx;
  623. }
  624. void CSelectionScreen::toggleTab(CIntObject *tab)
  625. {
  626. if(multiPlayer == CMenuScreen::MULTI_NETWORK_HOST && serv)
  627. {
  628. PregameGuiAction pga;
  629. if(tab == curTab)
  630. pga.action = PregameGuiAction::NO_TAB;
  631. else if(tab == opt)
  632. pga.action = PregameGuiAction::OPEN_OPTIONS;
  633. else if(tab == sel)
  634. pga.action = PregameGuiAction::OPEN_SCENARIO_LIST;
  635. *serv << &pga;
  636. }
  637. if(curTab && curTab->active)
  638. {
  639. curTab->deactivate();
  640. curTab->recActions = DISPOSE;
  641. }
  642. if(curTab != tab)
  643. {
  644. tab->recActions = 255;
  645. tab->activate();
  646. curTab = tab;
  647. }
  648. else
  649. {
  650. curTab = NULL;
  651. };
  652. GH.totalRedraw();
  653. }
  654. void CSelectionScreen::changeSelection( const CMapInfo *to )
  655. {
  656. if(multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  657. {
  658. vstd::clear_pointer(current);
  659. }
  660. current = to;
  661. if(to && (screenType == CMenuScreen::loadGame ||
  662. screenType == CMenuScreen::saveGame))
  663. SEL->sInfo.difficulty = to->scenarioOpts->difficulty;
  664. if(screenType != CMenuScreen::campaignList)
  665. {
  666. updateStartInfo(to ? to->filename : "", sInfo, to ? to->mapHeader : NULL);
  667. }
  668. card->changeSelection(to);
  669. if(screenType != CMenuScreen::campaignList)
  670. {
  671. opt->recreate();
  672. }
  673. if(multiPlayer == CMenuScreen::MULTI_NETWORK_HOST && serv)
  674. {
  675. SelectMap sm(*to);
  676. *serv << &sm;
  677. UpdateStartOptions uso(sInfo);
  678. *serv << &uso;
  679. }
  680. }
  681. void CSelectionScreen::startCampaign()
  682. {
  683. if (SEL->current)
  684. {
  685. CCampaign * ourCampaign = CCampaignHandler::getCampaign(SEL->current->filename, SEL->current->lodCmpgn);
  686. CCampaignState * campState = new CCampaignState();
  687. campState->camp = ourCampaign;
  688. GH.pushInt( new CBonusSelection(campState) );
  689. }
  690. }
  691. void CSelectionScreen::startGame()
  692. {
  693. if(screenType == CMenuScreen::newGame)
  694. {
  695. //there must be at least one human player before game can be started
  696. std::map<int, PlayerSettings>::const_iterator i;
  697. for(i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  698. if(i->second.human)
  699. break;
  700. if(i == SEL->sInfo.playerInfos.end())
  701. {
  702. GH.pushInt(CInfoWindow::create(CGI->generaltexth->allTexts[530])); //You must position yourself prior to starting the game.
  703. return;
  704. }
  705. }
  706. if(multiPlayer == CMenuScreen::MULTI_NETWORK_HOST)
  707. {
  708. start->block(true);
  709. StartWithCurrentSettings swcs;
  710. *serv << &swcs;
  711. ongoingClosing = true;
  712. return;
  713. }
  714. if(screenType != CMenuScreen::saveGame)
  715. {
  716. if(!current)
  717. return;
  718. selectedName = sInfo.mapname;
  719. StartInfo *si = new StartInfo(sInfo);
  720. CGP->removeFromGui();
  721. //SEL->current = NULL;
  722. //curOpts = NULL;
  723. ::startGame(si);
  724. }
  725. else
  726. {
  727. if(!(sel && sel->txt && sel->txt->text.size()))
  728. return;
  729. selectedName = GVCMIDirs.UserPath + "/Games/" + sel->txt->text + ".vlgm1";
  730. CFunctionList<void()> overWrite;
  731. overWrite += boost::bind(&CCallback::save, LOCPLINT->cb, sel->txt->text);
  732. overWrite += bind(&CGuiHandler::popIntTotally, &GH, this);
  733. if(fs::exists(selectedName))
  734. {
  735. std::string hlp = CGI->generaltexth->allTexts[493]; //%s exists. Overwrite?
  736. boost::algorithm::replace_first(hlp, "%s", sel->txt->text);
  737. LOCPLINT->showYesNoDialog(hlp, overWrite, 0, false);
  738. }
  739. else
  740. overWrite();
  741. // LOCPLINT->cb->save(sel->txt->text);
  742. // GH.popIntTotally(this);
  743. }
  744. }
  745. void CSelectionScreen::difficultyChange( int to )
  746. {
  747. assert(screenType == CMenuScreen::newGame);
  748. sInfo.difficulty = to;
  749. propagateOptions();
  750. redraw();
  751. }
  752. void CSelectionScreen::handleConnection()
  753. {
  754. setThreadName(-1, "CSelectionScreen::handleConnection");
  755. try
  756. {
  757. assert(serv);
  758. while(serv)
  759. {
  760. CPackForSelectionScreen *pack = NULL;
  761. *serv >> pack;
  762. assert(pack);
  763. if(QuitMenuWithoutStarting *endingPack = dynamic_cast<QuitMenuWithoutStarting *>(pack))
  764. {
  765. endingPack->apply(this);
  766. }
  767. else if(StartWithCurrentSettings *endingPack = dynamic_cast<StartWithCurrentSettings *>(pack))
  768. {
  769. endingPack->apply(this);
  770. }
  771. else
  772. {
  773. boost::unique_lock<boost::recursive_mutex> lll(*mx);
  774. upcomingPacks.push_back(pack);
  775. }
  776. }
  777. } HANDLE_EXCEPTION
  778. catch(int i)
  779. {
  780. if(i != 666)
  781. throw;
  782. }
  783. }
  784. void CSelectionScreen::setSInfo(const StartInfo &si)
  785. {
  786. std::map<int, PlayerSettings>::const_iterator i;
  787. for(i = si.playerInfos.begin(); i != si.playerInfos.end(); i++)
  788. {
  789. if(i->second.human == myNameID)
  790. {
  791. playerColor = i->first;
  792. break;
  793. }
  794. }
  795. if(i == si.playerInfos.end()) //not found
  796. playerColor = -1;
  797. sInfo = si;
  798. if(current)
  799. opt->recreate(); //will force to recreate using current sInfo
  800. card->difficulty->select(si.difficulty, 0);
  801. GH.totalRedraw();
  802. }
  803. void CSelectionScreen::processPacks()
  804. {
  805. boost::unique_lock<boost::recursive_mutex> lll(*mx);
  806. while(upcomingPacks.size())
  807. {
  808. CPackForSelectionScreen *pack = upcomingPacks.front();
  809. upcomingPacks.pop_front();
  810. CBaseForPGApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  811. apply->applyOnPG(this, pack);
  812. delete pack;
  813. }
  814. }
  815. void CSelectionScreen::update()
  816. {
  817. if(serverHandlingThread)
  818. processPacks();
  819. }
  820. void CSelectionScreen::propagateOptions()
  821. {
  822. if(isHost() && serv)
  823. {
  824. UpdateStartOptions ups(sInfo);
  825. *serv << &ups;
  826. }
  827. }
  828. void CSelectionScreen::postRequest(ui8 what, ui8 dir)
  829. {
  830. if(!isGuest() || !serv)
  831. return;
  832. RequestOptionsChange roc(what, dir, myNameID);
  833. *serv << &roc;
  834. }
  835. void CSelectionScreen::postChatMessage(const std::string &txt)
  836. {
  837. assert(serv);
  838. ChatMessage cm;
  839. cm.message = txt;
  840. cm.playerName = sInfo.getPlayersSettings(myNameID)->name;
  841. *serv << &cm;
  842. }
  843. void CSelectionScreen::propagateNames()
  844. {
  845. PlayersNames pn;
  846. pn.playerNames = playerNames;
  847. *serv << &pn;
  848. }
  849. void CSelectionScreen::showAll(SDL_Surface *to)
  850. {
  851. CIntObject::showAll(to);
  852. if (bordered && (pos.h != to->h || pos.w != to->w))
  853. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  854. }
  855. // A new size filter (Small, Medium, ...) has been selected. Populate
  856. // selMaps with the relevant data.
  857. void SelectionTab::filter( int size, bool selectFirst )
  858. {
  859. curItems.clear();
  860. if(tabType == CMenuScreen::campaignList)
  861. {
  862. for (size_t i=0; i<allItems.size(); i++)
  863. curItems.push_back(&allItems[i]);
  864. }
  865. else
  866. {
  867. for (size_t i=0; i<allItems.size(); i++)
  868. if( allItems[i].mapHeader && allItems[i].mapHeader->version && (!size || allItems[i].mapHeader->width == size))
  869. curItems.push_back(&allItems[i]);
  870. }
  871. if(curItems.size())
  872. {
  873. slider->block(false);
  874. slider->setAmount(curItems.size());
  875. sort();
  876. if(selectFirst)
  877. {
  878. slider->moveTo(0);
  879. onSelect(curItems[0]);
  880. }
  881. selectAbs(0);
  882. }
  883. else
  884. {
  885. slider->block(true);
  886. onSelect(NULL);
  887. }
  888. }
  889. void SelectionTab::getFiles(std::vector<FileInfo> &out, const std::string &dirname, const std::string &ext)
  890. {
  891. CFileUtility::getFilesWithExt(out, dirname, ext);
  892. allItems.resize(out.size());
  893. }
  894. void SelectionTab::parseMaps(std::vector<FileInfo> &files, int start, int threads)
  895. {
  896. int read=0;
  897. ui8 mapBuffer[1500];
  898. while(start < allItems.size())
  899. {
  900. gzFile tempf = gzopen(files[start].name.c_str(),"rb");
  901. read = gzread(tempf, mapBuffer, 1500);
  902. gzclose(tempf);
  903. if(read < 50 || !mapBuffer[4])
  904. {
  905. tlog3 << "\t\tWarning: corrupted map file: " << files[start].name << std::endl;
  906. }
  907. else //valid map
  908. {
  909. allItems[start].mapInit(files[start].name, mapBuffer);
  910. //allItems[start].date = "DATEDATE";// files[start].date;
  911. }
  912. start += threads;
  913. }
  914. }
  915. void SelectionTab::parseGames(std::vector<FileInfo> &files, bool multi)
  916. {
  917. for(int i=0; i<files.size(); i++)
  918. {
  919. try
  920. {
  921. CLoadFile lf(files[i].name);
  922. ui8 sign[8];
  923. lf >> sign;
  924. if(std::memcmp(sign,"VCMISVG",7))
  925. throw std::runtime_error("not a correct savefile!");
  926. allItems[i].mapHeader = new CMapHeader();
  927. lf >> *(allItems[i].mapHeader) >> allItems[i].scenarioOpts;
  928. allItems[i].filename = files[i].name;
  929. allItems[i].countPlayers();
  930. allItems[i].date = std::asctime(std::localtime(&files[i].date));
  931. if((allItems[i].actualHumanPlayers > 1) != multi) //if multi mode then only multi games, otherwise single
  932. {
  933. vstd::clear_pointer(allItems[i].mapHeader);
  934. }
  935. }
  936. catch(std::exception &e)
  937. {
  938. vstd::clear_pointer(allItems[i].mapHeader);
  939. tlog3 << "Failed to process " << files[i].name <<": " << e.what() << std::endl;
  940. }
  941. }
  942. }
  943. void SelectionTab::parseCampaigns( std::vector<FileInfo> & files )
  944. {
  945. for(int i=0; i<files.size(); i++)
  946. {
  947. //allItems[i].date = std::asctime(std::localtime(&files[i].date));
  948. allItems[i].filename = files[i].name;
  949. allItems[i].lodCmpgn = files[i].inLod;
  950. allItems[i].campaignInit();
  951. }
  952. }
  953. SelectionTab::SelectionTab(CMenuScreen::EState Type, const boost::function<void(CMapInfo *)> &OnSelect, CMenuScreen::EMultiMode MultiPlayer /*= CMenuScreen::SINGLE_PLAYER*/)
  954. :bg(NULL), onSelect(OnSelect)
  955. {
  956. OBJ_CONSTRUCTION;
  957. selectionPos = 0;
  958. addUsedEvents(LCLICK | WHEEL | KEYBOARD | DOUBLECLICK);
  959. slider = NULL;
  960. txt = NULL;
  961. tabType = Type;
  962. if (Type != CMenuScreen::campaignList)
  963. {
  964. bg = new CPicture("SCSELBCK.bmp", 0, 6);
  965. pos = bg->pos;
  966. }
  967. else
  968. {
  969. bg = nullptr; //use background from parent
  970. pos.w = parent->pos.w;
  971. pos.h = parent->pos.h;
  972. pos.x += 3; pos.y += 6;
  973. }
  974. if(MultiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  975. {
  976. positions = 18;
  977. }
  978. else
  979. {
  980. std::vector<FileInfo> toParse;
  981. std::vector<CCampaignHeader> cpm;
  982. switch(tabType)
  983. {
  984. case CMenuScreen::newGame:
  985. getFiles(toParse, GameConstants::DATA_DIR + "/Maps", "h3m"); //get all maps
  986. /* Load maps from user directory too, unless it is also the
  987. * same as the data directory (as is the case on
  988. * windows). */
  989. if (GVCMIDirs.UserPath != GameConstants::DATA_DIR)
  990. getFiles(toParse, GVCMIDirs.UserPath + "/Maps", "h3m"); //get all maps
  991. parseMaps(toParse);
  992. positions = 18;
  993. break;
  994. case CMenuScreen::loadGame:
  995. case CMenuScreen::saveGame:
  996. getFiles(toParse, GVCMIDirs.UserPath + "/Games", "vlgm1"); //get all saves
  997. parseGames(toParse, MultiPlayer);
  998. if(tabType == CMenuScreen::loadGame)
  999. {
  1000. positions = 18;
  1001. }
  1002. else
  1003. {
  1004. positions = 16;
  1005. }
  1006. if(tabType == CMenuScreen::saveGame)
  1007. txt = new CTextInput(Rect(32, 539, 350, 20), Point(-32, -25), "GSSTRIP.bmp", 0);
  1008. break;
  1009. case CMenuScreen::campaignList:
  1010. getFiles(toParse, GameConstants::DATA_DIR + "/Maps", "h3c"); //get all campaigns
  1011. /* Load campaingns from user directory too, unless it is also the
  1012. * same as the data directory (as is the case on
  1013. * windows). */
  1014. if (GVCMIDirs.UserPath != GameConstants::DATA_DIR)
  1015. getFiles(toParse, GVCMIDirs.UserPath + "/Maps", "h3c"); //get all maps
  1016. for (int g=0; g<toParse.size(); ++g)
  1017. {
  1018. toParse[g].inLod = false;
  1019. }
  1020. //add lod cmpgns
  1021. cpm = CCampaignHandler::getCampaignHeaders(CCampaignHandler::Custom);
  1022. for (int g = 0; g < cpm.size(); g++)
  1023. {
  1024. FileInfo fi;
  1025. fi.inLod = cpm[g].loadFromLod;
  1026. fi.name = cpm[g].filename;
  1027. if (cpm[g].loadFromLod)
  1028. {
  1029. toParse.push_back(fi);
  1030. allItems.push_back(CMapInfo(false));
  1031. }
  1032. }
  1033. parseCampaigns(toParse);
  1034. positions = 18;
  1035. break;
  1036. default:
  1037. assert(0);
  1038. break;
  1039. }
  1040. }
  1041. if (tabType != CMenuScreen::campaignList)
  1042. {
  1043. //size filter buttons
  1044. {
  1045. int sizes[] = {36, 72, 108, 144, 0};
  1046. const char * names[] = {"SCSMBUT.DEF", "SCMDBUT.DEF", "SCLGBUT.DEF", "SCXLBUT.DEF", "SCALBUT.DEF"};
  1047. for(int i = 0; i < 5; i++)
  1048. new CAdventureMapButton("", CGI->generaltexth->zelp[54+i].second, bind(&SelectionTab::filter, this, sizes[i], true), 158 + 47*i, 46, names[i]);
  1049. }
  1050. //sort buttons buttons
  1051. {
  1052. int xpos[] = {23, 55, 88, 121, 306, 339};
  1053. const char * names[] = {"SCBUTT1.DEF", "SCBUTT2.DEF", "SCBUTCP.DEF", "SCBUTT3.DEF", "SCBUTT4.DEF", "SCBUTT5.DEF"};
  1054. for(int i = 0; i < 6; i++)
  1055. new CAdventureMapButton("", CGI->generaltexth->zelp[107+i].second, bind(&SelectionTab::sortBy, this, i), xpos[i], 86, names[i]);
  1056. }
  1057. }
  1058. else
  1059. {
  1060. //sort by buttons
  1061. new CAdventureMapButton("", "", bind(&SelectionTab::sortBy, this, _numOfMaps), 23, 86, "CamCusM.DEF"); //by num of maps
  1062. new CAdventureMapButton("", "", bind(&SelectionTab::sortBy, this, _name), 55, 86, "CamCusL.DEF"); //by name
  1063. }
  1064. slider = new CSlider(372, 86, tabType != CMenuScreen::saveGame ? 480 : 430, bind(&SelectionTab::sliderMove, this, _1), positions, curItems.size(), 0, false, 1);
  1065. slider->addUsedEvents(WHEEL);
  1066. slider->slider->keepFrame = true;
  1067. format = CDefHandler::giveDef("SCSELC.DEF");
  1068. sortingBy = _format;
  1069. ascending = true;
  1070. filter(0);
  1071. //select(0);
  1072. switch(tabType)
  1073. {
  1074. case CMenuScreen::newGame:
  1075. selectFName(GameConstants::DATA_DIR + "/Maps/Arrogance.h3m");
  1076. break;
  1077. case CMenuScreen::loadGame:
  1078. case CMenuScreen::campaignList:
  1079. select(0);
  1080. break;
  1081. case CMenuScreen::saveGame:;
  1082. if(selectedName.size())
  1083. {
  1084. if(selectedName[2] == 'M') //name starts with ./Maps instead of ./Games => there was nothing to select
  1085. txt->setText("NEWGAME");
  1086. else
  1087. selectFName(selectedName);
  1088. }
  1089. }
  1090. }
  1091. SelectionTab::~SelectionTab()
  1092. {
  1093. delete format;
  1094. }
  1095. void SelectionTab::sortBy( int criteria )
  1096. {
  1097. if(criteria == sortingBy)
  1098. {
  1099. ascending = !ascending;
  1100. }
  1101. else
  1102. {
  1103. sortingBy = (ESortBy)criteria;
  1104. ascending = true;
  1105. }
  1106. sort();
  1107. selectAbs(0);
  1108. }
  1109. void SelectionTab::sort()
  1110. {
  1111. if(sortingBy != _name)
  1112. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(_name));
  1113. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  1114. if(!ascending)
  1115. std::reverse(curItems.begin(), curItems.end());
  1116. redraw();
  1117. }
  1118. void SelectionTab::select( int position )
  1119. {
  1120. if(!curItems.size()) return;
  1121. // New selection. py is the index in curItems.
  1122. int py = position + slider->value;
  1123. vstd::amax(py, 0);
  1124. vstd::amin(py, curItems.size()-1);
  1125. selectionPos = py;
  1126. if(position < 0)
  1127. slider->moveTo(slider->value + position);
  1128. else if(position >= positions)
  1129. slider->moveTo(slider->value + position - positions + 1);
  1130. if(txt)
  1131. txt->setText(fs::basename(curItems[py]->filename));
  1132. onSelect(curItems[py]);
  1133. }
  1134. void SelectionTab::selectAbs( int position )
  1135. {
  1136. select(position - slider->value);
  1137. }
  1138. int SelectionTab::getPosition( int x, int y )
  1139. {
  1140. return -1;
  1141. }
  1142. void SelectionTab::sliderMove( int slidPos )
  1143. {
  1144. if(!slider) return; //ignore spurious call when slider is being created
  1145. redraw();
  1146. }
  1147. // Display the tab with the scenario names
  1148. //
  1149. // elemIdx is the index of the maps or saved game to display on line 0
  1150. // slider->capacity contains the number of available screen lines
  1151. // slider->positionsAmnt is the number of elements after filtering
  1152. void SelectionTab::printMaps(SDL_Surface *to)
  1153. {
  1154. int elemIdx = slider->value;
  1155. // Display all elements if there's enough space
  1156. //if(slider->amount < slider->capacity)
  1157. // elemIdx = 0;
  1158. SDL_Color itemColor;
  1159. #define POS(xx, yy) pos.x + xx, pos.y + yy + line*25
  1160. for (int line = 0; line < positions && elemIdx < curItems.size(); elemIdx++, line++)
  1161. {
  1162. CMapInfo *currentItem = curItems[elemIdx];
  1163. if (elemIdx == selectionPos)
  1164. itemColor=Colors::Jasmine;
  1165. else
  1166. itemColor=Colors::Cornsilk;
  1167. if(tabType != CMenuScreen::campaignList)
  1168. {
  1169. //amount of players
  1170. std::ostringstream ostr(std::ostringstream::out);
  1171. ostr << currentItem->playerAmnt << "/" << currentItem->humenPlayers;
  1172. CSDL_Ext::printAt(ostr.str(), POS(29, 120), FONT_SMALL, itemColor, to);
  1173. //map size
  1174. std::string temp2 = "C";
  1175. switch (currentItem->mapHeader->width)
  1176. {
  1177. case 36:
  1178. temp2="S";
  1179. break;
  1180. case 72:
  1181. temp2="M";
  1182. break;
  1183. case 108:
  1184. temp2="L";
  1185. break;
  1186. case 144:
  1187. temp2="XL";
  1188. break;
  1189. }
  1190. CSDL_Ext::printAtMiddle(temp2, POS(70, 128), FONT_SMALL, itemColor, to);
  1191. int temp=-1;
  1192. switch (currentItem->mapHeader->version)
  1193. {
  1194. case CMapHeader::RoE:
  1195. temp=0;
  1196. break;
  1197. case CMapHeader::AB:
  1198. temp=1;
  1199. break;
  1200. case CMapHeader::SoD:
  1201. temp=2;
  1202. break;
  1203. case CMapHeader::WoG:
  1204. temp=3;
  1205. break;
  1206. default:
  1207. // Unknown version. Be safe and ignore that map
  1208. tlog2 << "Warning: " << currentItem->filename << " has wrong version!\n";
  1209. continue;
  1210. }
  1211. blitAt(format->ourImages[temp].bitmap, POS(88, 117), to);
  1212. //victory conditions
  1213. if (currentItem->mapHeader->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  1214. temp = 11;
  1215. else
  1216. temp = currentItem->mapHeader->victoryCondition.condition;
  1217. blitAt(CGP->victory->ourImages[temp].bitmap, POS(306, 117), to);
  1218. //loss conditions
  1219. if (currentItem->mapHeader->lossCondition.typeOfLossCon == ELossConditionType::LOSSSTANDARD)
  1220. temp=3;
  1221. else
  1222. temp=currentItem->mapHeader->lossCondition.typeOfLossCon;
  1223. blitAt(CGP->loss->ourImages[temp].bitmap, POS(339, 117), to);
  1224. }
  1225. else //if campaign
  1226. {
  1227. //number of maps in campaign
  1228. std::ostringstream ostr(std::ostringstream::out);
  1229. ostr << CGI->generaltexth->campaignRegionNames[ currentItem->campaignHeader->mapVersion ].size();
  1230. CSDL_Ext::printAt(ostr.str(), POS(29, 120), FONT_SMALL, itemColor, to);
  1231. }
  1232. std::string name;
  1233. if(tabType == CMenuScreen::newGame)
  1234. {
  1235. if (!currentItem->mapHeader->name.length())
  1236. currentItem->mapHeader->name = "Unnamed";
  1237. name = currentItem->mapHeader->name;
  1238. }
  1239. else if(tabType == CMenuScreen::campaignList)
  1240. {
  1241. name = currentItem->campaignHeader->name;
  1242. }
  1243. else
  1244. {
  1245. name = fs::basename(currentItem->filename);
  1246. }
  1247. //print name
  1248. CSDL_Ext::printAtMiddle(CSDL_Ext::trimToFit(name, 185, FONT_SMALL), POS(213, 128), FONT_SMALL, itemColor, to);
  1249. }
  1250. #undef POS
  1251. }
  1252. void SelectionTab::showAll(SDL_Surface * to)
  1253. {
  1254. CIntObject::showAll(to);
  1255. printMaps(to);
  1256. std::string title;
  1257. switch(tabType) {
  1258. case CMenuScreen::newGame:
  1259. title = CGI->generaltexth->arraytxt[229];
  1260. break;
  1261. case CMenuScreen::loadGame:
  1262. title = CGI->generaltexth->arraytxt[230];
  1263. break;
  1264. case CMenuScreen::saveGame:
  1265. title = CGI->generaltexth->arraytxt[231];
  1266. break;
  1267. case CMenuScreen::campaignList:
  1268. title = "Select a Campaign"; //TODO: find where is the title
  1269. break;
  1270. }
  1271. CSDL_Ext::printAtMiddle(title, pos.x+205, pos.y+28, FONT_MEDIUM, Colors::Jasmine, to); //Select a Scenario to Play
  1272. if(tabType != CMenuScreen::campaignList)
  1273. {
  1274. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[510], pos.x+87, pos.y+62, FONT_SMALL, Colors::Jasmine, to); //Map sizes
  1275. }
  1276. }
  1277. void SelectionTab::clickLeft( tribool down, bool previousState )
  1278. {
  1279. if(down)
  1280. {
  1281. int line = getLine();
  1282. if(line != -1)
  1283. select(line);
  1284. }
  1285. }
  1286. void SelectionTab::keyPressed( const SDL_KeyboardEvent & key )
  1287. {
  1288. if(key.state != SDL_PRESSED) return;
  1289. int moveBy = 0;
  1290. switch(key.keysym.sym)
  1291. {
  1292. case SDLK_UP:
  1293. moveBy = -1;
  1294. break;
  1295. case SDLK_DOWN:
  1296. moveBy = +1;
  1297. break;
  1298. case SDLK_PAGEUP:
  1299. moveBy = -positions+1;
  1300. break;
  1301. case SDLK_PAGEDOWN:
  1302. moveBy = +positions-1;
  1303. break;
  1304. case SDLK_HOME:
  1305. select(-slider->value);
  1306. return;
  1307. case SDLK_END:
  1308. select(curItems.size() - slider->value);
  1309. return;
  1310. default:
  1311. return;
  1312. }
  1313. select(selectionPos - slider->value + moveBy);
  1314. }
  1315. void SelectionTab::onDoubleClick()
  1316. {
  1317. if(getLine() != -1) //double clicked scenarios list
  1318. {
  1319. //act as if start button was pressed
  1320. (static_cast<CSelectionScreen*>(parent))->start->callback();
  1321. }
  1322. }
  1323. int SelectionTab::getLine()
  1324. {
  1325. int line = -1;
  1326. Point clickPos(GH.current->button.x, GH.current->button.y);
  1327. clickPos = clickPos - pos.topLeft();
  1328. if (clickPos.y > 115 && clickPos.y < 564 && clickPos.x > 22 && clickPos.x < 371)
  1329. {
  1330. line = (clickPos.y-115) / 25; //which line
  1331. }
  1332. return line;
  1333. }
  1334. void SelectionTab::selectFName( const std::string &fname )
  1335. {
  1336. for(int i = curItems.size() - 1; i >= 0; i--)
  1337. {
  1338. if(curItems[i]->filename == fname)
  1339. {
  1340. slider->moveTo(i);
  1341. selectAbs(i);
  1342. return;
  1343. }
  1344. }
  1345. selectAbs(0);
  1346. }
  1347. CChatBox::CChatBox(const Rect &rect)
  1348. {
  1349. OBJ_CONSTRUCTION;
  1350. pos += rect;
  1351. addUsedEvents(KEYBOARD);
  1352. captureAllKeys = true;
  1353. const int height = graphics->fonts[FONT_SMALL]->height;
  1354. inputBox = new CTextInput(Rect(0, rect.h - height, rect.w, height));
  1355. inputBox->removeUsedEvents(KEYBOARD);
  1356. chatHistory = new CTextBox("", Rect(0, 0, rect.w, rect.h - height), 1);
  1357. SDL_Color green = {0,252,0, SDL_ALPHA_OPAQUE};
  1358. chatHistory->color = green;
  1359. }
  1360. void CChatBox::keyPressed(const SDL_KeyboardEvent & key)
  1361. {
  1362. if(key.keysym.sym == SDLK_RETURN && key.state == SDL_PRESSED && inputBox->text.size())
  1363. {
  1364. SEL->postChatMessage(inputBox->text);
  1365. inputBox->setText("");
  1366. }
  1367. else
  1368. inputBox->keyPressed(key);
  1369. }
  1370. void CChatBox::addNewMessage(const std::string &text)
  1371. {
  1372. chatHistory->setTxt(chatHistory->text + text + "\n");
  1373. if(chatHistory->slider)
  1374. chatHistory->slider->moveToMax();
  1375. }
  1376. InfoCard::InfoCard( bool Network )
  1377. : bg(NULL), network(Network), chatOn(false), chat(NULL), playerListBg(NULL),
  1378. difficulty(NULL), sizes(NULL), sFlags(NULL)
  1379. {
  1380. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1381. pos.x += 393;
  1382. pos.y += 6;
  1383. addUsedEvents(RCLICK);
  1384. mapDescription = NULL;
  1385. Rect descriptionRect(26, 149, 320, 115);
  1386. mapDescription = new CTextBox("", descriptionRect, 1);
  1387. if(SEL->screenType == CMenuScreen::campaignList)
  1388. {
  1389. CSelectionScreen *ss = static_cast<CSelectionScreen*>(parent);
  1390. mapDescription->addChild(new CPicture(*ss->bg, descriptionRect + Point(-393, 0)), true); //move subpicture bg to our description control (by default it's our (Infocard) child)
  1391. }
  1392. else
  1393. {
  1394. bg = new CPicture("GSELPOP1.bmp", 0, 0);
  1395. parent->addChild(bg);
  1396. auto it = vstd::find(parent->children, this); //our position among parent children
  1397. parent->children.insert(it, bg); //put BG before us
  1398. parent->children.pop_back();
  1399. pos.w = bg->pos.w;
  1400. pos.h = bg->pos.h;
  1401. sizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
  1402. sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
  1403. difficulty = new CHighlightableButtonsGroup(0);
  1404. {
  1405. static const char *difButns[] = {"GSPBUT3.DEF", "GSPBUT4.DEF", "GSPBUT5.DEF", "GSPBUT6.DEF", "GSPBUT7.DEF"};
  1406. for(int i = 0; i < 5; i++)
  1407. {
  1408. difficulty->addButton(new CHighlightableButton("", CGI->generaltexth->zelp[24+i].second, 0, 110 + i*32, 450, difButns[i], i));
  1409. }
  1410. }
  1411. if(SEL->screenType != CMenuScreen::newGame)
  1412. difficulty->block(true);
  1413. //description needs bg
  1414. mapDescription->addChild(new CPicture(*bg, descriptionRect), true); //move subpicture bg to our description control (by default it's our (Infocard) child)
  1415. if(network)
  1416. {
  1417. playerListBg = new CPicture("CHATPLUG.bmp", 16, 276);
  1418. chat = new CChatBox(descriptionRect);
  1419. chat->chatHistory->addChild(new CPicture(*bg, chat->chatHistory->pos - pos), true); //move subpicture bg to our description control (by default it's our (Infocard) child)
  1420. chatOn = true;
  1421. mapDescription->disable();
  1422. }
  1423. }
  1424. }
  1425. InfoCard::~InfoCard()
  1426. {
  1427. delete sizes;
  1428. delete sFlags;
  1429. }
  1430. void InfoCard::showAll(SDL_Surface * to)
  1431. {
  1432. CIntObject::showAll(to);
  1433. //blit texts
  1434. if(SEL->screenType != CMenuScreen::campaignList)
  1435. {
  1436. printAtLoc(CGI->generaltexth->allTexts[390] + ":", 24, 400, FONT_SMALL, Colors::Cornsilk, to); //Allies
  1437. printAtLoc(CGI->generaltexth->allTexts[391] + ":", 190, 400, FONT_SMALL, Colors::Cornsilk, to); //Enemies
  1438. printAtLoc(CGI->generaltexth->allTexts[494], 33, 430, FONT_SMALL, Colors::Jasmine, to);//"Map Diff:"
  1439. printAtLoc(CGI->generaltexth->allTexts[492] + ":", 133,430, FONT_SMALL, Colors::Jasmine, to); //player difficulty
  1440. printAtLoc(CGI->generaltexth->allTexts[218] + ":", 290,430, FONT_SMALL, Colors::Jasmine, to); //"Rating:"
  1441. printAtLoc(CGI->generaltexth->allTexts[495], 26, 22, FONT_SMALL, Colors::Jasmine, to); //Scenario Name:
  1442. if(!chatOn)
  1443. {
  1444. printAtLoc(CGI->generaltexth->allTexts[496], 26, 132, FONT_SMALL, Colors::Jasmine, to); //Scenario Description:
  1445. printAtLoc(CGI->generaltexth->allTexts[497], 26, 283, FONT_SMALL, Colors::Jasmine, to); //Victory Condition:
  1446. printAtLoc(CGI->generaltexth->allTexts[498], 26, 339, FONT_SMALL, Colors::Jasmine, to); //Loss Condition:
  1447. }
  1448. else //players list
  1449. {
  1450. std::map<ui32, std::string> playerNames = SEL->playerNames;
  1451. int playerSoFar = 0;
  1452. for (std::map<int, PlayerSettings>::const_iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1453. {
  1454. if(i->second.human)
  1455. {
  1456. printAtLoc(i->second.name, 24, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->height, FONT_SMALL, Colors::Cornsilk, to);
  1457. playerNames.erase(i->second.human);
  1458. }
  1459. }
  1460. playerSoFar = 0;
  1461. for (std::map<ui32, std::string>::const_iterator i = playerNames.begin(); i != playerNames.end(); i++)
  1462. {
  1463. printAtLoc(i->second, 193, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->height, FONT_SMALL, Colors::Cornsilk, to);
  1464. }
  1465. }
  1466. }
  1467. if(SEL->current)
  1468. {
  1469. if(SEL->screenType != CMenuScreen::campaignList)
  1470. {
  1471. int temp = -1;
  1472. if(!chatOn)
  1473. {
  1474. //victory conditions
  1475. temp = SEL->current->mapHeader->victoryCondition.condition+1;
  1476. if (temp>20) temp=0;
  1477. std::string sss = CGI->generaltexth->victoryConditions[temp];
  1478. if (temp && SEL->current->mapHeader->victoryCondition.allowNormalVictory) sss+= "/" + CGI->generaltexth->victoryConditions[0];
  1479. printAtLoc(sss, 60, 307, FONT_SMALL, Colors::Cornsilk, to);
  1480. temp = SEL->current->mapHeader->victoryCondition.condition;
  1481. if (temp>12) temp=11;
  1482. blitAtLoc(CGP->victory->ourImages[temp].bitmap, 24, 302, to); //victory cond descr
  1483. //loss conditoins
  1484. temp = SEL->current->mapHeader->lossCondition.typeOfLossCon+1;
  1485. if (temp>20) temp=0;
  1486. sss = CGI->generaltexth->lossCondtions[temp];
  1487. printAtLoc(sss, 60, 366, FONT_SMALL, Colors::Cornsilk, to);
  1488. temp=SEL->current->mapHeader->lossCondition.typeOfLossCon;
  1489. if (temp>12) temp=3;
  1490. blitAtLoc(CGP->loss->ourImages[temp].bitmap, 24, 359, to); //loss cond
  1491. }
  1492. //difficulty
  1493. assert(SEL->current->mapHeader->difficulty <= 4);
  1494. std::string &diff = CGI->generaltexth->arraytxt[142 + SEL->current->mapHeader->difficulty];
  1495. printAtMiddleLoc(diff, 62, 472, FONT_SMALL, Colors::Cornsilk, to);
  1496. //selecting size icon
  1497. switch (SEL->current->mapHeader->width)
  1498. {
  1499. case 36:
  1500. temp=0;
  1501. break;
  1502. case 72:
  1503. temp=1;
  1504. break;
  1505. case 108:
  1506. temp=2;
  1507. break;
  1508. case 144:
  1509. temp=3;
  1510. break;
  1511. default:
  1512. temp=4;
  1513. break;
  1514. }
  1515. blitAtLoc(sizes->ourImages[temp].bitmap, 318, 22, to);
  1516. if(SEL->screenType == CMenuScreen::loadGame)
  1517. printToLoc((static_cast<const CMapInfo*>(SEL->current))->date,308,34, FONT_SMALL, Colors::Cornsilk, to);
  1518. //print flags
  1519. int fx = 34 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[390].c_str());
  1520. int ex = 200 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[391].c_str());
  1521. int myT;
  1522. if(playerColor >= 0)
  1523. myT = SEL->current->mapHeader->players[playerColor].team;
  1524. else
  1525. myT = -1;
  1526. for (std::map<int, PlayerSettings>::const_iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1527. {
  1528. int *myx = ((i->first == playerColor || SEL->current->mapHeader->players[i->first].team == myT) ? &fx : &ex);
  1529. blitAtLoc(sFlags->ourImages[i->first].bitmap, *myx, 399, to);
  1530. *myx += sFlags->ourImages[i->first].bitmap->w;
  1531. }
  1532. std::string tob;
  1533. switch (SEL->sInfo.difficulty)
  1534. {
  1535. case 0:
  1536. tob="80%";
  1537. break;
  1538. case 1:
  1539. tob="100%";
  1540. break;
  1541. case 2:
  1542. tob="130%";
  1543. break;
  1544. case 3:
  1545. tob="160%";
  1546. break;
  1547. case 4:
  1548. tob="200%";
  1549. break;
  1550. }
  1551. printAtMiddleLoc(tob, 311, 472, FONT_SMALL, Colors::Cornsilk, to);
  1552. }
  1553. //blit description
  1554. std::string name;
  1555. if (SEL->screenType == CMenuScreen::campaignList)
  1556. {
  1557. name = SEL->current->campaignHeader->name;
  1558. }
  1559. else
  1560. {
  1561. name = SEL->current->mapHeader->name;
  1562. }
  1563. //name
  1564. if (name.length())
  1565. printAtLoc(CSDL_Ext::trimToFit(name, 300, FONT_BIG), 26, 39, FONT_BIG, Colors::Jasmine, to);
  1566. else
  1567. printAtLoc("Unnamed", 26, 39, FONT_BIG, Colors::Jasmine, to);
  1568. }
  1569. }
  1570. void InfoCard::changeSelection( const CMapInfo *to )
  1571. {
  1572. if(to && mapDescription)
  1573. {
  1574. if (SEL->screenType == CMenuScreen::campaignList)
  1575. mapDescription->setTxt(to->campaignHeader->description);
  1576. else
  1577. mapDescription->setTxt(to->mapHeader->description);
  1578. if(SEL->screenType != CMenuScreen::newGame && SEL->screenType != CMenuScreen::campaignList) {
  1579. difficulty->block(true);
  1580. difficulty->select(SEL->sInfo.difficulty, 0);
  1581. }
  1582. }
  1583. GH.totalRedraw();
  1584. }
  1585. void InfoCard::clickRight( tribool down, bool previousState )
  1586. {
  1587. static const Rect flagArea(19, 397, 335, 23);
  1588. if(down && SEL->current && isItInLoc(flagArea, GH.current->motion.x, GH.current->motion.y))
  1589. showTeamsPopup();
  1590. }
  1591. void InfoCard::showTeamsPopup()
  1592. {
  1593. SDL_Surface *bmp = CMessage::drawDialogBox(256, 90 + 50 * SEL->current->mapHeader->howManyTeams);
  1594. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[657], 128, 30, FONT_MEDIUM, Colors::Jasmine, bmp); //{Team Alignments}
  1595. for(int i = 0; i < SEL->current->mapHeader->howManyTeams; i++)
  1596. {
  1597. std::vector<ui8> flags;
  1598. std::string hlp = CGI->generaltexth->allTexts[656]; //Team %d
  1599. hlp.replace(hlp.find("%d"), 2, boost::lexical_cast<std::string>(i+1));
  1600. CSDL_Ext::printAtMiddle(hlp, 128, 65 + 50*i, FONT_SMALL, Colors::Cornsilk, bmp);
  1601. for(int j = 0; j < GameConstants::PLAYER_LIMIT; j++)
  1602. if((SEL->current->mapHeader->players[j].canHumanPlay || SEL->current->mapHeader->players[j].canComputerPlay)
  1603. && SEL->current->mapHeader->players[j].team == i)
  1604. flags.push_back(j);
  1605. int curx = 128 - 9*flags.size();
  1606. for(int j = 0; j < flags.size(); j++)
  1607. {
  1608. blitAt(sFlags->ourImages[flags[j]].bitmap, curx, 75 + 50*i, bmp);
  1609. curx += 18;
  1610. }
  1611. }
  1612. GH.pushInt(new CInfoPopup(bmp, true));
  1613. }
  1614. void InfoCard::toggleChat()
  1615. {
  1616. setChat(!chatOn);
  1617. }
  1618. void InfoCard::setChat(bool activateChat)
  1619. {
  1620. if(chatOn == activateChat)
  1621. return;
  1622. assert(active);
  1623. if(activateChat)
  1624. {
  1625. mapDescription->disable();
  1626. chat->enable();
  1627. playerListBg->enable();
  1628. }
  1629. else
  1630. {
  1631. mapDescription->enable();
  1632. chat->disable();
  1633. playerListBg->disable();
  1634. }
  1635. chatOn = activateChat;
  1636. GH.totalRedraw();
  1637. }
  1638. OptionsTab::OptionsTab():
  1639. turnDuration(NULL)
  1640. {
  1641. OBJ_CONSTRUCTION;
  1642. bg = new CPicture("ADVOPTBK", 0, 6);
  1643. pos = bg->pos;
  1644. if(SEL->screenType == CMenuScreen::newGame)
  1645. turnDuration = new CSlider(55, 551, 194, bind(&OptionsTab::setTurnLength, this, _1), 1, 11, 11, true, 1);
  1646. }
  1647. OptionsTab::~OptionsTab()
  1648. {
  1649. }
  1650. void OptionsTab::showAll(SDL_Surface * to)
  1651. {
  1652. CIntObject::showAll(to);
  1653. printAtMiddleLoc(CGI->generaltexth->allTexts[515], 222, 30, FONT_BIG, Colors::Jasmine, to);
  1654. printAtMiddleWBLoc(CGI->generaltexth->allTexts[516], 222, 58, FONT_SMALL, 55, Colors::Cornsilk, to); //Select starting options, handicap, and name for each player in the game.
  1655. printAtMiddleWBLoc(CGI->generaltexth->allTexts[517], 107, 102, FONT_SMALL, 14, Colors::Jasmine, to); //Player Name Handicap Type
  1656. printAtMiddleWBLoc(CGI->generaltexth->allTexts[518], 197, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Town
  1657. printAtMiddleWBLoc(CGI->generaltexth->allTexts[519], 273, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Hero
  1658. printAtMiddleWBLoc(CGI->generaltexth->allTexts[520], 349, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Bonus
  1659. printAtMiddleLoc(CGI->generaltexth->allTexts[521], 222, 538, FONT_SMALL, Colors::Jasmine, to); // Player Turn Duration
  1660. if (turnDuration)
  1661. printAtMiddleLoc(CGI->generaltexth->turnDurations[turnDuration->value], 319,559, FONT_SMALL, Colors::Cornsilk, to);//Turn duration value
  1662. }
  1663. void OptionsTab::nextCastle( int player, int dir )
  1664. {
  1665. if(SEL->isGuest())
  1666. {
  1667. SEL->postRequest(RequestOptionsChange::TOWN, dir);
  1668. return;
  1669. }
  1670. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1671. si32 &cur = s.castle;
  1672. ui32 allowed = SEL->current->mapHeader->players[s.color].allowedFactions;
  1673. if (cur == -2) //no castle - no change
  1674. return;
  1675. if (cur == -1) //random => first/last available
  1676. {
  1677. int pom = (dir>0) ? (0) : (GameConstants::F_NUMBER-1); // last or first
  1678. for (;pom >= 0 && pom < GameConstants::F_NUMBER; pom+=dir)
  1679. {
  1680. if((1 << pom) & allowed)
  1681. {
  1682. cur=pom;
  1683. break;
  1684. }
  1685. }
  1686. }
  1687. else // next/previous available
  1688. {
  1689. for (;;)
  1690. {
  1691. cur+=dir;
  1692. if ((1 << cur) & allowed)
  1693. break;
  1694. if (cur >= GameConstants::F_NUMBER || cur<0)
  1695. {
  1696. double p1 = log((double)allowed) / log(2.0)+0.000001;
  1697. double check = p1 - ((int)p1);
  1698. if (check < 0.001)
  1699. cur = (int)p1;
  1700. else
  1701. cur = -1;
  1702. break;
  1703. }
  1704. }
  1705. }
  1706. if(s.hero >= 0)
  1707. s.hero = -1;
  1708. if(cur < 0 && s.bonus == PlayerSettings::bresource)
  1709. s.bonus = PlayerSettings::brandom;
  1710. entries[player]->selectButtons();
  1711. SEL->propagateOptions();
  1712. redraw();
  1713. }
  1714. void OptionsTab::nextHero( int player, int dir )
  1715. {
  1716. if(SEL->isGuest())
  1717. {
  1718. SEL->postRequest(RequestOptionsChange::HERO, dir);
  1719. return;
  1720. }
  1721. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1722. int old = s.hero;
  1723. if (s.castle < 0 || !s.human || s.hero == -2)
  1724. return;
  1725. if (s.hero == -1) //random => first/last available
  1726. {
  1727. int max = (s.castle*GameConstants::HEROES_PER_TYPE*2+15),
  1728. min = (s.castle*GameConstants::HEROES_PER_TYPE*2);
  1729. s.hero = nextAllowedHero(min,max,0,dir);
  1730. }
  1731. else
  1732. {
  1733. if(dir > 0)
  1734. s.hero = nextAllowedHero(s.hero,(s.castle*GameConstants::HEROES_PER_TYPE*2+16),1,dir);
  1735. else
  1736. s.hero = nextAllowedHero(s.castle*GameConstants::HEROES_PER_TYPE*2-1,s.hero,1,dir);
  1737. }
  1738. if(old != s.hero)
  1739. {
  1740. usedHeroes.erase(old);
  1741. usedHeroes.insert(s.hero);
  1742. redraw();
  1743. }
  1744. SEL->propagateOptions();
  1745. }
  1746. int OptionsTab::nextAllowedHero( int min, int max, int incl, int dir )
  1747. {
  1748. if(dir>0)
  1749. {
  1750. for(int i=min+incl; i<=max-incl; i++)
  1751. if(canUseThisHero(i))
  1752. return i;
  1753. }
  1754. else
  1755. {
  1756. for(int i=max-incl; i>=min+incl; i--)
  1757. if(canUseThisHero(i))
  1758. return i;
  1759. }
  1760. return -1;
  1761. }
  1762. bool OptionsTab::canUseThisHero( int ID )
  1763. {
  1764. //for(int i=0;i<CPG->ret.playerInfos.size();i++)
  1765. // if(CPG->ret.playerInfos[i].hero==ID) //hero is already taken
  1766. // return false;
  1767. return !vstd::contains(usedHeroes, ID) && SEL->current->mapHeader->allowedHeroes[ID];
  1768. }
  1769. void OptionsTab::nextBonus( int player, int dir )
  1770. {
  1771. if(SEL->isGuest())
  1772. {
  1773. SEL->postRequest(RequestOptionsChange::BONUS, dir);
  1774. return;
  1775. }
  1776. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1777. si8 &ret = s.bonus += dir;
  1778. if (s.hero==-2 && !SEL->current->mapHeader->players[s.color].heroesNames.size() && ret==PlayerSettings::bartifact) //no hero - can't be artifact
  1779. {
  1780. if (dir<0)
  1781. ret=PlayerSettings::brandom;
  1782. else ret=PlayerSettings::bgold;
  1783. }
  1784. if(ret > PlayerSettings::bresource)
  1785. ret = PlayerSettings::brandom;
  1786. if(ret < PlayerSettings::brandom)
  1787. ret = PlayerSettings::bresource;
  1788. if (s.castle==-1 && ret==PlayerSettings::bresource) //random castle - can't be resource
  1789. {
  1790. if (dir<0)
  1791. ret=PlayerSettings::bgold;
  1792. else ret=PlayerSettings::brandom;
  1793. }
  1794. SEL->propagateOptions();
  1795. redraw();
  1796. }
  1797. void OptionsTab::recreate()
  1798. {
  1799. for(std::map<int, PlayerOptionsEntry*>::iterator it = entries.begin(); it != entries.end(); ++it)
  1800. {
  1801. delete it->second;
  1802. }
  1803. entries.clear();
  1804. usedHeroes.clear();
  1805. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1806. for(std::map<int, PlayerSettings>::iterator it = SEL->sInfo.playerInfos.begin();
  1807. it != SEL->sInfo.playerInfos.end(); ++it)
  1808. {
  1809. entries.insert(std::make_pair(it->first, new PlayerOptionsEntry(this, it->second)));
  1810. const std::vector<SheroName> &heroes = SEL->current->mapHeader->players[it->first].heroesNames;
  1811. for(size_t hi=0; hi<heroes.size(); hi++)
  1812. usedHeroes.insert(heroes[hi].heroID);
  1813. }
  1814. }
  1815. void OptionsTab::setTurnLength( int npos )
  1816. {
  1817. static const int times[] = {1, 2, 4, 6, 8, 10, 15, 20, 25, 30, 0};
  1818. vstd::amin(npos, ARRAY_COUNT(times) - 1);
  1819. SEL->sInfo.turnTime = times[npos];
  1820. redraw();
  1821. }
  1822. void OptionsTab::flagPressed( int color )
  1823. {
  1824. PlayerSettings &clicked = SEL->sInfo.playerInfos[color];
  1825. PlayerSettings *old = NULL;
  1826. if(SEL->playerNames.size() == 1) //single player -> just swap
  1827. {
  1828. if(color == playerColor) //that color is already selected, no action needed
  1829. return;
  1830. old = &SEL->sInfo.playerInfos[playerColor];
  1831. swapPlayers(*old, clicked);
  1832. }
  1833. else
  1834. {
  1835. //identify clicked player
  1836. int clickedNameID = clicked.human; //human is a number of player, zero means AI
  1837. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  1838. {
  1839. PlayerSettings &restPos = SEL->sInfo.playerInfos[playerToRestore.color];
  1840. SEL->setPlayer(restPos, playerToRestore.id);
  1841. playerToRestore.reset();
  1842. }
  1843. int newPlayer; //which player will take clicked position
  1844. //who will be put here?
  1845. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  1846. {
  1847. newPlayer = SEL->getIdOfFirstUnallocatedPlayer();
  1848. if(!newPlayer) //no "free" player -> get just first one
  1849. newPlayer = SEL->playerNames.begin()->first;
  1850. }
  1851. else //human clicked -> take next
  1852. {
  1853. std::map<ui32, std::string>::const_iterator i = SEL->playerNames.find(clickedNameID); //clicked one
  1854. i++; //player AFTER clicked one
  1855. if(i != SEL->playerNames.end())
  1856. newPlayer = i->first;
  1857. else
  1858. newPlayer = 0; //AI if we scrolled through all players
  1859. }
  1860. SEL->setPlayer(clicked, newPlayer); //put player
  1861. //if that player was somewhere else, we need to replace him with computer
  1862. if(newPlayer) //not AI
  1863. {
  1864. for(std::map<int, PlayerSettings>::iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1865. {
  1866. int curNameID = i->second.human;
  1867. if(i->first != color && curNameID == newPlayer)
  1868. {
  1869. assert(i->second.human);
  1870. playerToRestore.color = i->first;
  1871. playerToRestore.id = newPlayer;
  1872. SEL->setPlayer(i->second, 0); //set computer
  1873. old = &i->second;
  1874. break;
  1875. }
  1876. }
  1877. }
  1878. }
  1879. entries[clicked.color]->selectButtons();
  1880. if(old)
  1881. {
  1882. entries[old->color]->selectButtons();
  1883. if(old->hero >= 0)
  1884. usedHeroes.erase(old->hero);
  1885. old->hero = entries[old->color]->pi.defaultHero();
  1886. }
  1887. SEL->propagateOptions();
  1888. GH.totalRedraw();
  1889. }
  1890. OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry( OptionsTab *owner, PlayerSettings &S)
  1891. : pi(SEL->current->mapHeader->players[S.color]), s(S)
  1892. {
  1893. OBJ_CONSTRUCTION;
  1894. defActions |= SHARE_POS;
  1895. int serial = 0;
  1896. for(int g=0; g < s.color; ++g)
  1897. {
  1898. PlayerInfo &itred = SEL->current->mapHeader->players[g];
  1899. if( itred.canComputerPlay || itred.canHumanPlay)
  1900. serial++;
  1901. }
  1902. pos.x += 54;
  1903. pos.y += 122 + serial*50;
  1904. static const char *flags[] = {"AOFLGBR.DEF", "AOFLGBB.DEF", "AOFLGBY.DEF", "AOFLGBG.DEF",
  1905. "AOFLGBO.DEF", "AOFLGBP.DEF", "AOFLGBT.DEF", "AOFLGBS.DEF"};
  1906. static const char *bgs[] = {"ADOPRPNL.bmp", "ADOPBPNL.bmp", "ADOPYPNL.bmp", "ADOPGPNL.bmp",
  1907. "ADOPOPNL.bmp", "ADOPPPNL.bmp", "ADOPTPNL.bmp", "ADOPSPNL.bmp"};
  1908. bg = new CPicture(BitmapHandler::loadBitmap(bgs[s.color]), 0, 0, true);
  1909. if(SEL->screenType == CMenuScreen::newGame)
  1910. {
  1911. btns[0] = new CAdventureMapButton(CGI->generaltexth->zelp[132], bind(&OptionsTab::nextCastle, owner, s.color, -1), 107, 5, "ADOPLFA.DEF");
  1912. btns[1] = new CAdventureMapButton(CGI->generaltexth->zelp[133], bind(&OptionsTab::nextCastle, owner, s.color, +1), 168, 5, "ADOPRTA.DEF");
  1913. btns[2] = new CAdventureMapButton(CGI->generaltexth->zelp[148], bind(&OptionsTab::nextHero, owner, s.color, -1), 183, 5, "ADOPLFA.DEF");
  1914. btns[3] = new CAdventureMapButton(CGI->generaltexth->zelp[149], bind(&OptionsTab::nextHero, owner, s.color, +1), 244, 5, "ADOPRTA.DEF");
  1915. btns[4] = new CAdventureMapButton(CGI->generaltexth->zelp[164], bind(&OptionsTab::nextBonus, owner, s.color, -1), 259, 5, "ADOPLFA.DEF");
  1916. btns[5] = new CAdventureMapButton(CGI->generaltexth->zelp[165], bind(&OptionsTab::nextBonus, owner, s.color, +1), 320, 5, "ADOPRTA.DEF");
  1917. }
  1918. else
  1919. for(int i = 0; i < 6; i++)
  1920. btns[i] = NULL;
  1921. selectButtons();
  1922. assert(SEL->current && SEL->current->mapHeader);
  1923. const PlayerInfo &p = SEL->current->mapHeader->players[s.color];
  1924. assert(p.canComputerPlay || p.canHumanPlay); //someone must be able to control this player
  1925. if(p.canHumanPlay && p.canComputerPlay)
  1926. whoCanPlay = HUMAN_OR_CPU;
  1927. else if(p.canComputerPlay)
  1928. whoCanPlay = CPU;
  1929. else
  1930. whoCanPlay = HUMAN;
  1931. if(SEL->screenType != CMenuScreen::scenarioInfo
  1932. && SEL->current->mapHeader->players[s.color].canHumanPlay
  1933. && SEL->multiPlayer != CMenuScreen::MULTI_NETWORK_GUEST)
  1934. {
  1935. flag = new CAdventureMapButton(CGI->generaltexth->zelp[180], bind(&OptionsTab::flagPressed, owner, s.color), -43, 2, flags[s.color]);
  1936. flag->hoverable = true;
  1937. }
  1938. else
  1939. flag = NULL;
  1940. town = new SelectedBox(TOWN, s.color);
  1941. town->pos.x += 119;
  1942. town->pos.y += 2;
  1943. hero = new SelectedBox(HERO, s.color);
  1944. hero->pos.x += 195;
  1945. hero->pos.y += 2;
  1946. bonus = new SelectedBox(BONUS, s.color);
  1947. bonus->pos.x += 271;
  1948. bonus->pos.y += 2;
  1949. }
  1950. void OptionsTab::PlayerOptionsEntry::showAll(SDL_Surface * to)
  1951. {
  1952. CIntObject::showAll(to);
  1953. printAtMiddleLoc(s.name, 55, 10, FONT_SMALL, Colors::Cornsilk, to);
  1954. printAtMiddleWBLoc(CGI->generaltexth->arraytxt[206+whoCanPlay], 28, 34, FONT_TINY, 8, Colors::Cornsilk, to);
  1955. }
  1956. void OptionsTab::PlayerOptionsEntry::selectButtons()
  1957. {
  1958. if(!btns[0])
  1959. return;
  1960. if( (pi.defaultCastle() != -1) //fixed tow
  1961. || (SEL->isGuest() && s.color != playerColor)) //or not our player
  1962. {
  1963. btns[0]->disable();
  1964. btns[1]->disable();
  1965. }
  1966. else
  1967. {
  1968. btns[0]->enable();
  1969. btns[1]->enable();
  1970. }
  1971. if( (pi.defaultHero() != -1 || !s.human || s.castle < 0) //fixed hero
  1972. || (SEL->isGuest() && s.color != playerColor))//or not our player
  1973. {
  1974. btns[2]->disable();
  1975. btns[3]->disable();
  1976. }
  1977. else
  1978. {
  1979. btns[2]->enable();
  1980. btns[3]->enable();
  1981. }
  1982. if(SEL->isGuest() && s.color != playerColor)//or not our player
  1983. {
  1984. btns[4]->disable();
  1985. btns[5]->disable();
  1986. }
  1987. else
  1988. {
  1989. btns[4]->enable();
  1990. btns[5]->enable();
  1991. }
  1992. }
  1993. void OptionsTab::SelectedBox::showAll(SDL_Surface * to)
  1994. {
  1995. //PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1996. SDL_Surface *toBlit = getImg();
  1997. const std::string *toPrint = getText();
  1998. blitAt(toBlit, pos, to);
  1999. printAtMiddleLoc(*toPrint, 23, 39, FONT_TINY, Colors::Cornsilk, to);
  2000. }
  2001. OptionsTab::SelectedBox::SelectedBox( SelType Which, ui8 Player )
  2002. :which(Which), player(Player)
  2003. {
  2004. SDL_Surface *img = getImg();
  2005. pos.w = img->w;
  2006. pos.h = img->h;
  2007. addUsedEvents(RCLICK);
  2008. }
  2009. SDL_Surface * OptionsTab::SelectedBox::getImg() const
  2010. {
  2011. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2012. switch(which)
  2013. {
  2014. case TOWN:
  2015. if (s.castle < GameConstants::F_NUMBER && s.castle >= 0)
  2016. return graphics->getPic(s.castle, true, false);
  2017. else if (s.castle == -1)
  2018. return CGP->rTown;
  2019. else if (s.castle == -2)
  2020. return CGP->nTown;
  2021. case HERO:
  2022. if (s.hero == -1)
  2023. {
  2024. return CGP->rHero;
  2025. }
  2026. else if (s.hero == -2)
  2027. {
  2028. if(s.heroPortrait >= 0)
  2029. return graphics->portraitSmall[s.heroPortrait];
  2030. else
  2031. return CGP->nHero;
  2032. }
  2033. else
  2034. {
  2035. return graphics->portraitSmall[s.hero];
  2036. }
  2037. break;
  2038. case BONUS:
  2039. {
  2040. int pom;
  2041. switch (s.bonus)
  2042. {
  2043. case -1:
  2044. pom=10;
  2045. break;
  2046. case 0:
  2047. pom=9;
  2048. break;
  2049. case 1:
  2050. pom=8;
  2051. break;
  2052. case 2:
  2053. pom=CGI->townh->towns[s.castle].bonus;
  2054. break;
  2055. default:
  2056. assert(0);
  2057. }
  2058. return CGP->bonuses->ourImages[pom].bitmap;
  2059. }
  2060. default:
  2061. return NULL;
  2062. }
  2063. }
  2064. const std::string * OptionsTab::SelectedBox::getText() const
  2065. {
  2066. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2067. switch(which)
  2068. {
  2069. case TOWN:
  2070. if (s.castle < GameConstants::F_NUMBER && s.castle >= 0)
  2071. return &CGI->townh->towns[s.castle].Name();
  2072. else if (s.castle == -1)
  2073. return &CGI->generaltexth->allTexts[522];
  2074. else if (s.castle == -2)
  2075. return &CGI->generaltexth->allTexts[523];
  2076. case HERO:
  2077. if (s.hero == -1)
  2078. return &CGI->generaltexth->allTexts[522];
  2079. else if (s.hero == -2)
  2080. {
  2081. if(s.heroPortrait >= 0)
  2082. {
  2083. if(s.heroName.length())
  2084. return &s.heroName;
  2085. else
  2086. return &CGI->heroh->heroes[s.heroPortrait]->name;
  2087. }
  2088. else
  2089. return &CGI->generaltexth->allTexts[523];
  2090. }
  2091. else
  2092. {
  2093. //if(s.heroName.length())
  2094. // return &s.heroName;
  2095. //else
  2096. return &CGI->heroh->heroes[s.hero]->name;
  2097. }
  2098. case BONUS:
  2099. switch (s.bonus)
  2100. {
  2101. case -1:
  2102. return &CGI->generaltexth->allTexts[522];
  2103. default:
  2104. return &CGI->generaltexth->arraytxt[214 + s.bonus];
  2105. }
  2106. default:
  2107. return NULL;
  2108. }
  2109. }
  2110. void OptionsTab::SelectedBox::clickRight( tribool down, bool previousState )
  2111. {
  2112. if(indeterminate(down) || !down) return;
  2113. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2114. SDL_Surface *bmp = NULL;
  2115. const std::string *title = NULL, *subTitle = NULL;
  2116. subTitle = getText();
  2117. int val=-1;
  2118. switch(which)
  2119. {
  2120. case TOWN:
  2121. val = s.castle;
  2122. break;
  2123. case HERO:
  2124. val = s.hero;
  2125. if(val == -2) //none => we may have some preset info
  2126. {
  2127. int p9 = SEL->current->mapHeader->players[s.color].p9;
  2128. if(p9 != 255 && SEL->sInfo.playerInfos[player].heroPortrait >= 0)
  2129. val = p9;
  2130. }
  2131. break;
  2132. case BONUS:
  2133. val = s.bonus;
  2134. break;
  2135. }
  2136. if(val == -1 || which == BONUS) //random or bonus box
  2137. {
  2138. bmp = CMessage::drawDialogBox(256, 190);
  2139. std::string *description = NULL;
  2140. switch(which)
  2141. {
  2142. case TOWN:
  2143. title = &CGI->generaltexth->allTexts[103];
  2144. description = &CGI->generaltexth->allTexts[104];
  2145. break;
  2146. case HERO:
  2147. title = &CGI->generaltexth->allTexts[101];
  2148. description = &CGI->generaltexth->allTexts[102];
  2149. break;
  2150. case BONUS:
  2151. {
  2152. switch(val)
  2153. {
  2154. case PlayerSettings::brandom:
  2155. title = &CGI->generaltexth->allTexts[86]; //{Random Bonus}
  2156. description = &CGI->generaltexth->allTexts[94]; //Gold, wood and ore, or an artifact is randomly chosen as your starting bonus
  2157. break;
  2158. case PlayerSettings::bartifact:
  2159. title = &CGI->generaltexth->allTexts[83]; //{Artifact Bonus}
  2160. description = &CGI->generaltexth->allTexts[90]; //An artifact is randomly chosen and equipped to your starting hero
  2161. break;
  2162. case PlayerSettings::bgold:
  2163. title = &CGI->generaltexth->allTexts[84]; //{Gold Bonus}
  2164. subTitle = &CGI->generaltexth->allTexts[87]; //500-1000
  2165. description = &CGI->generaltexth->allTexts[92]; //At the start of the game, 500-1000 gold is added to your Kingdom's resource pool
  2166. break;
  2167. case PlayerSettings::bresource:
  2168. {
  2169. title = &CGI->generaltexth->allTexts[85]; //{Resource Bonus}
  2170. switch(CGI->townh->towns[s.castle].primaryRes)
  2171. {
  2172. case 1:
  2173. subTitle = &CGI->generaltexth->allTexts[694];
  2174. description = &CGI->generaltexth->allTexts[690];
  2175. break;
  2176. case 3:
  2177. subTitle = &CGI->generaltexth->allTexts[695];
  2178. description = &CGI->generaltexth->allTexts[691];
  2179. break;
  2180. case 4:
  2181. subTitle = &CGI->generaltexth->allTexts[692];
  2182. description = &CGI->generaltexth->allTexts[688];
  2183. break;
  2184. case 5:
  2185. subTitle = &CGI->generaltexth->allTexts[693];
  2186. description = &CGI->generaltexth->allTexts[689];
  2187. break;
  2188. case 127:
  2189. subTitle = &CGI->generaltexth->allTexts[89]; //5-10 wood / 5-10 ore
  2190. description = &CGI->generaltexth->allTexts[93]; //At the start of the game, 5-10 wood and 5-10 ore are added to your Kingdom's resource pool
  2191. break;
  2192. }
  2193. }
  2194. break;
  2195. }
  2196. }
  2197. break;
  2198. }
  2199. if(description)
  2200. CSDL_Ext::printAtMiddleWB(*description, 125, 145, FONT_SMALL, 37, Colors::Cornsilk, bmp);
  2201. }
  2202. else if(val == -2)
  2203. {
  2204. return;
  2205. }
  2206. else if(which == TOWN)
  2207. {
  2208. bmp = CMessage::drawDialogBox(256, 319);
  2209. title = &CGI->generaltexth->allTexts[80];
  2210. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[79], 135, 137, FONT_MEDIUM, Colors::Jasmine, bmp);
  2211. const CTown &t = CGI->townh->towns[val];
  2212. //print creatures
  2213. int x = 60, y = 159;
  2214. for(int i = 0; i < 7; i++)
  2215. {
  2216. int c = t.basicCreatures[i];
  2217. blitAt(graphics->smallImgs[c], x, y, bmp);
  2218. CSDL_Ext::printAtMiddleWB(CGI->creh->creatures[c]->nameSing, x + 16, y + 45, FONT_TINY, 10, Colors::Cornsilk, bmp);
  2219. if(i == 2)
  2220. {
  2221. x = 40;
  2222. y += 76;
  2223. }
  2224. else
  2225. {
  2226. x += 52;
  2227. }
  2228. }
  2229. }
  2230. else if(val >= 0)
  2231. {
  2232. const CHero *h = CGI->heroh->heroes[val];
  2233. bmp = CMessage::drawDialogBox(320, 255);
  2234. title = &CGI->generaltexth->allTexts[77];
  2235. CSDL_Ext::printAtMiddle(*title, 167, 36, FONT_MEDIUM, Colors::Jasmine, bmp);
  2236. CSDL_Ext::printAtMiddle(*subTitle + " - " + h->heroClass->name, 160, 99, FONT_SMALL, Colors::Cornsilk, bmp);
  2237. blitAt(getImg(), 136, 56, bmp);
  2238. //print specialty
  2239. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[78], 166, 132, FONT_MEDIUM, Colors::Jasmine, bmp);
  2240. blitAt(graphics->un44->ourImages[val].bitmap, 140, 150, bmp);
  2241. CSDL_Ext::printAtMiddle(CGI->generaltexth->hTxts[val].bonusName, 166, 203, FONT_SMALL, Colors::Cornsilk, bmp);
  2242. GH.pushInt(new CInfoPopup(bmp, true));
  2243. return;
  2244. }
  2245. if(title)
  2246. CSDL_Ext::printAtMiddle(*title, 135, 36, FONT_MEDIUM, Colors::Jasmine, bmp);
  2247. if(subTitle)
  2248. CSDL_Ext::printAtMiddle(*subTitle, 127, 103, FONT_SMALL, Colors::Cornsilk, bmp);
  2249. blitAt(getImg(), 104, 60, bmp);
  2250. GH.pushInt(new CInfoPopup(bmp, true));
  2251. }
  2252. CScenarioInfo::CScenarioInfo(const CMapHeader *mapHeader, const StartInfo *startInfo)
  2253. {
  2254. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2255. for(std::map<int, PlayerSettings>::const_iterator it = startInfo->playerInfos.begin();
  2256. it != startInfo->playerInfos.end(); ++it)
  2257. {
  2258. if(it->second.human)
  2259. {
  2260. playerColor = it->first;
  2261. }
  2262. }
  2263. pos.w = 762;
  2264. pos.h = 584;
  2265. center(pos);
  2266. assert(LOCPLINT);
  2267. sInfo = *LOCPLINT->cb->getStartInfo();
  2268. assert(!SEL->current);
  2269. current = mapInfoFromGame();
  2270. setPlayersFromGame();
  2271. screenType = CMenuScreen::scenarioInfo;
  2272. card = new InfoCard();
  2273. opt = new OptionsTab();
  2274. opt->recreate();
  2275. card->changeSelection(current);
  2276. card->difficulty->select(startInfo->difficulty, 0);
  2277. back = new CAdventureMapButton("", CGI->generaltexth->zelp[105].second, bind(&CGuiHandler::popIntTotally, &GH, this), 584, 535, "SCNRBACK.DEF", SDLK_ESCAPE);
  2278. }
  2279. CScenarioInfo::~CScenarioInfo()
  2280. {
  2281. delete current;
  2282. }
  2283. bool mapSorter::operator()(const CMapInfo *aaa, const CMapInfo *bbb)
  2284. {
  2285. const CMapHeader * a = aaa->mapHeader,
  2286. * b = bbb->mapHeader;
  2287. if(a && b) //if we are sorting scenarios
  2288. {
  2289. switch (sortBy)
  2290. {
  2291. case _format: //by map format (RoE, WoG, etc)
  2292. return (a->version<b->version);
  2293. break;
  2294. case _loscon: //by loss conditions
  2295. return (a->lossCondition.typeOfLossCon<b->lossCondition.typeOfLossCon);
  2296. break;
  2297. case _playerAm: //by player amount
  2298. int playerAmntB,humenPlayersB,playerAmntA,humenPlayersA;
  2299. playerAmntB=humenPlayersB=playerAmntA=humenPlayersA=0;
  2300. for (int i=0;i<8;i++)
  2301. {
  2302. if (a->players[i].canHumanPlay) {playerAmntA++;humenPlayersA++;}
  2303. else if (a->players[i].canComputerPlay) {playerAmntA++;}
  2304. if (b->players[i].canHumanPlay) {playerAmntB++;humenPlayersB++;}
  2305. else if (b->players[i].canComputerPlay) {playerAmntB++;}
  2306. }
  2307. if (playerAmntB!=playerAmntA)
  2308. return (playerAmntA<playerAmntB);
  2309. else
  2310. return (humenPlayersA<humenPlayersB);
  2311. break;
  2312. case _size: //by size of map
  2313. return (a->width<b->width);
  2314. break;
  2315. case _viccon: //by victory conditions
  2316. return (a->victoryCondition.condition < b->victoryCondition.condition);
  2317. break;
  2318. case _name: //by name
  2319. return boost::ilexicographical_compare(a->name, b->name);
  2320. default:
  2321. return boost::ilexicographical_compare(a->name, b->name);
  2322. }
  2323. }
  2324. else //if we are sorting campaigns
  2325. {
  2326. switch(sortBy)
  2327. {
  2328. case _numOfMaps: //by number of maps in campaign
  2329. return CGI->generaltexth->campaignRegionNames[ aaa->campaignHeader->mapVersion ].size() <
  2330. CGI->generaltexth->campaignRegionNames[ bbb->campaignHeader->mapVersion ].size();
  2331. break;
  2332. case _name: //by name
  2333. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2334. default:
  2335. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2336. }
  2337. }
  2338. }
  2339. CMultiMode::CMultiMode()
  2340. {
  2341. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2342. bg = new CPicture("MUPOPUP.bmp");
  2343. bg->convertToScreenBPP(); //so we could draw without problems
  2344. blitAt(CPicture("MUMAP.bmp"), 16, 77, *bg); //blit img
  2345. pos = bg->center(); //center, window has size of bg graphic
  2346. bar = new CGStatusBar(new CPicture(Rect(7, 465, 440, 18), 0));//226, 472
  2347. txt = new CTextInput(Rect(19, 436, 334, 16), *bg);
  2348. txt->setText(settings["general"]["playerName"].String()); //Player
  2349. btns[0] = new CAdventureMapButton(CGI->generaltexth->zelp[266], bind(&CMultiMode::openHotseat, this), 373, 78, "MUBHOT.DEF");
  2350. btns[1] = new CAdventureMapButton("Host TCP/IP game", "", bind(&CMultiMode::hostTCP, this), 373, 78 + 57*1, "MUBHOST.DEF");
  2351. btns[2] = new CAdventureMapButton("Join TCP/IP game", "", bind(&CMultiMode::joinTCP, this), 373, 78 + 57*2, "MUBJOIN.DEF");
  2352. btns[6] = new CAdventureMapButton(CGI->generaltexth->zelp[288], bind(&CGuiHandler::popIntTotally, ref(GH), this), 373, 424, "MUBCANC.DEF", SDLK_ESCAPE);
  2353. }
  2354. void CMultiMode::openHotseat()
  2355. {
  2356. GH.pushInt(new CHotSeatPlayers(txt->text));
  2357. }
  2358. void CMultiMode::hostTCP()
  2359. {
  2360. Settings name = settings.write["general"]["playerName"];
  2361. name->String() = txt->text;
  2362. GH.popIntTotally(this);
  2363. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_NETWORK_HOST));
  2364. }
  2365. void CMultiMode::joinTCP()
  2366. {
  2367. Settings name = settings.write["general"]["playerName"];
  2368. name->String() = txt->text;
  2369. GH.popIntTotally(this);
  2370. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_NETWORK_GUEST));
  2371. }
  2372. CHotSeatPlayers::CHotSeatPlayers(const std::string &firstPlayer)
  2373. {
  2374. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2375. bg = new CPicture("MUHOTSEA.bmp");
  2376. pos = bg->center(); //center, window has size of bg graphic
  2377. std::string text = CGI->generaltexth->allTexts[446];
  2378. boost::replace_all(text, "\t","\n");
  2379. Rect boxRect(25, 20, 315, 50);
  2380. title = new CTextBox(text, boxRect, 0, FONT_BIG, CENTER, Colors::Cornsilk);//HOTSEAT Please enter names
  2381. for(int i = 0; i < ARRAY_COUNT(txt); i++)
  2382. {
  2383. txt[i] = new CTextInput(Rect(60, 85 + i*30, 280, 16), *bg);
  2384. txt[i]->cb += boost::bind(&CHotSeatPlayers::onChange, this, _1);
  2385. }
  2386. ok = new CAdventureMapButton(CGI->generaltexth->zelp[560], bind(&CHotSeatPlayers::enterSelectionScreen, this), 95, 338, "MUBCHCK.DEF", SDLK_RETURN);
  2387. cancel = new CAdventureMapButton(CGI->generaltexth->zelp[561], bind(&CGuiHandler::popIntTotally, ref(GH), this), 205, 338, "MUBCANC.DEF", SDLK_ESCAPE);
  2388. bar = new CGStatusBar(new CPicture(Rect(7, 381, 348, 18), 0));//226, 472
  2389. txt[0]->setText(firstPlayer, true);
  2390. txt[0]->giveFocus();
  2391. }
  2392. void CHotSeatPlayers::onChange(std::string newText)
  2393. {
  2394. size_t namesCount = 0;
  2395. for(int i = 0; i < ARRAY_COUNT(txt); i++)
  2396. if(!txt[i]->text.empty())
  2397. namesCount++;
  2398. ok->block(namesCount < 2);
  2399. }
  2400. void CHotSeatPlayers::enterSelectionScreen()
  2401. {
  2402. std::map<ui32, std::string> names;
  2403. for(int i = 0, j = 1; i < ARRAY_COUNT(txt); i++)
  2404. if(txt[i]->text.length())
  2405. names[j++] = txt[i]->text;
  2406. Settings name = settings.write["general"]["playerName"];
  2407. name->String() = names.begin()->second;
  2408. GH.popInts(2); //pop MP mode window and this
  2409. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_HOT_SEAT, &names));
  2410. }
  2411. CBonusSelection::CBonusSelection( CCampaignState * _ourCampaign )
  2412. : highlightedRegion(NULL), ourCampaign(_ourCampaign), ourHeader(NULL),
  2413. diffLb(NULL), diffRb(NULL), bonuses(NULL)
  2414. {
  2415. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2416. static const std::string bgNames [] = {"E1_BG.BMP", "G2_BG.BMP", "E2_BG.BMP", "G1_BG.BMP", "G3_BG.BMP", "N1_BG.BMP",
  2417. "S1_BG.BMP", "BR_BG.BMP", "IS_BG.BMP", "KR_BG.BMP", "NI_BG.BMP", "TA_BG.BMP", "AR_BG.BMP", "HS_BG.BMP",
  2418. "BB_BG.BMP", "NB_BG.BMP", "EL_BG.BMP", "RN_BG.BMP", "UA_BG.BMP", "SP_BG.BMP"};
  2419. loadPositionsOfGraphics();
  2420. background = BitmapHandler::loadBitmap(bgNames[ourCampaign->camp->header.mapVersion]);
  2421. pos.h = background->h;
  2422. pos.w = background->w;
  2423. center();
  2424. SDL_Surface * panel = BitmapHandler::loadBitmap("CAMPBRF.BMP");
  2425. blitAt(panel, 456, 6, background);
  2426. startB = new CAdventureMapButton("", "", bind(&CBonusSelection::startMap, this), 475, 536, "CBBEGIB.DEF", SDLK_RETURN);
  2427. backB = new CAdventureMapButton("", "", bind(&CBonusSelection::goBack, this), 624, 536, "CBCANCB.DEF", SDLK_ESCAPE);
  2428. startB->setState(CButtonBase::BLOCKED);
  2429. //campaign name
  2430. if (ourCampaign->camp->header.name.length())
  2431. CSDL_Ext::printAt(ourCampaign->camp->header.name, 481, 28, FONT_BIG, Colors::Jasmine, background);
  2432. else
  2433. CSDL_Ext::printAt("Unnamed", 481, 28, FONT_BIG, Colors::Jasmine, background);
  2434. //map size icon
  2435. sizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
  2436. //campaign description
  2437. CSDL_Ext::printAt(CGI->generaltexth->allTexts[38], 481, 63, FONT_SMALL, Colors::Jasmine, background);
  2438. cmpgDesc = new CTextBox(ourCampaign->camp->header.description, Rect(480, 86, 286, 117), 1);
  2439. //cmpgDesc->showAll(background);
  2440. //map description
  2441. mapDesc = new CTextBox("", Rect(480, 280, 286, 117), 1);
  2442. //bonus choosing
  2443. CSDL_Ext::printAt(CGI->generaltexth->allTexts[71], 511, 432, FONT_MEDIUM, Colors::Cornsilk, background); //Choose a bonus:
  2444. bonuses = new CHighlightableButtonsGroup(bind(&CBonusSelection::selectBonus, this, _1));
  2445. //set left part of window
  2446. for (int g=0; g<ourCampaign->camp->scenarios.size(); ++g)
  2447. {
  2448. if(ourCampaign->camp->conquerable(g))
  2449. {
  2450. regions.push_back(new CRegion(this, true, true, g));
  2451. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2452. if (highlightedRegion == NULL)
  2453. {
  2454. highlightedRegion = regions.back();
  2455. selectMap(g);
  2456. }
  2457. }
  2458. else if (ourCampaign->camp->scenarios[g].conquered) //display as striped
  2459. {
  2460. regions.push_back(new CRegion(this, false, false, g));
  2461. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2462. }
  2463. }
  2464. //init campaign state if necessary
  2465. if (ourCampaign->campaignName.size() == 0)
  2466. {
  2467. ourCampaign->initNewCampaign(sInfo);
  2468. }
  2469. //allies / enemies
  2470. CSDL_Ext::printAt(CGI->generaltexth->allTexts[390] + ":", 486, 407, FONT_SMALL, Colors::Cornsilk, background); //Allies
  2471. CSDL_Ext::printAt(CGI->generaltexth->allTexts[391] + ":", 619, 407, FONT_SMALL, Colors::Cornsilk, background); //Enemies
  2472. SDL_FreeSurface(panel);
  2473. //difficulty
  2474. std::vector<std::string> difficulty;
  2475. boost::split(difficulty, CGI->generaltexth->allTexts[492], boost::is_any_of(" "));
  2476. CSDL_Ext::printAt(difficulty.back(), 689, 432, FONT_MEDIUM, Colors::Cornsilk, background); //Difficulty
  2477. //difficulty pics
  2478. for (int b=0; b<ARRAY_COUNT(diffPics); ++b)
  2479. {
  2480. CDefEssential * cde = CDefHandler::giveDefEss("GSPBUT" + boost::lexical_cast<std::string>(b+3) + ".DEF");
  2481. SDL_Surface * surfToDuplicate = cde->ourImages[0].bitmap;
  2482. diffPics[b] = SDL_ConvertSurface(surfToDuplicate, surfToDuplicate->format,
  2483. surfToDuplicate->flags);
  2484. delete cde;
  2485. }
  2486. //difficulty selection buttons
  2487. if (ourCampaign->camp->header.difficultyChoosenByPlayer)
  2488. {
  2489. diffLb = new CAdventureMapButton("", "", bind(&CBonusSelection::changeDiff, this, false), 694, 508, "SCNRBLF.DEF");
  2490. diffRb = new CAdventureMapButton("", "", bind(&CBonusSelection::changeDiff, this, true), 738, 508, "SCNRBRT.DEF");
  2491. }
  2492. //load miniflags
  2493. sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
  2494. }
  2495. CBonusSelection::~CBonusSelection()
  2496. {
  2497. SDL_FreeSurface(background);
  2498. delete sizes;
  2499. delete ourHeader;
  2500. delete sFlags;
  2501. for (int b=0; b<ARRAY_COUNT(diffPics); ++b)
  2502. {
  2503. SDL_FreeSurface(diffPics[b]);
  2504. }
  2505. }
  2506. void CBonusSelection::goBack()
  2507. {
  2508. GH.popIntTotally(this);
  2509. }
  2510. void CBonusSelection::showAll(SDL_Surface * to)
  2511. {
  2512. blitAt(background, pos.x, pos.y, to);
  2513. CIntObject::showAll(to);
  2514. show(to);
  2515. if (pos.h != to->h || pos.w != to->w)
  2516. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  2517. }
  2518. void CBonusSelection::loadPositionsOfGraphics()
  2519. {
  2520. const JsonNode config(GameConstants::DATA_DIR + "/config/campaign_regions.json");
  2521. int idx = 0;
  2522. BOOST_FOREACH(const JsonNode &campaign, config["campaign_regions"].Vector())
  2523. {
  2524. SCampPositions sc;
  2525. sc.campPrefix = campaign["prefix"].String();
  2526. sc.colorSuffixLength = campaign["color_suffix_length"].Float();
  2527. BOOST_FOREACH(const JsonNode &desc, campaign["desc"].Vector())
  2528. {
  2529. SCampPositions::SRegionDesc rd;
  2530. rd.infix = desc["infix"].String();
  2531. rd.xpos = desc["x"].Float();
  2532. rd.ypos = desc["y"].Float();
  2533. sc.regions.push_back(rd);
  2534. }
  2535. campDescriptions.push_back(sc);
  2536. idx++;
  2537. }
  2538. assert(idx == CGI->generaltexth->campaignMapNames.size());
  2539. }
  2540. void CBonusSelection::selectMap( int whichOne )
  2541. {
  2542. sInfo.difficulty = ourCampaign->camp->scenarios[whichOne].difficulty;
  2543. sInfo.mapname = ourCampaign->camp->header.filename;
  2544. sInfo.mode = StartInfo::CAMPAIGN;
  2545. //get header
  2546. int i = 0;
  2547. delete ourHeader;
  2548. ourHeader = new CMapHeader();
  2549. ourHeader->initFromMemory((const unsigned char*)ourCampaign->camp->mapPieces.find(whichOne)->second.c_str(), i);
  2550. std::map<ui32, std::string> names;
  2551. names[1] = settings["general"]["playerName"].String();
  2552. updateStartInfo(ourCampaign->camp->header.filename, sInfo, ourHeader, names);
  2553. sInfo.turnTime = 0;
  2554. sInfo.whichMapInCampaign = whichOne;
  2555. sInfo.difficulty = ourCampaign->camp->scenarios[whichOne].difficulty;
  2556. ourCampaign->currentMap = whichOne;
  2557. mapDesc->setTxt(ourHeader->description);
  2558. updateBonusSelection();
  2559. }
  2560. void CBonusSelection::show(SDL_Surface * to)
  2561. {
  2562. //blitAt(background, pos.x, pos.y, to);
  2563. //map name
  2564. std::string mapName = ourHeader->name;
  2565. if (mapName.length())
  2566. printAtLoc(mapName, 481, 219, FONT_BIG, Colors::Jasmine, to);
  2567. else
  2568. printAtLoc("Unnamed", 481, 219, FONT_BIG, Colors::Jasmine, to);
  2569. //map description
  2570. printAtLoc(CGI->generaltexth->allTexts[496], 481, 253, FONT_SMALL, Colors::Jasmine, to);
  2571. mapDesc->showAll(to); //showAll because CTextBox has no show()
  2572. //map size icon
  2573. int temp;
  2574. switch (ourHeader->width)
  2575. {
  2576. case 36:
  2577. temp=0;
  2578. break;
  2579. case 72:
  2580. temp=1;
  2581. break;
  2582. case 108:
  2583. temp=2;
  2584. break;
  2585. case 144:
  2586. temp=3;
  2587. break;
  2588. default:
  2589. temp=4;
  2590. break;
  2591. }
  2592. blitAtLoc(sizes->ourImages[temp].bitmap, 735, 26, to);
  2593. //flags
  2594. int fx = 496 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[390].c_str());
  2595. int ex = 629 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[391].c_str());
  2596. int myT;
  2597. myT = ourHeader->players[playerColor].team;
  2598. for (std::map<int, PlayerSettings>::const_iterator i = sInfo.playerInfos.begin(); i != sInfo.playerInfos.end(); i++)
  2599. {
  2600. int *myx = ((i->first == playerColor || ourHeader->players[i->first].team == myT) ? &fx : &ex);
  2601. blitAtLoc(sFlags->ourImages[i->first].bitmap, pos.x + *myx, pos.y + 405, to);
  2602. *myx += sFlags->ourImages[i->first].bitmap->w;
  2603. }
  2604. //difficulty
  2605. blitAtLoc(diffPics[sInfo.difficulty], 709, 455, to);
  2606. CIntObject::show(to);
  2607. }
  2608. void CBonusSelection::updateBonusSelection()
  2609. {
  2610. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2611. //graphics:
  2612. //spell - SPELLBON.DEF
  2613. //monster - TWCRPORT.DEF
  2614. //building - BO*.BMP graphics
  2615. //artifact - ARTIFBON.DEF
  2616. //spell scroll - SPELLBON.DEF
  2617. //prim skill - PSKILBON.DEF
  2618. //sec skill - SSKILBON.DEF
  2619. //resource - BORES.DEF
  2620. //player - CREST58.DEF
  2621. //hero - PORTRAITSLARGE (HPL###.BMPs)
  2622. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[sInfo.whichMapInCampaign];
  2623. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  2624. for (size_t i=0; i<bonuses->buttons.size(); i++)
  2625. {
  2626. if (bonuses->buttons[i]->active)
  2627. bonuses->buttons[i]->deactivate();
  2628. delete bonuses->buttons[i];
  2629. }
  2630. bonuses->buttons.clear();
  2631. static const char *bonusPics[] = {"SPELLBON.DEF", "TWCRPORT.DEF", "", "ARTIFBON.DEF", "SPELLBON.DEF",
  2632. "PSKILBON.DEF", "SSKILBON.DEF", "BORES.DEF", "CREST58.DEF", "PORTRAITSLARGE"};
  2633. for(int i = 0; i < bonDescs.size(); i++)
  2634. {
  2635. std::string picName=bonusPics[bonDescs[i].type];
  2636. size_t picNumber=bonDescs[i].info2;
  2637. std::string desc;
  2638. switch(bonDescs[i].type)
  2639. {
  2640. case 0: //spell
  2641. desc = CGI->generaltexth->allTexts[715];
  2642. boost::algorithm::replace_first(desc, "%s", CGI->spellh->spells[bonDescs[i].info2]->name);
  2643. break;
  2644. case 1: //monster
  2645. picNumber = bonDescs[i].info2 + 2;
  2646. desc = CGI->generaltexth->allTexts[717];
  2647. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info3));
  2648. boost::algorithm::replace_first(desc, "%s", CGI->creh->creatures[bonDescs[i].info2]->namePl);
  2649. break;
  2650. case 2: //building
  2651. {
  2652. int faction = -1;
  2653. for(std::map<int, PlayerSettings>::iterator it = sInfo.playerInfos.begin();
  2654. it != sInfo.playerInfos.end(); ++it)
  2655. {
  2656. if (it->second.human)
  2657. {
  2658. faction = it->second.castle;
  2659. break;
  2660. }
  2661. }
  2662. assert(faction != -1);
  2663. int buildID = CBuildingHandler::campToERMU(bonDescs[i].info1, faction, std::set<si32>());
  2664. picName = graphics->ERMUtoPicture[faction][buildID];
  2665. picNumber = -1;
  2666. tlog1<<CGI->buildh->buildings.size()<<"\t"<<faction<<"\t"<<CGI->buildh->buildings[faction].size()<<"\t"<<buildID<<"\n";
  2667. if (vstd::contains(CGI->buildh->buildings[faction], buildID))
  2668. desc = CGI->buildh->buildings[faction].find(buildID)->second->Description();
  2669. }
  2670. break;
  2671. case 3: //artifact
  2672. desc = CGI->generaltexth->allTexts[715];
  2673. boost::algorithm::replace_first(desc, "%s", CGI->arth->artifacts[bonDescs[i].info2]->Name());
  2674. break;
  2675. case 4: //spell scroll
  2676. desc = CGI->generaltexth->allTexts[716];
  2677. boost::algorithm::replace_first(desc, "%s", CGI->spellh->spells[bonDescs[i].info2]->name);
  2678. break;
  2679. case 5: //primary skill
  2680. {
  2681. int leadingSkill = -1;
  2682. std::vector<std::pair<int, int> > toPrint; //primary skills to be listed <num, val>
  2683. const ui8* ptr = reinterpret_cast<const ui8*>(&bonDescs[i].info2);
  2684. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  2685. {
  2686. if (leadingSkill == -1 || ptr[g] > ptr[leadingSkill])
  2687. {
  2688. leadingSkill = g;
  2689. }
  2690. if (ptr[g] != 0)
  2691. {
  2692. toPrint.push_back(std::make_pair(g, ptr[g]));
  2693. }
  2694. }
  2695. picNumber = leadingSkill;
  2696. desc = CGI->generaltexth->allTexts[715];
  2697. std::string substitute; //text to be printed instead of %s
  2698. for (int v=0; v<toPrint.size(); ++v)
  2699. {
  2700. substitute += boost::lexical_cast<std::string>(toPrint[v].second);
  2701. substitute += " " + CGI->generaltexth->primarySkillNames[toPrint[v].first];
  2702. if(v != toPrint.size() - 1)
  2703. {
  2704. substitute += ", ";
  2705. }
  2706. }
  2707. boost::algorithm::replace_first(desc, "%s", substitute);
  2708. break;
  2709. }
  2710. case 6: //secondary skill
  2711. desc = CGI->generaltexth->allTexts[718];
  2712. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->levels[bonDescs[i].info3]); //skill level
  2713. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->skillName[bonDescs[i].info2]); //skill name
  2714. break;
  2715. case 7: //resource
  2716. {
  2717. int serialResID = 0;
  2718. switch(bonDescs[i].info1)
  2719. {
  2720. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  2721. serialResID = bonDescs[i].info1;
  2722. break;
  2723. case 0xFD: //wood + ore
  2724. serialResID = 7;
  2725. break;
  2726. case 0xFE: //rare resources
  2727. serialResID = 8;
  2728. break;
  2729. }
  2730. picNumber = serialResID;
  2731. desc = CGI->generaltexth->allTexts[717];
  2732. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info2));
  2733. std::string replacement;
  2734. if (serialResID <= 6)
  2735. {
  2736. replacement = CGI->generaltexth->restypes[serialResID];
  2737. }
  2738. else
  2739. {
  2740. replacement = CGI->generaltexth->allTexts[714 + serialResID];
  2741. }
  2742. boost::algorithm::replace_first(desc, "%s", replacement);
  2743. }
  2744. break;
  2745. case 8: //player aka hero crossover
  2746. picNumber = bonDescs[i].info1;
  2747. desc = CGI->generaltexth->allTexts[718];
  2748. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->capColors[bonDescs[i].info1]); //player color
  2749. boost::algorithm::replace_first(desc, "%s", ourCampaign->camp->scenarios[bonDescs[i].info2].mapName); //scenario
  2750. break;
  2751. case 9: //hero
  2752. desc = CGI->generaltexth->allTexts[718];
  2753. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->capColors[bonDescs[i].info1]); //hero's color
  2754. if (bonDescs[i].info2 == 0xFFFF)
  2755. {
  2756. boost::algorithm::replace_first(desc, "%s", CGI->heroh->heroes[0]->name); //hero's name
  2757. picNumber = 0;
  2758. }
  2759. else
  2760. {
  2761. boost::algorithm::replace_first(desc, "%s", CGI->heroh->heroes[bonDescs[i].info2]->name); //hero's name
  2762. }
  2763. break;
  2764. }
  2765. CHighlightableButton *bonusButton = new CHighlightableButton(desc, desc, 0, 475 + i*68, 455, "", i);
  2766. if (picNumber != -1)
  2767. picName += ":" + boost::lexical_cast<std::string>(picNumber);
  2768. CAnimation * anim = new CAnimation();
  2769. anim->setCustom(picName, 0);
  2770. bonusButton->setImage(anim);
  2771. bonusButton->borderColor = Colors::Maize; // yellow border
  2772. bonuses->addButton(bonusButton);
  2773. }
  2774. }
  2775. void CBonusSelection::startMap()
  2776. {
  2777. StartInfo *si = new StartInfo(sInfo);
  2778. if (ourCampaign->mapsConquered.size())
  2779. {
  2780. GH.popInts(1);
  2781. }
  2782. else
  2783. {
  2784. CGP->removeFromGui();
  2785. }
  2786. ::startGame(si);
  2787. }
  2788. void CBonusSelection::selectBonus( int id )
  2789. {
  2790. // Total redraw is needed because the border around the bonus images
  2791. // have to be undrawn/drawn.
  2792. if (id != sInfo.choosenCampaignBonus)
  2793. {
  2794. sInfo.choosenCampaignBonus = id;
  2795. GH.totalRedraw();
  2796. if (startB->getState() == CButtonBase::BLOCKED)
  2797. startB->setState(CButtonBase::NORMAL);
  2798. }
  2799. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[sInfo.whichMapInCampaign];
  2800. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  2801. if (bonDescs[id].type == 8) //hero crossover
  2802. {
  2803. SEL->setPlayer(sInfo.playerInfos[0], bonDescs[id].info1); //TODO: substitute with appropriate color
  2804. }
  2805. }
  2806. void CBonusSelection::changeDiff( bool increase )
  2807. {
  2808. if (increase)
  2809. {
  2810. sInfo.difficulty = std::min(sInfo.difficulty + 1, 4);
  2811. }
  2812. else
  2813. {
  2814. sInfo.difficulty = std::max(sInfo.difficulty - 1, 0);
  2815. }
  2816. }
  2817. CBonusSelection::CRegion::CRegion( CBonusSelection * _owner, bool _accessible, bool _selectable, int _myNumber )
  2818. : owner(_owner), accessible(_accessible), selectable(_selectable), myNumber(_myNumber)
  2819. {
  2820. OBJ_CONSTRUCTION;
  2821. addUsedEvents(LCLICK | RCLICK);
  2822. static const std::string colors[2][8] = {
  2823. {"R", "B", "N", "G", "O", "V", "T", "P"},
  2824. {"Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi"}};
  2825. const SCampPositions & campDsc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion];
  2826. const SCampPositions::SRegionDesc & desc = campDsc.regions[myNumber];
  2827. pos.x += desc.xpos;
  2828. pos.y += desc.ypos;
  2829. //loading of graphics
  2830. std::string prefix = campDsc.campPrefix + desc.infix + "_";
  2831. std::string suffix = colors[campDsc.colorSuffixLength - 1][owner->ourCampaign->camp->scenarios[myNumber].regionColor];
  2832. static const std::string infix [] = {"En", "Se", "Co"};
  2833. for (int g = 0; g < ARRAY_COUNT(infix); g++)
  2834. {
  2835. graphics[g] = BitmapHandler::loadBitmap(prefix + infix[g] + suffix + ".BMP");
  2836. }
  2837. pos.w = graphics[0]->w;
  2838. pos.h = graphics[0]->h;
  2839. }
  2840. CBonusSelection::CRegion::~CRegion()
  2841. {
  2842. for (int g=0; g<ARRAY_COUNT(graphics); ++g)
  2843. {
  2844. SDL_FreeSurface(graphics[g]);
  2845. }
  2846. }
  2847. void CBonusSelection::CRegion::clickLeft( tribool down, bool previousState )
  2848. {
  2849. //select if selectable & clicked inside our graphic
  2850. if ( indeterminate(down) )
  2851. {
  2852. return;
  2853. }
  2854. if( !down && selectable && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) )
  2855. {
  2856. owner->selectMap(myNumber);
  2857. owner->highlightedRegion = this;
  2858. parent->showAll(screen);
  2859. }
  2860. }
  2861. void CBonusSelection::CRegion::clickRight( tribool down, bool previousState )
  2862. {
  2863. //show r-click text
  2864. if( down && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) &&
  2865. rclickText.size() )
  2866. {
  2867. CRClickPopup::createAndPush(rclickText);
  2868. }
  2869. }
  2870. void CBonusSelection::CRegion::show(SDL_Surface * to)
  2871. {
  2872. //const SCampPositions::SRegionDesc & desc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion].regions[myNumber];
  2873. if (!accessible)
  2874. {
  2875. //show as striped
  2876. blitAtLoc(graphics[2], 0, 0, to);
  2877. }
  2878. else if (this == owner->highlightedRegion)
  2879. {
  2880. //show as selected
  2881. blitAtLoc(graphics[1], 0, 0, to);
  2882. }
  2883. else
  2884. {
  2885. //show as not selected selected
  2886. blitAtLoc(graphics[0], 0, 0, to);
  2887. }
  2888. }
  2889. CSavingScreen::CSavingScreen(bool hotseat)
  2890. : CSelectionScreen(CMenuScreen::saveGame, hotseat ? CMenuScreen::MULTI_HOT_SEAT : CMenuScreen::SINGLE_PLAYER)
  2891. {
  2892. ourGame = mapInfoFromGame();
  2893. sInfo = *LOCPLINT->cb->getStartInfo();
  2894. setPlayersFromGame();
  2895. }
  2896. CSavingScreen::~CSavingScreen()
  2897. {
  2898. }
  2899. ISelectionScreenInfo::ISelectionScreenInfo(const std::map<ui32, std::string> *Names /*= NULL*/)
  2900. {
  2901. multiPlayer = CMenuScreen::SINGLE_PLAYER;
  2902. assert(!SEL);
  2903. SEL = this;
  2904. current = NULL;
  2905. if(Names && Names->size()) //if have custom set of player names - use it
  2906. playerNames = *Names;
  2907. else
  2908. playerNames[1] = settings["general"]["playerName"].String(); //by default we have only one player and his name is "Player" (or whatever the last used name was)
  2909. }
  2910. ISelectionScreenInfo::~ISelectionScreenInfo()
  2911. {
  2912. assert(SEL == this);
  2913. SEL = NULL;
  2914. }
  2915. void ISelectionScreenInfo::updateStartInfo(std::string filename, StartInfo & sInfo, const CMapHeader * mapHeader)
  2916. {
  2917. ::updateStartInfo(filename, sInfo, mapHeader, playerNames);
  2918. }
  2919. void ISelectionScreenInfo::setPlayer(PlayerSettings &pset, unsigned player)
  2920. {
  2921. ::setPlayer(pset, player, playerNames);
  2922. }
  2923. int ISelectionScreenInfo::getIdOfFirstUnallocatedPlayer()
  2924. {
  2925. for(std::map<ui32, std::string>::const_iterator i = playerNames.begin(); i != playerNames.end(); i++)
  2926. if(!sInfo.getPlayersSettings(i->first)) //
  2927. return i->first;
  2928. return 0;
  2929. }
  2930. bool ISelectionScreenInfo::isGuest() const
  2931. {
  2932. return multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST;
  2933. }
  2934. bool ISelectionScreenInfo::isHost() const
  2935. {
  2936. return multiPlayer == CMenuScreen::MULTI_NETWORK_HOST;
  2937. }
  2938. void ChatMessage::apply(CSelectionScreen *selScreen)
  2939. {
  2940. selScreen->card->chat->addNewMessage(playerName + ": " + message);
  2941. GH.totalRedraw();
  2942. }
  2943. void QuitMenuWithoutStarting::apply(CSelectionScreen *selScreen)
  2944. {
  2945. if(!selScreen->ongoingClosing)
  2946. {
  2947. *selScreen->serv << this; //resend to confirm
  2948. GH.popIntTotally(selScreen); //will wait with deleting us before this thread ends
  2949. }
  2950. vstd::clear_pointer(selScreen->serv);
  2951. }
  2952. void PlayerJoined::apply(CSelectionScreen *selScreen)
  2953. {
  2954. //assert(SEL->playerNames.size() == connectionID); //temporary, TODO when player exits
  2955. SEL->playerNames[connectionID] = playerName;
  2956. //put new player in first slot with AI
  2957. for(std::map<int, PlayerSettings>::iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  2958. {
  2959. if(!i->second.human)
  2960. {
  2961. selScreen->setPlayer(i->second, connectionID);
  2962. selScreen->opt->entries[i->second.color]->selectButtons();
  2963. break;
  2964. }
  2965. }
  2966. selScreen->propagateNames();
  2967. selScreen->propagateOptions();
  2968. GH.totalRedraw();
  2969. }
  2970. void SelectMap::apply(CSelectionScreen *selScreen)
  2971. {
  2972. if(selScreen->multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  2973. {
  2974. free = false;
  2975. selScreen->changeSelection(mapInfo);
  2976. }
  2977. }
  2978. void UpdateStartOptions::apply(CSelectionScreen *selScreen)
  2979. {
  2980. if(!selScreen->isGuest())
  2981. return;
  2982. selScreen->setSInfo(*options);
  2983. }
  2984. void PregameGuiAction::apply(CSelectionScreen *selScreen)
  2985. {
  2986. if(!selScreen->isGuest())
  2987. return;
  2988. switch(action)
  2989. {
  2990. case NO_TAB:
  2991. selScreen->toggleTab(selScreen->curTab);
  2992. break;
  2993. case OPEN_OPTIONS:
  2994. selScreen->toggleTab(selScreen->opt);
  2995. break;
  2996. case OPEN_SCENARIO_LIST:
  2997. selScreen->toggleTab(selScreen->sel);
  2998. break;
  2999. }
  3000. }
  3001. void RequestOptionsChange::apply(CSelectionScreen *selScreen)
  3002. {
  3003. if(!selScreen->isHost())
  3004. return;
  3005. ui8 color = selScreen->sInfo.getPlayersSettings(playerID)->color;
  3006. switch(what)
  3007. {
  3008. case TOWN:
  3009. selScreen->opt->nextCastle(color, direction);
  3010. break;
  3011. case HERO:
  3012. selScreen->opt->nextHero(color, direction);
  3013. break;
  3014. case BONUS:
  3015. selScreen->opt->nextBonus(color, direction);
  3016. break;
  3017. }
  3018. }
  3019. void PlayerLeft::apply(CSelectionScreen *selScreen)
  3020. {
  3021. if(selScreen->isGuest())
  3022. return;
  3023. SEL->playerNames.erase(playerID);
  3024. if(PlayerSettings *s = selScreen->sInfo.getPlayersSettings(playerID)) //it's possible that player was unallocated
  3025. {
  3026. selScreen->setPlayer(*s, 0);
  3027. selScreen->opt->entries[s->color]->selectButtons();
  3028. }
  3029. selScreen->propagateNames();
  3030. selScreen->propagateOptions();
  3031. GH.totalRedraw();
  3032. }
  3033. void PlayersNames::apply(CSelectionScreen *selScreen)
  3034. {
  3035. if(selScreen->isGuest())
  3036. selScreen->playerNames = playerNames;
  3037. }
  3038. void StartWithCurrentSettings::apply(CSelectionScreen *selScreen)
  3039. {
  3040. startingInfo.reset();
  3041. startingInfo.serv = selScreen->serv;
  3042. startingInfo.sInfo = new StartInfo(selScreen->sInfo);
  3043. if(!selScreen->ongoingClosing)
  3044. {
  3045. *selScreen->serv << this; //resend to confirm
  3046. }
  3047. selScreen->serv = NULL; //hide it so it won't be deleted
  3048. vstd::clear_pointer(selScreen->serverHandlingThread); //detach us
  3049. selectedName = selScreen->sInfo.mapname;
  3050. CGP->removeFromGui();
  3051. ::startGame(startingInfo.sInfo, startingInfo.serv);
  3052. throw 666; //EVIL, EVIL, EVIL workaround to kill thread (does "goto catch" outside listening loop)
  3053. }
  3054. CCampaignScreen::CCampaignButton::CCampaignButton(const JsonNode &config )
  3055. {
  3056. pos.x += config["x"].Float();
  3057. pos.y += config["y"].Float();
  3058. pos.w = 200;
  3059. pos.h = 116;
  3060. campFile = config["file"].String();
  3061. video = config["video"].String();
  3062. //On linux we can only play *.mjpg videos from LOKI release
  3063. #ifdef _WIN32
  3064. std::transform(video.begin(), video.end(), video.begin(), toupper);
  3065. video += ".BIK";
  3066. #else
  3067. std::transform(video.begin(), video.end(), video.begin(), tolower);
  3068. video += ".mjpg";
  3069. #endif
  3070. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3071. status = config["open"].Bool() ? CCampaignScreen::ENABLED : CCampaignScreen::DISABLED;
  3072. CCampaignHeader header = CCampaignHandler::getHeader(campFile, true);
  3073. hoverText = header.name;
  3074. if (status != CCampaignScreen::DISABLED)
  3075. {
  3076. addUsedEvents(LCLICK | HOVER);
  3077. image = new CPicture(config["image"].String());
  3078. hoverLabel = new CLabel(pos.w / 2, pos.h + 20, FONT_MEDIUM, CENTER, Colors::Jasmine, "");
  3079. parent->addChild(hoverLabel);
  3080. }
  3081. if (status == CCampaignScreen::COMPLETED)
  3082. checkMark = new CPicture("CAMPCHK");
  3083. }
  3084. void CCampaignScreen::CCampaignButton::clickLeft(tribool down, bool previousState)
  3085. {
  3086. if (down)
  3087. {
  3088. // Close running video and open the selected campaign
  3089. CCS->videoh->close();
  3090. CCampaign * ourCampaign = CCampaignHandler::getCampaign(campFile, true);
  3091. CCampaignState * campState = new CCampaignState();
  3092. campState->camp = ourCampaign;
  3093. GH.pushInt( new CBonusSelection(campState) );
  3094. }
  3095. }
  3096. void CCampaignScreen::CCampaignButton::hover(bool on)
  3097. {
  3098. if (on)
  3099. hoverLabel->setTxt(hoverText); // Shows the name of the campaign when you get into the bounds of the button
  3100. else
  3101. hoverLabel->setTxt(" ");
  3102. }
  3103. void CCampaignScreen::CCampaignButton::show(SDL_Surface * to)
  3104. {
  3105. if (status == CCampaignScreen::DISABLED)
  3106. return;
  3107. CIntObject::show(to);
  3108. // Play the campaign button video when the mouse cursor is placed over the button
  3109. if (hovered)
  3110. {
  3111. if (CCS->videoh->fname != video)
  3112. CCS->videoh->open(video);
  3113. CCS->videoh->update(pos.x, pos.y, to, true, false); // plays sequentially frame by frame, starts at the beginning when the video is over
  3114. }
  3115. else if (CCS->videoh->fname == video) // When you got out of the bounds of the button then close the video
  3116. {
  3117. CCS->videoh->close();
  3118. redraw();
  3119. }
  3120. }
  3121. CAdventureMapButton* CCampaignScreen::createExitButton(const JsonNode& button)
  3122. {
  3123. std::pair<std::string, std::string> help;
  3124. if (!button["help"].isNull() && button["help"].Float() > 0)
  3125. help = CGI->generaltexth->zelp[button["help"].Float()];
  3126. boost::function<void()> close = boost::bind(&CGuiHandler::popIntTotally, &GH, this);
  3127. return new CAdventureMapButton(help, close, button["x"].Float(), button["y"].Float(), button["name"].String(), button["hotkey"].Float());
  3128. }
  3129. CCampaignScreen::CCampaignScreen(const JsonNode &config)
  3130. {
  3131. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3132. BOOST_FOREACH(const JsonNode& node, config["images"].Vector())
  3133. images.push_back(createPicture(node));
  3134. if (!images.empty())
  3135. {
  3136. images[0]->center(); // move background to center
  3137. moveTo(images[0]->pos.topLeft()); // move everything else to center
  3138. images[0]->moveTo(pos.topLeft()); // restore moved twice background
  3139. pos = images[0]->pos; // fix height\width of this window
  3140. }
  3141. if (!config["exitbutton"].isNull())
  3142. {
  3143. back = createExitButton(config["exitbutton"]);
  3144. back->hoverable = true;
  3145. }
  3146. BOOST_FOREACH(const JsonNode& node, config["items"].Vector())
  3147. campButtons.push_back(new CCampaignButton(node));
  3148. }
  3149. void CCampaignScreen::showAll(SDL_Surface *to)
  3150. {
  3151. CIntObject::showAll(to);
  3152. if (pos.h != to->h || pos.w != to->w)
  3153. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  3154. }