CComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * CComponent.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 "CComponent.h"
  12. #include "CArtifactHolder.h"
  13. #include "Images.h"
  14. #include <vcmi/spells/Service.h>
  15. #include <vcmi/spells/Spell.h>
  16. #include "../gui/CGuiHandler.h"
  17. #include "../gui/CursorHandler.h"
  18. #include "../gui/TextAlignment.h"
  19. #include "../gui/Shortcut.h"
  20. #include "../render/Canvas.h"
  21. #include "../windows/CMessage.h"
  22. #include "../windows/InfoWindows.h"
  23. #include "../widgets/TextControls.h"
  24. #include "../CGameInfo.h"
  25. #include "../../lib/ArtifactUtils.h"
  26. #include "../../lib/CTownHandler.h"
  27. #include "../../lib/spells/CSpellHandler.h"
  28. #include "../../lib/CCreatureHandler.h"
  29. #include "../../lib/CSkillHandler.h"
  30. #include "../../lib/CGeneralTextHandler.h"
  31. #include "../../lib/NetPacksBase.h"
  32. #include "../../lib/CArtHandler.h"
  33. CComponent::CComponent(Etype Type, int Subtype, int Val, ESize imageSize, EFonts font):
  34. perDay(false)
  35. {
  36. init(Type, Subtype, Val, imageSize, font);
  37. }
  38. CComponent::CComponent(const Component & c, ESize imageSize, EFonts font)
  39. : perDay(false)
  40. {
  41. if(c.id == Component::EComponentType::RESOURCE && c.when==-1)
  42. perDay = true;
  43. init((Etype)c.id, c.subtype, c.val, imageSize, font);
  44. }
  45. void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize, EFonts fnt)
  46. {
  47. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  48. addUsedEvents(SHOW_POPUP);
  49. compType = Type;
  50. subtype = Subtype;
  51. val = Val;
  52. size = imageSize;
  53. font = fnt;
  54. assert(compType < typeInvalid);
  55. assert(size < sizeInvalid);
  56. setSurface(getFileName()[size], (int)getIndex());
  57. pos.w = image->pos.w;
  58. pos.h = image->pos.h;
  59. if (imageSize < small)
  60. font = FONT_TINY; //for tiny images - tiny font
  61. pos.h += 4; //distance between text and image
  62. auto max = 80;
  63. if (size < large)
  64. max = 72;
  65. if (size < medium)
  66. max = 40;
  67. if (size < small)
  68. max = 30;
  69. std::vector<std::string> textLines = CMessage::breakText(getSubtitle(), std::max<int>(max, pos.w), font);
  70. for(auto & line : textLines)
  71. {
  72. int height = static_cast<int>(graphics->fonts[font]->getLineHeight());
  73. auto label = std::make_shared<CLabel>(pos.w/2, pos.h + height/2, font, ETextAlignment::CENTER, Colors::WHITE, line);
  74. pos.h += height;
  75. if(label->pos.w > pos.w)
  76. {
  77. pos.x -= (label->pos.w - pos.w)/2;
  78. pos.w = label->pos.w;
  79. }
  80. lines.push_back(label);
  81. }
  82. }
  83. const std::vector<std::string> CComponent::getFileName()
  84. {
  85. static const std::string primSkillsArr [] = {"PSKIL32", "PSKIL32", "PSKIL42", "PSKILL"};
  86. static const std::string secSkillsArr [] = {"SECSK32", "SECSK32", "SECSKILL", "SECSK82"};
  87. static const std::string resourceArr [] = {"SMALRES", "RESOURCE", "RESOURCE", "RESOUR82"};
  88. static const std::string creatureArr [] = {"CPRSMALL", "CPRSMALL", "CPRSMALL", "TWCRPORT"};
  89. static const std::string artifactArr[] = {"Artifact", "Artifact", "Artifact", "Artifact"};
  90. static const std::string spellsArr [] = {"SpellInt", "SpellInt", "SpellInt", "SPELLSCR"};
  91. static const std::string moraleArr [] = {"IMRL22", "IMRL30", "IMRL42", "imrl82"};
  92. static const std::string luckArr [] = {"ILCK22", "ILCK30", "ILCK42", "ilck82"};
  93. static const std::string heroArr [] = {"PortraitsSmall", "PortraitsSmall", "PortraitsSmall", "PortraitsLarge"};
  94. static const std::string flagArr [] = {"CREST58", "CREST58", "CREST58", "CREST58"};
  95. auto gen = [](const std::string * arr)
  96. {
  97. return std::vector<std::string>(arr, arr + 4);
  98. };
  99. switch(compType)
  100. {
  101. case primskill: return gen(primSkillsArr);
  102. case secskill: return gen(secSkillsArr);
  103. case resource: return gen(resourceArr);
  104. case creature: return gen(creatureArr);
  105. case artifact: return gen(artifactArr);
  106. case experience: return gen(primSkillsArr);
  107. case spell: return gen(spellsArr);
  108. case morale: return gen(moraleArr);
  109. case luck: return gen(luckArr);
  110. case building: return std::vector<std::string>(4, (*CGI->townh)[subtype]->town->clientInfo.buildingsIcons);
  111. case hero: return gen(heroArr);
  112. case flag: return gen(flagArr);
  113. }
  114. assert(0);
  115. return std::vector<std::string>();
  116. }
  117. size_t CComponent::getIndex()
  118. {
  119. switch(compType)
  120. {
  121. case primskill: return subtype;
  122. case secskill: return subtype*3 + 3 + val - 1;
  123. case resource: return subtype;
  124. case creature: return CGI->creatures()->getByIndex(subtype)->getIconIndex();
  125. case artifact: return CGI->artifacts()->getByIndex(subtype)->getIconIndex();
  126. case experience: return 4;
  127. case spell: return (size < large) ? subtype + 1 : subtype;
  128. case morale: return val+3;
  129. case luck: return val+3;
  130. case building: return val;
  131. case hero: return subtype;
  132. case flag: return subtype;
  133. }
  134. assert(0);
  135. return 0;
  136. }
  137. std::string CComponent::getDescription()
  138. {
  139. switch(compType)
  140. {
  141. case primskill: return (subtype < 4)? CGI->generaltexth->arraytxt[2+subtype] //Primary skill
  142. : CGI->generaltexth->allTexts[149]; //mana
  143. case secskill: return CGI->skillh->getByIndex(subtype)->getDescriptionTranslated(val);
  144. case resource: return CGI->generaltexth->allTexts[242];
  145. case creature: return "";
  146. case artifact:
  147. {
  148. auto artID = ArtifactID(subtype);
  149. std::unique_ptr<CArtifactInstance> art;
  150. if (artID != ArtifactID::SPELL_SCROLL)
  151. {
  152. art.reset(ArtifactUtils::createNewArtifactInstance(artID));
  153. }
  154. else
  155. {
  156. art.reset(ArtifactUtils::createScroll(SpellID(val)));
  157. }
  158. return art->getDescription();
  159. }
  160. case experience: return CGI->generaltexth->allTexts[241];
  161. case spell: return (*CGI->spellh)[subtype]->getDescriptionTranslated(val);
  162. case morale: return CGI->generaltexth->heroscrn[ 4 - (val>0) + (val<0)];
  163. case luck: return CGI->generaltexth->heroscrn[ 7 - (val>0) + (val<0)];
  164. case building: return (*CGI->townh)[subtype]->town->buildings[BuildingID(val)]->getDescriptionTranslated();
  165. case hero: return "";
  166. case flag: return "";
  167. }
  168. assert(0);
  169. return "";
  170. }
  171. std::string CComponent::getSubtitle()
  172. {
  173. if(!perDay)
  174. return getSubtitleInternal();
  175. std::string ret = CGI->generaltexth->allTexts[3];
  176. boost::replace_first(ret, "%d", getSubtitleInternal());
  177. return ret;
  178. }
  179. std::string CComponent::getSubtitleInternal()
  180. {
  181. //FIXME: some of these are horrible (e.g creature)
  182. switch(compType)
  183. {
  184. case primskill: return boost::str(boost::format("%+d %s") % val % (subtype < 4 ? CGI->generaltexth->primarySkillNames[subtype] : CGI->generaltexth->allTexts[387]));
  185. case secskill: return CGI->generaltexth->levels[val-1] + "\n" + CGI->skillh->getByIndex(subtype)->getNameTranslated();
  186. case resource: return std::to_string(val);
  187. case creature:
  188. {
  189. auto creature = CGI->creh->getByIndex(subtype);
  190. if ( val )
  191. return std::to_string(val) + " " + (val > 1 ? creature->getNamePluralTranslated() : creature->getNameSingularTranslated());
  192. else
  193. return val > 1 ? creature->getNamePluralTranslated() : creature->getNameSingularTranslated();
  194. }
  195. case artifact: return CGI->artifacts()->getByIndex(subtype)->getNameTranslated();
  196. case experience:
  197. {
  198. if(subtype == 1) //+1 level - tree of knowledge
  199. {
  200. std::string level = CGI->generaltexth->allTexts[442];
  201. boost::replace_first(level, "1", std::to_string(val));
  202. return level;
  203. }
  204. else
  205. {
  206. return std::to_string(val); //amount of experience OR level required for seer hut;
  207. }
  208. }
  209. case spell: return CGI->spells()->getByIndex(subtype)->getNameTranslated();
  210. case morale: return "";
  211. case luck: return "";
  212. case building:
  213. {
  214. auto building = (*CGI->townh)[subtype]->town->buildings[BuildingID(val)];
  215. if(!building)
  216. {
  217. logGlobal->error("Town of faction %s has no building #%d", (*CGI->townh)[subtype]->town->faction->getNameTranslated(), val);
  218. return (boost::format("Missing building #%d") % val).str();
  219. }
  220. return building->getNameTranslated();
  221. }
  222. case hero: return "";
  223. case flag: return CGI->generaltexth->capColors[subtype];
  224. }
  225. logGlobal->error("Invalid CComponent type: %d", (int)compType);
  226. return "";
  227. }
  228. void CComponent::setSurface(std::string defName, int imgPos)
  229. {
  230. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  231. image = std::make_shared<CAnimImage>(defName, imgPos);
  232. }
  233. void CComponent::showPopupWindow()
  234. {
  235. if(!getDescription().empty())
  236. CRClickPopup::createAndPush(getDescription());
  237. }
  238. void CSelectableComponent::clickLeft(tribool down, bool previousState)
  239. {
  240. if (down)
  241. {
  242. if(onSelect)
  243. onSelect();
  244. }
  245. }
  246. void CSelectableComponent::init()
  247. {
  248. selected = false;
  249. }
  250. CSelectableComponent::CSelectableComponent(const Component &c, std::function<void()> OnSelect):
  251. CComponent(c),onSelect(OnSelect)
  252. {
  253. type |= REDRAW_PARENT;
  254. addUsedEvents(LCLICK | KEYBOARD);
  255. init();
  256. }
  257. CSelectableComponent::CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize, std::function<void()> OnSelect):
  258. CComponent(Type,Sub,Val, imageSize),onSelect(OnSelect)
  259. {
  260. type |= REDRAW_PARENT;
  261. addUsedEvents(LCLICK | KEYBOARD);
  262. init();
  263. }
  264. void CSelectableComponent::select(bool on)
  265. {
  266. if(on != selected)
  267. {
  268. selected = on;
  269. redraw();
  270. }
  271. }
  272. void CSelectableComponent::showAll(Canvas & to)
  273. {
  274. CComponent::showAll(to);
  275. if(selected)
  276. {
  277. to.drawBorder(Rect::createAround(image->pos, 1), Colors::BRIGHT_YELLOW);
  278. }
  279. }
  280. void CComponentBox::selectionChanged(std::shared_ptr<CSelectableComponent> newSelection)
  281. {
  282. if (newSelection == selected)
  283. return;
  284. if (selected)
  285. selected->select(false);
  286. selected = newSelection;
  287. if (onSelect)
  288. onSelect(selectedIndex());
  289. if (selected)
  290. selected->select(true);
  291. }
  292. int CComponentBox::selectedIndex()
  293. {
  294. if (selected)
  295. return static_cast<int>(std::find(components.begin(), components.end(), selected) - components.begin());
  296. return -1;
  297. }
  298. Point CComponentBox::getOrTextPos(CComponent *left, CComponent *right)
  299. {
  300. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  301. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  302. int fullDistance = getDistance(left, right) + leftSubtitle + rightSubtitle;
  303. return Point(fullDistance/2 - leftSubtitle, (left->image->pos.h + right->image->pos.h) / 4);
  304. }
  305. int CComponentBox::getDistance(CComponent *left, CComponent *right)
  306. {
  307. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  308. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  309. int subtitlesOffset = leftSubtitle + rightSubtitle;
  310. return std::max(betweenSubtitlesMin, betweenImagesMin - subtitlesOffset);
  311. }
  312. void CComponentBox::placeComponents(bool selectable)
  313. {
  314. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  315. if (components.empty())
  316. return;
  317. //prepare components
  318. for(auto & comp : components)
  319. {
  320. addChild(comp.get());
  321. comp->moveTo(Point(pos.x, pos.y));
  322. }
  323. struct RowData
  324. {
  325. size_t comps;
  326. int width;
  327. int height;
  328. RowData (size_t Comps, int Width, int Height):
  329. comps(Comps), width (Width), height (Height){};
  330. };
  331. std::vector<RowData> rows;
  332. rows.push_back (RowData (0,0,0));
  333. //split components in rows
  334. std::shared_ptr<CComponent> prevComp;
  335. for(std::shared_ptr<CComponent> comp : components)
  336. {
  337. //make sure that components are smaller than our width
  338. //assert(pos.w == 0 || pos.w < comp->pos.w);
  339. const int distance = prevComp ? getDistance(prevComp.get(), comp.get()) : 0;
  340. //start next row
  341. if ((pos.w != 0 && rows.back().width + comp->pos.w + distance > pos.w) // row is full
  342. || rows.back().comps >= componentsInRow)
  343. {
  344. prevComp = nullptr;
  345. rows.push_back (RowData (0,0,0));
  346. }
  347. if (prevComp)
  348. rows.back().width += distance;
  349. rows.back().comps++;
  350. rows.back().width += comp->pos.w;
  351. vstd::amax(rows.back().height, comp->pos.h);
  352. prevComp = comp;
  353. }
  354. if (pos.w == 0)
  355. {
  356. for(auto & row : rows)
  357. vstd::amax(pos.w, row.width);
  358. }
  359. int height = ((int)rows.size() - 1) * betweenRows;
  360. for(auto & row : rows)
  361. height += row.height;
  362. //assert(pos.h == 0 || pos.h < height);
  363. if (pos.h == 0)
  364. pos.h = height;
  365. auto iter = components.begin();
  366. int currentY = (pos.h - height) / 2;
  367. //move components to their positions
  368. for (auto & rows_row : rows)
  369. {
  370. // amount of free space we may add on each side of every component
  371. int freeSpace = (pos.w - rows_row.width) / ((int)rows_row.comps * 2);
  372. prevComp = nullptr;
  373. int currentX = 0;
  374. for (size_t col = 0; col < rows_row.comps; col++)
  375. {
  376. currentX += freeSpace;
  377. if (prevComp)
  378. {
  379. if (selectable)
  380. {
  381. Point orPos = Point(currentX - freeSpace, currentY) + getOrTextPos(prevComp.get(), iter->get());
  382. orLabels.push_back(std::make_shared<CLabel>(orPos.x, orPos.y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[4]));
  383. }
  384. currentX += getDistance(prevComp.get(), iter->get());
  385. }
  386. (*iter)->moveBy(Point(currentX, currentY));
  387. currentX += (*iter)->pos.w;
  388. currentX += freeSpace;
  389. prevComp = *(iter++);
  390. }
  391. currentY += rows_row.height + betweenRows;
  392. }
  393. }
  394. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CComponent>> _components, Rect position):
  395. CComponentBox(_components, position, defaultBetweenImagesMin, defaultBetweenSubtitlesMin, defaultBetweenRows, defaultComponentsInRow)
  396. {
  397. }
  398. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CComponent>> _components, Rect position, int betweenImagesMin, int betweenSubtitlesMin, int betweenRows, int componentsInRow):
  399. components(_components),
  400. betweenImagesMin(betweenImagesMin),
  401. betweenSubtitlesMin(betweenSubtitlesMin),
  402. betweenRows(betweenRows),
  403. componentsInRow(componentsInRow)
  404. {
  405. type |= REDRAW_PARENT;
  406. pos = position + pos.topLeft();
  407. placeComponents(false);
  408. }
  409. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CSelectableComponent>> _components, Rect position, std::function<void(int newID)> _onSelect):
  410. CComponentBox(_components, position, _onSelect, defaultBetweenImagesMin, defaultBetweenSubtitlesMin, defaultBetweenRows, defaultComponentsInRow)
  411. {
  412. }
  413. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CSelectableComponent>> _components, Rect position, std::function<void(int newID)> _onSelect, int betweenImagesMin, int betweenSubtitlesMin, int betweenRows, int componentsInRow):
  414. components(_components.begin(), _components.end()),
  415. onSelect(_onSelect),
  416. betweenImagesMin(betweenImagesMin),
  417. betweenSubtitlesMin(betweenSubtitlesMin),
  418. betweenRows(betweenRows),
  419. componentsInRow(componentsInRow)
  420. {
  421. type |= REDRAW_PARENT;
  422. pos = position + pos.topLeft();
  423. placeComponents(true);
  424. assert(!components.empty());
  425. auto key = EShortcut::SELECT_INDEX_1;
  426. for(auto & comp : _components)
  427. {
  428. comp->onSelect = std::bind(&CComponentBox::selectionChanged, this, comp);
  429. comp->assignedKey = key;
  430. key = vstd::next(key, 1);
  431. }
  432. selectionChanged(_components.front());
  433. }