CPreGame.cpp 114 KB

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