CSpellWindow.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /*
  2. * CSpellWindow.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CSpellWindow.h"
  12. #include "../../lib/ScopeGuard.h"
  13. #include "GUIClasses.h"
  14. #include "InfoWindows.h"
  15. #include "CCastleInterface.h"
  16. #include "../CPlayerInterface.h"
  17. #include "../PlayerLocalState.h"
  18. #include "../battle/BattleInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/Shortcut.h"
  22. #include "../gui/WindowHandler.h"
  23. #include "../media/IVideoPlayer.h"
  24. #include "../render/CAnimation.h"
  25. #include "../render/IRenderHandler.h"
  26. #include "../widgets/GraphicalPrimitiveCanvas.h"
  27. #include "../widgets/CComponent.h"
  28. #include "../widgets/CTextInput.h"
  29. #include "../widgets/TextControls.h"
  30. #include "../widgets/Buttons.h"
  31. #include "../widgets/VideoWidget.h"
  32. #include "../adventureMap/AdventureMapInterface.h"
  33. #include "../eventsSDL/InputHandler.h"
  34. #include "../../lib/CConfigHandler.h"
  35. #include "../../lib/GameConstants.h"
  36. #include "../../lib/GameLibrary.h"
  37. #include "../../lib/battle/CPlayerBattleCallback.h"
  38. #include "../../lib/callback/CCallback.h"
  39. #include "../../lib/spells/CSpellHandler.h"
  40. #include "../../lib/spells/ISpellMechanics.h"
  41. #include "../../lib/spells/adventure/AdventureSpellEffect.h"
  42. #include "../../lib/spells/Problem.h"
  43. #include "../../lib/spells/SpellSchoolHandler.h"
  44. #include "../../lib/texts/CGeneralTextHandler.h"
  45. #include "../../lib/texts/TextOperations.h"
  46. #include "../../lib/mapObjects/CGHeroInstance.h"
  47. // Ordering of spell school tabs in SpelTab.def
  48. static const std::array schoolTabOrder =
  49. {
  50. SpellSchool::AIR,
  51. SpellSchool::FIRE,
  52. SpellSchool::WATER,
  53. SpellSchool::EARTH,
  54. SpellSchool::ANY
  55. };
  56. int getAnimFrameFromSchool(SpellSchool school)
  57. {
  58. auto it = std::find(schoolTabOrder.begin(), schoolTabOrder.end(), school);
  59. if (it != schoolTabOrder.end())
  60. return std::distance(schoolTabOrder.begin(), it);
  61. else
  62. return -1;
  63. }
  64. bool isLegacySpellSchool(SpellSchool school)
  65. {
  66. return getAnimFrameFromSchool(school) != -1;
  67. }
  68. CSpellWindow::InteractiveArea::InteractiveArea(const Rect & myRect, const std::function<void()> & funcL, int helpTextId, CSpellWindow * _owner)
  69. {
  70. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  71. pos = myRect;
  72. onLeft = funcL;
  73. hoverText = LIBRARY->generaltexth->zelp[helpTextId].first;
  74. helpText = LIBRARY->generaltexth->zelp[helpTextId].second;
  75. owner = _owner;
  76. }
  77. CSpellWindow::InteractiveArea::InteractiveArea(const Rect & myRect, const std::function<void()> & funcL, std::string textId, CSpellWindow * _owner)
  78. {
  79. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  80. pos = myRect;
  81. onLeft = funcL;
  82. auto hoverTextTmp = MetaString::createFromTextID("vcmi.spellBook.tab.hover");
  83. hoverTextTmp.replaceTextID(textId);
  84. hoverText = hoverTextTmp.toString();
  85. auto helpTextTmp = MetaString::createFromTextID("vcmi.spellBook.tab.help");
  86. helpTextTmp.replaceTextID(textId);
  87. helpText = helpTextTmp.toString();
  88. owner = _owner;
  89. }
  90. void CSpellWindow::InteractiveArea::clickPressed(const Point & cursorPosition)
  91. {
  92. ENGINE->input().hapticFeedback();
  93. onLeft();
  94. }
  95. void CSpellWindow::InteractiveArea::showPopupWindow(const Point & cursorPosition)
  96. {
  97. CRClickPopup::createAndPush(helpText);
  98. }
  99. void CSpellWindow::InteractiveArea::hover(bool on)
  100. {
  101. if(on)
  102. owner->statusBar->write(hoverText);
  103. else
  104. owner->statusBar->clear();
  105. }
  106. class SpellbookSpellSorter
  107. {
  108. public:
  109. bool operator()(const CSpell * A, const CSpell * B)
  110. {
  111. if(A->getLevel() < B->getLevel())
  112. return true;
  113. if(A->getLevel() > B->getLevel())
  114. return false;
  115. for (const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects())
  116. {
  117. if(A->schools.count(schoolId) && !B->schools.count(schoolId))
  118. return true;
  119. if(!A->schools.count(schoolId) && B->schools.count(schoolId))
  120. return false;
  121. }
  122. return TextOperations::compareLocalizedStrings(A->getNameTranslated(), B->getNameTranslated());
  123. }
  124. };
  125. CSpellWindow::CSpellWindow(const CGHeroInstance * _myHero, CPlayerInterface * _myInt, bool openOnBattleSpells, const std::function<void(SpellID)> & onSpellSelect):
  126. CWindowObject(PLAYER_COLORED | (settings["gameTweaks"]["enableLargeSpellbook"].Bool() ? BORDERED : 0)),
  127. battleSpellsOnly(openOnBattleSpells),
  128. selectedTab(SpellSchool::ANY),
  129. currentPage(0),
  130. myHero(_myHero),
  131. myInt(_myInt),
  132. openOnBattleSpells(openOnBattleSpells),
  133. onSpellSelect(onSpellSelect),
  134. isBigSpellbook(settings["gameTweaks"]["enableLargeSpellbook"].Bool()),
  135. spellsPerPage(24),
  136. offL(-11),
  137. offR(195),
  138. offRM(110),
  139. offT(-37),
  140. offB(56)
  141. {
  142. OBJECT_CONSTRUCTION;
  143. for(const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects())
  144. if(
  145. !isLegacySpellSchool(schoolId) &&
  146. customSpellSchools.size() < (isBigSpellbook ? MAX_CUSTOM_SPELL_SCHOOLS_BIG : MAX_CUSTOM_SPELL_SCHOOLS) &&
  147. !LIBRARY->spellSchoolHandler->getById(schoolId)->getSchoolBookmarkPath().empty() &&
  148. !LIBRARY->spellSchoolHandler->getById(schoolId)->getSchoolHeaderPath().empty()
  149. )
  150. customSpellSchools.push_back(schoolId);
  151. if(isBigSpellbook)
  152. {
  153. background = std::make_shared<CPicture>(ImagePath::builtin("SpellBookLarge"), 0, 0);
  154. updateShadow();
  155. }
  156. else
  157. {
  158. background = std::make_shared<CPicture>(ImagePath::builtin("SpelBack"), 0, 0);
  159. offL = offR = offT = offB = offRM = 0;
  160. spellsPerPage = 12;
  161. }
  162. pos = background->center(Point(pos.w/2 + pos.x, pos.h/2 + pos.y));
  163. Rect r(90, isBigSpellbook ? 480 : 420, isBigSpellbook ? 160 : 110, 16);
  164. if(settings["general"]["enableUiEnhancements"].Bool())
  165. {
  166. const ColorRGBA rectangleColor = ColorRGBA(0, 0, 0, 75);
  167. const ColorRGBA borderColor = ColorRGBA(128, 100, 75);
  168. const ColorRGBA grayedColor = ColorRGBA(158, 130, 105);
  169. searchBoxRectangle = std::make_shared<TransparentFilledRectangle>(r.resize(1), rectangleColor, borderColor);
  170. searchBoxDescription = std::make_shared<CLabel>(r.center().x, r.center().y, FONT_SMALL, ETextAlignment::CENTER, grayedColor, LIBRARY->generaltexth->translate("vcmi.spellBook.search"));
  171. searchBox = std::make_shared<CTextInput>(r, FONT_SMALL, ETextAlignment::CENTER, false);
  172. searchBox->setCallback(std::bind(&CSpellWindow::searchInput, this));
  173. }
  174. if(onSpellSelect)
  175. {
  176. Point boxPos = r.bottomLeft() + Point(-2, 5);
  177. showAllSpells = std::make_shared<CToggleButton>(boxPos, AnimationPath::builtin("sysopchk.def"), CButton::tooltip(LIBRARY->generaltexth->translate("core.help.458.hover"), LIBRARY->generaltexth->translate("core.help.458.hover")), [this](bool state){ searchInput(); });
  178. showAllSpellsDescription = std::make_shared<CLabel>(boxPos.x + 40, boxPos.y + 12, FONT_SMALL, ETextAlignment::CENTERLEFT, Colors::WHITE, LIBRARY->generaltexth->translate("core.help.458.hover"));
  179. }
  180. processSpells();
  181. //numbers of spell pages computed
  182. leftCorner = std::make_shared<CPicture>(ImagePath::builtin("SpelTrnL.bmp"), 97 + offL, 77 + offT);
  183. rightCorner = std::make_shared<CPicture>(ImagePath::builtin("SpelTrnR.bmp"), 487 + offR, 72 + offT);
  184. schoolTab = std::make_shared<CAnimImage>(AnimationPath::builtin("SpelTab"), getAnimFrameFromSchool(selectedTab), 0, 524 + offR, 88);
  185. for(int i = 0; i < customSpellSchools.size(); i++)
  186. schoolTabCustom.push_back(std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(customSpellSchools[i])->getSchoolBookmarkPath(), i == 0 ? 0 : 1, 0, isBigSpellbook ? 0 : 15, 93 + 62 * i));
  187. schoolPicture = std::make_shared<CAnimImage>(AnimationPath::builtin("Schools"), 0, 0, 117 + offL, 74 + offT);
  188. mana = std::make_shared<CLabel>(435 + (isBigSpellbook ? 159 : 0), 426 + offB, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, std::to_string(myHero->mana));
  189. if(isBigSpellbook)
  190. statusBar = CGStatusBar::create(400, 587);
  191. else
  192. statusBar = CGStatusBar::create(7, 569, ImagePath::builtin("Spelroll.bmp"));
  193. Rect schoolRect( 549 + pos.x + offR, 94 + pos.y, 45, 35);
  194. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 479 + pos.x + (isBigSpellbook ? 175 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fexitb, this), 460, this));
  195. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 221 + pos.x + (isBigSpellbook ? 43 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fbattleSpellsb, this), 453, this));
  196. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 355 + pos.x + (isBigSpellbook ? 110 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fadvSpellsb, this), 452, this));
  197. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 418 + pos.x + (isBigSpellbook ? 142 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fmanaPtsb, this), 459, this));
  198. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 0), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::AIR), 454, this));
  199. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 57), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::EARTH), 457, this));
  200. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 116), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::FIRE), 455, this));
  201. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 176), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::WATER), 456, this));
  202. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 236), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::ANY), 458, this));
  203. for(int i = 0; i < customSpellSchools.size(); i++)
  204. interactiveAreas.push_back(std::make_shared<InteractiveArea>(Rect(schoolTabCustom[i]->pos.topLeft(), Point(80, 60)), std::bind(&CSpellWindow::selectSchool, this, customSpellSchools[i]), LIBRARY->spellSchoolHandler->getById(customSpellSchools[i])->getNameTextID(), this));
  205. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 97 + offL + pos.x, 77 + offT + pos.y, leftCorner->pos.h, leftCorner->pos.w ), std::bind(&CSpellWindow::fLcornerb, this), 450, this));
  206. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 487 + offR + pos.x, 72 + offT + pos.y, rightCorner->pos.h, rightCorner->pos.w ), std::bind(&CSpellWindow::fRcornerb, this), 451, this));
  207. //areas for spells
  208. int xpos = 117 + offL + pos.x;
  209. int ypos = 90 + offT + pos.y;
  210. for(int v=0; v<spellsPerPage; ++v)
  211. {
  212. spellAreas[v] = std::make_shared<SpellArea>( Rect(xpos, ypos, 65, 78), this);
  213. if(v == (spellsPerPage / 2) - 1) //to right page
  214. {
  215. xpos = offRM + 336 + pos.x; ypos = 90 + offT + pos.y;
  216. }
  217. else
  218. {
  219. if(v%(isBigSpellbook ? 3 : 2) == 0 || (v%3 == 1 && isBigSpellbook))
  220. {
  221. xpos+=85;
  222. }
  223. else
  224. {
  225. xpos -= (isBigSpellbook ? 2 : 1)*85; ypos+=97;
  226. }
  227. }
  228. }
  229. SpellSchool school = battleSpellsOnly ? myInt->localState->getSpellbookSettings().spellbookLastTabBattle : myInt->localState->getSpellbookSettings().spellbookLastTabAdvmap;
  230. bool schoolFound = false;
  231. for(const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects()) // check if spellschool exists -> if not, then keep any
  232. if(schoolId == school)
  233. schoolFound = true;
  234. if(schoolFound)
  235. selectedTab = school;
  236. setSchoolImages(selectedTab);
  237. int cp = battleSpellsOnly ? myInt->localState->getSpellbookSettings().spellbookLastPageBattle : myInt->localState->getSpellbookSettings().spellbookLastPageAdvmap;
  238. // spellbook last page battle index is not reset after battle, so this needs to stay here
  239. vstd::abetween(cp, 0, std::max(0, pagesWithinCurrentTab() - 1));
  240. if(!schoolFound)
  241. cp = 0;
  242. setCurrentPage(cp);
  243. computeSpellsPerArea();
  244. addUsedEvents(KEYBOARD);
  245. }
  246. CSpellWindow::~CSpellWindow()
  247. {
  248. }
  249. void CSpellWindow::searchInput()
  250. {
  251. if(searchBox)
  252. searchBoxDescription->setEnabled(searchBox->getText().empty());
  253. processSpells();
  254. int cp = 0;
  255. // spellbook last page battle index is not reset after battle, so this needs to stay here
  256. vstd::abetween(cp, 0, std::max(0, pagesWithinCurrentTab() - 1));
  257. setCurrentPage(cp);
  258. computeSpellsPerArea();
  259. }
  260. void CSpellWindow::processSpells()
  261. {
  262. mySpells.clear();
  263. //initializing castable spells
  264. mySpells.reserve(LIBRARY->spellh->objects.size());
  265. for(auto const & spell : LIBRARY->spellh->objects)
  266. {
  267. bool searchTextFound = !searchBox || TextOperations::textSearchSimilarityScore(searchBox->getText(), spell->getNameTranslated());
  268. if(onSpellSelect)
  269. {
  270. if(spell->isCombat() == openOnBattleSpells
  271. && !spell->isSpecial()
  272. && !spell->isCreatureAbility()
  273. && searchTextFound
  274. && (showAllSpells->isSelected() || myHero->canCastThisSpell(spell.get())))
  275. {
  276. mySpells.push_back(spell.get());
  277. }
  278. continue;
  279. }
  280. if(!spell->isCreatureAbility() && myHero->canCastThisSpell(spell.get()) && searchTextFound)
  281. mySpells.push_back(spell.get());
  282. }
  283. SpellbookSpellSorter spellsorter;
  284. std::sort(mySpells.begin(), mySpells.end(), spellsorter);
  285. for(const auto spell : mySpells)
  286. {
  287. auto& sitesPerOurTab = spell->isCombat() ? sitesPerTabBattle : sitesPerTabAdv;
  288. ++sitesPerOurTab[SpellSchool::ANY];
  289. spell->forEachSchool([&sitesPerOurTab](const SpellSchool & school, bool & stop)
  290. {
  291. ++sitesPerOurTab[school];
  292. });
  293. }
  294. if(sitesPerTabAdv[SpellSchool::ANY] % spellsPerPage == 0)
  295. sitesPerTabAdv[SpellSchool::ANY]/=spellsPerPage;
  296. else
  297. sitesPerTabAdv[SpellSchool::ANY] = sitesPerTabAdv[SpellSchool::ANY]/spellsPerPage + 1;
  298. for(const auto v : LIBRARY->spellSchoolHandler->getAllObjects())
  299. {
  300. if(v == SpellSchool::ANY)
  301. continue;
  302. if(sitesPerTabAdv[v] <= spellsPerPage - 2)
  303. sitesPerTabAdv[v] = 1;
  304. else
  305. {
  306. if((sitesPerTabAdv[v] - (spellsPerPage - 2)) % spellsPerPage == 0)
  307. sitesPerTabAdv[v] = (sitesPerTabAdv[v] - (spellsPerPage - 2)) / spellsPerPage + 1;
  308. else
  309. sitesPerTabAdv[v] = (sitesPerTabAdv[v] - (spellsPerPage - 2)) / spellsPerPage + 2;
  310. }
  311. }
  312. if(sitesPerTabBattle[SpellSchool::ANY] % spellsPerPage == 0)
  313. sitesPerTabBattle[SpellSchool::ANY]/=spellsPerPage;
  314. else
  315. sitesPerTabBattle[SpellSchool::ANY] = sitesPerTabBattle[SpellSchool::ANY]/spellsPerPage + 1;
  316. for(const auto v : LIBRARY->spellSchoolHandler->getAllObjects())
  317. {
  318. if(v == SpellSchool::ANY)
  319. continue;
  320. if(sitesPerTabBattle[v] <= spellsPerPage - 2)
  321. sitesPerTabBattle[v] = 1;
  322. else
  323. {
  324. if((sitesPerTabBattle[v] - (spellsPerPage - 2)) % spellsPerPage == 0)
  325. sitesPerTabBattle[v] = (sitesPerTabBattle[v] - (spellsPerPage - 2)) / spellsPerPage + 1;
  326. else
  327. sitesPerTabBattle[v] = (sitesPerTabBattle[v] - (spellsPerPage - 2)) / spellsPerPage + 2;
  328. }
  329. }
  330. }
  331. void CSpellWindow::fexitb()
  332. {
  333. auto spellBookState = myInt->localState->getSpellbookSettings();
  334. if(myInt->battleInt)
  335. {
  336. spellBookState.spellbookLastTabBattle = selectedTab;
  337. spellBookState.spellbookLastPageBattle = currentPage;
  338. }
  339. else
  340. {
  341. spellBookState.spellbookLastTabAdvmap = selectedTab;
  342. spellBookState.spellbookLastPageAdvmap = currentPage;
  343. }
  344. myInt->localState->setSpellbookSettings(spellBookState);
  345. if(onSpellSelect)
  346. onSpellSelect(SpellID::NONE);
  347. close();
  348. }
  349. void CSpellWindow::fadvSpellsb()
  350. {
  351. if(battleSpellsOnly == true)
  352. {
  353. turnPageRight();
  354. battleSpellsOnly = false;
  355. setCurrentPage(0);
  356. }
  357. computeSpellsPerArea();
  358. }
  359. void CSpellWindow::fbattleSpellsb()
  360. {
  361. if(battleSpellsOnly == false)
  362. {
  363. turnPageLeft();
  364. battleSpellsOnly = true;
  365. setCurrentPage(0);
  366. }
  367. computeSpellsPerArea();
  368. }
  369. void CSpellWindow::toggleSearchBoxFocus()
  370. {
  371. if(searchBox != nullptr)
  372. {
  373. searchBox->hasFocus() ? searchBox->removeFocus() : searchBox->giveFocus();
  374. }
  375. }
  376. void CSpellWindow::fmanaPtsb()
  377. {
  378. }
  379. void CSpellWindow::selectSchool(SpellSchool school)
  380. {
  381. if(selectedTab != school)
  382. {
  383. if(selectedTab < school)
  384. turnPageLeft();
  385. else
  386. turnPageRight();
  387. selectedTab = school;
  388. setSchoolImages(selectedTab);
  389. setCurrentPage(0);
  390. }
  391. computeSpellsPerArea();
  392. }
  393. void CSpellWindow::fLcornerb()
  394. {
  395. if(currentPage>0)
  396. {
  397. turnPageLeft();
  398. setCurrentPage(currentPage - 1);
  399. }
  400. computeSpellsPerArea();
  401. }
  402. void CSpellWindow::fRcornerb()
  403. {
  404. if((currentPage + 1) < (pagesWithinCurrentTab()))
  405. {
  406. turnPageRight();
  407. setCurrentPage(currentPage + 1);
  408. }
  409. computeSpellsPerArea();
  410. }
  411. void CSpellWindow::show(Canvas & to)
  412. {
  413. if(video)
  414. video->show(to);
  415. statusBar->show(to);
  416. }
  417. void CSpellWindow::computeSpellsPerArea()
  418. {
  419. std::vector<const CSpell *> spellsCurSite;
  420. spellsCurSite.reserve(mySpells.size());
  421. for(const CSpell * spell : mySpells)
  422. {
  423. if(spell->isCombat() ^ !battleSpellsOnly
  424. && ((selectedTab == SpellSchool::ANY) || spell->schools.count(selectedTab))
  425. )
  426. {
  427. spellsCurSite.push_back(spell);
  428. }
  429. }
  430. if(selectedTab == SpellSchool::ANY)
  431. {
  432. if(spellsCurSite.size() > spellsPerPage)
  433. {
  434. spellsCurSite = std::vector<const CSpell *>(spellsCurSite.begin() + currentPage*spellsPerPage, spellsCurSite.end());
  435. if(spellsCurSite.size() > spellsPerPage)
  436. {
  437. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage, spellsCurSite.end());
  438. }
  439. }
  440. }
  441. else
  442. {
  443. if(spellsCurSite.size() > spellsPerPage - 2)
  444. {
  445. if(currentPage == 0)
  446. {
  447. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage-2, spellsCurSite.end());
  448. }
  449. else
  450. {
  451. spellsCurSite = std::vector<const CSpell *>(spellsCurSite.begin() + (currentPage-1)*spellsPerPage + spellsPerPage-2, spellsCurSite.end());
  452. if(spellsCurSite.size() > spellsPerPage)
  453. {
  454. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage, spellsCurSite.end());
  455. }
  456. }
  457. }
  458. }
  459. //applying
  460. if(selectedTab == SpellSchool::ANY || currentPage != 0)
  461. {
  462. for(size_t c=0; c<spellsPerPage; ++c)
  463. {
  464. if(c < spellsCurSite.size())
  465. {
  466. spellAreas[c]->setSpell(spellsCurSite[c]);
  467. }
  468. else
  469. {
  470. spellAreas[c]->setSpell(nullptr);
  471. }
  472. }
  473. }
  474. else
  475. {
  476. spellAreas[0]->setSpell(nullptr);
  477. spellAreas[1]->setSpell(nullptr);
  478. for(size_t c=0; c<spellsPerPage-2; ++c)
  479. {
  480. if(c < spellsCurSite.size())
  481. spellAreas[c+2]->setSpell(spellsCurSite[c]);
  482. else
  483. spellAreas[c+2]->setSpell(nullptr);
  484. }
  485. }
  486. redraw();
  487. }
  488. void CSpellWindow::setSchoolImages(SpellSchool school)
  489. {
  490. OBJECT_CONSTRUCTION;
  491. schoolTabAnyDisabled.reset();
  492. if(isLegacySpellSchool(school))
  493. {
  494. schoolTab->setFrame(getAnimFrameFromSchool(school), 0);
  495. schoolTab->visible = true;
  496. }
  497. else
  498. {
  499. schoolTabAnyDisabled = std::make_shared<CPicture>(ImagePath::builtin("SpelTabNone.png"), 524 + offR, 88);
  500. schoolTab->visible = false;
  501. }
  502. auto it = std::find(customSpellSchools.begin(), customSpellSchools.end(), school);
  503. int pos = (it == customSpellSchools.end()) ? -1 : std::distance(customSpellSchools.begin(), it);
  504. for(int i = 0; i < schoolTabCustom.size(); i++)
  505. schoolTabCustom[i]->setFrame(i == pos ? 0 : 1, 0);
  506. schoolPicture->visible = school != SpellSchool::ANY && currentPage == 0 && isLegacySpellSchool(school);
  507. if(school != SpellSchool::ANY && isLegacySpellSchool(school))
  508. schoolPicture->setFrame(getAnimFrameFromSchool(school), 0);
  509. schoolPictureCustom.reset();
  510. if(!isLegacySpellSchool(school))
  511. schoolPictureCustom = std::make_shared<CPicture>(LIBRARY->spellSchoolHandler->getById(school)->getSchoolHeaderPath(), 117 + offL, 74 + offT);
  512. }
  513. void CSpellWindow::setCurrentPage(int value)
  514. {
  515. currentPage = value;
  516. setSchoolImages(selectedTab);
  517. if (currentPage != 0)
  518. leftCorner->enable();
  519. else
  520. leftCorner->disable();
  521. if (currentPage + 1 < pagesWithinCurrentTab())
  522. rightCorner->enable();
  523. else
  524. rightCorner->disable();
  525. mana->setText(std::to_string(myHero->mana));//just in case, it will be possible to cast spell without closing book
  526. }
  527. void CSpellWindow::turnPageLeft()
  528. {
  529. OBJECT_CONSTRUCTION;
  530. if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook)
  531. video = std::make_shared<VideoWidgetOnce>(Point(13, 14), VideoPath::builtin("PGTRNLFT.SMK"), false, this);
  532. }
  533. void CSpellWindow::turnPageRight()
  534. {
  535. OBJECT_CONSTRUCTION;
  536. if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook)
  537. video = std::make_shared<VideoWidgetOnce>(Point(13, 14), VideoPath::builtin("PGTRNRGH.SMK"), false, this);
  538. }
  539. void CSpellWindow::onVideoPlaybackFinished()
  540. {
  541. video.reset();
  542. redraw();
  543. }
  544. void CSpellWindow::keyPressed(EShortcut key)
  545. {
  546. switch(key)
  547. {
  548. case EShortcut::GLOBAL_RETURN:
  549. fexitb();
  550. break;
  551. case EShortcut::MOVE_LEFT:
  552. fLcornerb();
  553. break;
  554. case EShortcut::MOVE_RIGHT:
  555. fRcornerb();
  556. break;
  557. case EShortcut::MOVE_UP:
  558. case EShortcut::MOVE_DOWN:
  559. {
  560. bool down = key == EShortcut::MOVE_DOWN;
  561. static const std::array schoolsOrder = { SpellSchool::AIR, SpellSchool::EARTH, SpellSchool::FIRE, SpellSchool::WATER, SpellSchool::ANY };
  562. int index = -1;
  563. while(schoolsOrder[++index] != selectedTab);
  564. index += (down ? 1 : -1);
  565. vstd::abetween<int>(index, 0, std::size(schoolsOrder) - 1);
  566. if(selectedTab != schoolsOrder[index])
  567. selectSchool(schoolsOrder[index]);
  568. break;
  569. }
  570. case EShortcut::SPELLBOOK_TAB_COMBAT:
  571. fbattleSpellsb();
  572. break;
  573. case EShortcut::SPELLBOOK_TAB_ADVENTURE:
  574. fadvSpellsb();
  575. break;
  576. case EShortcut::SPELLBOOK_SEARCH_FOCUS:
  577. toggleSearchBoxFocus();
  578. break;
  579. }
  580. }
  581. int CSpellWindow::pagesWithinCurrentTab()
  582. {
  583. return battleSpellsOnly ? sitesPerTabBattle[selectedTab] : sitesPerTabAdv[selectedTab];
  584. }
  585. CSpellWindow::SpellArea::SpellArea(Rect pos, CSpellWindow * owner)
  586. {
  587. this->pos = pos;
  588. this->owner = owner;
  589. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  590. schoolLevel = -1;
  591. mySpell = nullptr;
  592. OBJECT_CONSTRUCTION;
  593. image = std::make_shared<CAnimImage>(AnimationPath::builtin("Spells"), 0, 0);
  594. image->visible = false;
  595. name = std::make_shared<CLabel>(39, 70, FONT_TINY, ETextAlignment::CENTER);
  596. level = std::make_shared<CLabel>(39, 82, FONT_TINY, ETextAlignment::CENTER);
  597. cost = std::make_shared<CLabel>(39, 94, FONT_TINY, ETextAlignment::CENTER);
  598. for(auto l : {name, level, cost})
  599. l->setAutoRedraw(false);
  600. }
  601. CSpellWindow::SpellArea::~SpellArea() = default;
  602. void CSpellWindow::SpellArea::clickPressed(const Point & cursorPosition)
  603. {
  604. if(mySpell)
  605. {
  606. ENGINE->input().hapticFeedback();
  607. if(owner->onSpellSelect)
  608. {
  609. owner->onSpellSelect(mySpell->id);
  610. owner->close();
  611. return;
  612. }
  613. auto spellCost = owner->myInt->cb->getSpellCost(mySpell, owner->myHero);
  614. if(spellCost > owner->myHero->mana) //insufficient mana
  615. {
  616. GAME->interface()->showInfoDialog(boost::str(boost::format(LIBRARY->generaltexth->allTexts[206]) % spellCost % owner->myHero->mana));
  617. return;
  618. }
  619. //anything that is not combat spell is adventure spell
  620. //this not an error in general to cast even creature ability with hero
  621. const bool combatSpell = mySpell->isCombat();
  622. if(combatSpell == mySpell->isAdventure())
  623. {
  624. logGlobal->error("Spell have invalid flags");
  625. return;
  626. }
  627. const bool inCombat = owner->myInt->battleInt != nullptr;
  628. const bool inCastle = owner->myInt->castleInt != nullptr;
  629. //battle spell on adv map or adventure map spell during combat => display infowindow, not cast
  630. if((combatSpell != inCombat) || inCastle || (!combatSpell && !GAME->interface()->makingTurn))
  631. {
  632. std::vector<std::shared_ptr<CComponent>> hlp(1, std::make_shared<CComponent>(ComponentType::SPELL, mySpell->id));
  633. GAME->interface()->showInfoDialog(mySpell->getDescriptionTranslated(schoolLevel), hlp);
  634. }
  635. else if(combatSpell)
  636. {
  637. spells::detail::ProblemImpl problem;
  638. if(mySpell->canBeCast(problem, owner->myInt->battleInt->getBattle().get(), spells::Mode::HERO, owner->myHero))
  639. {
  640. owner->myInt->battleInt->castThisSpell(mySpell->id);
  641. owner->fexitb();
  642. }
  643. else
  644. {
  645. std::vector<std::string> texts;
  646. problem.getAll(texts);
  647. if(!texts.empty())
  648. GAME->interface()->showInfoDialog(texts.front());
  649. else
  650. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->translate("vcmi.adventureMap.spellUnknownProblem"));
  651. }
  652. }
  653. else //adventure spell
  654. {
  655. const CGHeroInstance * h = owner->myHero;
  656. ENGINE->windows().popWindows(1);
  657. auto guard = vstd::makeScopeGuard([this]()
  658. {
  659. auto spellBookState = owner->myInt->localState->getSpellbookSettings();
  660. spellBookState.spellbookLastTabAdvmap = owner->selectedTab;
  661. spellBookState.spellbookLastPageAdvmap = owner->currentPage;
  662. owner->myInt->localState->setSpellbookSettings(spellBookState);
  663. });
  664. spells::detail::ProblemImpl problem;
  665. if (mySpell->getAdventureMechanics().canBeCast(problem, GAME->interface()->cb.get(), owner->myHero))
  666. {
  667. const auto * rangeEffect = mySpell->getAdventureMechanics().getEffectAs<AdventureSpellRangedEffect>(owner->myHero);
  668. if(rangeEffect != nullptr)
  669. adventureInt->enterCastingMode(mySpell);
  670. else
  671. owner->myInt->cb->castSpell(h, mySpell->id);
  672. }
  673. else
  674. {
  675. std::vector<std::string> texts;
  676. problem.getAll(texts);
  677. if(!texts.empty())
  678. GAME->interface()->showInfoDialog(texts.front());
  679. else
  680. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->translate("vcmi.adventureMap.spellUnknownProblem"));
  681. }
  682. }
  683. }
  684. }
  685. void CSpellWindow::SpellArea::showPopupWindow(const Point & cursorPosition)
  686. {
  687. if(mySpell)
  688. {
  689. std::string dmgInfo;
  690. auto causedDmg = owner->myInt->cb->estimateSpellDamage(mySpell, owner->myHero);
  691. if(causedDmg == 0 || mySpell->id == SpellID::TITANS_LIGHTNING_BOLT) //Titan's Lightning Bolt already has damage info included
  692. dmgInfo.clear();
  693. else
  694. {
  695. dmgInfo = LIBRARY->generaltexth->allTexts[343];
  696. boost::algorithm::replace_first(dmgInfo, "%d", std::to_string(causedDmg));
  697. }
  698. CRClickPopup::createAndPush(mySpell->getDescriptionTranslated(schoolLevel) + dmgInfo, std::make_shared<CComponent>(ComponentType::SPELL, mySpell->id));
  699. }
  700. }
  701. void CSpellWindow::SpellArea::hover(bool on)
  702. {
  703. if(mySpell)
  704. {
  705. if(on)
  706. owner->statusBar->write(boost::str(boost::format("%s (%s)") % mySpell->getNameTranslated() % LIBRARY->generaltexth->allTexts[171+mySpell->getLevel()]));
  707. else
  708. owner->statusBar->clear();
  709. }
  710. }
  711. void CSpellWindow::SpellArea::setSpell(const CSpell * spell)
  712. {
  713. schoolBorder.reset();
  714. image->visible = false;
  715. name->setText("");
  716. level->setText("");
  717. cost->setText("");
  718. mySpell = spell;
  719. if(mySpell)
  720. {
  721. SpellSchool whichSchool;
  722. schoolLevel = owner->myHero->getSpellSchoolLevel(mySpell, &whichSchool);
  723. auto spellCost = owner->myInt->cb->getSpellCost(mySpell, owner->myHero);
  724. image->setFrame(mySpell->id.getNum());
  725. image->visible = true;
  726. {
  727. OBJECT_CONSTRUCTION;
  728. schoolBorder.reset();
  729. if (!isLegacySpellSchool(owner->selectedTab) || owner->selectedTab == SpellSchool::ANY)
  730. {
  731. if (whichSchool.hasValue())
  732. schoolBorder = std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(whichSchool)->getSpellBordersPath(), schoolLevel);
  733. }
  734. else
  735. schoolBorder = std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(owner->selectedTab)->getSpellBordersPath(), schoolLevel);
  736. }
  737. ColorRGBA firstLineColor, secondLineColor;
  738. if(spellCost > owner->myHero->mana && !owner->onSpellSelect) //hero cannot cast this spell
  739. {
  740. firstLineColor = Colors::WHITE;
  741. secondLineColor = Colors::ORANGE;
  742. }
  743. else
  744. {
  745. firstLineColor = Colors::YELLOW;
  746. secondLineColor = Colors::WHITE;
  747. }
  748. name->color = firstLineColor;
  749. name->setText(mySpell->getNameTranslated());
  750. level->color = secondLineColor;
  751. if(schoolLevel > 0)
  752. {
  753. boost::format fmt("%s/%s");
  754. fmt % LIBRARY->generaltexth->allTexts[171 + mySpell->getLevel()];
  755. fmt % LIBRARY->generaltexth->levels[3+(schoolLevel-1)];//lines 4-6
  756. level->setText(fmt.str());
  757. }
  758. else
  759. level->setText(LIBRARY->generaltexth->allTexts[171 + mySpell->getLevel()]);
  760. cost->color = secondLineColor;
  761. boost::format costfmt("%s: %d");
  762. costfmt % LIBRARY->generaltexth->allTexts[387] % spellCost;
  763. cost->setText(costfmt.str());
  764. }
  765. }