Graphics.cpp 12 KB

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