RenderHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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(ResourcePath path, 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(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. toAdd["file"].String() = basepath + node["file"].String();
  125. source[group][frame] = ImageLocator(toAdd);
  126. }
  127. }
  128. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path)
  129. {
  130. auto tmp = getScalePath(path);
  131. auto animPath = AnimationPath::builtin(tmp.first.getName());
  132. AnimationPath actualPath = boost::starts_with(animPath.getName(), "SPRITES") ? animPath : animPath.addPrefix("SPRITES/");
  133. auto it = animationLayouts.find(actualPath);
  134. if (it != animationLayouts.end())
  135. return it->second;
  136. AnimationLayoutMap result;
  137. auto defFile = getAnimationFile(actualPath);
  138. if(defFile)
  139. {
  140. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  141. for (const auto & defEntry : defEntries)
  142. result[defEntry.first].resize(defEntry.second);
  143. }
  144. auto jsonResource = actualPath.toType<EResType::JSON>();
  145. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  146. for(auto & loader : configList)
  147. {
  148. auto stream = loader->load(jsonResource);
  149. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  150. stream->read(textData.get(), stream->getSize());
  151. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), animPath.getOriginalName());
  152. initFromJson(result, config);
  153. }
  154. for(auto & g : result)
  155. for(auto & i : g.second)
  156. i.preScaledFactor = tmp.second;
  157. animationLayouts[actualPath] = result;
  158. return animationLayouts[actualPath];
  159. }
  160. int RenderHandler::getScalingFactor() const
  161. {
  162. return GH.screenHandler().getScalingFactor();
  163. }
  164. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group)
  165. {
  166. const auto & layout = getAnimationLayout(path);
  167. if (!layout.count(group))
  168. return ImageLocator(ImagePath::builtin("DEFAULT"));
  169. if (frame >= layout.at(group).size())
  170. return ImageLocator(ImagePath::builtin("DEFAULT"));
  171. const auto & locator = layout.at(group).at(frame);
  172. if (locator.image || locator.defFile)
  173. return locator;
  174. return ImageLocator(path, frame, group);
  175. }
  176. std::shared_ptr<const ISharedImage> RenderHandler::loadImageImpl(const ImageLocator & locator)
  177. {
  178. auto it = imageFiles.find(locator);
  179. if (it != imageFiles.end())
  180. return it->second;
  181. // TODO: order should be different:
  182. // 1) try to find correctly scaled image
  183. // 2) if fails -> try to find correctly transformed
  184. // 3) if also fails -> try to find image from correct file
  185. // 4) load missing part of the sequence
  186. // TODO: check whether (load -> transform -> scale) or (load -> scale -> transform) order should be used for proper loading of pre-scaled data
  187. auto imageFromFile = loadImageFromFile(locator.copyFile());
  188. auto transformedImage = transformImage(locator.copyFileTransform(), imageFromFile);
  189. auto scaledImage = scaleImage(locator.copyFileTransformScale(), transformedImage);
  190. return scaledImage;
  191. }
  192. std::shared_ptr<const ISharedImage> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  193. {
  194. if (locator.image)
  195. {
  196. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  197. return std::make_shared<SDLImageShared>(*locator.image, locator.preScaledFactor);
  198. }
  199. if (locator.defFile)
  200. {
  201. auto defFile = getAnimationFile(*locator.defFile);
  202. int preScaledFactor = locator.preScaledFactor;
  203. if(!defFile) // no prescale for this frame
  204. {
  205. auto tmpPath = (*locator.defFile).getName();
  206. boost::algorithm::replace_all(tmpPath, "SPRITES2X/", "SPRITES/");
  207. boost::algorithm::replace_all(tmpPath, "SPRITES3X/", "SPRITES/");
  208. boost::algorithm::replace_all(tmpPath, "SPRITES4X/", "SPRITES/");
  209. preScaledFactor = 1;
  210. defFile = getAnimationFile(AnimationPath::builtin(tmpPath));
  211. }
  212. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup, preScaledFactor);
  213. }
  214. throw std::runtime_error("Invalid image locator received!");
  215. }
  216. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  217. {
  218. imageFiles[locator] = image;
  219. #if 0
  220. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "imageCache" / (locator.toString() + ".png");
  221. boost::filesystem::path outDir = outPath;
  222. outDir.remove_filename();
  223. boost::filesystem::create_directories(outDir);
  224. image->exportBitmap(outPath , nullptr);
  225. #endif
  226. }
  227. std::shared_ptr<const ISharedImage> RenderHandler::loadImageFromFile(const ImageLocator & locator)
  228. {
  229. if (imageFiles.count(locator))
  230. return imageFiles.at(locator);
  231. auto result = loadImageFromFileUncached(locator);
  232. storeCachedImage(locator, result);
  233. return result;
  234. }
  235. std::shared_ptr<const ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  236. {
  237. if (imageFiles.count(locator))
  238. return imageFiles.at(locator);
  239. auto result = image;
  240. if (locator.verticalFlip)
  241. result = result->verticalFlip();
  242. if (locator.horizontalFlip)
  243. result = result->horizontalFlip();
  244. storeCachedImage(locator, result);
  245. return result;
  246. }
  247. std::shared_ptr<const ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  248. {
  249. if (imageFiles.count(locator))
  250. return imageFiles.at(locator);
  251. auto handle = image->createImageReference(locator.layer);
  252. assert(locator.scalingFactor != 1); // should be filtered-out before
  253. if (locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  254. handle->playerColored(locator.playerColored);
  255. handle->scaleInteger(locator.scalingFactor);
  256. auto result = handle->getSharedImage();
  257. storeCachedImage(locator, result);
  258. return result;
  259. }
  260. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  261. {
  262. ImageLocator adjustedLocator = locator;
  263. if(adjustedLocator.image)
  264. {
  265. std::string imgPath = (*adjustedLocator.image).getName();
  266. if(adjustedLocator.layer == EImageBlitMode::ONLY_OVERLAY)
  267. imgPath += "-OVERLAY";
  268. if(adjustedLocator.layer == EImageBlitMode::ONLY_SHADOW)
  269. imgPath += "-SHADOW";
  270. if(CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath)) ||
  271. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("DATA/")) ||
  272. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("SPRITES/")))
  273. adjustedLocator.image = ImagePath::builtin(imgPath);
  274. }
  275. if(adjustedLocator.defFile && adjustedLocator.scalingFactor == 0)
  276. {
  277. auto tmp = getScalePath(*adjustedLocator.defFile);
  278. adjustedLocator.defFile = AnimationPath::builtin(tmp.first.getName());
  279. adjustedLocator.preScaledFactor = tmp.second;
  280. }
  281. if(adjustedLocator.image && adjustedLocator.scalingFactor == 0)
  282. {
  283. auto tmp = getScalePath(*adjustedLocator.image);
  284. adjustedLocator.image = ImagePath::builtin(tmp.first.getName());
  285. adjustedLocator.preScaledFactor = tmp.second;
  286. }
  287. if (adjustedLocator.scalingFactor == 0 && getScalingFactor() != 1 )
  288. {
  289. auto unscaledLocator = adjustedLocator;
  290. auto scaledLocator = adjustedLocator;
  291. unscaledLocator.scalingFactor = 1;
  292. scaledLocator.scalingFactor = getScalingFactor();
  293. auto unscaledImage = loadImageImpl(unscaledLocator);
  294. return std::make_shared<ImageScaled>(scaledLocator, unscaledImage, mode);
  295. }
  296. if (adjustedLocator.scalingFactor == 0)
  297. {
  298. auto scaledLocator = adjustedLocator;
  299. scaledLocator.scalingFactor = getScalingFactor();
  300. return loadImageImpl(scaledLocator)->createImageReference(mode);
  301. }
  302. else
  303. return loadImageImpl(adjustedLocator)->createImageReference(mode);
  304. }
  305. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  306. {
  307. auto tmp = getScalePath(path);
  308. ImageLocator locator = getLocatorForAnimationFrame(AnimationPath::builtin(tmp.first.getName()), frame, group);
  309. locator.preScaledFactor = tmp.second;
  310. return loadImage(locator, mode);
  311. }
  312. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  313. {
  314. ImageLocator locator(path);
  315. return loadImage(locator, mode);
  316. }
  317. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  318. {
  319. return std::make_shared<SDLImageShared>(source)->createImageReference(EImageBlitMode::SIMPLE);
  320. }
  321. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  322. {
  323. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  324. }
  325. void RenderHandler::addImageListEntries(const EntityService * service)
  326. {
  327. service->forEachBase([this](const Entity * entity, bool & stop)
  328. {
  329. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  330. {
  331. if (imageName.empty())
  332. return;
  333. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  334. JsonNode entry;
  335. entry["file"].String() = imageName;
  336. if (index >= layout[group].size())
  337. layout[group].resize(index + 1);
  338. layout[group][index] = ImageLocator(entry);
  339. });
  340. });
  341. }
  342. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  343. {
  344. addImageListEntries(services->creatures());
  345. addImageListEntries(services->heroTypes());
  346. addImageListEntries(services->artifacts());
  347. addImageListEntries(services->factions());
  348. addImageListEntries(services->spells());
  349. addImageListEntries(services->skills());
  350. }
  351. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  352. {
  353. if (fonts.count(font))
  354. return fonts.at(font);
  355. const int8_t index = static_cast<int8_t>(font);
  356. logGlobal->debug("Loading font %d", static_cast<int>(index));
  357. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  358. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  359. std::string bitmapPath;
  360. for(auto & loader : configList)
  361. {
  362. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  363. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  364. stream->read(textData.get(), stream->getSize());
  365. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  366. const JsonVector & bmpConf = config["bitmap"].Vector();
  367. const JsonNode & ttfConf = config["trueType"];
  368. bitmapPath = bmpConf[index].String();
  369. if (!ttfConf[bitmapPath].isNull())
  370. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  371. }
  372. loadedFont->addBitmapFont(bitmapPath);
  373. fonts[font] = loadedFont;
  374. return loadedFont;
  375. }