RenderHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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<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<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<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<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<ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<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<ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<ISharedImage> image)
  248. {
  249. if (imageFiles.count(locator))
  250. return imageFiles.at(locator);
  251. auto handle = image->createImageReference(locator.layer == EImageLayer::ALL ? EImageBlitMode::OPAQUE : EImageBlitMode::ALPHA);
  252. assert(locator.scalingFactor != 1); // should be filtered-out before
  253. handle->setBodyEnabled(locator.layer == EImageLayer::ALL || locator.layer == EImageLayer::BODY);
  254. if (locator.layer != EImageLayer::ALL)
  255. {
  256. handle->setOverlayEnabled(locator.layer == EImageLayer::OVERLAY);
  257. handle->setShadowEnabled( locator.layer == EImageLayer::SHADOW);
  258. }
  259. if (locator.layer == EImageLayer::ALL && locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  260. handle->playerColored(locator.playerColored);
  261. handle->scaleInteger(locator.scalingFactor);
  262. // TODO: try to optimize image size (possibly even before scaling?) - trim image borders if they are completely transparent
  263. auto result = handle->getSharedImage();
  264. storeCachedImage(locator, result);
  265. return result;
  266. }
  267. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  268. {
  269. ImageLocator adjustedLocator = locator;
  270. if(adjustedLocator.image)
  271. {
  272. std::string imgPath = (*adjustedLocator.image).getName();
  273. if(adjustedLocator.layer == EImageLayer::OVERLAY)
  274. imgPath += "-OVERLAY";
  275. if(adjustedLocator.layer == EImageLayer::SHADOW)
  276. imgPath += "-SHADOW";
  277. if(CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath)) ||
  278. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("DATA/")) ||
  279. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("SPRITES/")))
  280. adjustedLocator.image = ImagePath::builtin(imgPath);
  281. }
  282. if(adjustedLocator.defFile && adjustedLocator.scalingFactor == 0)
  283. {
  284. auto tmp = getScalePath(*adjustedLocator.defFile);
  285. adjustedLocator.defFile = AnimationPath::builtin(tmp.first.getName());
  286. adjustedLocator.preScaledFactor = tmp.second;
  287. }
  288. if(adjustedLocator.image && adjustedLocator.scalingFactor == 0)
  289. {
  290. auto tmp = getScalePath(*adjustedLocator.image);
  291. adjustedLocator.image = ImagePath::builtin(tmp.first.getName());
  292. adjustedLocator.preScaledFactor = tmp.second;
  293. }
  294. if (adjustedLocator.scalingFactor == 0 && getScalingFactor() != 1 )
  295. {
  296. auto unscaledLocator = adjustedLocator;
  297. auto scaledLocator = adjustedLocator;
  298. unscaledLocator.scalingFactor = 1;
  299. scaledLocator.scalingFactor = getScalingFactor();
  300. auto unscaledImage = loadImageImpl(unscaledLocator);
  301. return std::make_shared<ImageScaled>(scaledLocator, unscaledImage, mode);
  302. }
  303. if (adjustedLocator.scalingFactor == 0)
  304. {
  305. auto scaledLocator = adjustedLocator;
  306. scaledLocator.scalingFactor = getScalingFactor();
  307. return loadImageImpl(scaledLocator)->createImageReference(mode);
  308. }
  309. else
  310. return loadImageImpl(adjustedLocator)->createImageReference(mode);
  311. }
  312. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  313. {
  314. auto tmp = getScalePath(path);
  315. ImageLocator locator = getLocatorForAnimationFrame(AnimationPath::builtin(tmp.first.getName()), frame, group);
  316. locator.preScaledFactor = tmp.second;
  317. return loadImage(locator, mode);
  318. }
  319. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  320. {
  321. ImageLocator locator(path);
  322. return loadImage(locator, mode);
  323. }
  324. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  325. {
  326. return std::make_shared<SDLImageShared>(source)->createImageReference(EImageBlitMode::ALPHA);
  327. }
  328. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  329. {
  330. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  331. }
  332. void RenderHandler::addImageListEntries(const EntityService * service)
  333. {
  334. service->forEachBase([this](const Entity * entity, bool & stop)
  335. {
  336. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  337. {
  338. if (imageName.empty())
  339. return;
  340. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  341. JsonNode entry;
  342. entry["file"].String() = imageName;
  343. if (index >= layout[group].size())
  344. layout[group].resize(index + 1);
  345. layout[group][index] = ImageLocator(entry);
  346. });
  347. });
  348. }
  349. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  350. {
  351. addImageListEntries(services->creatures());
  352. addImageListEntries(services->heroTypes());
  353. addImageListEntries(services->artifacts());
  354. addImageListEntries(services->factions());
  355. addImageListEntries(services->spells());
  356. addImageListEntries(services->skills());
  357. }
  358. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  359. {
  360. if (fonts.count(font))
  361. return fonts.at(font);
  362. const int8_t index = static_cast<int8_t>(font);
  363. logGlobal->debug("Loading font %d", static_cast<int>(index));
  364. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  365. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  366. std::string bitmapPath;
  367. for(auto & loader : configList)
  368. {
  369. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  370. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  371. stream->read(textData.get(), stream->getSize());
  372. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  373. const JsonVector & bmpConf = config["bitmap"].Vector();
  374. const JsonNode & ttfConf = config["trueType"];
  375. bitmapPath = bmpConf[index].String();
  376. if (!ttfConf[bitmapPath].isNull())
  377. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  378. }
  379. loadedFont->addBitmapFont(bitmapPath);
  380. fonts[font] = loadedFont;
  381. return loadedFont;
  382. }