RenderHandler.cpp 13 KB

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