RenderHandler.cpp 18 KB

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