RenderHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 "ScalableImage.h"
  14. #include "FontChain.h"
  15. #include "../gui/CGuiHandler.h"
  16. #include "../render/AssetGenerator.h"
  17. #include "../render/CAnimation.h"
  18. #include "../render/CanvasImage.h"
  19. #include "../render/CDefFile.h"
  20. #include "../render/Colors.h"
  21. #include "../render/ColorFilter.h"
  22. #include "../render/IScreenHandler.h"
  23. #include "../../lib/CConfigHandler.h"
  24. #include "../../lib/CThreadHelper.h"
  25. #include "../../lib/ExceptionsCommon.h"
  26. #include "../../lib/VCMIDirs.h"
  27. #include "../../lib/constants/StringConstants.h"
  28. #include "../../lib/entities/building/CBuilding.h"
  29. #include "../../lib/entities/faction/CTown.h"
  30. #include "../../lib/entities/faction/CTownHandler.h"
  31. #include "../../lib/filesystem/Filesystem.h"
  32. #include "../../lib/json/JsonUtils.h"
  33. #include <vcmi/ArtifactService.h>
  34. #include <vcmi/CreatureService.h>
  35. #include <vcmi/Entity.h>
  36. #include <vcmi/FactionService.h>
  37. #include <vcmi/HeroTypeService.h>
  38. #include <vcmi/Services.h>
  39. #include <vcmi/SkillService.h>
  40. #include <vcmi/spells/Service.h>
  41. RenderHandler::RenderHandler()
  42. :assetGenerator(std::make_unique<AssetGenerator>())
  43. {
  44. }
  45. RenderHandler::~RenderHandler() = default;
  46. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  47. {
  48. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  49. auto it = animationFiles.find(actualPath);
  50. if (it != animationFiles.end())
  51. {
  52. auto locked = it->second.lock();
  53. if (locked)
  54. return locked;
  55. }
  56. if (!CResourceHandler::get()->existsResource(actualPath))
  57. return nullptr;
  58. auto result = std::make_shared<CDefFile>(actualPath);
  59. animationFiles[actualPath] = result;
  60. return result;
  61. }
  62. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config, EImageBlitMode mode)
  63. {
  64. std::string basepath;
  65. basepath = config["basepath"].String();
  66. JsonNode base;
  67. base["margins"] = config["margins"];
  68. base["width"] = config["width"];
  69. base["height"] = config["height"];
  70. for(const JsonNode & group : config["sequences"].Vector())
  71. {
  72. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  73. source[groupID].clear();
  74. for(const JsonNode & frame : group["frames"].Vector())
  75. {
  76. JsonNode toAdd = frame;
  77. JsonUtils::inherit(toAdd, base);
  78. toAdd["file"].String() = basepath + frame.String();
  79. source[groupID].emplace_back(toAdd, mode);
  80. }
  81. }
  82. for(const JsonNode & node : config["images"].Vector())
  83. {
  84. size_t group = node["group"].Integer();
  85. size_t frame = node["frame"].Integer();
  86. if (source[group].size() <= frame)
  87. source[group].resize(frame+1);
  88. JsonNode toAdd = node;
  89. JsonUtils::inherit(toAdd, base);
  90. if (toAdd.Struct().count("file"))
  91. toAdd["file"].String() = basepath + node["file"].String();
  92. if (toAdd.Struct().count("defFile"))
  93. toAdd["defFile"].String() = basepath + node["defFile"].String();
  94. source[group][frame] = ImageLocator(toAdd, mode);
  95. }
  96. }
  97. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path, int scalingFactor, EImageBlitMode mode)
  98. {
  99. static constexpr std::array scaledSpritesPath = {
  100. "", // 0x
  101. "SPRITES/",
  102. "SPRITES2X/",
  103. "SPRITES3X/",
  104. "SPRITES4X/",
  105. };
  106. std::string pathString = path.getName();
  107. if (boost::starts_with(pathString, "SPRITES/"))
  108. pathString = pathString.substr(std::string("SPRITES/").length());
  109. AnimationPath actualPath = AnimationPath::builtin(scaledSpritesPath.at(scalingFactor) + pathString);
  110. auto it = animationLayouts.find(actualPath);
  111. if (it != animationLayouts.end())
  112. return it->second;
  113. AnimationLayoutMap result;
  114. auto defFile = getAnimationFile(actualPath);
  115. if(defFile)
  116. {
  117. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  118. for (const auto & defEntry : defEntries)
  119. result[defEntry.first].resize(defEntry.second);
  120. }
  121. auto jsonResource = actualPath.toType<EResType::JSON>();
  122. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  123. for(auto & loader : configList)
  124. {
  125. try {
  126. auto stream = loader->load(jsonResource);
  127. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  128. stream->read(textData.get(), stream->getSize());
  129. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  130. initFromJson(result, config, mode);
  131. }
  132. catch (const DataLoadingException & e)
  133. {
  134. // FIXME: sometimes triggered by generated animation assets, e.g. lava/water tiles
  135. logGlobal->error("Failed to load animation file! Reason: %s", e.what());
  136. }
  137. }
  138. animationLayouts[actualPath] = result;
  139. return animationLayouts[actualPath];
  140. }
  141. int RenderHandler::getScalingFactor() const
  142. {
  143. return GH.screenHandler().getScalingFactor();
  144. }
  145. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group, int scaling, EImageBlitMode mode)
  146. {
  147. const auto & layout = getAnimationLayout(path, scaling, mode);
  148. if (!layout.count(group))
  149. return ImageLocator();
  150. if (frame >= layout.at(group).size())
  151. return ImageLocator();
  152. const auto & locator = layout.at(group).at(frame);
  153. if (locator.image || locator.defFile)
  154. return locator;
  155. return ImageLocator(path, frame, group, mode);
  156. }
  157. std::shared_ptr<ScalableImageShared> RenderHandler::loadImageImpl(const ImageLocator & locator)
  158. {
  159. auto it = imageFiles.find(locator);
  160. if (it != imageFiles.end())
  161. {
  162. auto locked = it->second.lock();
  163. if (locked)
  164. return locked;
  165. }
  166. auto sdlImage = loadImageFromFileUncached(locator);
  167. auto scaledImage = std::make_shared<ScalableImageShared>(locator, sdlImage);
  168. storeCachedImage(locator, scaledImage);
  169. return scaledImage;
  170. }
  171. std::shared_ptr<ISharedImage> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  172. {
  173. if(locator.image)
  174. {
  175. auto imagePath = *locator.image;
  176. auto imagePathSprites = imagePath.addPrefix("SPRITES/");
  177. auto imagePathData = imagePath.addPrefix("DATA/");
  178. if(CResourceHandler::get()->existsResource(imagePathSprites))
  179. return std::make_shared<SDLImageShared>(imagePathSprites);
  180. if(CResourceHandler::get()->existsResource(imagePathData))
  181. return std::make_shared<SDLImageShared>(imagePathData);
  182. if(CResourceHandler::get()->existsResource(imagePath))
  183. return std::make_shared<SDLImageShared>(imagePath);
  184. auto generated = assetGenerator->generateImage(imagePath);
  185. if (generated)
  186. return generated;
  187. logGlobal->error("Failed to load image %s", locator.image->getOriginalName());
  188. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  189. }
  190. if(locator.defFile)
  191. {
  192. auto defFile = getAnimationFile(*locator.defFile);
  193. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  194. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  195. else
  196. {
  197. logGlobal->error("Frame %d in group %d not found in file: %s",
  198. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  199. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  200. }
  201. }
  202. throw std::runtime_error("Invalid image locator received!");
  203. }
  204. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<ScalableImageShared> image)
  205. {
  206. imageFiles[locator] = image;
  207. }
  208. std::shared_ptr<SDLImageShared> RenderHandler::loadScaledImage(const ImageLocator & locator)
  209. {
  210. static constexpr std::array scaledDataPath = {
  211. "", // 0x
  212. "DATA/",
  213. "DATA2X/",
  214. "DATA3X/",
  215. "DATA4X/",
  216. };
  217. static constexpr std::array scaledSpritesPath = {
  218. "", // 0x
  219. "SPRITES/",
  220. "SPRITES2X/",
  221. "SPRITES3X/",
  222. "SPRITES4X/",
  223. };
  224. ImagePath pathToLoad;
  225. if(locator.defFile)
  226. {
  227. auto remappedLocator = getLocatorForAnimationFrame(*locator.defFile, locator.defFrame, locator.defGroup, locator.scalingFactor, locator.layer);
  228. // we expect that .def's are only used for 1x data, upscaled assets should use standalone images
  229. if (!remappedLocator.image)
  230. return nullptr;
  231. pathToLoad = *remappedLocator.image;
  232. }
  233. if(locator.image)
  234. pathToLoad = *locator.image;
  235. if (pathToLoad.empty())
  236. return nullptr;
  237. std::string imagePathString = pathToLoad.getName();
  238. if(locator.layer == EImageBlitMode::ONLY_FLAG_COLOR || locator.layer == EImageBlitMode::ONLY_SELECTION)
  239. imagePathString += "-OVERLAY";
  240. if(locator.layer == EImageBlitMode::ONLY_SHADOW_HIDE_SELECTION || locator.layer == EImageBlitMode::ONLY_SHADOW_HIDE_FLAG_COLOR)
  241. imagePathString += "-SHADOW";
  242. if(locator.playerColored.isValidPlayer())
  243. imagePathString += "-" + boost::to_upper_copy(GameConstants::PLAYER_COLOR_NAMES[locator.playerColored.getNum()]);
  244. if(locator.playerColored == PlayerColor::NEUTRAL)
  245. imagePathString += "-NEUTRAL";
  246. auto imagePath = ImagePath::builtin(imagePathString);
  247. auto imagePathSprites = ImagePath::builtin(imagePathString).addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  248. auto imagePathData = ImagePath::builtin(imagePathString).addPrefix(scaledDataPath.at(locator.scalingFactor));
  249. if(CResourceHandler::get()->existsResource(imagePathSprites))
  250. return std::make_shared<SDLImageShared>(imagePathSprites);
  251. if(CResourceHandler::get()->existsResource(imagePathData))
  252. return std::make_shared<SDLImageShared>(imagePathData);
  253. if(CResourceHandler::get()->existsResource(imagePath))
  254. return std::make_shared<SDLImageShared>(imagePath);
  255. return nullptr;
  256. }
  257. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator)
  258. {
  259. ImageLocator adjustedLocator = locator;
  260. std::shared_ptr<ScalableImageInstance> result;
  261. if (adjustedLocator.scalingFactor == 0)
  262. {
  263. auto scaledLocator = adjustedLocator;
  264. scaledLocator.scalingFactor = getScalingFactor();
  265. result = loadImageImpl(scaledLocator)->createImageReference();
  266. }
  267. else
  268. result = loadImageImpl(adjustedLocator)->createImageReference();
  269. if (locator.horizontalFlip)
  270. result->horizontalFlip();
  271. if (locator.verticalFlip)
  272. result->verticalFlip();
  273. return result;
  274. }
  275. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  276. {
  277. ImageLocator locator = getLocatorForAnimationFrame(path, frame, group, 1, mode);
  278. if (!locator.empty())
  279. return loadImage(locator);
  280. else
  281. {
  282. logGlobal->error("Failed to load non-existing image");
  283. return loadImage(ImageLocator(ImagePath::builtin("DEFAULT"), mode));
  284. }
  285. }
  286. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  287. {
  288. ImageLocator locator(path, mode);
  289. return loadImage(locator);
  290. }
  291. std::shared_ptr<CanvasImage> RenderHandler::createImage(const Point & size, CanvasScalingPolicy scalingPolicy)
  292. {
  293. return std::make_shared<CanvasImage>(size, scalingPolicy);
  294. }
  295. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  296. {
  297. return std::make_shared<CAnimation>(path, getAnimationLayout(path, 1, mode), mode);
  298. }
  299. void RenderHandler::addImageListEntries(const EntityService * service)
  300. {
  301. service->forEachBase([this](const Entity * entity, bool & stop)
  302. {
  303. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  304. {
  305. if (imageName.empty())
  306. return;
  307. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName), 1, EImageBlitMode::COLORKEY);
  308. JsonNode entry;
  309. entry["file"].String() = imageName;
  310. if (index >= layout[group].size())
  311. layout[group].resize(index + 1);
  312. layout[group][index] = ImageLocator(entry, EImageBlitMode::SIMPLE);
  313. });
  314. });
  315. }
  316. static void detectOverlappingBuildings(RenderHandler * renderHandler, const Faction * factionBase)
  317. {
  318. if (!factionBase->hasTown())
  319. return;
  320. auto faction = dynamic_cast<const CFaction*>(factionBase);
  321. for (const auto & left : faction->town->clientInfo.structures)
  322. {
  323. for (const auto & right : faction->town->clientInfo.structures)
  324. {
  325. if (left->identifier <= right->identifier)
  326. continue; // only a<->b comparison is needed, not a<->a or b<->a
  327. if (left->building && right->building && left->building->getBase() == right->building->getBase())
  328. {
  329. if (left->pos.z != right->pos.z)
  330. logMod->warn("Town %s: Upgrades of same building have different z-index: '%s' and '%s'", faction->getJsonKey(), left->identifier, right->identifier);
  331. continue; // upgrades of the same buildings are expected to overlap
  332. }
  333. if (left->pos.z != right->pos.z)
  334. continue; // buildings already have different z-index and have well-defined overlap logic
  335. auto leftImage = renderHandler->loadImage(left->defName, 0, 0, EImageBlitMode::COLORKEY);
  336. auto rightImage = renderHandler->loadImage(right->defName, 0, 0, EImageBlitMode::COLORKEY);
  337. Rect leftRect( left->pos.x, left->pos.y, leftImage->width(), leftImage->height());
  338. Rect rightRect( right->pos.x, right->pos.y, rightImage->width(), rightImage->height());
  339. Rect intersection = leftRect.intersect(rightRect);
  340. Point intersectionPosition;
  341. bool intersectionFound = false;
  342. for (int y = 0; y < intersection.h && !intersectionFound; ++y)
  343. {
  344. for (int x = 0; x < intersection.w && !intersectionFound; ++x)
  345. {
  346. Point leftPoint = Point(x,y) - leftRect.topLeft() + intersection.topLeft();
  347. Point rightPoint = Point(x,y) - rightRect.topLeft() + intersection.topLeft();
  348. if (!leftImage->isTransparent(leftPoint) && !rightImage->isTransparent(rightPoint))
  349. {
  350. intersectionFound = true;
  351. intersectionPosition = intersection.topLeft() + Point(x,y);
  352. }
  353. }
  354. }
  355. if (intersectionFound)
  356. logMod->warn("Town %s: Detected overlapping buildings '%s' and '%s' at (%d, %d) with same z-index!", faction->getJsonKey(), left->identifier, right->identifier, intersectionPosition.x, intersectionPosition.y);
  357. }
  358. }
  359. };
  360. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  361. {
  362. assert(animationLayouts.empty());
  363. assetGenerator->initialize();
  364. animationLayouts = assetGenerator->generateAllAnimations();
  365. addImageListEntries(services->creatures());
  366. addImageListEntries(services->heroTypes());
  367. addImageListEntries(services->artifacts());
  368. addImageListEntries(services->factions());
  369. addImageListEntries(services->spells());
  370. addImageListEntries(services->skills());
  371. if (settings["mods"]["validation"].String() == "full")
  372. {
  373. services->factions()->forEach([this](const Faction * factionBase, bool & stop)
  374. {
  375. detectOverlappingBuildings(this, factionBase);
  376. });
  377. }
  378. }
  379. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  380. {
  381. if (fonts.count(font))
  382. return fonts.at(font);
  383. const int8_t index = static_cast<int8_t>(font);
  384. logGlobal->debug("Loading font %d", static_cast<int>(index));
  385. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  386. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  387. std::string bitmapPath;
  388. for(auto & loader : configList)
  389. {
  390. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  391. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  392. stream->read(textData.get(), stream->getSize());
  393. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  394. const JsonVector & bmpConf = config["bitmap"].Vector();
  395. const JsonNode & ttfConf = config["trueType"];
  396. bitmapPath = bmpConf[index].String();
  397. if (!ttfConf[bitmapPath].isNull())
  398. loadedFont->addTrueTypeFont(ttfConf[bitmapPath], !config["lowPriority"].Bool());
  399. }
  400. loadedFont->addBitmapFont(bitmapPath);
  401. fonts[font] = loadedFont;
  402. return loadedFont;
  403. }
  404. void RenderHandler::exportGeneratedAssets()
  405. {
  406. for (const auto & entry : assetGenerator->generateAllImages())
  407. entry.second->exportBitmap(VCMIDirs::get().userDataPath() / "Generated" / (entry.first.getOriginalName() + ".png"), nullptr);
  408. }