CComponent.cpp 15 KB

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