CComponent.cpp 15 KB

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