minetest/src/client/guiscalingfilter.cpp

227 lines
7.4 KiB
C++
Raw Normal View History

/*
Copyright (C) 2015 Aaron Suen <warr1024@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "guiscalingfilter.h"
#include "imagefilters.h"
#include "porting.h"
#include "settings.h"
#include "util/numeric.h"
#include <cstdio>
#include "client/renderingengine.h"
#include "client/tile.h" // hasNPotSupport()
/* Maintain a static cache to store the images that correspond to textures
* in a format that's manipulable by code. Some platforms exhibit issues
* converting textures back into images repeatedly, and some don't even
* allow it at all.
*/
2015-04-01 06:19:10 +02:00
std::map<io::path, video::IImage *> g_imgCache;
/* Maintain a static cache of all pre-scaled textures. These need to be
* cleared as well when the cached images.
*/
2015-04-01 06:19:10 +02:00
std::map<io::path, video::ITexture *> g_txrCache;
/* Manually insert an image into the cache, useful to avoid texture-to-image
* conversion whenever we can intercept it.
*/
Optimize string (mis)handling (#8128) * Optimize statbar drawing The texture name of the statbar is a string passed by value. That slows down the client and creates litter in the heap as the content of the string is allocated there. Convert the offending parameter to a const reference to avoid the performance hit. * Optimize texture cache There is an unnecessary temporary created when the texture path is being generated. This slows down the cache each time a new texture is encountered and it needs to be loaded into the cache. Additionally, the heap litter created by this unnecessary temporary is particularly troublesome here as the following code then piles another string (the resulting full path of the texture) on top of it, followed by the texture itself, which both are quite long term objects as they are subsequently inserted into the cache where they can remain for quite a while (especially if the texture turns out to be a common one like dirt, grass or stone). Use std::string.append to get rid of the temporary which solves both issues (speed and heap fragmentation). * Optimize animations in client Each time an animated node is updated, an unnecessary copy of the texture name is created, littering the heap with lots of fragments. This can be specifically troublesome when looking at oceans or large lava lakes as both of these nodes are usually animated (the lava animation is pretty visible). Convert the parameter of GenericCAO::updateTextures to a const reference to get rid of the unnecessary copy. There is a comment stating "std::string copy is mandatory as mod can be a class member and there is a swap on those class members ... do NOT pass by reference", reinforcing the belief that the unnecessary copy is in fact necessary. However one of the first things the code of the method does is to assign the parameter to its class member, creating another copy. By rearranging the code a little bit this "another copy" can then be used by the subsequent code, getting rid of the need to pass the parameter by value and thus saving that copying effort. * Optimize chat console history handling The GUIChatConsole::replaceAndAddToHistory was getting the line to work on by value which turns out to be unnecessary. Get rid of that unnecessary copy by converting the parameter to a const reference. * Optimize gui texture setting The code used to set the texture for GUI components was getting the name of the texture by value, creating unnecessary performance bottleneck for mods/games with heavily textured GUIs. Get rid of the bottleneck by passing the texture name as a const reference. * Optimize sound playing code in GUIEngine The GUIEngine's code receives the specification of the sound to be played by value, which turns out to be most likely a mistake as the underlying sound manager interface receives the same thing by reference. Convert the offending parameter to a const reference to get rid of the rather bulky copying effort and the associated performance hit. * Silence CLANG TIDY warnings for unit tests Change "std::string" to "const std::string &" to avoid an unnecessary local value copy, silencing the CLANG TIDY process. * Optimize formspec handling The "formspec prepend" parameter was passed to the formspec handling code by value, creating unnecessary copy of std::string and slowing down the game if mods add things like textured backgrounds for the player inventory and/or other forms. Get rid of that performance bottleneck by converting the parameter to a const reference. * Optimize hotbar image handling The code that sets the background images for the hotbar is getting the name of the image by value, creating an unnecessary std::string copying effort. Fix that by converting the relevant parameters to const references. * Optimize inventory deserialization The inventory manager deserialization code gets the serialized version of the inventory by value, slowing the server and the client down when there are inventory updates. This can get particularly troublesome with pipeworks which adds nodes that can mess around with inventories automatically or with mods that have mobs with inventories that actively use them. * Optimize texture scaling cache There is an io::path parameter passed by value in the procedure used to add images converted from textures, leading to slowdown when the image is not yet created and the conversion is thus needed. The performance hit is quite significant as io::path is similar to std::string so convert the parameter to a const reference to get rid of it. * Optimize translation file loader Use "std::string::append" when calculating the final index for the translation table to avoid unnecessary temporary strings. This speeds the translation file loader up significantly as std::string uses heap allocation which tends to be rather slow. Additionally, the heap is no longer being littered by these unnecessary string temporaries, increasing performance of code that gets executed after the translation file loader finishes. * Optimize server map saving When the directory structure for the world data is created during server map saving, an unnecessary value passing of the directory name slows things down. Remove that overhead by converting the offending parameter to a const reference.
2019-05-18 17:19:13 +02:00
void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value)
2015-04-01 06:19:10 +02:00
{
if (!g_settings->getBool("gui_scaling_filter"))
return;
video::IImage *copied = driver->createImage(value->getColorFormat(),
value->getDimension());
value->copyTo(copied);
2015-04-01 06:19:10 +02:00
g_imgCache[key] = copied;
}
// Manually clear the cache, e.g. when switching to different worlds.
void guiScalingCacheClear()
2015-04-01 06:19:10 +02:00
{
for (auto &it : g_imgCache) {
if (it.second)
it.second->drop();
}
2015-04-01 06:19:10 +02:00
g_imgCache.clear();
for (auto &it : g_txrCache) {
if (it.second)
RenderingEngine::get_video_driver()->removeTexture(it.second);
}
2015-04-01 06:19:10 +02:00
g_txrCache.clear();
}
/* Get a cached, high-quality pre-scaled texture for display purposes. If the
* texture is not already cached, attempt to create it. Returns a pre-scaled texture,
* or the original texture if unable to pre-scale it.
*/
2015-04-01 06:19:10 +02:00
video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver,
video::ITexture *src, const core::rect<s32> &srcrect,
const core::rect<s32> &destrect)
{
if (src == NULL)
return src;
if (!g_settings->getBool("gui_scaling_filter"))
return src;
// Calculate scaled texture name.
char rectstr[200];
porting::mt_snprintf(rectstr, sizeof(rectstr), "%d:%d:%d:%d:%d:%d",
srcrect.UpperLeftCorner.X,
srcrect.UpperLeftCorner.Y,
srcrect.getWidth(),
srcrect.getHeight(),
destrect.getWidth(),
destrect.getHeight());
io::path origname = src->getName().getPath();
io::path scalename = origname + "@guiScalingFilter:" + rectstr;
// Search for existing scaled texture.
2015-04-01 06:19:10 +02:00
video::ITexture *scaled = g_txrCache[scalename];
if (scaled)
return scaled;
// Try to find the texture converted to an image in the cache.
// If the image was not found, try to extract it from the texture.
2015-04-01 06:19:10 +02:00
video::IImage* srcimg = g_imgCache[origname];
if (srcimg == NULL) {
if (!g_settings->getBool("gui_scaling_filter_txr2img"))
return src;
srcimg = driver->createImageFromData(src->getColorFormat(),
src->getSize(), src->lock(), false);
src->unlock();
2015-04-01 06:19:10 +02:00
g_imgCache[origname] = srcimg;
}
// Create a new destination image and scale the source into it.
imageCleanTransparent(srcimg, 0);
video::IImage *destimg = driver->createImage(src->getColorFormat(),
core::dimension2d<u32>((u32)destrect.getWidth(),
(u32)destrect.getHeight()));
imageScaleNNAA(srcimg, srcrect, destimg);
#if ENABLE_GLES
// Some platforms are picky about textures being powers of 2, so expand
// the image dimensions to the next power of 2, if necessary.
if (!hasNPotSupport()) {
video::IImage *po2img = driver->createImage(src->getColorFormat(),
core::dimension2d<u32>(npot2((u32)destrect.getWidth()),
npot2((u32)destrect.getHeight())));
po2img->fill(video::SColor(0, 0, 0, 0));
destimg->copyTo(po2img);
destimg->drop();
destimg = po2img;
}
#endif
// Convert the scaled image back into a texture.
2021-03-16 19:55:10 +01:00
scaled = driver->addTexture(scalename, destimg);
destimg->drop();
2015-04-01 06:19:10 +02:00
g_txrCache[scalename] = scaled;
return scaled;
}
/* Convenience wrapper for guiScalingResizeCached that accepts parameters that
* are available at GUI imagebutton creation time.
*/
2015-04-01 06:19:10 +02:00
video::ITexture *guiScalingImageButton(video::IVideoDriver *driver,
video::ITexture *src, s32 width, s32 height)
{
if (src == NULL)
return src;
return guiScalingResizeCached(driver, src,
core::rect<s32>(0, 0, src->getSize().Width, src->getSize().Height),
core::rect<s32>(0, 0, width, height));
}
/* Replacement for driver->draw2DImage() that uses the high-quality pre-scaled
* texture, if configured.
*/
void draw2DImageFilterScaled(video::IVideoDriver *driver, video::ITexture *txr,
const core::rect<s32> &destrect, const core::rect<s32> &srcrect,
const core::rect<s32> *cliprect, const video::SColor *const colors,
2015-04-01 06:19:10 +02:00
bool usealpha)
{
// Attempt to pre-scale image in software in high quality.
video::ITexture *scaled = guiScalingResizeCached(driver, txr, srcrect, destrect);
if (scaled == NULL)
return;
// Correct source rect based on scaled image.
const core::rect<s32> mysrcrect = (scaled != txr)
? core::rect<s32>(0, 0, destrect.getWidth(), destrect.getHeight())
: srcrect;
driver->draw2DImage(scaled, destrect, mysrcrect, cliprect, colors, usealpha);
}
void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture,
const core::rect<s32> &rect, const core::rect<s32> &middle,
const core::rect<s32> *cliprect, const video::SColor *const colors)
{
auto originalSize = texture->getOriginalSize();
core::vector2di lowerRightOffset = core::vector2di(originalSize.Width, originalSize.Height) - middle.LowerRightCorner;
for (int y = 0; y < 3; ++y) {
for (int x = 0; x < 3; ++x) {
core::rect<s32> src({0, 0}, originalSize);
core::rect<s32> dest = rect;
switch (x) {
case 0:
dest.LowerRightCorner.X = rect.UpperLeftCorner.X + middle.UpperLeftCorner.X;
src.LowerRightCorner.X = middle.UpperLeftCorner.X;
break;
case 1:
dest.UpperLeftCorner.X += middle.UpperLeftCorner.X;
dest.LowerRightCorner.X -= lowerRightOffset.X;
src.UpperLeftCorner.X = middle.UpperLeftCorner.X;
src.LowerRightCorner.X = middle.LowerRightCorner.X;
break;
case 2:
dest.UpperLeftCorner.X = rect.LowerRightCorner.X - lowerRightOffset.X;
src.UpperLeftCorner.X = middle.LowerRightCorner.X;
break;
}
switch (y) {
case 0:
dest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + middle.UpperLeftCorner.Y;
src.LowerRightCorner.Y = middle.UpperLeftCorner.Y;
break;
case 1:
dest.UpperLeftCorner.Y += middle.UpperLeftCorner.Y;
dest.LowerRightCorner.Y -= lowerRightOffset.Y;
src.UpperLeftCorner.Y = middle.UpperLeftCorner.Y;
src.LowerRightCorner.Y = middle.LowerRightCorner.Y;
break;
case 2:
dest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - lowerRightOffset.Y;
src.UpperLeftCorner.Y = middle.LowerRightCorner.Y;
break;
}
draw2DImageFilterScaled(driver, texture, dest, src, cliprect, colors, true);
}
}
}