Graphics.cpp 12 KB

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