RenderHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  216. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup, preScaledFactor);
  217. else
  218. {
  219. logGlobal->error("Frame %d in group %d not found in file: %s",
  220. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  221. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"), locator.preScaledFactor);
  222. }
  223. }
  224. throw std::runtime_error("Invalid image locator received!");
  225. }
  226. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  227. {
  228. imageFiles[locator] = image;
  229. #if 0
  230. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "imageCache" / (locator.toString() + ".png");
  231. boost::filesystem::path outDir = outPath;
  232. outDir.remove_filename();
  233. boost::filesystem::create_directories(outDir);
  234. image->exportBitmap(outPath , nullptr);
  235. #endif
  236. }
  237. std::shared_ptr<const ISharedImage> RenderHandler::loadImageFromFile(const ImageLocator & locator)
  238. {
  239. if (imageFiles.count(locator))
  240. return imageFiles.at(locator);
  241. auto result = loadImageFromFileUncached(locator);
  242. storeCachedImage(locator, result);
  243. return result;
  244. }
  245. std::shared_ptr<const ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  246. {
  247. if (imageFiles.count(locator))
  248. return imageFiles.at(locator);
  249. auto result = image;
  250. if (locator.verticalFlip)
  251. result = result->verticalFlip();
  252. if (locator.horizontalFlip)
  253. result = result->horizontalFlip();
  254. storeCachedImage(locator, result);
  255. return result;
  256. }
  257. std::shared_ptr<const ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<const ISharedImage> image)
  258. {
  259. if (imageFiles.count(locator))
  260. return imageFiles.at(locator);
  261. auto handle = image->createImageReference(locator.layer);
  262. assert(locator.scalingFactor != 1); // should be filtered-out before
  263. if (locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  264. handle->playerColored(locator.playerColored);
  265. handle->scaleInteger(locator.scalingFactor);
  266. auto result = handle->getSharedImage();
  267. storeCachedImage(locator, result);
  268. return result;
  269. }
  270. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  271. {
  272. ImageLocator adjustedLocator = locator;
  273. if(adjustedLocator.image)
  274. {
  275. std::string imgPath = (*adjustedLocator.image).getName();
  276. if(adjustedLocator.layer == EImageBlitMode::ONLY_OVERLAY)
  277. imgPath += "-OVERLAY";
  278. if(adjustedLocator.layer == EImageBlitMode::ONLY_SHADOW)
  279. imgPath += "-SHADOW";
  280. if(CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath)) ||
  281. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("DATA/")) ||
  282. CResourceHandler::get()->existsResource(ImagePath::builtin(imgPath).addPrefix("SPRITES/")))
  283. adjustedLocator.image = ImagePath::builtin(imgPath);
  284. }
  285. if(adjustedLocator.defFile && adjustedLocator.scalingFactor == 0)
  286. {
  287. auto tmp = getScalePath(*adjustedLocator.defFile);
  288. adjustedLocator.defFile = AnimationPath::builtin(tmp.first.getName());
  289. adjustedLocator.preScaledFactor = tmp.second;
  290. }
  291. if(adjustedLocator.image && adjustedLocator.scalingFactor == 0)
  292. {
  293. auto tmp = getScalePath(*adjustedLocator.image);
  294. adjustedLocator.image = ImagePath::builtin(tmp.first.getName());
  295. adjustedLocator.preScaledFactor = tmp.second;
  296. }
  297. if (adjustedLocator.scalingFactor == 0 && getScalingFactor() != 1 )
  298. {
  299. auto unscaledLocator = adjustedLocator;
  300. auto scaledLocator = adjustedLocator;
  301. unscaledLocator.scalingFactor = 1;
  302. scaledLocator.scalingFactor = getScalingFactor();
  303. auto unscaledImage = loadImageImpl(unscaledLocator);
  304. return std::make_shared<ImageScaled>(scaledLocator, unscaledImage, mode);
  305. }
  306. if (adjustedLocator.scalingFactor == 0)
  307. {
  308. auto scaledLocator = adjustedLocator;
  309. scaledLocator.scalingFactor = getScalingFactor();
  310. return loadImageImpl(scaledLocator)->createImageReference(mode);
  311. }
  312. else
  313. return loadImageImpl(adjustedLocator)->createImageReference(mode);
  314. }
  315. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  316. {
  317. auto tmp = getScalePath(path);
  318. ImageLocator locator = getLocatorForAnimationFrame(AnimationPath::builtin(tmp.first.getName()), frame, group);
  319. locator.preScaledFactor = tmp.second;
  320. return loadImage(locator, mode);
  321. }
  322. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  323. {
  324. ImageLocator locator(path);
  325. return loadImage(locator, mode);
  326. }
  327. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  328. {
  329. return std::make_shared<SDLImageShared>(source)->createImageReference(EImageBlitMode::SIMPLE);
  330. }
  331. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  332. {
  333. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  334. }
  335. void RenderHandler::addImageListEntries(const EntityService * service)
  336. {
  337. service->forEachBase([this](const Entity * entity, bool & stop)
  338. {
  339. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  340. {
  341. if (imageName.empty())
  342. return;
  343. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  344. JsonNode entry;
  345. entry["file"].String() = imageName;
  346. if (index >= layout[group].size())
  347. layout[group].resize(index + 1);
  348. layout[group][index] = ImageLocator(entry);
  349. });
  350. });
  351. }
  352. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  353. {
  354. addImageListEntries(services->creatures());
  355. addImageListEntries(services->heroTypes());
  356. addImageListEntries(services->artifacts());
  357. addImageListEntries(services->factions());
  358. addImageListEntries(services->spells());
  359. addImageListEntries(services->skills());
  360. }
  361. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  362. {
  363. if (fonts.count(font))
  364. return fonts.at(font);
  365. const int8_t index = static_cast<int8_t>(font);
  366. logGlobal->debug("Loading font %d", static_cast<int>(index));
  367. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  368. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  369. std::string bitmapPath;
  370. for(auto & loader : configList)
  371. {
  372. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  373. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  374. stream->read(textData.get(), stream->getSize());
  375. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  376. const JsonVector & bmpConf = config["bitmap"].Vector();
  377. const JsonNode & ttfConf = config["trueType"];
  378. bitmapPath = bmpConf[index].String();
  379. if (!ttfConf[bitmapPath].isNull())
  380. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  381. }
  382. loadedFont->addBitmapFont(bitmapPath);
  383. fonts[font] = loadedFont;
  384. return loadedFont;
  385. }