Graphics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. * Graphics.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 "Graphics.h"
  12. #include <vcmi/Entity.h>
  13. #include <vcmi/ArtifactService.h>
  14. #include <vcmi/CreatureService.h>
  15. #include <vcmi/FactionService.h>
  16. #include <vcmi/HeroTypeService.h>
  17. #include <vcmi/SkillService.h>
  18. #include <vcmi/spells/Service.h>
  19. #include "../lib/filesystem/Filesystem.h"
  20. #include "../lib/filesystem/CBinaryReader.h"
  21. #include "gui/SDL_Extensions.h"
  22. #include "gui/CAnimation.h"
  23. #include <SDL_ttf.h>
  24. #include "../lib/CThreadHelper.h"
  25. #include "CGameInfo.h"
  26. #include "../lib/VCMI_Lib.h"
  27. #include "../CCallback.h"
  28. #include "../lib/CGeneralTextHandler.h"
  29. #include "CBitmapHandler.h"
  30. #include "../lib/CGameState.h"
  31. #include "../lib/JsonNode.h"
  32. #include "../lib/vcmi_endian.h"
  33. #include "../lib/CStopWatch.h"
  34. #include "../lib/mapObjects/CObjectClassesHandler.h"
  35. #include "../lib/mapObjects/CObjectHandler.h"
  36. #include "../lib/CHeroHandler.h"
  37. using namespace CSDL_Ext;
  38. Graphics * graphics = nullptr;
  39. void Graphics::loadPaletteAndColors()
  40. {
  41. auto textFile = CResourceHandler::get()->load(ResourceID("DATA/PLAYERS.PAL"))->readAll();
  42. std::string pals((char*)textFile.first.get(), textFile.second);
  43. playerColorPalette = new SDL_Color[256];
  44. neutralColor = new SDL_Color;
  45. playerColors = new SDL_Color[PlayerColor::PLAYER_LIMIT_I];
  46. int startPoint = 24; //beginning byte; used to read
  47. for(int i=0; i<256; ++i)
  48. {
  49. SDL_Color col;
  50. col.r = pals[startPoint++];
  51. col.g = pals[startPoint++];
  52. col.b = pals[startPoint++];
  53. col.a = SDL_ALPHA_OPAQUE;
  54. startPoint++;
  55. playerColorPalette[i] = col;
  56. }
  57. neutralColorPalette = new SDL_Color[32];
  58. auto stream = CResourceHandler::get()->load(ResourceID("config/NEUTRAL.PAL"));
  59. CBinaryReader reader(stream.get());
  60. for(int i=0; i<32; ++i)
  61. {
  62. neutralColorPalette[i].r = reader.readUInt8();
  63. neutralColorPalette[i].g = reader.readUInt8();
  64. neutralColorPalette[i].b = reader.readUInt8();
  65. reader.readUInt8(); // this is "flags" entry, not alpha
  66. neutralColorPalette[i].a = SDL_ALPHA_OPAQUE;
  67. }
  68. //colors initialization
  69. SDL_Color colors[] = {
  70. {0xff,0, 0, SDL_ALPHA_OPAQUE},
  71. {0x31,0x52,0xff,SDL_ALPHA_OPAQUE},
  72. {0x9c,0x73,0x52,SDL_ALPHA_OPAQUE},
  73. {0x42,0x94,0x29,SDL_ALPHA_OPAQUE},
  74. {0xff,0x84,0, SDL_ALPHA_OPAQUE},
  75. {0x8c,0x29,0xa5,SDL_ALPHA_OPAQUE},
  76. {0x09,0x9c,0xa5,SDL_ALPHA_OPAQUE},
  77. {0xc6,0x7b,0x8c,SDL_ALPHA_OPAQUE}};
  78. for(int i=0;i<8;i++)
  79. {
  80. playerColors[i] = colors[i];
  81. }
  82. //gray
  83. neutralColor->r = 0x84;
  84. neutralColor->g = 0x84;
  85. neutralColor->b = 0x84;
  86. neutralColor->a = SDL_ALPHA_OPAQUE;
  87. }
  88. void Graphics::initializeBattleGraphics()
  89. {
  90. const JsonNode config(ResourceID("config/battles_graphics.json"));
  91. // Reserve enough space for the terrains
  92. int idx = static_cast<int>(config["backgrounds"].Vector().size());
  93. battleBacks.resize(idx+1); // 1 to idx, 0 is unused
  94. idx = 1;
  95. for(const JsonNode &t : config["backgrounds"].Vector()) {
  96. battleBacks[idx].push_back(t.String());
  97. idx++;
  98. }
  99. //initialization of AC->def name mapping
  100. for(const JsonNode &ac : config["ac_mapping"].Vector()) {
  101. int ACid = static_cast<int>(ac["id"].Float());
  102. std::vector< std::string > toAdd;
  103. for(const JsonNode &defname : ac["defnames"].Vector()) {
  104. toAdd.push_back(defname.String());
  105. }
  106. battleACToDef[ACid] = toAdd;
  107. }
  108. }
  109. Graphics::Graphics()
  110. {
  111. #if 0
  112. std::vector<Task> tasks; //preparing list of graphics to load
  113. tasks += std::bind(&Graphics::loadFonts,this);
  114. tasks += std::bind(&Graphics::loadPaletteAndColors,this);
  115. tasks += std::bind(&Graphics::initializeBattleGraphics,this);
  116. tasks += std::bind(&Graphics::loadErmuToPicture,this);
  117. tasks += std::bind(&Graphics::initializeImageLists,this);
  118. CThreadHelper th(&tasks,std::max((ui32)1,boost::thread::hardware_concurrency()));
  119. th.run();
  120. #else
  121. loadFonts();
  122. loadPaletteAndColors();
  123. initializeBattleGraphics();
  124. loadErmuToPicture();
  125. initializeImageLists();
  126. #endif
  127. //(!) do not load any CAnimation here
  128. }
  129. Graphics::~Graphics()
  130. {
  131. delete[] playerColors;
  132. delete neutralColor;
  133. delete[] playerColorPalette;
  134. delete[] neutralColorPalette;
  135. }
  136. void Graphics::load()
  137. {
  138. heroMoveArrows = std::make_shared<CAnimation>("ADAG");
  139. heroMoveArrows->preload();
  140. loadHeroAnimations();
  141. loadHeroFlagAnimations();
  142. loadFogOfWar();
  143. }
  144. void Graphics::loadHeroAnimations()
  145. {
  146. for(auto & elem : CGI->heroh->classes.objects)
  147. {
  148. for (auto & templ : VLC->objtypeh->getHandlerFor(Obj::HERO, elem->getIndex())->getTemplates())
  149. {
  150. if (!heroAnimations.count(templ.animationFile))
  151. heroAnimations[templ.animationFile] = loadHeroAnimation(templ.animationFile);
  152. }
  153. }
  154. boatAnimations[0] = loadHeroAnimation("AB01_.DEF");
  155. boatAnimations[1] = loadHeroAnimation("AB02_.DEF");
  156. boatAnimations[2] = loadHeroAnimation("AB03_.DEF");
  157. mapObjectAnimations["AB01_.DEF"] = boatAnimations[0];
  158. mapObjectAnimations["AB02_.DEF"] = boatAnimations[1];
  159. mapObjectAnimations["AB03_.DEF"] = boatAnimations[2];
  160. }
  161. void Graphics::loadHeroFlagAnimations()
  162. {
  163. static const std::vector<std::string> HERO_FLAG_ANIMATIONS =
  164. {
  165. "AF00", "AF01","AF02","AF03",
  166. "AF04", "AF05","AF06","AF07"
  167. };
  168. static const std::vector< std::vector<std::string> > BOAT_FLAG_ANIMATIONS =
  169. {
  170. {
  171. "ABF01L", "ABF01G", "ABF01R", "ABF01D",
  172. "ABF01B", "ABF01P", "ABF01W", "ABF01K"
  173. },
  174. {
  175. "ABF02L", "ABF02G", "ABF02R", "ABF02D",
  176. "ABF02B", "ABF02P", "ABF02W", "ABF02K"
  177. },
  178. {
  179. "ABF03L", "ABF03G", "ABF03R", "ABF03D",
  180. "ABF03B", "ABF03P", "ABF03W", "ABF03K"
  181. }
  182. };
  183. for(const auto & name : HERO_FLAG_ANIMATIONS)
  184. heroFlagAnimations.push_back(loadHeroFlagAnimation(name));
  185. for(int i = 0; i < BOAT_FLAG_ANIMATIONS.size(); i++)
  186. for(const auto & name : BOAT_FLAG_ANIMATIONS[i])
  187. boatFlagAnimations[i].push_back(loadHeroFlagAnimation(name));
  188. }
  189. std::shared_ptr<CAnimation> Graphics::loadHeroFlagAnimation(const std::string & name)
  190. {
  191. //first - group number to be rotated, second - group number after rotation
  192. static const std::vector<std::pair<int,int> > rotations =
  193. {
  194. {6,10}, {7,11}, {8,12}, {1,13},
  195. {2,14}, {3,15}
  196. };
  197. std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
  198. anim->preload();
  199. for(const auto & rotation : rotations)
  200. {
  201. const int sourceGroup = rotation.first;
  202. const int targetGroup = rotation.second;
  203. anim->createFlippedGroup(sourceGroup, targetGroup);
  204. }
  205. return anim;
  206. }
  207. std::shared_ptr<CAnimation> Graphics::loadHeroAnimation(const std::string &name)
  208. {
  209. //first - group number to be rotated, second - group number after rotation
  210. static const std::vector<std::pair<int,int> > rotations =
  211. {
  212. {6,10}, {7,11}, {8,12}, {1,13},
  213. {2,14}, {3,15}
  214. };
  215. std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
  216. anim->preload();
  217. for(const auto & rotation : rotations)
  218. {
  219. const int sourceGroup = rotation.first;
  220. const int targetGroup = rotation.second;
  221. anim->createFlippedGroup(sourceGroup, targetGroup);
  222. }
  223. return anim;
  224. }
  225. void Graphics::blueToPlayersAdv(SDL_Surface * sur, PlayerColor player)
  226. {
  227. if(sur->format->palette)
  228. {
  229. SDL_Color * palette = nullptr;
  230. if(player < PlayerColor::PLAYER_LIMIT)
  231. {
  232. palette = playerColorPalette + 32*player.getNum();
  233. }
  234. else if(player == PlayerColor::NEUTRAL)
  235. {
  236. palette = neutralColorPalette;
  237. }
  238. else
  239. {
  240. logGlobal->error("Wrong player id in blueToPlayersAdv (%s)!", player.getStr());
  241. return;
  242. }
  243. //FIXME: not all player colored images have player palette at last 32 indexes
  244. //NOTE: following code is much more correct but still not perfect (bugged with status bar)
  245. SDL_SetColors(sur, palette, 224, 32);
  246. #if 0
  247. SDL_Color * bluePalette = playerColorPalette + 32;
  248. SDL_Palette * oldPalette = sur->format->palette;
  249. SDL_Palette * newPalette = SDL_AllocPalette(256);
  250. for(size_t destIndex = 0; destIndex < 256; destIndex++)
  251. {
  252. SDL_Color old = oldPalette->colors[destIndex];
  253. bool found = false;
  254. for(size_t srcIndex = 0; srcIndex < 32; srcIndex++)
  255. {
  256. if(old.b == bluePalette[srcIndex].b && old.g == bluePalette[srcIndex].g && old.r == bluePalette[srcIndex].r)
  257. {
  258. found = true;
  259. newPalette->colors[destIndex] = palette[srcIndex];
  260. break;
  261. }
  262. }
  263. if(!found)
  264. newPalette->colors[destIndex] = old;
  265. }
  266. SDL_SetSurfacePalette(sur, newPalette);
  267. SDL_FreePalette(newPalette);
  268. #endif // 0
  269. }
  270. else
  271. {
  272. //TODO: implement. H3 method works only for images with palettes.
  273. // Add some kind of player-colored overlay?
  274. // Or keep palette approach here and replace only colors of specific value(s)
  275. // Or just wait for OpenGL support?
  276. logGlobal->warn("Image must have palette to be player-colored!");
  277. }
  278. }
  279. void Graphics::loadFogOfWar()
  280. {
  281. fogOfWarFullHide = std::make_shared<CAnimation>("TSHRC");
  282. fogOfWarFullHide->preload();
  283. fogOfWarPartialHide = std::make_shared<CAnimation>("TSHRE");
  284. fogOfWarPartialHide->preload();
  285. static const int rotations [] = {22, 15, 2, 13, 12, 16, 28, 17, 20, 19, 7, 24, 26, 25, 30, 32, 27};
  286. size_t size = fogOfWarPartialHide->size(0);//group size after next rotation
  287. for(const int rotation : rotations)
  288. {
  289. fogOfWarPartialHide->duplicateImage(0, rotation, 0);
  290. auto image = fogOfWarPartialHide->getImage(size, 0);
  291. image->verticalFlip();
  292. size++;
  293. }
  294. }
  295. void Graphics::loadFonts()
  296. {
  297. const JsonNode config(ResourceID("config/fonts.json"));
  298. const JsonVector & bmpConf = config["bitmap"].Vector();
  299. const JsonNode & ttfConf = config["trueType"];
  300. const JsonNode & hanConf = config["bitmapHan"];
  301. assert(bmpConf.size() == FONTS_NUMBER);
  302. for (size_t i=0; i<FONTS_NUMBER; i++)
  303. {
  304. std::string filename = bmpConf[i].String();
  305. if (!hanConf[filename].isNull())
  306. fonts[i] = std::make_shared<CBitmapHanFont>(hanConf[filename]);
  307. else if (!ttfConf[filename].isNull()) // no ttf override
  308. fonts[i] = std::make_shared<CTrueTypeFont>(ttfConf[filename]);
  309. else
  310. fonts[i] = std::make_shared<CBitmapFont>(filename);
  311. }
  312. }
  313. std::shared_ptr<CAnimation> Graphics::getAnimation(const CGObjectInstance* obj)
  314. {
  315. return getAnimation(obj->appearance);
  316. }
  317. std::shared_ptr<CAnimation> Graphics::getAnimation(const ObjectTemplate & info)
  318. {
  319. //the only(?) invisible object
  320. if(info.id == Obj::EVENT)
  321. {
  322. return std::shared_ptr<CAnimation>();
  323. }
  324. if(info.animationFile.empty())
  325. {
  326. logGlobal->warn("Def name for obj (%d,%d) is empty!", info.id, info.subid);
  327. return std::shared_ptr<CAnimation>();
  328. }
  329. std::shared_ptr<CAnimation> ret = mapObjectAnimations[info.animationFile];
  330. //already loaded
  331. if(ret)
  332. {
  333. ret->preload();
  334. return ret;
  335. }
  336. ret = std::make_shared<CAnimation>(info.animationFile);
  337. mapObjectAnimations[info.animationFile] = ret;
  338. ret->preload();
  339. return ret;
  340. }
  341. void Graphics::loadErmuToPicture()
  342. {
  343. //loading ERMU to picture
  344. const JsonNode config(ResourceID("config/ERMU_to_picture.json"));
  345. int etp_idx = 0;
  346. for(const JsonNode &etp : config["ERMU_to_picture"].Vector()) {
  347. int idx = 0;
  348. for(const JsonNode &n : etp.Vector()) {
  349. ERMUtoPicture[idx][etp_idx] = n.String();
  350. idx ++;
  351. }
  352. assert (idx == ARRAY_COUNT(ERMUtoPicture));
  353. etp_idx ++;
  354. }
  355. assert (etp_idx == 44);
  356. }
  357. void Graphics::addImageListEntry(size_t index, const std::string & listName, const std::string & imageName)
  358. {
  359. if (!imageName.empty())
  360. {
  361. JsonNode entry;
  362. entry["frame"].Integer() = index;
  363. entry["file"].String() = imageName;
  364. imageLists["SPRITES/" + listName]["images"].Vector().push_back(entry);
  365. }
  366. }
  367. void Graphics::addImageListEntries(const EntityService * service)
  368. {
  369. auto cb = std::bind(&Graphics::addImageListEntry, this, _1, _2, _3);
  370. auto loopCb = [&](const Entity * entity, bool & stop)
  371. {
  372. entity->registerIcons(cb);
  373. };
  374. service->forEachBase(loopCb);
  375. }
  376. void Graphics::initializeImageLists()
  377. {
  378. addImageListEntries(CGI->creatures());
  379. addImageListEntries(CGI->heroTypes());
  380. addImageListEntries(CGI->artifacts());
  381. addImageListEntries(CGI->factions());
  382. addImageListEntries(CGI->spells());
  383. addImageListEntries(CGI->skills());
  384. }