CPreGame.cpp 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665
  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. {
  1008. txt = new CTextInput(Rect(32, 539, 350, 20), Point(-32, -25), "GSSTRIP.bmp", 0);
  1009. txt->filters.add(CTextInput::filenameFilter);
  1010. }
  1011. break;
  1012. case CMenuScreen::campaignList:
  1013. getFiles(toParse, GameConstants::DATA_DIR + "/Maps", "h3c"); //get all campaigns
  1014. /* Load campaingns from user directory too, unless it is also the
  1015. * same as the data directory (as is the case on
  1016. * windows). */
  1017. if (GVCMIDirs.UserPath != GameConstants::DATA_DIR)
  1018. getFiles(toParse, GVCMIDirs.UserPath + "/Maps", "h3c"); //get all maps
  1019. for (int g=0; g<toParse.size(); ++g)
  1020. {
  1021. toParse[g].inLod = false;
  1022. }
  1023. //add lod cmpgns
  1024. cpm = CCampaignHandler::getCampaignHeaders(CCampaignHandler::Custom);
  1025. for (int g = 0; g < cpm.size(); g++)
  1026. {
  1027. FileInfo fi;
  1028. fi.inLod = cpm[g].loadFromLod;
  1029. fi.name = cpm[g].filename;
  1030. if (cpm[g].loadFromLod)
  1031. {
  1032. toParse.push_back(fi);
  1033. allItems.push_back(CMapInfo(false));
  1034. }
  1035. }
  1036. parseCampaigns(toParse);
  1037. positions = 18;
  1038. break;
  1039. default:
  1040. assert(0);
  1041. break;
  1042. }
  1043. }
  1044. if (tabType != CMenuScreen::campaignList)
  1045. {
  1046. //size filter buttons
  1047. {
  1048. int sizes[] = {36, 72, 108, 144, 0};
  1049. const char * names[] = {"SCSMBUT.DEF", "SCMDBUT.DEF", "SCLGBUT.DEF", "SCXLBUT.DEF", "SCALBUT.DEF"};
  1050. for(int i = 0; i < 5; i++)
  1051. new CAdventureMapButton("", CGI->generaltexth->zelp[54+i].second, bind(&SelectionTab::filter, this, sizes[i], true), 158 + 47*i, 46, names[i]);
  1052. }
  1053. //sort buttons buttons
  1054. {
  1055. int xpos[] = {23, 55, 88, 121, 306, 339};
  1056. const char * names[] = {"SCBUTT1.DEF", "SCBUTT2.DEF", "SCBUTCP.DEF", "SCBUTT3.DEF", "SCBUTT4.DEF", "SCBUTT5.DEF"};
  1057. for(int i = 0; i < 6; i++)
  1058. new CAdventureMapButton("", CGI->generaltexth->zelp[107+i].second, bind(&SelectionTab::sortBy, this, i), xpos[i], 86, names[i]);
  1059. }
  1060. }
  1061. else
  1062. {
  1063. //sort by buttons
  1064. new CAdventureMapButton("", "", bind(&SelectionTab::sortBy, this, _numOfMaps), 23, 86, "CamCusM.DEF"); //by num of maps
  1065. new CAdventureMapButton("", "", bind(&SelectionTab::sortBy, this, _name), 55, 86, "CamCusL.DEF"); //by name
  1066. }
  1067. slider = new CSlider(372, 86, tabType != CMenuScreen::saveGame ? 480 : 430, bind(&SelectionTab::sliderMove, this, _1), positions, curItems.size(), 0, false, 1);
  1068. slider->addUsedEvents(WHEEL);
  1069. slider->slider->keepFrame = true;
  1070. format = CDefHandler::giveDef("SCSELC.DEF");
  1071. sortingBy = _format;
  1072. ascending = true;
  1073. filter(0);
  1074. //select(0);
  1075. switch(tabType)
  1076. {
  1077. case CMenuScreen::newGame:
  1078. selectFName(GameConstants::DATA_DIR + "/Maps/Arrogance.h3m");
  1079. break;
  1080. case CMenuScreen::loadGame:
  1081. case CMenuScreen::campaignList:
  1082. select(0);
  1083. break;
  1084. case CMenuScreen::saveGame:;
  1085. if(selectedName.size())
  1086. {
  1087. if(selectedName[2] == 'M') //name starts with ./Maps instead of ./Games => there was nothing to select
  1088. txt->setTxt("NEWGAME");
  1089. else
  1090. selectFName(selectedName);
  1091. }
  1092. }
  1093. }
  1094. SelectionTab::~SelectionTab()
  1095. {
  1096. delete format;
  1097. }
  1098. void SelectionTab::sortBy( int criteria )
  1099. {
  1100. if(criteria == sortingBy)
  1101. {
  1102. ascending = !ascending;
  1103. }
  1104. else
  1105. {
  1106. sortingBy = (ESortBy)criteria;
  1107. ascending = true;
  1108. }
  1109. sort();
  1110. selectAbs(0);
  1111. }
  1112. void SelectionTab::sort()
  1113. {
  1114. if(sortingBy != _name)
  1115. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(_name));
  1116. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  1117. if(!ascending)
  1118. std::reverse(curItems.begin(), curItems.end());
  1119. redraw();
  1120. }
  1121. void SelectionTab::select( int position )
  1122. {
  1123. if(!curItems.size()) return;
  1124. // New selection. py is the index in curItems.
  1125. int py = position + slider->value;
  1126. vstd::amax(py, 0);
  1127. vstd::amin(py, curItems.size()-1);
  1128. selectionPos = py;
  1129. if(position < 0)
  1130. slider->moveTo(slider->value + position);
  1131. else if(position >= positions)
  1132. slider->moveTo(slider->value + position - positions + 1);
  1133. if(txt)
  1134. txt->setTxt(fs::basename(curItems[py]->filename));
  1135. onSelect(curItems[py]);
  1136. }
  1137. void SelectionTab::selectAbs( int position )
  1138. {
  1139. select(position - slider->value);
  1140. }
  1141. int SelectionTab::getPosition( int x, int y )
  1142. {
  1143. return -1;
  1144. }
  1145. void SelectionTab::sliderMove( int slidPos )
  1146. {
  1147. if(!slider) return; //ignore spurious call when slider is being created
  1148. redraw();
  1149. }
  1150. // Display the tab with the scenario names
  1151. //
  1152. // elemIdx is the index of the maps or saved game to display on line 0
  1153. // slider->capacity contains the number of available screen lines
  1154. // slider->positionsAmnt is the number of elements after filtering
  1155. void SelectionTab::printMaps(SDL_Surface *to)
  1156. {
  1157. int elemIdx = slider->value;
  1158. // Display all elements if there's enough space
  1159. //if(slider->amount < slider->capacity)
  1160. // elemIdx = 0;
  1161. SDL_Color itemColor;
  1162. #define POS(xx, yy) pos.x + xx, pos.y + yy + line*25
  1163. for (int line = 0; line < positions && elemIdx < curItems.size(); elemIdx++, line++)
  1164. {
  1165. CMapInfo *currentItem = curItems[elemIdx];
  1166. if (elemIdx == selectionPos)
  1167. itemColor=Colors::Jasmine;
  1168. else
  1169. itemColor=Colors::Cornsilk;
  1170. if(tabType != CMenuScreen::campaignList)
  1171. {
  1172. //amount of players
  1173. std::ostringstream ostr(std::ostringstream::out);
  1174. ostr << currentItem->playerAmnt << "/" << currentItem->humenPlayers;
  1175. CSDL_Ext::printAt(ostr.str(), POS(29, 120), FONT_SMALL, itemColor, to);
  1176. //map size
  1177. std::string temp2 = "C";
  1178. switch (currentItem->mapHeader->width)
  1179. {
  1180. case 36:
  1181. temp2="S";
  1182. break;
  1183. case 72:
  1184. temp2="M";
  1185. break;
  1186. case 108:
  1187. temp2="L";
  1188. break;
  1189. case 144:
  1190. temp2="XL";
  1191. break;
  1192. }
  1193. CSDL_Ext::printAtMiddle(temp2, POS(70, 128), FONT_SMALL, itemColor, to);
  1194. int temp=-1;
  1195. switch (currentItem->mapHeader->version)
  1196. {
  1197. case CMapHeader::RoE:
  1198. temp=0;
  1199. break;
  1200. case CMapHeader::AB:
  1201. temp=1;
  1202. break;
  1203. case CMapHeader::SoD:
  1204. temp=2;
  1205. break;
  1206. case CMapHeader::WoG:
  1207. temp=3;
  1208. break;
  1209. default:
  1210. // Unknown version. Be safe and ignore that map
  1211. tlog2 << "Warning: " << currentItem->filename << " has wrong version!\n";
  1212. continue;
  1213. }
  1214. blitAt(format->ourImages[temp].bitmap, POS(88, 117), to);
  1215. //victory conditions
  1216. if (currentItem->mapHeader->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  1217. temp = 11;
  1218. else
  1219. temp = currentItem->mapHeader->victoryCondition.condition;
  1220. blitAt(CGP->victory->ourImages[temp].bitmap, POS(306, 117), to);
  1221. //loss conditions
  1222. if (currentItem->mapHeader->lossCondition.typeOfLossCon == ELossConditionType::LOSSSTANDARD)
  1223. temp=3;
  1224. else
  1225. temp=currentItem->mapHeader->lossCondition.typeOfLossCon;
  1226. blitAt(CGP->loss->ourImages[temp].bitmap, POS(339, 117), to);
  1227. }
  1228. else //if campaign
  1229. {
  1230. //number of maps in campaign
  1231. std::ostringstream ostr(std::ostringstream::out);
  1232. ostr << CGI->generaltexth->campaignRegionNames[ currentItem->campaignHeader->mapVersion ].size();
  1233. CSDL_Ext::printAt(ostr.str(), POS(29, 120), FONT_SMALL, itemColor, to);
  1234. }
  1235. std::string name;
  1236. if(tabType == CMenuScreen::newGame)
  1237. {
  1238. if (!currentItem->mapHeader->name.length())
  1239. currentItem->mapHeader->name = "Unnamed";
  1240. name = currentItem->mapHeader->name;
  1241. }
  1242. else if(tabType == CMenuScreen::campaignList)
  1243. {
  1244. name = currentItem->campaignHeader->name;
  1245. }
  1246. else
  1247. {
  1248. name = fs::basename(currentItem->filename);
  1249. }
  1250. //print name
  1251. CSDL_Ext::printAtMiddle(CSDL_Ext::trimToFit(name, 185, FONT_SMALL), POS(213, 128), FONT_SMALL, itemColor, to);
  1252. }
  1253. #undef POS
  1254. }
  1255. void SelectionTab::showAll(SDL_Surface * to)
  1256. {
  1257. CIntObject::showAll(to);
  1258. printMaps(to);
  1259. std::string title;
  1260. switch(tabType) {
  1261. case CMenuScreen::newGame:
  1262. title = CGI->generaltexth->arraytxt[229];
  1263. break;
  1264. case CMenuScreen::loadGame:
  1265. title = CGI->generaltexth->arraytxt[230];
  1266. break;
  1267. case CMenuScreen::saveGame:
  1268. title = CGI->generaltexth->arraytxt[231];
  1269. break;
  1270. case CMenuScreen::campaignList:
  1271. title = "Select a Campaign"; //TODO: find where is the title
  1272. break;
  1273. }
  1274. CSDL_Ext::printAtMiddle(title, pos.x+205, pos.y+28, FONT_MEDIUM, Colors::Jasmine, to); //Select a Scenario to Play
  1275. if(tabType != CMenuScreen::campaignList)
  1276. {
  1277. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[510], pos.x+87, pos.y+62, FONT_SMALL, Colors::Jasmine, to); //Map sizes
  1278. }
  1279. }
  1280. void SelectionTab::clickLeft( tribool down, bool previousState )
  1281. {
  1282. if(down)
  1283. {
  1284. int line = getLine();
  1285. if(line != -1)
  1286. select(line);
  1287. }
  1288. }
  1289. void SelectionTab::keyPressed( const SDL_KeyboardEvent & key )
  1290. {
  1291. if(key.state != SDL_PRESSED) return;
  1292. int moveBy = 0;
  1293. switch(key.keysym.sym)
  1294. {
  1295. case SDLK_UP:
  1296. moveBy = -1;
  1297. break;
  1298. case SDLK_DOWN:
  1299. moveBy = +1;
  1300. break;
  1301. case SDLK_PAGEUP:
  1302. moveBy = -positions+1;
  1303. break;
  1304. case SDLK_PAGEDOWN:
  1305. moveBy = +positions-1;
  1306. break;
  1307. case SDLK_HOME:
  1308. select(-slider->value);
  1309. return;
  1310. case SDLK_END:
  1311. select(curItems.size() - slider->value);
  1312. return;
  1313. default:
  1314. return;
  1315. }
  1316. select(selectionPos - slider->value + moveBy);
  1317. }
  1318. void SelectionTab::onDoubleClick()
  1319. {
  1320. if(getLine() != -1) //double clicked scenarios list
  1321. {
  1322. //act as if start button was pressed
  1323. (static_cast<CSelectionScreen*>(parent))->start->callback();
  1324. }
  1325. }
  1326. int SelectionTab::getLine()
  1327. {
  1328. int line = -1;
  1329. Point clickPos(GH.current->button.x, GH.current->button.y);
  1330. clickPos = clickPos - pos.topLeft();
  1331. if (clickPos.y > 115 && clickPos.y < 564 && clickPos.x > 22 && clickPos.x < 371)
  1332. {
  1333. line = (clickPos.y-115) / 25; //which line
  1334. }
  1335. return line;
  1336. }
  1337. void SelectionTab::selectFName( const std::string &fname )
  1338. {
  1339. for(int i = curItems.size() - 1; i >= 0; i--)
  1340. {
  1341. if(curItems[i]->filename == fname)
  1342. {
  1343. slider->moveTo(i);
  1344. selectAbs(i);
  1345. return;
  1346. }
  1347. }
  1348. selectAbs(0);
  1349. }
  1350. CChatBox::CChatBox(const Rect &rect)
  1351. {
  1352. OBJ_CONSTRUCTION;
  1353. pos += rect;
  1354. addUsedEvents(KEYBOARD);
  1355. captureAllKeys = true;
  1356. const int height = graphics->fonts[FONT_SMALL]->height;
  1357. inputBox = new CTextInput(Rect(0, rect.h - height, rect.w, height));
  1358. inputBox->removeUsedEvents(KEYBOARD);
  1359. chatHistory = new CTextBox("", Rect(0, 0, rect.w, rect.h - height), 1);
  1360. SDL_Color green = {0,252,0, SDL_ALPHA_OPAQUE};
  1361. chatHistory->color = green;
  1362. }
  1363. void CChatBox::keyPressed(const SDL_KeyboardEvent & key)
  1364. {
  1365. if(key.keysym.sym == SDLK_RETURN && key.state == SDL_PRESSED && inputBox->text.size())
  1366. {
  1367. SEL->postChatMessage(inputBox->text);
  1368. inputBox->setTxt("");
  1369. }
  1370. else
  1371. inputBox->keyPressed(key);
  1372. }
  1373. void CChatBox::addNewMessage(const std::string &text)
  1374. {
  1375. chatHistory->setTxt(chatHistory->text + text + "\n");
  1376. if(chatHistory->slider)
  1377. chatHistory->slider->moveToMax();
  1378. }
  1379. InfoCard::InfoCard( bool Network )
  1380. : bg(NULL), network(Network), chatOn(false), chat(NULL), playerListBg(NULL),
  1381. difficulty(NULL), sizes(NULL), sFlags(NULL)
  1382. {
  1383. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1384. pos.x += 393;
  1385. pos.y += 6;
  1386. addUsedEvents(RCLICK);
  1387. mapDescription = NULL;
  1388. Rect descriptionRect(26, 149, 320, 115);
  1389. mapDescription = new CTextBox("", descriptionRect, 1);
  1390. if(SEL->screenType == CMenuScreen::campaignList)
  1391. {
  1392. CSelectionScreen *ss = static_cast<CSelectionScreen*>(parent);
  1393. 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)
  1394. }
  1395. else
  1396. {
  1397. bg = new CPicture("GSELPOP1.bmp", 0, 0);
  1398. parent->addChild(bg);
  1399. auto it = vstd::find(parent->children, this); //our position among parent children
  1400. parent->children.insert(it, bg); //put BG before us
  1401. parent->children.pop_back();
  1402. pos.w = bg->pos.w;
  1403. pos.h = bg->pos.h;
  1404. sizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
  1405. sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
  1406. difficulty = new CHighlightableButtonsGroup(0);
  1407. {
  1408. static const char *difButns[] = {"GSPBUT3.DEF", "GSPBUT4.DEF", "GSPBUT5.DEF", "GSPBUT6.DEF", "GSPBUT7.DEF"};
  1409. for(int i = 0; i < 5; i++)
  1410. {
  1411. difficulty->addButton(new CHighlightableButton("", CGI->generaltexth->zelp[24+i].second, 0, 110 + i*32, 450, difButns[i], i));
  1412. }
  1413. }
  1414. if(SEL->screenType != CMenuScreen::newGame)
  1415. difficulty->block(true);
  1416. //description needs bg
  1417. mapDescription->addChild(new CPicture(*bg, descriptionRect), true); //move subpicture bg to our description control (by default it's our (Infocard) child)
  1418. if(network)
  1419. {
  1420. playerListBg = new CPicture("CHATPLUG.bmp", 16, 276);
  1421. chat = new CChatBox(descriptionRect);
  1422. 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)
  1423. chatOn = true;
  1424. mapDescription->disable();
  1425. }
  1426. }
  1427. }
  1428. InfoCard::~InfoCard()
  1429. {
  1430. delete sizes;
  1431. delete sFlags;
  1432. }
  1433. void InfoCard::showAll(SDL_Surface * to)
  1434. {
  1435. CIntObject::showAll(to);
  1436. //blit texts
  1437. if(SEL->screenType != CMenuScreen::campaignList)
  1438. {
  1439. printAtLoc(CGI->generaltexth->allTexts[390] + ":", 24, 400, FONT_SMALL, Colors::Cornsilk, to); //Allies
  1440. printAtLoc(CGI->generaltexth->allTexts[391] + ":", 190, 400, FONT_SMALL, Colors::Cornsilk, to); //Enemies
  1441. printAtLoc(CGI->generaltexth->allTexts[494], 33, 430, FONT_SMALL, Colors::Jasmine, to);//"Map Diff:"
  1442. printAtLoc(CGI->generaltexth->allTexts[492] + ":", 133,430, FONT_SMALL, Colors::Jasmine, to); //player difficulty
  1443. printAtLoc(CGI->generaltexth->allTexts[218] + ":", 290,430, FONT_SMALL, Colors::Jasmine, to); //"Rating:"
  1444. printAtLoc(CGI->generaltexth->allTexts[495], 26, 22, FONT_SMALL, Colors::Jasmine, to); //Scenario Name:
  1445. if(!chatOn)
  1446. {
  1447. printAtLoc(CGI->generaltexth->allTexts[496], 26, 132, FONT_SMALL, Colors::Jasmine, to); //Scenario Description:
  1448. printAtLoc(CGI->generaltexth->allTexts[497], 26, 283, FONT_SMALL, Colors::Jasmine, to); //Victory Condition:
  1449. printAtLoc(CGI->generaltexth->allTexts[498], 26, 339, FONT_SMALL, Colors::Jasmine, to); //Loss Condition:
  1450. }
  1451. else //players list
  1452. {
  1453. std::map<ui32, std::string> playerNames = SEL->playerNames;
  1454. int playerSoFar = 0;
  1455. for (std::map<int, PlayerSettings>::const_iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1456. {
  1457. if(i->second.human)
  1458. {
  1459. printAtLoc(i->second.name, 24, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->height, FONT_SMALL, Colors::Cornsilk, to);
  1460. playerNames.erase(i->second.human);
  1461. }
  1462. }
  1463. playerSoFar = 0;
  1464. for (std::map<ui32, std::string>::const_iterator i = playerNames.begin(); i != playerNames.end(); i++)
  1465. {
  1466. printAtLoc(i->second, 193, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->height, FONT_SMALL, Colors::Cornsilk, to);
  1467. }
  1468. }
  1469. }
  1470. if(SEL->current)
  1471. {
  1472. if(SEL->screenType != CMenuScreen::campaignList)
  1473. {
  1474. int temp = -1;
  1475. if(!chatOn)
  1476. {
  1477. //victory conditions
  1478. temp = SEL->current->mapHeader->victoryCondition.condition+1;
  1479. if (temp>20) temp=0;
  1480. std::string sss = CGI->generaltexth->victoryConditions[temp];
  1481. if (temp && SEL->current->mapHeader->victoryCondition.allowNormalVictory) sss+= "/" + CGI->generaltexth->victoryConditions[0];
  1482. printAtLoc(sss, 60, 307, FONT_SMALL, Colors::Cornsilk, to);
  1483. temp = SEL->current->mapHeader->victoryCondition.condition;
  1484. if (temp>12) temp=11;
  1485. blitAtLoc(CGP->victory->ourImages[temp].bitmap, 24, 302, to); //victory cond descr
  1486. //loss conditoins
  1487. temp = SEL->current->mapHeader->lossCondition.typeOfLossCon+1;
  1488. if (temp>20) temp=0;
  1489. sss = CGI->generaltexth->lossCondtions[temp];
  1490. printAtLoc(sss, 60, 366, FONT_SMALL, Colors::Cornsilk, to);
  1491. temp=SEL->current->mapHeader->lossCondition.typeOfLossCon;
  1492. if (temp>12) temp=3;
  1493. blitAtLoc(CGP->loss->ourImages[temp].bitmap, 24, 359, to); //loss cond
  1494. }
  1495. //difficulty
  1496. assert(SEL->current->mapHeader->difficulty <= 4);
  1497. std::string &diff = CGI->generaltexth->arraytxt[142 + SEL->current->mapHeader->difficulty];
  1498. printAtMiddleLoc(diff, 62, 472, FONT_SMALL, Colors::Cornsilk, to);
  1499. //selecting size icon
  1500. switch (SEL->current->mapHeader->width)
  1501. {
  1502. case 36:
  1503. temp=0;
  1504. break;
  1505. case 72:
  1506. temp=1;
  1507. break;
  1508. case 108:
  1509. temp=2;
  1510. break;
  1511. case 144:
  1512. temp=3;
  1513. break;
  1514. default:
  1515. temp=4;
  1516. break;
  1517. }
  1518. blitAtLoc(sizes->ourImages[temp].bitmap, 318, 22, to);
  1519. if(SEL->screenType == CMenuScreen::loadGame)
  1520. printToLoc((static_cast<const CMapInfo*>(SEL->current))->date,308,34, FONT_SMALL, Colors::Cornsilk, to);
  1521. //print flags
  1522. int fx = 34 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[390].c_str());
  1523. int ex = 200 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[391].c_str());
  1524. int myT;
  1525. if(playerColor >= 0)
  1526. myT = SEL->current->mapHeader->players[playerColor].team;
  1527. else
  1528. myT = -1;
  1529. for (std::map<int, PlayerSettings>::const_iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1530. {
  1531. int *myx = ((i->first == playerColor || SEL->current->mapHeader->players[i->first].team == myT) ? &fx : &ex);
  1532. blitAtLoc(sFlags->ourImages[i->first].bitmap, *myx, 399, to);
  1533. *myx += sFlags->ourImages[i->first].bitmap->w;
  1534. }
  1535. std::string tob;
  1536. switch (SEL->sInfo.difficulty)
  1537. {
  1538. case 0:
  1539. tob="80%";
  1540. break;
  1541. case 1:
  1542. tob="100%";
  1543. break;
  1544. case 2:
  1545. tob="130%";
  1546. break;
  1547. case 3:
  1548. tob="160%";
  1549. break;
  1550. case 4:
  1551. tob="200%";
  1552. break;
  1553. }
  1554. printAtMiddleLoc(tob, 311, 472, FONT_SMALL, Colors::Cornsilk, to);
  1555. }
  1556. //blit description
  1557. std::string name;
  1558. if (SEL->screenType == CMenuScreen::campaignList)
  1559. {
  1560. name = SEL->current->campaignHeader->name;
  1561. }
  1562. else
  1563. {
  1564. name = SEL->current->mapHeader->name;
  1565. }
  1566. //name
  1567. if (name.length())
  1568. printAtLoc(CSDL_Ext::trimToFit(name, 300, FONT_BIG), 26, 39, FONT_BIG, Colors::Jasmine, to);
  1569. else
  1570. printAtLoc("Unnamed", 26, 39, FONT_BIG, Colors::Jasmine, to);
  1571. }
  1572. }
  1573. void InfoCard::changeSelection( const CMapInfo *to )
  1574. {
  1575. if(to && mapDescription)
  1576. {
  1577. if (SEL->screenType == CMenuScreen::campaignList)
  1578. mapDescription->setTxt(to->campaignHeader->description);
  1579. else
  1580. mapDescription->setTxt(to->mapHeader->description);
  1581. if(SEL->screenType != CMenuScreen::newGame && SEL->screenType != CMenuScreen::campaignList) {
  1582. difficulty->block(true);
  1583. difficulty->select(SEL->sInfo.difficulty, 0);
  1584. }
  1585. }
  1586. GH.totalRedraw();
  1587. }
  1588. void InfoCard::clickRight( tribool down, bool previousState )
  1589. {
  1590. static const Rect flagArea(19, 397, 335, 23);
  1591. if(down && SEL->current && isItInLoc(flagArea, GH.current->motion.x, GH.current->motion.y))
  1592. showTeamsPopup();
  1593. }
  1594. void InfoCard::showTeamsPopup()
  1595. {
  1596. SDL_Surface *bmp = CMessage::drawDialogBox(256, 90 + 50 * SEL->current->mapHeader->howManyTeams);
  1597. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[657], 128, 30, FONT_MEDIUM, Colors::Jasmine, bmp); //{Team Alignments}
  1598. for(int i = 0; i < SEL->current->mapHeader->howManyTeams; i++)
  1599. {
  1600. std::vector<ui8> flags;
  1601. std::string hlp = CGI->generaltexth->allTexts[656]; //Team %d
  1602. hlp.replace(hlp.find("%d"), 2, boost::lexical_cast<std::string>(i+1));
  1603. CSDL_Ext::printAtMiddle(hlp, 128, 65 + 50*i, FONT_SMALL, Colors::Cornsilk, bmp);
  1604. for(int j = 0; j < GameConstants::PLAYER_LIMIT; j++)
  1605. if((SEL->current->mapHeader->players[j].canHumanPlay || SEL->current->mapHeader->players[j].canComputerPlay)
  1606. && SEL->current->mapHeader->players[j].team == i)
  1607. flags.push_back(j);
  1608. int curx = 128 - 9*flags.size();
  1609. for(int j = 0; j < flags.size(); j++)
  1610. {
  1611. blitAt(sFlags->ourImages[flags[j]].bitmap, curx, 75 + 50*i, bmp);
  1612. curx += 18;
  1613. }
  1614. }
  1615. GH.pushInt(new CInfoPopup(bmp, true));
  1616. }
  1617. void InfoCard::toggleChat()
  1618. {
  1619. setChat(!chatOn);
  1620. }
  1621. void InfoCard::setChat(bool activateChat)
  1622. {
  1623. if(chatOn == activateChat)
  1624. return;
  1625. assert(active);
  1626. if(activateChat)
  1627. {
  1628. mapDescription->disable();
  1629. chat->enable();
  1630. playerListBg->enable();
  1631. }
  1632. else
  1633. {
  1634. mapDescription->enable();
  1635. chat->disable();
  1636. playerListBg->disable();
  1637. }
  1638. chatOn = activateChat;
  1639. GH.totalRedraw();
  1640. }
  1641. OptionsTab::OptionsTab():
  1642. turnDuration(NULL)
  1643. {
  1644. OBJ_CONSTRUCTION;
  1645. bg = new CPicture("ADVOPTBK", 0, 6);
  1646. pos = bg->pos;
  1647. if(SEL->screenType == CMenuScreen::newGame)
  1648. turnDuration = new CSlider(55, 551, 194, bind(&OptionsTab::setTurnLength, this, _1), 1, 11, 11, true, 1);
  1649. }
  1650. OptionsTab::~OptionsTab()
  1651. {
  1652. }
  1653. void OptionsTab::showAll(SDL_Surface * to)
  1654. {
  1655. CIntObject::showAll(to);
  1656. printAtMiddleLoc(CGI->generaltexth->allTexts[515], 222, 30, FONT_BIG, Colors::Jasmine, to);
  1657. 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.
  1658. printAtMiddleWBLoc(CGI->generaltexth->allTexts[517], 107, 102, FONT_SMALL, 14, Colors::Jasmine, to); //Player Name Handicap Type
  1659. printAtMiddleWBLoc(CGI->generaltexth->allTexts[518], 197, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Town
  1660. printAtMiddleWBLoc(CGI->generaltexth->allTexts[519], 273, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Hero
  1661. printAtMiddleWBLoc(CGI->generaltexth->allTexts[520], 349, 102, FONT_SMALL, 10, Colors::Jasmine, to); //Starting Bonus
  1662. printAtMiddleLoc(CGI->generaltexth->allTexts[521], 222, 538, FONT_SMALL, Colors::Jasmine, to); // Player Turn Duration
  1663. if (turnDuration)
  1664. printAtMiddleLoc(CGI->generaltexth->turnDurations[turnDuration->value], 319,559, FONT_SMALL, Colors::Cornsilk, to);//Turn duration value
  1665. }
  1666. void OptionsTab::nextCastle( int player, int dir )
  1667. {
  1668. if(SEL->isGuest())
  1669. {
  1670. SEL->postRequest(RequestOptionsChange::TOWN, dir);
  1671. return;
  1672. }
  1673. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1674. si32 &cur = s.castle;
  1675. ui32 allowed = SEL->current->mapHeader->players[s.color].allowedFactions;
  1676. if (cur == -2) //no castle - no change
  1677. return;
  1678. if (cur == -1) //random => first/last available
  1679. {
  1680. int pom = (dir>0) ? (0) : (GameConstants::F_NUMBER-1); // last or first
  1681. for (;pom >= 0 && pom < GameConstants::F_NUMBER; pom+=dir)
  1682. {
  1683. if((1 << pom) & allowed)
  1684. {
  1685. cur=pom;
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. else // next/previous available
  1691. {
  1692. for (;;)
  1693. {
  1694. cur+=dir;
  1695. if ((1 << cur) & allowed)
  1696. break;
  1697. if (cur >= GameConstants::F_NUMBER || cur<0)
  1698. {
  1699. double p1 = log((double)allowed) / log(2.0)+0.000001;
  1700. double check = p1 - ((int)p1);
  1701. if (check < 0.001)
  1702. cur = (int)p1;
  1703. else
  1704. cur = -1;
  1705. break;
  1706. }
  1707. }
  1708. }
  1709. if(s.hero >= 0)
  1710. s.hero = -1;
  1711. if(cur < 0 && s.bonus == PlayerSettings::bresource)
  1712. s.bonus = PlayerSettings::brandom;
  1713. entries[player]->selectButtons();
  1714. SEL->propagateOptions();
  1715. redraw();
  1716. }
  1717. void OptionsTab::nextHero( int player, int dir )
  1718. {
  1719. if(SEL->isGuest())
  1720. {
  1721. SEL->postRequest(RequestOptionsChange::HERO, dir);
  1722. return;
  1723. }
  1724. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1725. int old = s.hero;
  1726. if (s.castle < 0 || !s.human || s.hero == -2)
  1727. return;
  1728. if (s.hero == -1) //random => first/last available
  1729. {
  1730. int max = (s.castle*GameConstants::HEROES_PER_TYPE*2+15),
  1731. min = (s.castle*GameConstants::HEROES_PER_TYPE*2);
  1732. s.hero = nextAllowedHero(min,max,0,dir);
  1733. }
  1734. else
  1735. {
  1736. if(dir > 0)
  1737. s.hero = nextAllowedHero(s.hero,(s.castle*GameConstants::HEROES_PER_TYPE*2+16),1,dir);
  1738. else
  1739. s.hero = nextAllowedHero(s.castle*GameConstants::HEROES_PER_TYPE*2-1,s.hero,1,dir);
  1740. }
  1741. if(old != s.hero)
  1742. {
  1743. usedHeroes.erase(old);
  1744. usedHeroes.insert(s.hero);
  1745. redraw();
  1746. }
  1747. SEL->propagateOptions();
  1748. }
  1749. int OptionsTab::nextAllowedHero( int min, int max, int incl, int dir )
  1750. {
  1751. if(dir>0)
  1752. {
  1753. for(int i=min+incl; i<=max-incl; i++)
  1754. if(canUseThisHero(i))
  1755. return i;
  1756. }
  1757. else
  1758. {
  1759. for(int i=max-incl; i>=min+incl; i--)
  1760. if(canUseThisHero(i))
  1761. return i;
  1762. }
  1763. return -1;
  1764. }
  1765. bool OptionsTab::canUseThisHero( int ID )
  1766. {
  1767. //for(int i=0;i<CPG->ret.playerInfos.size();i++)
  1768. // if(CPG->ret.playerInfos[i].hero==ID) //hero is already taken
  1769. // return false;
  1770. return !vstd::contains(usedHeroes, ID) && SEL->current->mapHeader->allowedHeroes[ID];
  1771. }
  1772. void OptionsTab::nextBonus( int player, int dir )
  1773. {
  1774. if(SEL->isGuest())
  1775. {
  1776. SEL->postRequest(RequestOptionsChange::BONUS, dir);
  1777. return;
  1778. }
  1779. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1780. si8 &ret = s.bonus += dir;
  1781. if (s.hero==-2 && !SEL->current->mapHeader->players[s.color].heroesNames.size() && ret==PlayerSettings::bartifact) //no hero - can't be artifact
  1782. {
  1783. if (dir<0)
  1784. ret=PlayerSettings::brandom;
  1785. else ret=PlayerSettings::bgold;
  1786. }
  1787. if(ret > PlayerSettings::bresource)
  1788. ret = PlayerSettings::brandom;
  1789. if(ret < PlayerSettings::brandom)
  1790. ret = PlayerSettings::bresource;
  1791. if (s.castle==-1 && ret==PlayerSettings::bresource) //random castle - can't be resource
  1792. {
  1793. if (dir<0)
  1794. ret=PlayerSettings::bgold;
  1795. else ret=PlayerSettings::brandom;
  1796. }
  1797. SEL->propagateOptions();
  1798. redraw();
  1799. }
  1800. void OptionsTab::recreate()
  1801. {
  1802. for(std::map<int, PlayerOptionsEntry*>::iterator it = entries.begin(); it != entries.end(); ++it)
  1803. {
  1804. delete it->second;
  1805. }
  1806. entries.clear();
  1807. usedHeroes.clear();
  1808. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1809. for(std::map<int, PlayerSettings>::iterator it = SEL->sInfo.playerInfos.begin();
  1810. it != SEL->sInfo.playerInfos.end(); ++it)
  1811. {
  1812. entries.insert(std::make_pair(it->first, new PlayerOptionsEntry(this, it->second)));
  1813. const std::vector<SheroName> &heroes = SEL->current->mapHeader->players[it->first].heroesNames;
  1814. for(size_t hi=0; hi<heroes.size(); hi++)
  1815. usedHeroes.insert(heroes[hi].heroID);
  1816. }
  1817. }
  1818. void OptionsTab::setTurnLength( int npos )
  1819. {
  1820. static const int times[] = {1, 2, 4, 6, 8, 10, 15, 20, 25, 30, 0};
  1821. vstd::amin(npos, ARRAY_COUNT(times) - 1);
  1822. SEL->sInfo.turnTime = times[npos];
  1823. redraw();
  1824. }
  1825. void OptionsTab::flagPressed( int color )
  1826. {
  1827. PlayerSettings &clicked = SEL->sInfo.playerInfos[color];
  1828. PlayerSettings *old = NULL;
  1829. if(SEL->playerNames.size() == 1) //single player -> just swap
  1830. {
  1831. if(color == playerColor) //that color is already selected, no action needed
  1832. return;
  1833. old = &SEL->sInfo.playerInfos[playerColor];
  1834. swapPlayers(*old, clicked);
  1835. }
  1836. else
  1837. {
  1838. //identify clicked player
  1839. int clickedNameID = clicked.human; //human is a number of player, zero means AI
  1840. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  1841. {
  1842. PlayerSettings &restPos = SEL->sInfo.playerInfos[playerToRestore.color];
  1843. SEL->setPlayer(restPos, playerToRestore.id);
  1844. playerToRestore.reset();
  1845. }
  1846. int newPlayer; //which player will take clicked position
  1847. //who will be put here?
  1848. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  1849. {
  1850. newPlayer = SEL->getIdOfFirstUnallocatedPlayer();
  1851. if(!newPlayer) //no "free" player -> get just first one
  1852. newPlayer = SEL->playerNames.begin()->first;
  1853. }
  1854. else //human clicked -> take next
  1855. {
  1856. std::map<ui32, std::string>::const_iterator i = SEL->playerNames.find(clickedNameID); //clicked one
  1857. i++; //player AFTER clicked one
  1858. if(i != SEL->playerNames.end())
  1859. newPlayer = i->first;
  1860. else
  1861. newPlayer = 0; //AI if we scrolled through all players
  1862. }
  1863. SEL->setPlayer(clicked, newPlayer); //put player
  1864. //if that player was somewhere else, we need to replace him with computer
  1865. if(newPlayer) //not AI
  1866. {
  1867. for(std::map<int, PlayerSettings>::iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  1868. {
  1869. int curNameID = i->second.human;
  1870. if(i->first != color && curNameID == newPlayer)
  1871. {
  1872. assert(i->second.human);
  1873. playerToRestore.color = i->first;
  1874. playerToRestore.id = newPlayer;
  1875. SEL->setPlayer(i->second, 0); //set computer
  1876. old = &i->second;
  1877. break;
  1878. }
  1879. }
  1880. }
  1881. }
  1882. entries[clicked.color]->selectButtons();
  1883. if(old)
  1884. {
  1885. entries[old->color]->selectButtons();
  1886. if(old->hero >= 0)
  1887. usedHeroes.erase(old->hero);
  1888. old->hero = entries[old->color]->pi.defaultHero();
  1889. }
  1890. SEL->propagateOptions();
  1891. GH.totalRedraw();
  1892. }
  1893. OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry( OptionsTab *owner, PlayerSettings &S)
  1894. : pi(SEL->current->mapHeader->players[S.color]), s(S)
  1895. {
  1896. OBJ_CONSTRUCTION;
  1897. defActions |= SHARE_POS;
  1898. int serial = 0;
  1899. for(int g=0; g < s.color; ++g)
  1900. {
  1901. PlayerInfo &itred = SEL->current->mapHeader->players[g];
  1902. if( itred.canComputerPlay || itred.canHumanPlay)
  1903. serial++;
  1904. }
  1905. pos.x += 54;
  1906. pos.y += 122 + serial*50;
  1907. static const char *flags[] = {"AOFLGBR.DEF", "AOFLGBB.DEF", "AOFLGBY.DEF", "AOFLGBG.DEF",
  1908. "AOFLGBO.DEF", "AOFLGBP.DEF", "AOFLGBT.DEF", "AOFLGBS.DEF"};
  1909. static const char *bgs[] = {"ADOPRPNL.bmp", "ADOPBPNL.bmp", "ADOPYPNL.bmp", "ADOPGPNL.bmp",
  1910. "ADOPOPNL.bmp", "ADOPPPNL.bmp", "ADOPTPNL.bmp", "ADOPSPNL.bmp"};
  1911. bg = new CPicture(BitmapHandler::loadBitmap(bgs[s.color]), 0, 0, true);
  1912. if(SEL->screenType == CMenuScreen::newGame)
  1913. {
  1914. btns[0] = new CAdventureMapButton(CGI->generaltexth->zelp[132], bind(&OptionsTab::nextCastle, owner, s.color, -1), 107, 5, "ADOPLFA.DEF");
  1915. btns[1] = new CAdventureMapButton(CGI->generaltexth->zelp[133], bind(&OptionsTab::nextCastle, owner, s.color, +1), 168, 5, "ADOPRTA.DEF");
  1916. btns[2] = new CAdventureMapButton(CGI->generaltexth->zelp[148], bind(&OptionsTab::nextHero, owner, s.color, -1), 183, 5, "ADOPLFA.DEF");
  1917. btns[3] = new CAdventureMapButton(CGI->generaltexth->zelp[149], bind(&OptionsTab::nextHero, owner, s.color, +1), 244, 5, "ADOPRTA.DEF");
  1918. btns[4] = new CAdventureMapButton(CGI->generaltexth->zelp[164], bind(&OptionsTab::nextBonus, owner, s.color, -1), 259, 5, "ADOPLFA.DEF");
  1919. btns[5] = new CAdventureMapButton(CGI->generaltexth->zelp[165], bind(&OptionsTab::nextBonus, owner, s.color, +1), 320, 5, "ADOPRTA.DEF");
  1920. }
  1921. else
  1922. for(int i = 0; i < 6; i++)
  1923. btns[i] = NULL;
  1924. selectButtons();
  1925. assert(SEL->current && SEL->current->mapHeader);
  1926. const PlayerInfo &p = SEL->current->mapHeader->players[s.color];
  1927. assert(p.canComputerPlay || p.canHumanPlay); //someone must be able to control this player
  1928. if(p.canHumanPlay && p.canComputerPlay)
  1929. whoCanPlay = HUMAN_OR_CPU;
  1930. else if(p.canComputerPlay)
  1931. whoCanPlay = CPU;
  1932. else
  1933. whoCanPlay = HUMAN;
  1934. if(SEL->screenType != CMenuScreen::scenarioInfo
  1935. && SEL->current->mapHeader->players[s.color].canHumanPlay
  1936. && SEL->multiPlayer != CMenuScreen::MULTI_NETWORK_GUEST)
  1937. {
  1938. flag = new CAdventureMapButton(CGI->generaltexth->zelp[180], bind(&OptionsTab::flagPressed, owner, s.color), -43, 2, flags[s.color]);
  1939. flag->hoverable = true;
  1940. }
  1941. else
  1942. flag = NULL;
  1943. town = new SelectedBox(TOWN, s.color);
  1944. town->pos.x += 119;
  1945. town->pos.y += 2;
  1946. hero = new SelectedBox(HERO, s.color);
  1947. hero->pos.x += 195;
  1948. hero->pos.y += 2;
  1949. bonus = new SelectedBox(BONUS, s.color);
  1950. bonus->pos.x += 271;
  1951. bonus->pos.y += 2;
  1952. }
  1953. void OptionsTab::PlayerOptionsEntry::showAll(SDL_Surface * to)
  1954. {
  1955. CIntObject::showAll(to);
  1956. printAtMiddleLoc(s.name, 55, 10, FONT_SMALL, Colors::Cornsilk, to);
  1957. printAtMiddleWBLoc(CGI->generaltexth->arraytxt[206+whoCanPlay], 28, 34, FONT_TINY, 8, Colors::Cornsilk, to);
  1958. }
  1959. void OptionsTab::PlayerOptionsEntry::selectButtons()
  1960. {
  1961. if(!btns[0])
  1962. return;
  1963. if( (pi.defaultCastle() != -1) //fixed tow
  1964. || (SEL->isGuest() && s.color != playerColor)) //or not our player
  1965. {
  1966. btns[0]->disable();
  1967. btns[1]->disable();
  1968. }
  1969. else
  1970. {
  1971. btns[0]->enable();
  1972. btns[1]->enable();
  1973. }
  1974. if( (pi.defaultHero() != -1 || !s.human || s.castle < 0) //fixed hero
  1975. || (SEL->isGuest() && s.color != playerColor))//or not our player
  1976. {
  1977. btns[2]->disable();
  1978. btns[3]->disable();
  1979. }
  1980. else
  1981. {
  1982. btns[2]->enable();
  1983. btns[3]->enable();
  1984. }
  1985. if(SEL->isGuest() && s.color != playerColor)//or not our player
  1986. {
  1987. btns[4]->disable();
  1988. btns[5]->disable();
  1989. }
  1990. else
  1991. {
  1992. btns[4]->enable();
  1993. btns[5]->enable();
  1994. }
  1995. }
  1996. void OptionsTab::SelectedBox::showAll(SDL_Surface * to)
  1997. {
  1998. //PlayerSettings &s = SEL->sInfo.playerInfos[player];
  1999. SDL_Surface *toBlit = getImg();
  2000. const std::string *toPrint = getText();
  2001. blitAt(toBlit, pos, to);
  2002. printAtMiddleLoc(*toPrint, 23, 39, FONT_TINY, Colors::Cornsilk, to);
  2003. }
  2004. OptionsTab::SelectedBox::SelectedBox( SelType Which, ui8 Player )
  2005. :which(Which), player(Player)
  2006. {
  2007. SDL_Surface *img = getImg();
  2008. pos.w = img->w;
  2009. pos.h = img->h;
  2010. addUsedEvents(RCLICK);
  2011. }
  2012. SDL_Surface * OptionsTab::SelectedBox::getImg() const
  2013. {
  2014. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2015. switch(which)
  2016. {
  2017. case TOWN:
  2018. if (s.castle < GameConstants::F_NUMBER && s.castle >= 0)
  2019. return graphics->getPic(s.castle, true, false);
  2020. else if (s.castle == -1)
  2021. return CGP->rTown;
  2022. else if (s.castle == -2)
  2023. return CGP->nTown;
  2024. case HERO:
  2025. if (s.hero == -1)
  2026. {
  2027. return CGP->rHero;
  2028. }
  2029. else if (s.hero == -2)
  2030. {
  2031. if(s.heroPortrait >= 0)
  2032. return graphics->portraitSmall[s.heroPortrait];
  2033. else
  2034. return CGP->nHero;
  2035. }
  2036. else
  2037. {
  2038. return graphics->portraitSmall[s.hero];
  2039. }
  2040. break;
  2041. case BONUS:
  2042. {
  2043. int pom;
  2044. switch (s.bonus)
  2045. {
  2046. case -1:
  2047. pom=10;
  2048. break;
  2049. case 0:
  2050. pom=9;
  2051. break;
  2052. case 1:
  2053. pom=8;
  2054. break;
  2055. case 2:
  2056. pom=CGI->townh->towns[s.castle].bonus;
  2057. break;
  2058. default:
  2059. assert(0);
  2060. }
  2061. return CGP->bonuses->ourImages[pom].bitmap;
  2062. }
  2063. default:
  2064. return NULL;
  2065. }
  2066. }
  2067. const std::string * OptionsTab::SelectedBox::getText() const
  2068. {
  2069. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2070. switch(which)
  2071. {
  2072. case TOWN:
  2073. if (s.castle < GameConstants::F_NUMBER && s.castle >= 0)
  2074. return &CGI->townh->towns[s.castle].Name();
  2075. else if (s.castle == -1)
  2076. return &CGI->generaltexth->allTexts[522];
  2077. else if (s.castle == -2)
  2078. return &CGI->generaltexth->allTexts[523];
  2079. case HERO:
  2080. if (s.hero == -1)
  2081. return &CGI->generaltexth->allTexts[522];
  2082. else if (s.hero == -2)
  2083. {
  2084. if(s.heroPortrait >= 0)
  2085. {
  2086. if(s.heroName.length())
  2087. return &s.heroName;
  2088. else
  2089. return &CGI->heroh->heroes[s.heroPortrait]->name;
  2090. }
  2091. else
  2092. return &CGI->generaltexth->allTexts[523];
  2093. }
  2094. else
  2095. {
  2096. //if(s.heroName.length())
  2097. // return &s.heroName;
  2098. //else
  2099. return &CGI->heroh->heroes[s.hero]->name;
  2100. }
  2101. case BONUS:
  2102. switch (s.bonus)
  2103. {
  2104. case -1:
  2105. return &CGI->generaltexth->allTexts[522];
  2106. default:
  2107. return &CGI->generaltexth->arraytxt[214 + s.bonus];
  2108. }
  2109. default:
  2110. return NULL;
  2111. }
  2112. }
  2113. void OptionsTab::SelectedBox::clickRight( tribool down, bool previousState )
  2114. {
  2115. if(indeterminate(down) || !down) return;
  2116. const PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2117. SDL_Surface *bmp = NULL;
  2118. const std::string *title = NULL, *subTitle = NULL;
  2119. subTitle = getText();
  2120. int val=-1;
  2121. switch(which)
  2122. {
  2123. case TOWN:
  2124. val = s.castle;
  2125. break;
  2126. case HERO:
  2127. val = s.hero;
  2128. if(val == -2) //none => we may have some preset info
  2129. {
  2130. int p9 = SEL->current->mapHeader->players[s.color].p9;
  2131. if(p9 != 255 && SEL->sInfo.playerInfos[player].heroPortrait >= 0)
  2132. val = p9;
  2133. }
  2134. break;
  2135. case BONUS:
  2136. val = s.bonus;
  2137. break;
  2138. }
  2139. if(val == -1 || which == BONUS) //random or bonus box
  2140. {
  2141. bmp = CMessage::drawDialogBox(256, 190);
  2142. std::string *description = NULL;
  2143. switch(which)
  2144. {
  2145. case TOWN:
  2146. title = &CGI->generaltexth->allTexts[103];
  2147. description = &CGI->generaltexth->allTexts[104];
  2148. break;
  2149. case HERO:
  2150. title = &CGI->generaltexth->allTexts[101];
  2151. description = &CGI->generaltexth->allTexts[102];
  2152. break;
  2153. case BONUS:
  2154. {
  2155. switch(val)
  2156. {
  2157. case PlayerSettings::brandom:
  2158. title = &CGI->generaltexth->allTexts[86]; //{Random Bonus}
  2159. description = &CGI->generaltexth->allTexts[94]; //Gold, wood and ore, or an artifact is randomly chosen as your starting bonus
  2160. break;
  2161. case PlayerSettings::bartifact:
  2162. title = &CGI->generaltexth->allTexts[83]; //{Artifact Bonus}
  2163. description = &CGI->generaltexth->allTexts[90]; //An artifact is randomly chosen and equipped to your starting hero
  2164. break;
  2165. case PlayerSettings::bgold:
  2166. title = &CGI->generaltexth->allTexts[84]; //{Gold Bonus}
  2167. subTitle = &CGI->generaltexth->allTexts[87]; //500-1000
  2168. description = &CGI->generaltexth->allTexts[92]; //At the start of the game, 500-1000 gold is added to your Kingdom's resource pool
  2169. break;
  2170. case PlayerSettings::bresource:
  2171. {
  2172. title = &CGI->generaltexth->allTexts[85]; //{Resource Bonus}
  2173. switch(CGI->townh->towns[s.castle].primaryRes)
  2174. {
  2175. case 1:
  2176. subTitle = &CGI->generaltexth->allTexts[694];
  2177. description = &CGI->generaltexth->allTexts[690];
  2178. break;
  2179. case 3:
  2180. subTitle = &CGI->generaltexth->allTexts[695];
  2181. description = &CGI->generaltexth->allTexts[691];
  2182. break;
  2183. case 4:
  2184. subTitle = &CGI->generaltexth->allTexts[692];
  2185. description = &CGI->generaltexth->allTexts[688];
  2186. break;
  2187. case 5:
  2188. subTitle = &CGI->generaltexth->allTexts[693];
  2189. description = &CGI->generaltexth->allTexts[689];
  2190. break;
  2191. case 127:
  2192. subTitle = &CGI->generaltexth->allTexts[89]; //5-10 wood / 5-10 ore
  2193. 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
  2194. break;
  2195. }
  2196. }
  2197. break;
  2198. }
  2199. }
  2200. break;
  2201. }
  2202. if(description)
  2203. CSDL_Ext::printAtMiddleWB(*description, 125, 145, FONT_SMALL, 37, Colors::Cornsilk, bmp);
  2204. }
  2205. else if(val == -2)
  2206. {
  2207. return;
  2208. }
  2209. else if(which == TOWN)
  2210. {
  2211. bmp = CMessage::drawDialogBox(256, 319);
  2212. title = &CGI->generaltexth->allTexts[80];
  2213. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[79], 135, 137, FONT_MEDIUM, Colors::Jasmine, bmp);
  2214. const CTown &t = CGI->townh->towns[val];
  2215. //print creatures
  2216. int x = 60, y = 159;
  2217. for(int i = 0; i < 7; i++)
  2218. {
  2219. int c = t.basicCreatures[i];
  2220. blitAt(graphics->smallImgs[c], x, y, bmp);
  2221. CSDL_Ext::printAtMiddleWB(CGI->creh->creatures[c]->nameSing, x + 16, y + 45, FONT_TINY, 10, Colors::Cornsilk, bmp);
  2222. if(i == 2)
  2223. {
  2224. x = 40;
  2225. y += 76;
  2226. }
  2227. else
  2228. {
  2229. x += 52;
  2230. }
  2231. }
  2232. }
  2233. else if(val >= 0)
  2234. {
  2235. const CHero *h = CGI->heroh->heroes[val];
  2236. bmp = CMessage::drawDialogBox(320, 255);
  2237. title = &CGI->generaltexth->allTexts[77];
  2238. CSDL_Ext::printAtMiddle(*title, 167, 36, FONT_MEDIUM, Colors::Jasmine, bmp);
  2239. CSDL_Ext::printAtMiddle(*subTitle + " - " + h->heroClass->name, 160, 99, FONT_SMALL, Colors::Cornsilk, bmp);
  2240. blitAt(getImg(), 136, 56, bmp);
  2241. //print specialty
  2242. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[78], 166, 132, FONT_MEDIUM, Colors::Jasmine, bmp);
  2243. blitAt(graphics->un44->ourImages[val].bitmap, 140, 150, bmp);
  2244. CSDL_Ext::printAtMiddle(CGI->generaltexth->hTxts[val].bonusName, 166, 203, FONT_SMALL, Colors::Cornsilk, bmp);
  2245. GH.pushInt(new CInfoPopup(bmp, true));
  2246. return;
  2247. }
  2248. if(title)
  2249. CSDL_Ext::printAtMiddle(*title, 135, 36, FONT_MEDIUM, Colors::Jasmine, bmp);
  2250. if(subTitle)
  2251. CSDL_Ext::printAtMiddle(*subTitle, 127, 103, FONT_SMALL, Colors::Cornsilk, bmp);
  2252. blitAt(getImg(), 104, 60, bmp);
  2253. GH.pushInt(new CInfoPopup(bmp, true));
  2254. }
  2255. CScenarioInfo::CScenarioInfo(const CMapHeader *mapHeader, const StartInfo *startInfo)
  2256. {
  2257. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2258. for(std::map<int, PlayerSettings>::const_iterator it = startInfo->playerInfos.begin();
  2259. it != startInfo->playerInfos.end(); ++it)
  2260. {
  2261. if(it->second.human)
  2262. {
  2263. playerColor = it->first;
  2264. }
  2265. }
  2266. pos.w = 762;
  2267. pos.h = 584;
  2268. center(pos);
  2269. assert(LOCPLINT);
  2270. sInfo = *LOCPLINT->cb->getStartInfo();
  2271. assert(!SEL->current);
  2272. current = mapInfoFromGame();
  2273. setPlayersFromGame();
  2274. screenType = CMenuScreen::scenarioInfo;
  2275. card = new InfoCard();
  2276. opt = new OptionsTab();
  2277. opt->recreate();
  2278. card->changeSelection(current);
  2279. card->difficulty->select(startInfo->difficulty, 0);
  2280. back = new CAdventureMapButton("", CGI->generaltexth->zelp[105].second, bind(&CGuiHandler::popIntTotally, &GH, this), 584, 535, "SCNRBACK.DEF", SDLK_ESCAPE);
  2281. }
  2282. CScenarioInfo::~CScenarioInfo()
  2283. {
  2284. delete current;
  2285. }
  2286. bool mapSorter::operator()(const CMapInfo *aaa, const CMapInfo *bbb)
  2287. {
  2288. const CMapHeader * a = aaa->mapHeader,
  2289. * b = bbb->mapHeader;
  2290. if(a && b) //if we are sorting scenarios
  2291. {
  2292. switch (sortBy)
  2293. {
  2294. case _format: //by map format (RoE, WoG, etc)
  2295. return (a->version<b->version);
  2296. break;
  2297. case _loscon: //by loss conditions
  2298. return (a->lossCondition.typeOfLossCon<b->lossCondition.typeOfLossCon);
  2299. break;
  2300. case _playerAm: //by player amount
  2301. int playerAmntB,humenPlayersB,playerAmntA,humenPlayersA;
  2302. playerAmntB=humenPlayersB=playerAmntA=humenPlayersA=0;
  2303. for (int i=0;i<8;i++)
  2304. {
  2305. if (a->players[i].canHumanPlay) {playerAmntA++;humenPlayersA++;}
  2306. else if (a->players[i].canComputerPlay) {playerAmntA++;}
  2307. if (b->players[i].canHumanPlay) {playerAmntB++;humenPlayersB++;}
  2308. else if (b->players[i].canComputerPlay) {playerAmntB++;}
  2309. }
  2310. if (playerAmntB!=playerAmntA)
  2311. return (playerAmntA<playerAmntB);
  2312. else
  2313. return (humenPlayersA<humenPlayersB);
  2314. break;
  2315. case _size: //by size of map
  2316. return (a->width<b->width);
  2317. break;
  2318. case _viccon: //by victory conditions
  2319. return (a->victoryCondition.condition < b->victoryCondition.condition);
  2320. break;
  2321. case _name: //by name
  2322. return boost::ilexicographical_compare(a->name, b->name);
  2323. default:
  2324. return boost::ilexicographical_compare(a->name, b->name);
  2325. }
  2326. }
  2327. else //if we are sorting campaigns
  2328. {
  2329. switch(sortBy)
  2330. {
  2331. case _numOfMaps: //by number of maps in campaign
  2332. return CGI->generaltexth->campaignRegionNames[ aaa->campaignHeader->mapVersion ].size() <
  2333. CGI->generaltexth->campaignRegionNames[ bbb->campaignHeader->mapVersion ].size();
  2334. break;
  2335. case _name: //by name
  2336. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2337. default:
  2338. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2339. }
  2340. }
  2341. }
  2342. CMultiMode::CMultiMode()
  2343. {
  2344. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2345. bg = new CPicture("MUPOPUP.bmp");
  2346. bg->convertToScreenBPP(); //so we could draw without problems
  2347. blitAt(CPicture("MUMAP.bmp"), 16, 77, *bg); //blit img
  2348. pos = bg->center(); //center, window has size of bg graphic
  2349. bar = new CGStatusBar(new CPicture(Rect(7, 465, 440, 18), 0));//226, 472
  2350. txt = new CTextInput(Rect(19, 436, 334, 16), *bg);
  2351. txt->setTxt(settings["general"]["playerName"].String()); //Player
  2352. btns[0] = new CAdventureMapButton(CGI->generaltexth->zelp[266], bind(&CMultiMode::openHotseat, this), 373, 78, "MUBHOT.DEF");
  2353. btns[1] = new CAdventureMapButton("Host TCP/IP game", "", bind(&CMultiMode::hostTCP, this), 373, 78 + 57*1, "MUBHOST.DEF");
  2354. btns[2] = new CAdventureMapButton("Join TCP/IP game", "", bind(&CMultiMode::joinTCP, this), 373, 78 + 57*2, "MUBJOIN.DEF");
  2355. btns[6] = new CAdventureMapButton(CGI->generaltexth->zelp[288], bind(&CGuiHandler::popIntTotally, ref(GH), this), 373, 424, "MUBCANC.DEF", SDLK_ESCAPE);
  2356. }
  2357. void CMultiMode::openHotseat()
  2358. {
  2359. GH.pushInt(new CHotSeatPlayers(txt->text));
  2360. }
  2361. void CMultiMode::hostTCP()
  2362. {
  2363. Settings name = settings.write["general"]["playerName"];
  2364. name->String() = txt->text;
  2365. GH.popIntTotally(this);
  2366. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_NETWORK_HOST));
  2367. }
  2368. void CMultiMode::joinTCP()
  2369. {
  2370. Settings name = settings.write["general"]["playerName"];
  2371. name->String() = txt->text;
  2372. GH.popIntTotally(this);
  2373. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_NETWORK_GUEST));
  2374. }
  2375. CHotSeatPlayers::CHotSeatPlayers(const std::string &firstPlayer)
  2376. {
  2377. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2378. bg = new CPicture("MUHOTSEA.bmp");
  2379. pos = bg->center(); //center, window has size of bg graphic
  2380. std::string text = CGI->generaltexth->allTexts[446];
  2381. boost::replace_all(text, "\t","\n");
  2382. Rect boxRect(25, 20, 315, 50);
  2383. title = new CTextBox(text, boxRect, 0, FONT_BIG, CENTER, Colors::Cornsilk);//HOTSEAT Please enter names
  2384. for(int i = 0; i < ARRAY_COUNT(txt); i++)
  2385. {
  2386. txt[i] = new CTextInput(Rect(60, 85 + i*30, 280, 16), *bg);
  2387. txt[i]->cb += boost::bind(&CHotSeatPlayers::onChange, this, _1);
  2388. }
  2389. ok = new CAdventureMapButton(CGI->generaltexth->zelp[560], bind(&CHotSeatPlayers::enterSelectionScreen, this), 95, 338, "MUBCHCK.DEF", SDLK_RETURN);
  2390. cancel = new CAdventureMapButton(CGI->generaltexth->zelp[561], bind(&CGuiHandler::popIntTotally, ref(GH), this), 205, 338, "MUBCANC.DEF", SDLK_ESCAPE);
  2391. bar = new CGStatusBar(new CPicture(Rect(7, 381, 348, 18), 0));//226, 472
  2392. txt[0]->setTxt(firstPlayer, true);
  2393. txt[0]->giveFocus();
  2394. }
  2395. void CHotSeatPlayers::onChange(std::string newText)
  2396. {
  2397. size_t namesCount = 0;
  2398. for(int i = 0; i < ARRAY_COUNT(txt); i++)
  2399. if(!txt[i]->text.empty())
  2400. namesCount++;
  2401. ok->block(namesCount < 2);
  2402. }
  2403. void CHotSeatPlayers::enterSelectionScreen()
  2404. {
  2405. std::map<ui32, std::string> names;
  2406. for(int i = 0, j = 1; i < ARRAY_COUNT(txt); i++)
  2407. if(txt[i]->text.length())
  2408. names[j++] = txt[i]->text;
  2409. Settings name = settings.write["general"]["playerName"];
  2410. name->String() = names.begin()->second;
  2411. GH.popInts(2); //pop MP mode window and this
  2412. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_HOT_SEAT, &names));
  2413. }
  2414. CBonusSelection::CBonusSelection( CCampaignState * _ourCampaign )
  2415. : highlightedRegion(NULL), ourCampaign(_ourCampaign), ourHeader(NULL),
  2416. diffLb(NULL), diffRb(NULL), bonuses(NULL)
  2417. {
  2418. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2419. static const std::string bgNames [] = {"E1_BG.BMP", "G2_BG.BMP", "E2_BG.BMP", "G1_BG.BMP", "G3_BG.BMP", "N1_BG.BMP",
  2420. "S1_BG.BMP", "BR_BG.BMP", "IS_BG.BMP", "KR_BG.BMP", "NI_BG.BMP", "TA_BG.BMP", "AR_BG.BMP", "HS_BG.BMP",
  2421. "BB_BG.BMP", "NB_BG.BMP", "EL_BG.BMP", "RN_BG.BMP", "UA_BG.BMP", "SP_BG.BMP"};
  2422. loadPositionsOfGraphics();
  2423. background = BitmapHandler::loadBitmap(bgNames[ourCampaign->camp->header.mapVersion]);
  2424. pos.h = background->h;
  2425. pos.w = background->w;
  2426. center();
  2427. SDL_Surface * panel = BitmapHandler::loadBitmap("CAMPBRF.BMP");
  2428. blitAt(panel, 456, 6, background);
  2429. startB = new CAdventureMapButton("", "", bind(&CBonusSelection::startMap, this), 475, 536, "CBBEGIB.DEF", SDLK_RETURN);
  2430. backB = new CAdventureMapButton("", "", bind(&CBonusSelection::goBack, this), 624, 536, "CBCANCB.DEF", SDLK_ESCAPE);
  2431. startB->setState(CButtonBase::BLOCKED);
  2432. //campaign name
  2433. if (ourCampaign->camp->header.name.length())
  2434. CSDL_Ext::printAt(ourCampaign->camp->header.name, 481, 28, FONT_BIG, Colors::Jasmine, background);
  2435. else
  2436. CSDL_Ext::printAt("Unnamed", 481, 28, FONT_BIG, Colors::Jasmine, background);
  2437. //map size icon
  2438. sizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
  2439. //campaign description
  2440. CSDL_Ext::printAt(CGI->generaltexth->allTexts[38], 481, 63, FONT_SMALL, Colors::Jasmine, background);
  2441. cmpgDesc = new CTextBox(ourCampaign->camp->header.description, Rect(480, 86, 286, 117), 1);
  2442. //cmpgDesc->showAll(background);
  2443. //map description
  2444. mapDesc = new CTextBox("", Rect(480, 280, 286, 117), 1);
  2445. //bonus choosing
  2446. CSDL_Ext::printAt(CGI->generaltexth->allTexts[71], 511, 432, FONT_MEDIUM, Colors::Cornsilk, background); //Choose a bonus:
  2447. bonuses = new CHighlightableButtonsGroup(bind(&CBonusSelection::selectBonus, this, _1));
  2448. //set left part of window
  2449. for (int g=0; g<ourCampaign->camp->scenarios.size(); ++g)
  2450. {
  2451. if(ourCampaign->camp->conquerable(g))
  2452. {
  2453. regions.push_back(new CRegion(this, true, true, g));
  2454. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2455. if (highlightedRegion == NULL)
  2456. {
  2457. highlightedRegion = regions.back();
  2458. selectMap(g);
  2459. }
  2460. }
  2461. else if (ourCampaign->camp->scenarios[g].conquered) //display as striped
  2462. {
  2463. regions.push_back(new CRegion(this, false, false, g));
  2464. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2465. }
  2466. }
  2467. //init campaign state if necessary
  2468. if (ourCampaign->campaignName.size() == 0)
  2469. {
  2470. ourCampaign->initNewCampaign(sInfo);
  2471. }
  2472. //allies / enemies
  2473. CSDL_Ext::printAt(CGI->generaltexth->allTexts[390] + ":", 486, 407, FONT_SMALL, Colors::Cornsilk, background); //Allies
  2474. CSDL_Ext::printAt(CGI->generaltexth->allTexts[391] + ":", 619, 407, FONT_SMALL, Colors::Cornsilk, background); //Enemies
  2475. SDL_FreeSurface(panel);
  2476. //difficulty
  2477. std::vector<std::string> difficulty;
  2478. boost::split(difficulty, CGI->generaltexth->allTexts[492], boost::is_any_of(" "));
  2479. CSDL_Ext::printAt(difficulty.back(), 689, 432, FONT_MEDIUM, Colors::Cornsilk, background); //Difficulty
  2480. //difficulty pics
  2481. for (int b=0; b<ARRAY_COUNT(diffPics); ++b)
  2482. {
  2483. CDefEssential * cde = CDefHandler::giveDefEss("GSPBUT" + boost::lexical_cast<std::string>(b+3) + ".DEF");
  2484. SDL_Surface * surfToDuplicate = cde->ourImages[0].bitmap;
  2485. diffPics[b] = SDL_ConvertSurface(surfToDuplicate, surfToDuplicate->format,
  2486. surfToDuplicate->flags);
  2487. delete cde;
  2488. }
  2489. //difficulty selection buttons
  2490. if (ourCampaign->camp->header.difficultyChoosenByPlayer)
  2491. {
  2492. diffLb = new CAdventureMapButton("", "", bind(&CBonusSelection::changeDiff, this, false), 694, 508, "SCNRBLF.DEF");
  2493. diffRb = new CAdventureMapButton("", "", bind(&CBonusSelection::changeDiff, this, true), 738, 508, "SCNRBRT.DEF");
  2494. }
  2495. //load miniflags
  2496. sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
  2497. }
  2498. CBonusSelection::~CBonusSelection()
  2499. {
  2500. SDL_FreeSurface(background);
  2501. delete sizes;
  2502. delete ourHeader;
  2503. delete sFlags;
  2504. for (int b=0; b<ARRAY_COUNT(diffPics); ++b)
  2505. {
  2506. SDL_FreeSurface(diffPics[b]);
  2507. }
  2508. }
  2509. void CBonusSelection::goBack()
  2510. {
  2511. GH.popIntTotally(this);
  2512. }
  2513. void CBonusSelection::showAll(SDL_Surface * to)
  2514. {
  2515. blitAt(background, pos.x, pos.y, to);
  2516. CIntObject::showAll(to);
  2517. show(to);
  2518. if (pos.h != to->h || pos.w != to->w)
  2519. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  2520. }
  2521. void CBonusSelection::loadPositionsOfGraphics()
  2522. {
  2523. const JsonNode config(GameConstants::DATA_DIR + "/config/campaign_regions.json");
  2524. int idx = 0;
  2525. BOOST_FOREACH(const JsonNode &campaign, config["campaign_regions"].Vector())
  2526. {
  2527. SCampPositions sc;
  2528. sc.campPrefix = campaign["prefix"].String();
  2529. sc.colorSuffixLength = campaign["color_suffix_length"].Float();
  2530. BOOST_FOREACH(const JsonNode &desc, campaign["desc"].Vector())
  2531. {
  2532. SCampPositions::SRegionDesc rd;
  2533. rd.infix = desc["infix"].String();
  2534. rd.xpos = desc["x"].Float();
  2535. rd.ypos = desc["y"].Float();
  2536. sc.regions.push_back(rd);
  2537. }
  2538. campDescriptions.push_back(sc);
  2539. idx++;
  2540. }
  2541. assert(idx == CGI->generaltexth->campaignMapNames.size());
  2542. }
  2543. void CBonusSelection::selectMap( int whichOne )
  2544. {
  2545. sInfo.difficulty = ourCampaign->camp->scenarios[whichOne].difficulty;
  2546. sInfo.mapname = ourCampaign->camp->header.filename;
  2547. sInfo.mode = StartInfo::CAMPAIGN;
  2548. //get header
  2549. int i = 0;
  2550. delete ourHeader;
  2551. ourHeader = new CMapHeader();
  2552. ourHeader->initFromMemory((const unsigned char*)ourCampaign->camp->mapPieces.find(whichOne)->second.c_str(), i);
  2553. std::map<ui32, std::string> names;
  2554. names[1] = settings["general"]["playerName"].String();
  2555. updateStartInfo(ourCampaign->camp->header.filename, sInfo, ourHeader, names);
  2556. sInfo.turnTime = 0;
  2557. sInfo.whichMapInCampaign = whichOne;
  2558. sInfo.difficulty = ourCampaign->camp->scenarios[whichOne].difficulty;
  2559. ourCampaign->currentMap = whichOne;
  2560. mapDesc->setTxt(ourHeader->description);
  2561. updateBonusSelection();
  2562. }
  2563. void CBonusSelection::show(SDL_Surface * to)
  2564. {
  2565. //blitAt(background, pos.x, pos.y, to);
  2566. //map name
  2567. std::string mapName = ourHeader->name;
  2568. if (mapName.length())
  2569. printAtLoc(mapName, 481, 219, FONT_BIG, Colors::Jasmine, to);
  2570. else
  2571. printAtLoc("Unnamed", 481, 219, FONT_BIG, Colors::Jasmine, to);
  2572. //map description
  2573. printAtLoc(CGI->generaltexth->allTexts[496], 481, 253, FONT_SMALL, Colors::Jasmine, to);
  2574. mapDesc->showAll(to); //showAll because CTextBox has no show()
  2575. //map size icon
  2576. int temp;
  2577. switch (ourHeader->width)
  2578. {
  2579. case 36:
  2580. temp=0;
  2581. break;
  2582. case 72:
  2583. temp=1;
  2584. break;
  2585. case 108:
  2586. temp=2;
  2587. break;
  2588. case 144:
  2589. temp=3;
  2590. break;
  2591. default:
  2592. temp=4;
  2593. break;
  2594. }
  2595. blitAtLoc(sizes->ourImages[temp].bitmap, 735, 26, to);
  2596. //flags
  2597. int fx = 496 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[390].c_str());
  2598. int ex = 629 + graphics->fonts[FONT_SMALL]->getWidth(CGI->generaltexth->allTexts[391].c_str());
  2599. int myT;
  2600. myT = ourHeader->players[playerColor].team;
  2601. for (std::map<int, PlayerSettings>::const_iterator i = sInfo.playerInfos.begin(); i != sInfo.playerInfos.end(); i++)
  2602. {
  2603. int *myx = ((i->first == playerColor || ourHeader->players[i->first].team == myT) ? &fx : &ex);
  2604. blitAtLoc(sFlags->ourImages[i->first].bitmap, pos.x + *myx, pos.y + 405, to);
  2605. *myx += sFlags->ourImages[i->first].bitmap->w;
  2606. }
  2607. //difficulty
  2608. blitAtLoc(diffPics[sInfo.difficulty], 709, 455, to);
  2609. CIntObject::show(to);
  2610. }
  2611. void CBonusSelection::updateBonusSelection()
  2612. {
  2613. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2614. //graphics:
  2615. //spell - SPELLBON.DEF
  2616. //monster - TWCRPORT.DEF
  2617. //building - BO*.BMP graphics
  2618. //artifact - ARTIFBON.DEF
  2619. //spell scroll - SPELLBON.DEF
  2620. //prim skill - PSKILBON.DEF
  2621. //sec skill - SSKILBON.DEF
  2622. //resource - BORES.DEF
  2623. //player - CREST58.DEF
  2624. //hero - PORTRAITSLARGE (HPL###.BMPs)
  2625. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[sInfo.whichMapInCampaign];
  2626. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  2627. for (size_t i=0; i<bonuses->buttons.size(); i++)
  2628. {
  2629. if (bonuses->buttons[i]->active)
  2630. bonuses->buttons[i]->deactivate();
  2631. delete bonuses->buttons[i];
  2632. }
  2633. bonuses->buttons.clear();
  2634. static const char *bonusPics[] = {"SPELLBON.DEF", "TWCRPORT.DEF", "", "ARTIFBON.DEF", "SPELLBON.DEF",
  2635. "PSKILBON.DEF", "SSKILBON.DEF", "BORES.DEF", "CREST58.DEF", "PORTRAITSLARGE"};
  2636. for(int i = 0; i < bonDescs.size(); i++)
  2637. {
  2638. std::string picName=bonusPics[bonDescs[i].type];
  2639. size_t picNumber=bonDescs[i].info2;
  2640. std::string desc;
  2641. switch(bonDescs[i].type)
  2642. {
  2643. case 0: //spell
  2644. desc = CGI->generaltexth->allTexts[715];
  2645. boost::algorithm::replace_first(desc, "%s", CGI->spellh->spells[bonDescs[i].info2]->name);
  2646. break;
  2647. case 1: //monster
  2648. picNumber = bonDescs[i].info2 + 2;
  2649. desc = CGI->generaltexth->allTexts[717];
  2650. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info3));
  2651. boost::algorithm::replace_first(desc, "%s", CGI->creh->creatures[bonDescs[i].info2]->namePl);
  2652. break;
  2653. case 2: //building
  2654. {
  2655. int faction = -1;
  2656. for(std::map<int, PlayerSettings>::iterator it = sInfo.playerInfos.begin();
  2657. it != sInfo.playerInfos.end(); ++it)
  2658. {
  2659. if (it->second.human)
  2660. {
  2661. faction = it->second.castle;
  2662. break;
  2663. }
  2664. }
  2665. assert(faction != -1);
  2666. int buildID = CBuildingHandler::campToERMU(bonDescs[i].info1, faction, std::set<si32>());
  2667. picName = graphics->ERMUtoPicture[faction][buildID];
  2668. picNumber = -1;
  2669. tlog1<<CGI->buildh->buildings.size()<<"\t"<<faction<<"\t"<<CGI->buildh->buildings[faction].size()<<"\t"<<buildID<<"\n";
  2670. if (vstd::contains(CGI->buildh->buildings[faction], buildID))
  2671. desc = CGI->buildh->buildings[faction].find(buildID)->second->Description();
  2672. }
  2673. break;
  2674. case 3: //artifact
  2675. desc = CGI->generaltexth->allTexts[715];
  2676. boost::algorithm::replace_first(desc, "%s", CGI->arth->artifacts[bonDescs[i].info2]->Name());
  2677. break;
  2678. case 4: //spell scroll
  2679. desc = CGI->generaltexth->allTexts[716];
  2680. boost::algorithm::replace_first(desc, "%s", CGI->spellh->spells[bonDescs[i].info2]->name);
  2681. break;
  2682. case 5: //primary skill
  2683. {
  2684. int leadingSkill = -1;
  2685. std::vector<std::pair<int, int> > toPrint; //primary skills to be listed <num, val>
  2686. const ui8* ptr = reinterpret_cast<const ui8*>(&bonDescs[i].info2);
  2687. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  2688. {
  2689. if (leadingSkill == -1 || ptr[g] > ptr[leadingSkill])
  2690. {
  2691. leadingSkill = g;
  2692. }
  2693. if (ptr[g] != 0)
  2694. {
  2695. toPrint.push_back(std::make_pair(g, ptr[g]));
  2696. }
  2697. }
  2698. picNumber = leadingSkill;
  2699. desc = CGI->generaltexth->allTexts[715];
  2700. std::string substitute; //text to be printed instead of %s
  2701. for (int v=0; v<toPrint.size(); ++v)
  2702. {
  2703. substitute += boost::lexical_cast<std::string>(toPrint[v].second);
  2704. substitute += " " + CGI->generaltexth->primarySkillNames[toPrint[v].first];
  2705. if(v != toPrint.size() - 1)
  2706. {
  2707. substitute += ", ";
  2708. }
  2709. }
  2710. boost::algorithm::replace_first(desc, "%s", substitute);
  2711. break;
  2712. }
  2713. case 6: //secondary skill
  2714. desc = CGI->generaltexth->allTexts[718];
  2715. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->levels[bonDescs[i].info3]); //skill level
  2716. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->skillName[bonDescs[i].info2]); //skill name
  2717. break;
  2718. case 7: //resource
  2719. {
  2720. int serialResID = 0;
  2721. switch(bonDescs[i].info1)
  2722. {
  2723. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  2724. serialResID = bonDescs[i].info1;
  2725. break;
  2726. case 0xFD: //wood + ore
  2727. serialResID = 7;
  2728. break;
  2729. case 0xFE: //rare resources
  2730. serialResID = 8;
  2731. break;
  2732. }
  2733. picNumber = serialResID;
  2734. desc = CGI->generaltexth->allTexts[717];
  2735. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info2));
  2736. std::string replacement;
  2737. if (serialResID <= 6)
  2738. {
  2739. replacement = CGI->generaltexth->restypes[serialResID];
  2740. }
  2741. else
  2742. {
  2743. replacement = CGI->generaltexth->allTexts[714 + serialResID];
  2744. }
  2745. boost::algorithm::replace_first(desc, "%s", replacement);
  2746. }
  2747. break;
  2748. case 8: //player aka hero crossover
  2749. picNumber = bonDescs[i].info1;
  2750. desc = CGI->generaltexth->allTexts[718];
  2751. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->capColors[bonDescs[i].info1]); //player color
  2752. boost::algorithm::replace_first(desc, "%s", ourCampaign->camp->scenarios[bonDescs[i].info2].mapName); //scenario
  2753. break;
  2754. case 9: //hero
  2755. desc = CGI->generaltexth->allTexts[718];
  2756. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->capColors[bonDescs[i].info1]); //hero's color
  2757. if (bonDescs[i].info2 == 0xFFFF)
  2758. {
  2759. boost::algorithm::replace_first(desc, "%s", CGI->heroh->heroes[0]->name); //hero's name
  2760. picNumber = 0;
  2761. }
  2762. else
  2763. {
  2764. boost::algorithm::replace_first(desc, "%s", CGI->heroh->heroes[bonDescs[i].info2]->name); //hero's name
  2765. }
  2766. break;
  2767. }
  2768. CHighlightableButton *bonusButton = new CHighlightableButton(desc, desc, 0, 475 + i*68, 455, "", i);
  2769. if (picNumber != -1)
  2770. picName += ":" + boost::lexical_cast<std::string>(picNumber);
  2771. CAnimation * anim = new CAnimation();
  2772. anim->setCustom(picName, 0);
  2773. bonusButton->setImage(anim);
  2774. bonusButton->borderColor = Colors::Maize; // yellow border
  2775. bonuses->addButton(bonusButton);
  2776. }
  2777. }
  2778. void CBonusSelection::startMap()
  2779. {
  2780. StartInfo *si = new StartInfo(sInfo);
  2781. if (ourCampaign->mapsConquered.size())
  2782. {
  2783. GH.popInts(1);
  2784. }
  2785. else
  2786. {
  2787. CGP->removeFromGui();
  2788. }
  2789. ::startGame(si);
  2790. }
  2791. void CBonusSelection::selectBonus( int id )
  2792. {
  2793. // Total redraw is needed because the border around the bonus images
  2794. // have to be undrawn/drawn.
  2795. if (id != sInfo.choosenCampaignBonus)
  2796. {
  2797. sInfo.choosenCampaignBonus = id;
  2798. GH.totalRedraw();
  2799. if (startB->getState() == CButtonBase::BLOCKED)
  2800. startB->setState(CButtonBase::NORMAL);
  2801. }
  2802. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[sInfo.whichMapInCampaign];
  2803. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  2804. if (bonDescs[id].type == 8) //hero crossover
  2805. {
  2806. SEL->setPlayer(sInfo.playerInfos[0], bonDescs[id].info1); //TODO: substitute with appropriate color
  2807. }
  2808. }
  2809. void CBonusSelection::changeDiff( bool increase )
  2810. {
  2811. if (increase)
  2812. {
  2813. sInfo.difficulty = std::min(sInfo.difficulty + 1, 4);
  2814. }
  2815. else
  2816. {
  2817. sInfo.difficulty = std::max(sInfo.difficulty - 1, 0);
  2818. }
  2819. }
  2820. CBonusSelection::CRegion::CRegion( CBonusSelection * _owner, bool _accessible, bool _selectable, int _myNumber )
  2821. : owner(_owner), accessible(_accessible), selectable(_selectable), myNumber(_myNumber)
  2822. {
  2823. OBJ_CONSTRUCTION;
  2824. addUsedEvents(LCLICK | RCLICK);
  2825. static const std::string colors[2][8] = {
  2826. {"R", "B", "N", "G", "O", "V", "T", "P"},
  2827. {"Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi"}};
  2828. const SCampPositions & campDsc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion];
  2829. const SCampPositions::SRegionDesc & desc = campDsc.regions[myNumber];
  2830. pos.x += desc.xpos;
  2831. pos.y += desc.ypos;
  2832. //loading of graphics
  2833. std::string prefix = campDsc.campPrefix + desc.infix + "_";
  2834. std::string suffix = colors[campDsc.colorSuffixLength - 1][owner->ourCampaign->camp->scenarios[myNumber].regionColor];
  2835. static const std::string infix [] = {"En", "Se", "Co"};
  2836. for (int g = 0; g < ARRAY_COUNT(infix); g++)
  2837. {
  2838. graphics[g] = BitmapHandler::loadBitmap(prefix + infix[g] + suffix + ".BMP");
  2839. }
  2840. pos.w = graphics[0]->w;
  2841. pos.h = graphics[0]->h;
  2842. }
  2843. CBonusSelection::CRegion::~CRegion()
  2844. {
  2845. for (int g=0; g<ARRAY_COUNT(graphics); ++g)
  2846. {
  2847. SDL_FreeSurface(graphics[g]);
  2848. }
  2849. }
  2850. void CBonusSelection::CRegion::clickLeft( tribool down, bool previousState )
  2851. {
  2852. //select if selectable & clicked inside our graphic
  2853. if ( indeterminate(down) )
  2854. {
  2855. return;
  2856. }
  2857. if( !down && selectable && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) )
  2858. {
  2859. owner->selectMap(myNumber);
  2860. owner->highlightedRegion = this;
  2861. parent->showAll(screen);
  2862. }
  2863. }
  2864. void CBonusSelection::CRegion::clickRight( tribool down, bool previousState )
  2865. {
  2866. //show r-click text
  2867. if( down && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) &&
  2868. rclickText.size() )
  2869. {
  2870. CRClickPopup::createAndPush(rclickText);
  2871. }
  2872. }
  2873. void CBonusSelection::CRegion::show(SDL_Surface * to)
  2874. {
  2875. //const SCampPositions::SRegionDesc & desc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion].regions[myNumber];
  2876. if (!accessible)
  2877. {
  2878. //show as striped
  2879. blitAtLoc(graphics[2], 0, 0, to);
  2880. }
  2881. else if (this == owner->highlightedRegion)
  2882. {
  2883. //show as selected
  2884. blitAtLoc(graphics[1], 0, 0, to);
  2885. }
  2886. else
  2887. {
  2888. //show as not selected selected
  2889. blitAtLoc(graphics[0], 0, 0, to);
  2890. }
  2891. }
  2892. CSavingScreen::CSavingScreen(bool hotseat)
  2893. : CSelectionScreen(CMenuScreen::saveGame, hotseat ? CMenuScreen::MULTI_HOT_SEAT : CMenuScreen::SINGLE_PLAYER)
  2894. {
  2895. ourGame = mapInfoFromGame();
  2896. sInfo = *LOCPLINT->cb->getStartInfo();
  2897. setPlayersFromGame();
  2898. }
  2899. CSavingScreen::~CSavingScreen()
  2900. {
  2901. }
  2902. ISelectionScreenInfo::ISelectionScreenInfo(const std::map<ui32, std::string> *Names /*= NULL*/)
  2903. {
  2904. multiPlayer = CMenuScreen::SINGLE_PLAYER;
  2905. assert(!SEL);
  2906. SEL = this;
  2907. current = NULL;
  2908. if(Names && Names->size()) //if have custom set of player names - use it
  2909. playerNames = *Names;
  2910. else
  2911. 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)
  2912. }
  2913. ISelectionScreenInfo::~ISelectionScreenInfo()
  2914. {
  2915. assert(SEL == this);
  2916. SEL = NULL;
  2917. }
  2918. void ISelectionScreenInfo::updateStartInfo(std::string filename, StartInfo & sInfo, const CMapHeader * mapHeader)
  2919. {
  2920. ::updateStartInfo(filename, sInfo, mapHeader, playerNames);
  2921. }
  2922. void ISelectionScreenInfo::setPlayer(PlayerSettings &pset, unsigned player)
  2923. {
  2924. ::setPlayer(pset, player, playerNames);
  2925. }
  2926. int ISelectionScreenInfo::getIdOfFirstUnallocatedPlayer()
  2927. {
  2928. for(std::map<ui32, std::string>::const_iterator i = playerNames.begin(); i != playerNames.end(); i++)
  2929. if(!sInfo.getPlayersSettings(i->first)) //
  2930. return i->first;
  2931. return 0;
  2932. }
  2933. bool ISelectionScreenInfo::isGuest() const
  2934. {
  2935. return multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST;
  2936. }
  2937. bool ISelectionScreenInfo::isHost() const
  2938. {
  2939. return multiPlayer == CMenuScreen::MULTI_NETWORK_HOST;
  2940. }
  2941. void ChatMessage::apply(CSelectionScreen *selScreen)
  2942. {
  2943. selScreen->card->chat->addNewMessage(playerName + ": " + message);
  2944. GH.totalRedraw();
  2945. }
  2946. void QuitMenuWithoutStarting::apply(CSelectionScreen *selScreen)
  2947. {
  2948. if(!selScreen->ongoingClosing)
  2949. {
  2950. *selScreen->serv << this; //resend to confirm
  2951. GH.popIntTotally(selScreen); //will wait with deleting us before this thread ends
  2952. }
  2953. vstd::clear_pointer(selScreen->serv);
  2954. }
  2955. void PlayerJoined::apply(CSelectionScreen *selScreen)
  2956. {
  2957. //assert(SEL->playerNames.size() == connectionID); //temporary, TODO when player exits
  2958. SEL->playerNames[connectionID] = playerName;
  2959. //put new player in first slot with AI
  2960. for(std::map<int, PlayerSettings>::iterator i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  2961. {
  2962. if(!i->second.human)
  2963. {
  2964. selScreen->setPlayer(i->second, connectionID);
  2965. selScreen->opt->entries[i->second.color]->selectButtons();
  2966. break;
  2967. }
  2968. }
  2969. selScreen->propagateNames();
  2970. selScreen->propagateOptions();
  2971. GH.totalRedraw();
  2972. }
  2973. void SelectMap::apply(CSelectionScreen *selScreen)
  2974. {
  2975. if(selScreen->multiPlayer == CMenuScreen::MULTI_NETWORK_GUEST)
  2976. {
  2977. free = false;
  2978. selScreen->changeSelection(mapInfo);
  2979. }
  2980. }
  2981. void UpdateStartOptions::apply(CSelectionScreen *selScreen)
  2982. {
  2983. if(!selScreen->isGuest())
  2984. return;
  2985. selScreen->setSInfo(*options);
  2986. }
  2987. void PregameGuiAction::apply(CSelectionScreen *selScreen)
  2988. {
  2989. if(!selScreen->isGuest())
  2990. return;
  2991. switch(action)
  2992. {
  2993. case NO_TAB:
  2994. selScreen->toggleTab(selScreen->curTab);
  2995. break;
  2996. case OPEN_OPTIONS:
  2997. selScreen->toggleTab(selScreen->opt);
  2998. break;
  2999. case OPEN_SCENARIO_LIST:
  3000. selScreen->toggleTab(selScreen->sel);
  3001. break;
  3002. }
  3003. }
  3004. void RequestOptionsChange::apply(CSelectionScreen *selScreen)
  3005. {
  3006. if(!selScreen->isHost())
  3007. return;
  3008. ui8 color = selScreen->sInfo.getPlayersSettings(playerID)->color;
  3009. switch(what)
  3010. {
  3011. case TOWN:
  3012. selScreen->opt->nextCastle(color, direction);
  3013. break;
  3014. case HERO:
  3015. selScreen->opt->nextHero(color, direction);
  3016. break;
  3017. case BONUS:
  3018. selScreen->opt->nextBonus(color, direction);
  3019. break;
  3020. }
  3021. }
  3022. void PlayerLeft::apply(CSelectionScreen *selScreen)
  3023. {
  3024. if(selScreen->isGuest())
  3025. return;
  3026. SEL->playerNames.erase(playerID);
  3027. if(PlayerSettings *s = selScreen->sInfo.getPlayersSettings(playerID)) //it's possible that player was unallocated
  3028. {
  3029. selScreen->setPlayer(*s, 0);
  3030. selScreen->opt->entries[s->color]->selectButtons();
  3031. }
  3032. selScreen->propagateNames();
  3033. selScreen->propagateOptions();
  3034. GH.totalRedraw();
  3035. }
  3036. void PlayersNames::apply(CSelectionScreen *selScreen)
  3037. {
  3038. if(selScreen->isGuest())
  3039. selScreen->playerNames = playerNames;
  3040. }
  3041. void StartWithCurrentSettings::apply(CSelectionScreen *selScreen)
  3042. {
  3043. startingInfo.reset();
  3044. startingInfo.serv = selScreen->serv;
  3045. startingInfo.sInfo = new StartInfo(selScreen->sInfo);
  3046. if(!selScreen->ongoingClosing)
  3047. {
  3048. *selScreen->serv << this; //resend to confirm
  3049. }
  3050. selScreen->serv = NULL; //hide it so it won't be deleted
  3051. vstd::clear_pointer(selScreen->serverHandlingThread); //detach us
  3052. selectedName = selScreen->sInfo.mapname;
  3053. CGP->removeFromGui();
  3054. ::startGame(startingInfo.sInfo, startingInfo.serv);
  3055. throw 666; //EVIL, EVIL, EVIL workaround to kill thread (does "goto catch" outside listening loop)
  3056. }
  3057. CCampaignScreen::CCampaignButton::CCampaignButton(const JsonNode &config )
  3058. {
  3059. pos.x += config["x"].Float();
  3060. pos.y += config["y"].Float();
  3061. pos.w = 200;
  3062. pos.h = 116;
  3063. campFile = config["file"].String();
  3064. video = config["video"].String();
  3065. //On linux we can only play *.mjpg videos from LOKI release
  3066. #ifdef _WIN32
  3067. std::transform(video.begin(), video.end(), video.begin(), toupper);
  3068. video += ".BIK";
  3069. #else
  3070. std::transform(video.begin(), video.end(), video.begin(), tolower);
  3071. video += ".mjpg";
  3072. #endif
  3073. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3074. status = config["open"].Bool() ? CCampaignScreen::ENABLED : CCampaignScreen::DISABLED;
  3075. CCampaignHeader header = CCampaignHandler::getHeader(campFile, true);
  3076. hoverText = header.name;
  3077. if (status != CCampaignScreen::DISABLED)
  3078. {
  3079. addUsedEvents(LCLICK | HOVER);
  3080. image = new CPicture(config["image"].String());
  3081. hoverLabel = new CLabel(pos.w / 2, pos.h + 20, FONT_MEDIUM, CENTER, Colors::Jasmine, "");
  3082. parent->addChild(hoverLabel);
  3083. }
  3084. if (status == CCampaignScreen::COMPLETED)
  3085. checkMark = new CPicture("CAMPCHK");
  3086. }
  3087. void CCampaignScreen::CCampaignButton::clickLeft(tribool down, bool previousState)
  3088. {
  3089. if (down)
  3090. {
  3091. // Close running video and open the selected campaign
  3092. CCS->videoh->close();
  3093. CCampaign * ourCampaign = CCampaignHandler::getCampaign(campFile, true);
  3094. CCampaignState * campState = new CCampaignState();
  3095. campState->camp = ourCampaign;
  3096. GH.pushInt( new CBonusSelection(campState) );
  3097. }
  3098. }
  3099. void CCampaignScreen::CCampaignButton::hover(bool on)
  3100. {
  3101. if (on)
  3102. hoverLabel->setTxt(hoverText); // Shows the name of the campaign when you get into the bounds of the button
  3103. else
  3104. hoverLabel->setTxt(" ");
  3105. }
  3106. void CCampaignScreen::CCampaignButton::show(SDL_Surface * to)
  3107. {
  3108. if (status == CCampaignScreen::DISABLED)
  3109. return;
  3110. CIntObject::show(to);
  3111. // Play the campaign button video when the mouse cursor is placed over the button
  3112. if (hovered)
  3113. {
  3114. if (CCS->videoh->fname != video)
  3115. CCS->videoh->open(video);
  3116. CCS->videoh->update(pos.x, pos.y, to, true, false); // plays sequentially frame by frame, starts at the beginning when the video is over
  3117. }
  3118. else if (CCS->videoh->fname == video) // When you got out of the bounds of the button then close the video
  3119. {
  3120. CCS->videoh->close();
  3121. redraw();
  3122. }
  3123. }
  3124. CAdventureMapButton* CCampaignScreen::createExitButton(const JsonNode& button)
  3125. {
  3126. std::pair<std::string, std::string> help;
  3127. if (!button["help"].isNull() && button["help"].Float() > 0)
  3128. help = CGI->generaltexth->zelp[button["help"].Float()];
  3129. boost::function<void()> close = boost::bind(&CGuiHandler::popIntTotally, &GH, this);
  3130. return new CAdventureMapButton(help, close, button["x"].Float(), button["y"].Float(), button["name"].String(), button["hotkey"].Float());
  3131. }
  3132. CCampaignScreen::CCampaignScreen(const JsonNode &config)
  3133. {
  3134. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3135. BOOST_FOREACH(const JsonNode& node, config["images"].Vector())
  3136. images.push_back(createPicture(node));
  3137. if (!images.empty())
  3138. {
  3139. images[0]->center(); // move background to center
  3140. moveTo(images[0]->pos.topLeft()); // move everything else to center
  3141. images[0]->moveTo(pos.topLeft()); // restore moved twice background
  3142. pos = images[0]->pos; // fix height\width of this window
  3143. }
  3144. if (!config["exitbutton"].isNull())
  3145. {
  3146. back = createExitButton(config["exitbutton"]);
  3147. back->hoverable = true;
  3148. }
  3149. BOOST_FOREACH(const JsonNode& node, config["items"].Vector())
  3150. campButtons.push_back(new CCampaignButton(node));
  3151. }
  3152. void CCampaignScreen::showAll(SDL_Surface *to)
  3153. {
  3154. CIntObject::showAll(to);
  3155. if (pos.h != to->h || pos.w != to->w)
  3156. CMessage::drawBorder(1, to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  3157. }