CComponent.cpp 15 KB

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