2
0

RenderHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * RenderHandler.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 "RenderHandler.h"
  12. #include "SDLImage.h"
  13. #include "ScalableImage.h"
  14. #include "FontChain.h"
  15. #include "../gui/CGuiHandler.h"
  16. #include "../render/CAnimation.h"
  17. #include "../render/CDefFile.h"
  18. #include "../render/Colors.h"
  19. #include "../render/ColorFilter.h"
  20. #include "../render/IScreenHandler.h"
  21. #include "../../lib/json/JsonUtils.h"
  22. #include "../../lib/CThreadHelper.h"
  23. #include "../../lib/filesystem/Filesystem.h"
  24. #include "../../lib/VCMIDirs.h"
  25. #include <vcmi/ArtifactService.h>
  26. #include <vcmi/CreatureService.h>
  27. #include <vcmi/Entity.h>
  28. #include <vcmi/FactionService.h>
  29. #include <vcmi/HeroTypeService.h>
  30. #include <vcmi/Services.h>
  31. #include <vcmi/SkillService.h>
  32. #include <vcmi/spells/Service.h>
  33. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  34. {
  35. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  36. auto it = animationFiles.find(actualPath);
  37. if (it != animationFiles.end())
  38. return it->second;
  39. if (!CResourceHandler::get()->existsResource(actualPath))
  40. {
  41. animationFiles[actualPath] = nullptr;
  42. return nullptr;
  43. }
  44. auto result = std::make_shared<CDefFile>(actualPath);
  45. animationFiles[actualPath] = result;
  46. return result;
  47. }
  48. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config, EImageBlitMode mode)
  49. {
  50. std::string basepath;
  51. basepath = config["basepath"].String();
  52. JsonNode base;
  53. base["margins"] = config["margins"];
  54. base["width"] = config["width"];
  55. base["height"] = config["height"];
  56. for(const JsonNode & group : config["sequences"].Vector())
  57. {
  58. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  59. source[groupID].clear();
  60. for(const JsonNode & frame : group["frames"].Vector())
  61. {
  62. JsonNode toAdd = frame;
  63. JsonUtils::inherit(toAdd, base);
  64. toAdd["file"].String() = basepath + frame.String();
  65. source[groupID].emplace_back(toAdd, mode);
  66. }
  67. }
  68. for(const JsonNode & node : config["images"].Vector())
  69. {
  70. size_t group = node["group"].Integer();
  71. size_t frame = node["frame"].Integer();
  72. if (source[group].size() <= frame)
  73. source[group].resize(frame+1);
  74. JsonNode toAdd = node;
  75. JsonUtils::inherit(toAdd, base);
  76. if (toAdd.Struct().count("file"))
  77. toAdd["file"].String() = basepath + node["file"].String();
  78. if (toAdd.Struct().count("defFile"))
  79. toAdd["defFile"].String() = basepath + node["defFile"].String();
  80. source[group][frame] = ImageLocator(toAdd, mode);
  81. }
  82. }
  83. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path, int scalingFactor, EImageBlitMode mode)
  84. {
  85. static constexpr std::array scaledSpritesPath = {
  86. "", // 0x
  87. "SPRITES/",
  88. "SPRITES2X/",
  89. "SPRITES3X/",
  90. "SPRITES4X/",
  91. };
  92. std::string pathString = path.getName();
  93. if (boost::starts_with(pathString, "SPRITES/"))
  94. pathString = pathString.substr(std::string("SPRITES/").length());
  95. AnimationPath actualPath = AnimationPath::builtin(scaledSpritesPath.at(scalingFactor) + pathString);
  96. auto it = animationLayouts.find(actualPath);
  97. if (it != animationLayouts.end())
  98. return it->second;
  99. AnimationLayoutMap result;
  100. auto defFile = getAnimationFile(actualPath);
  101. if(defFile)
  102. {
  103. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  104. for (const auto & defEntry : defEntries)
  105. result[defEntry.first].resize(defEntry.second);
  106. }
  107. auto jsonResource = actualPath.toType<EResType::JSON>();
  108. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  109. for(auto & loader : configList)
  110. {
  111. auto stream = loader->load(jsonResource);
  112. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  113. stream->read(textData.get(), stream->getSize());
  114. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  115. initFromJson(result, config, mode);
  116. }
  117. animationLayouts[actualPath] = result;
  118. return animationLayouts[actualPath];
  119. }
  120. int RenderHandler::getScalingFactor() const
  121. {
  122. return GH.screenHandler().getScalingFactor();
  123. }
  124. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  125. {
  126. const auto & layout = getAnimationLayout(path, 1, mode);
  127. if (!layout.count(group))
  128. return ImageLocator(ImagePath::builtin("DEFAULT"), mode);
  129. if (frame >= layout.at(group).size())
  130. return ImageLocator(ImagePath::builtin("DEFAULT"), mode);
  131. const auto & locator = layout.at(group).at(frame);
  132. if (locator.image || locator.defFile)
  133. return locator;
  134. return ImageLocator(path, frame, group, mode);
  135. }
  136. std::shared_ptr<ScalableImageShared> RenderHandler::loadImageImpl(const ImageLocator & locator)
  137. {
  138. auto it = imageFiles.find(locator);
  139. if (it != imageFiles.end())
  140. return it->second;
  141. auto sdlImage = loadImageFromFileUncached(locator);
  142. auto scaledImage = std::make_shared<ScalableImageShared>(locator, sdlImage);
  143. storeCachedImage(locator, scaledImage);
  144. return scaledImage;
  145. }
  146. std::shared_ptr<SDLImageShared> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  147. {
  148. if(locator.image)
  149. {
  150. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  151. return std::make_shared<SDLImageShared>(*locator.image);
  152. }
  153. if(locator.defFile)
  154. {
  155. auto defFile = getAnimationFile(*locator.defFile);
  156. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  157. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  158. else
  159. {
  160. logGlobal->error("Frame %d in group %d not found in file: %s",
  161. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  162. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  163. }
  164. }
  165. throw std::runtime_error("Invalid image locator received!");
  166. }
  167. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<ScalableImageShared> image)
  168. {
  169. imageFiles[locator] = image;
  170. }
  171. std::shared_ptr<SDLImageShared> RenderHandler::loadSingleImage(const ImageLocator & locator)
  172. {
  173. assert(locator.scalingFactor != 0);
  174. static constexpr std::array scaledDataPath = {
  175. "", // 0x
  176. "DATA/",
  177. "DATA2X/",
  178. "DATA3X/",
  179. "DATA4X/",
  180. };
  181. static constexpr std::array scaledSpritesPath = {
  182. "", // 0x
  183. "SPRITES/",
  184. "SPRITES2X/",
  185. "SPRITES3X/",
  186. "SPRITES4X/",
  187. };
  188. if(locator.image)
  189. {
  190. std::string imagePathString = locator.image->getName();
  191. if(locator.layer == EImageBlitMode::ONLY_OVERLAY)
  192. imagePathString += "-OVERLAY";
  193. if(locator.layer == EImageBlitMode::ONLY_SHADOW)
  194. imagePathString += "-SHADOW";
  195. auto imagePath = ImagePath::builtin(imagePathString);
  196. auto imagePathSprites = ImagePath::builtin(imagePathString).addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  197. auto imagePathData = ImagePath::builtin(imagePathString).addPrefix(scaledDataPath.at(locator.scalingFactor));
  198. if(CResourceHandler::get()->existsResource(imagePathSprites))
  199. return std::make_shared<SDLImageShared>(imagePathSprites);
  200. if(CResourceHandler::get()->existsResource(imagePathData))
  201. return std::make_shared<SDLImageShared>(imagePathData);
  202. if(CResourceHandler::get()->existsResource(imagePath))
  203. return std::make_shared<SDLImageShared>(imagePath);
  204. }
  205. if(locator.defFile)
  206. {
  207. AnimationPath defFilePath = locator.defFile->addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  208. auto defFile = getAnimationFile(defFilePath);
  209. if(defFile && defFile->hasFrame(locator.defFrame, locator.defGroup))
  210. {
  211. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  212. }
  213. }
  214. return nullptr;
  215. }
  216. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator)
  217. {
  218. ImageLocator adjustedLocator = locator;
  219. std::shared_ptr<ScalableImageInstance> result;
  220. if (adjustedLocator.scalingFactor == 0)
  221. {
  222. auto scaledLocator = adjustedLocator;
  223. scaledLocator.scalingFactor = getScalingFactor();
  224. result = loadImageImpl(scaledLocator)->createImageReference();
  225. }
  226. else
  227. result = loadImageImpl(adjustedLocator)->createImageReference();
  228. if (locator.horizontalFlip)
  229. result->horizontalFlip();
  230. if (locator.verticalFlip)
  231. result->verticalFlip();
  232. return result;
  233. }
  234. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  235. {
  236. ImageLocator locator = getLocatorForAnimationFrame(path, frame, group, mode);
  237. return loadImage(locator);
  238. }
  239. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  240. {
  241. ImageLocator locator(path, mode);
  242. return loadImage(locator);
  243. }
  244. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  245. {
  246. auto baseImage = std::make_shared<SDLImageShared>(source);
  247. SharedImageLocator locator;
  248. locator.layer = EImageBlitMode::SIMPLE;
  249. auto scalableImage = std::make_shared<ScalableImageShared>(locator, baseImage);
  250. return scalableImage->createImageReference();
  251. }
  252. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  253. {
  254. return std::make_shared<CAnimation>(path, getAnimationLayout(path, 1, mode), mode);
  255. }
  256. void RenderHandler::addImageListEntries(const EntityService * service)
  257. {
  258. service->forEachBase([this](const Entity * entity, bool & stop)
  259. {
  260. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  261. {
  262. if (imageName.empty())
  263. return;
  264. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName), 1, EImageBlitMode::SIMPLE);
  265. JsonNode entry;
  266. entry["file"].String() = imageName;
  267. if (index >= layout[group].size())
  268. layout[group].resize(index + 1);
  269. layout[group][index] = ImageLocator(entry, EImageBlitMode::SIMPLE);
  270. });
  271. });
  272. }
  273. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  274. {
  275. addImageListEntries(services->creatures());
  276. addImageListEntries(services->heroTypes());
  277. addImageListEntries(services->artifacts());
  278. addImageListEntries(services->factions());
  279. addImageListEntries(services->spells());
  280. addImageListEntries(services->skills());
  281. }
  282. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  283. {
  284. if (fonts.count(font))
  285. return fonts.at(font);
  286. const int8_t index = static_cast<int8_t>(font);
  287. logGlobal->debug("Loading font %d", static_cast<int>(index));
  288. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  289. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  290. std::string bitmapPath;
  291. for(auto & loader : configList)
  292. {
  293. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  294. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  295. stream->read(textData.get(), stream->getSize());
  296. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  297. const JsonVector & bmpConf = config["bitmap"].Vector();
  298. const JsonNode & ttfConf = config["trueType"];
  299. bitmapPath = bmpConf[index].String();
  300. if (!ttfConf[bitmapPath].isNull())
  301. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  302. }
  303. loadedFont->addBitmapFont(bitmapPath);
  304. fonts[font] = loadedFont;
  305. return loadedFont;
  306. }