RenderHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 "ImageScaled.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/filesystem/Filesystem.h"
  23. #include "../../lib/VCMIDirs.h"
  24. #include <vcmi/ArtifactService.h>
  25. #include <vcmi/CreatureService.h>
  26. #include <vcmi/Entity.h>
  27. #include <vcmi/FactionService.h>
  28. #include <vcmi/HeroTypeService.h>
  29. #include <vcmi/Services.h>
  30. #include <vcmi/SkillService.h>
  31. #include <vcmi/spells/Service.h>
  32. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  33. {
  34. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  35. auto it = animationFiles.find(actualPath);
  36. if (it != animationFiles.end())
  37. return it->second;
  38. if (!CResourceHandler::get()->existsResource(actualPath))
  39. {
  40. animationFiles[actualPath] = nullptr;
  41. return nullptr;
  42. }
  43. auto result = std::make_shared<CDefFile>(actualPath);
  44. animationFiles[actualPath] = result;
  45. return result;
  46. }
  47. std::optional<ResourcePath> RenderHandler::getPathForScaleFactor(const ResourcePath & path, const std::string & factor)
  48. {
  49. if(path.getType() == EResType::IMAGE)
  50. {
  51. auto p = ImagePath::builtin(path.getName());
  52. if(CResourceHandler::get()->existsResource(p.addPrefix("SPRITES" + factor + "X/")))
  53. return std::optional<ResourcePath>(p.addPrefix("SPRITES" + factor + "X/"));
  54. if(CResourceHandler::get()->existsResource(p.addPrefix("DATA" + factor + "X/")))
  55. return std::optional<ResourcePath>(p.addPrefix("DATA" + factor + "X/"));
  56. }
  57. else
  58. {
  59. auto p = AnimationPath::builtin(path.getName());
  60. auto pJson = p.toType<EResType::JSON>();
  61. if(CResourceHandler::get()->existsResource(p.addPrefix("SPRITES" + factor + "X/")))
  62. return std::optional<ResourcePath>(p.addPrefix("SPRITES" + factor + "X/"));
  63. if(CResourceHandler::get()->existsResource(pJson))
  64. return std::optional<ResourcePath>(p);
  65. if(CResourceHandler::get()->existsResource(pJson.addPrefix("SPRITES" + factor + "X/")))
  66. return std::optional<ResourcePath>(p.addPrefix("SPRITES" + factor + "X/"));
  67. }
  68. return std::nullopt;
  69. }
  70. std::pair<ResourcePath, int> RenderHandler::getScalePath(const ResourcePath & p)
  71. {
  72. auto path = p;
  73. int scaleFactor = 1;
  74. if(getScalingFactor() > 1)
  75. {
  76. std::vector<int> factorsToCheck = {getScalingFactor(), 4, 3, 2};
  77. for(auto factorToCheck : factorsToCheck)
  78. {
  79. std::string name = boost::algorithm::to_upper_copy(p.getName());
  80. boost::replace_all(name, "SPRITES/", std::string("SPRITES") + std::to_string(factorToCheck) + std::string("X/"));
  81. boost::replace_all(name, "DATA/", std::string("DATA") + std::to_string(factorToCheck) + std::string("X/"));
  82. ResourcePath scaledPath = ImagePath::builtin(name);
  83. if(p.getType() != EResType::IMAGE)
  84. scaledPath = AnimationPath::builtin(name);
  85. auto tmpPath = getPathForScaleFactor(scaledPath, std::to_string(factorToCheck));
  86. if(tmpPath)
  87. {
  88. path = *tmpPath;
  89. scaleFactor = factorToCheck;
  90. break;
  91. }
  92. }
  93. }
  94. return std::pair<ResourcePath, int>(path, scaleFactor);
  95. };
  96. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config)
  97. {
  98. std::string basepath;
  99. basepath = config["basepath"].String();
  100. JsonNode base;
  101. base["margins"] = config["margins"];
  102. base["width"] = config["width"];
  103. base["height"] = config["height"];
  104. for(const JsonNode & group : config["sequences"].Vector())
  105. {
  106. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  107. source[groupID].clear();
  108. for(const JsonNode & frame : group["frames"].Vector())
  109. {
  110. JsonNode toAdd = frame;
  111. JsonUtils::inherit(toAdd, base);
  112. toAdd["file"].String() = basepath + frame.String();
  113. source[groupID].emplace_back(toAdd);
  114. }
  115. }
  116. for(const JsonNode & node : config["images"].Vector())
  117. {
  118. size_t group = node["group"].Integer();
  119. size_t frame = node["frame"].Integer();
  120. if (source[group].size() <= frame)
  121. source[group].resize(frame+1);
  122. JsonNode toAdd = node;
  123. JsonUtils::inherit(toAdd, base);
  124. if (toAdd.Struct().count("file"))
  125. toAdd["file"].String() = basepath + node["file"].String();
  126. if (toAdd.Struct().count("defFile"))
  127. toAdd["defFile"].String() = basepath + node["defFile"].String();
  128. source[group][frame] = ImageLocator(toAdd);
  129. }
  130. }
  131. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path)
  132. {
  133. auto tmp = getScalePath(path);
  134. auto animPath = AnimationPath::builtin(tmp.first.getName());
  135. AnimationPath actualPath = boost::starts_with(animPath.getName(), "SPRITES") ? animPath : animPath.addPrefix("SPRITES/");
  136. auto it = animationLayouts.find(actualPath);
  137. if (it != animationLayouts.end())
  138. return it->second;
  139. AnimationLayoutMap result;
  140. auto defFile = getAnimationFile(actualPath);
  141. if(defFile)
  142. {
  143. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  144. for (const auto & defEntry : defEntries)
  145. result[defEntry.first].resize(defEntry.second);
  146. }
  147. auto jsonResource = actualPath.toType<EResType::JSON>();
  148. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  149. for(auto & loader : configList)
  150. {
  151. auto stream = loader->load(jsonResource);
  152. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  153. stream->read(textData.get(), stream->getSize());
  154. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), animPath.getOriginalName());
  155. initFromJson(result, config);
  156. }
  157. for(auto & g : result)
  158. for(auto & i : g.second)
  159. i.preScaledFactor = tmp.second;
  160. animationLayouts[actualPath] = result;
  161. return animationLayouts[actualPath];
  162. }
  163. int RenderHandler::getScalingFactor() const
  164. {
  165. return GH.screenHandler().getScalingFactor();
  166. }
  167. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group)
  168. {
  169. const auto & layout = getAnimationLayout(path);
  170. if (!layout.count(group))
  171. return ImageLocator(ImagePath::builtin("DEFAULT"));
  172. if (frame >= layout.at(group).size())
  173. return ImageLocator(ImagePath::builtin("DEFAULT"));
  174. const auto & locator = layout.at(group).at(frame);
  175. if (locator.image || locator.defFile)
  176. return locator;
  177. return ImageLocator(path, frame, group);
  178. }
  179. std::shared_ptr<const ISharedImage> RenderHandler::loadImageImpl(const ImageLocator & locator)
  180. {
  181. auto it = imageFiles.find(locator);
  182. if (it != imageFiles.end())
  183. return it->second;
  184. // TODO: order should be different:
  185. // 1) try to find correctly scaled image
  186. // 2) if fails -> try to find correctly transformed
  187. // 3) if also fails -> try to find image from correct file
  188. // 4) load missing part of the sequence
  189. // TODO: check whether (load -> transform -> scale) or (load -> scale -> transform) order should be used for proper loading of pre-scaled data
  190. auto imageFromFile = loadImageFromFile(locator.copyFile());
  191. auto transformedImage = transformImage(locator.copyFileTransform(), imageFromFile);
  192. auto scaledImage = scaleImage(locator.copyFileTransformScale(), transformedImage);
  193. return scaledImage;
  194. }
  195. std::shared_ptr<const ISharedImage> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  196. {
  197. if (locator.image)
  198. {
  199. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  200. return std::make_shared<SDLImageShared>(*locator.image, locator.preScaledFactor);
  201. }
  202. if (locator.defFile)
  203. {
  204. auto defFile = getAnimationFile(*locator.defFile);
  205. int preScaledFactor = locator.preScaledFactor;
  206. if(!defFile) // no prescale for this frame
  207. {
  208. auto tmpPath = (*locator.defFile).getName();
  209. boost::algorithm::replace_all(tmpPath, "SPRITES2X/", "SPRITES/");
  210. boost::algorithm::replace_all(tmpPath, "SPRITES3X/", "SPRITES/");
  211. boost::algorithm::replace_all(tmpPath, "SPRITES4X/", "SPRITES/");
  212. preScaledFactor = 1;
  213. defFile = getAnimationFile(AnimationPath::builtin(tmpPath));
  214. }
  215. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup, preScaledFactor);
  216. }
  217. throw std::runtime_error("Invalid image locator received!");
  218. }
  219. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  220. {
  221. imageFiles[locator] = image;
  222. #if 0
  223. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "imageCache" / (locator.toString() + ".png");
  224. boost::filesystem::path outDir = outPath;
  225. outDir.remove_filename();
  226. boost::filesystem::create_directories(outDir);
  227. image->exportBitmap(outPath , nullptr);
  228. #endif
  229. }
  230. std::shared_ptr<const ISharedImage> RenderHandler::loadImageFromFile(const ImageLocator & locator)
  231. {
  232. if (imageFiles.count(locator))
  233. return imageFiles.at(locator);
  234. auto result = loadImageFromFileUncached(locator);
  235. storeCachedImage(locator, result);
  236. return result;
  237. }
  238. std::shared_ptr<const ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  239. {
  240. if (imageFiles.count(locator))
  241. return imageFiles.at(locator);
  242. auto result = image;
  243. if (locator.verticalFlip)
  244. result = result->verticalFlip();
  245. if (locator.horizontalFlip)
  246. result = result->horizontalFlip();
  247. storeCachedImage(locator, result);
  248. return result;
  249. }
  250. std::shared_ptr<const ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  251. {
  252. if (imageFiles.count(locator))
  253. return imageFiles.at(locator);
  254. auto handle = image->createImageReference(locator.layer);
  255. assert(locator.scalingFactor != 1); // should be filtered-out before
  256. if (locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  257. handle->playerColored(locator.playerColored);
  258. handle->scaleInteger(locator.scalingFactor);
  259. auto result = handle->getSharedImage();
  260. storeCachedImage(locator, result);
  261. return result;
  262. }
  263. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  264. {
  265. ImageLocator adjustedLocator = locator;
  266. if(adjustedLocator.image)
  267. {
  268. std::string imgPath = (*adjustedLocator.image).getName();
  269. if(adjustedLocator.layer == EImageBlitMode::ONLY_OVERLAY)
  270. imgPath += "-OVERLAY";
  271. if(adjustedLocator.layer == EImageBlitMode::ONLY_SHADOW)
  272. imgPath += "-SHADOW";
  273. if(CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath)) ||
  274. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("DATA/")) ||
  275. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("SPRITES/")))
  276. adjustedLocator.image = ImagePath::builtin(imgPath);
  277. }
  278. if(adjustedLocator.defFile && adjustedLocator.scalingFactor == 0)
  279. {
  280. auto tmp = getScalePath(*adjustedLocator.defFile);
  281. adjustedLocator.defFile = AnimationPath::builtin(tmp.first.getName());
  282. adjustedLocator.preScaledFactor = tmp.second;
  283. }
  284. if(adjustedLocator.image && adjustedLocator.scalingFactor == 0)
  285. {
  286. auto tmp = getScalePath(*adjustedLocator.image);
  287. adjustedLocator.image = ImagePath::builtin(tmp.first.getName());
  288. adjustedLocator.preScaledFactor = tmp.second;
  289. }
  290. if (adjustedLocator.scalingFactor == 0 && getScalingFactor() != 1 )
  291. {
  292. auto unscaledLocator = adjustedLocator;
  293. auto scaledLocator = adjustedLocator;
  294. unscaledLocator.scalingFactor = 1;
  295. scaledLocator.scalingFactor = getScalingFactor();
  296. auto unscaledImage = loadImageImpl(unscaledLocator);
  297. return std::make_shared<ImageScaled>(scaledLocator, unscaledImage, mode);
  298. }
  299. if (adjustedLocator.scalingFactor == 0)
  300. {
  301. auto scaledLocator = adjustedLocator;
  302. scaledLocator.scalingFactor = getScalingFactor();
  303. return loadImageImpl(scaledLocator)->createImageReference(mode);
  304. }
  305. else
  306. return loadImageImpl(adjustedLocator)->createImageReference(mode);
  307. }
  308. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  309. {
  310. auto tmp = getScalePath(path);
  311. ImageLocator locator = getLocatorForAnimationFrame(AnimationPath::builtin(tmp.first.getName()), frame, group);
  312. locator.preScaledFactor = tmp.second;
  313. return loadImage(locator, mode);
  314. }
  315. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  316. {
  317. ImageLocator locator(path);
  318. return loadImage(locator, mode);
  319. }
  320. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  321. {
  322. return std::make_shared<SDLImageShared>(source)->createImageReference(EImageBlitMode::SIMPLE);
  323. }
  324. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  325. {
  326. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  327. }
  328. void RenderHandler::addImageListEntries(const EntityService * service)
  329. {
  330. service->forEachBase([this](const Entity * entity, bool & stop)
  331. {
  332. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  333. {
  334. if (imageName.empty())
  335. return;
  336. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  337. JsonNode entry;
  338. entry["file"].String() = imageName;
  339. if (index >= layout[group].size())
  340. layout[group].resize(index + 1);
  341. layout[group][index] = ImageLocator(entry);
  342. });
  343. });
  344. }
  345. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  346. {
  347. addImageListEntries(services->creatures());
  348. addImageListEntries(services->heroTypes());
  349. addImageListEntries(services->artifacts());
  350. addImageListEntries(services->factions());
  351. addImageListEntries(services->spells());
  352. addImageListEntries(services->skills());
  353. }
  354. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  355. {
  356. if (fonts.count(font))
  357. return fonts.at(font);
  358. const int8_t index = static_cast<int8_t>(font);
  359. logGlobal->debug("Loading font %d", static_cast<int>(index));
  360. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  361. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  362. std::string bitmapPath;
  363. for(auto & loader : configList)
  364. {
  365. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  366. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  367. stream->read(textData.get(), stream->getSize());
  368. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  369. const JsonVector & bmpConf = config["bitmap"].Vector();
  370. const JsonNode & ttfConf = config["trueType"];
  371. bitmapPath = bmpConf[index].String();
  372. if (!ttfConf[bitmapPath].isNull())
  373. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  374. }
  375. loadedFont->addBitmapFont(bitmapPath);
  376. fonts[font] = loadedFont;
  377. return loadedFont;
  378. }