/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola 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 "tile.h" #include #include "util/string.h" #include "util/container.h" #include "util/thread.h" #include "util/numeric.h" #include "irrlichttypes_extrabloated.h" #include "debug.h" #include "filesys.h" #include "settings.h" #include "mesh.h" #include "log.h" #include "gamedef.h" #include "util/strfnd.h" #include "util/string.h" // for parseColorString() #include "imagefilters.h" #include "guiscalingfilter.h" #include "nodedef.h" #ifdef __ANDROID__ #include #endif /* A cache from texture name to texture path */ MutexedMap g_texturename_to_path_cache; /* Replaces the filename extension. eg: std::string image = "a/image.png" replace_ext(image, "jpg") -> image = "a/image.jpg" Returns true on success. */ static bool replace_ext(std::string &path, const char *ext) { if (ext == NULL) return false; // Find place of last dot, fail if \ or / found. s32 last_dot_i = -1; for (s32 i=path.size()-1; i>=0; i--) { if (path[i] == '.') { last_dot_i = i; break; } if (path[i] == '\\' || path[i] == '/') break; } // If not found, return an empty string if (last_dot_i == -1) return false; // Else make the new path path = path.substr(0, last_dot_i+1) + ext; return true; } /* Find out the full path of an image by trying different filename extensions. If failed, return "". */ std::string getImagePath(std::string path) { // A NULL-ended list of possible image extensions const char *extensions[] = { "png", "jpg", "bmp", "tga", "pcx", "ppm", "psd", "wal", "rgb", NULL }; // If there is no extension, add one if (removeStringEnd(path, extensions) == "") path = path + ".png"; // Check paths until something is found to exist const char **ext = extensions; do{ bool r = replace_ext(path, *ext); if (r == false) return ""; if (fs::PathExists(path)) return path; } while((++ext) != NULL); return ""; } /* Gets the path to a texture by first checking if the texture exists in texture_path and if not, using the data path. Checks all supported extensions by replacing the original extension. If not found, returns "". Utilizes a thread-safe cache. */ std::string getTexturePath(const std::string &filename) { std::string fullpath = ""; /* Check from cache */ bool incache = g_texturename_to_path_cache.get(filename, &fullpath); if (incache) return fullpath; /* Check from texture_path */ std::string texture_path = g_settings->get("texture_path"); if (texture_path != "") { std::string testpath = texture_path + DIR_DELIM + filename; // Check all filename extensions. Returns "" if not found. fullpath = getImagePath(testpath); } /* Check from default data directory */ if (fullpath == "") { std::string base_path = porting::path_share + DIR_DELIM + "textures" + DIR_DELIM + "base" + DIR_DELIM + "pack"; std::string testpath = base_path + DIR_DELIM + filename; // Check all filename extensions. Returns "" if not found. fullpath = getImagePath(testpath); } // Add to cache (also an empty result is cached) g_texturename_to_path_cache.set(filename, fullpath); // Finally return it return fullpath; } void clearTextureNameCache() { g_texturename_to_path_cache.clear(); } /* Stores internal information about a texture. */ struct TextureInfo { std::string name; video::ITexture *texture; TextureInfo( const std::string &name_, video::ITexture *texture_=NULL ): name(name_), texture(texture_) { } }; /* SourceImageCache: A cache used for storing source images. */ class SourceImageCache { public: ~SourceImageCache() { for (std::map::iterator iter = m_images.begin(); iter != m_images.end(); ++iter) { iter->second->drop(); } m_images.clear(); } void insert(const std::string &name, video::IImage *img, bool prefer_local, video::IVideoDriver *driver) { assert(img); // Pre-condition // Remove old image std::map::iterator n; n = m_images.find(name); if (n != m_images.end()){ if (n->second) n->second->drop(); } video::IImage* toadd = img; bool need_to_grab = true; // Try to use local texture instead if asked to if (prefer_local){ std::string path = getTexturePath(name); if (path != ""){ video::IImage *img2 = driver->createImageFromFile(path.c_str()); if (img2){ toadd = img2; need_to_grab = false; } } } if (need_to_grab) toadd->grab(); m_images[name] = toadd; } video::IImage* get(const std::string &name) { std::map::iterator n; n = m_images.find(name); if (n != m_images.end()) return n->second; return NULL; } // Primarily fetches from cache, secondarily tries to read from filesystem video::IImage* getOrLoad(const std::string &name, IrrlichtDevice *device) { std::map::iterator n; n = m_images.find(name); if (n != m_images.end()){ n->second->grab(); // Grab for caller return n->second; } video::IVideoDriver* driver = device->getVideoDriver(); std::string path = getTexturePath(name); if (path == ""){ infostream<<"SourceImageCache::getOrLoad(): No path found for \"" <createImageFromFile(path.c_str()); if (img){ m_images[name] = img; img->grab(); // Grab for caller } return img; } private: std::map m_images; }; /* TextureSource */ class TextureSource : public IWritableTextureSource { public: TextureSource(IrrlichtDevice *device); virtual ~TextureSource(); /* Example case: Now, assume a texture with the id 1 exists, and has the name "stone.png^mineral1". Then a random thread calls getTextureId for a texture called "stone.png^mineral1^crack0". ...Now, WTF should happen? Well: - getTextureId strips off stuff recursively from the end until the remaining part is found, or nothing is left when something is stripped out But it is slow to search for textures by names and modify them like that? - ContentFeatures is made to contain ids for the basic plain textures - Crack textures can be slow by themselves, but the framework must be fast. Example case #2: - Assume a texture with the id 1 exists, and has the name "stone.png^mineral_coal.png". - Now getNodeTile() stumbles upon a node which uses texture id 1, and determines that MATERIAL_FLAG_CRACK must be applied to the tile - MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and has received the current crack level 0 from the client. It finds out the name of the texture with getTextureName(1), appends "^crack0" to it and gets a new texture id with getTextureId("stone.png^mineral_coal.png^crack0"). */ /* Gets a texture id from cache or - if main thread, generates the texture, adds to cache and returns id. - if other thread, adds to request queue and waits for main thread. The id 0 points to a NULL texture. It is returned in case of error. */ u32 getTextureId(const std::string &name); // Finds out the name of a cached texture. std::string getTextureName(u32 id); /* If texture specified by the name pointed by the id doesn't exist, create it, then return the cached texture. Can be called from any thread. If called from some other thread and not found in cache, the call is queued to the main thread for processing. */ video::ITexture* getTexture(u32 id); video::ITexture* getTexture(const std::string &name, u32 *id = NULL); /* Get a texture specifically intended for mesh application, i.e. not HUD, compositing, or other 2D use. This texture may be a different size and may have had additional filters applied. */ video::ITexture* getTextureForMesh(const std::string &name, u32 *id); // Returns a pointer to the irrlicht device virtual IrrlichtDevice* getDevice() { return m_device; } bool isKnownSourceImage(const std::string &name) { bool is_known = false; bool cache_found = m_source_image_existence.get(name, &is_known); if (cache_found) return is_known; // Not found in cache; find out if a local file exists is_known = (getTexturePath(name) != ""); m_source_image_existence.set(name, is_known); return is_known; } // Processes queued texture requests from other threads. // Shall be called from the main thread. void processQueue(); // Insert an image into the cache without touching the filesystem. // Shall be called from the main thread. void insertSourceImage(const std::string &name, video::IImage *img); // Rebuild images and textures from the current set of source images // Shall be called from the main thread. void rebuildImagesAndTextures(); // Render a mesh to a texture. // Returns NULL if render-to-texture failed. // Shall be called from the main thread. video::ITexture* generateTextureFromMesh( const TextureFromMeshParams ¶ms); video::IImage* generateImage(const std::string &name); video::ITexture* getNormalTexture(const std::string &name); video::SColor getTextureAverageColor(const std::string &name); video::ITexture *getShaderFlagsTexture(bool normamap_present); private: // The id of the thread that is allowed to use irrlicht directly threadid_t m_main_thread; // The irrlicht device IrrlichtDevice *m_device; // Cache of source images // This should be only accessed from the main thread SourceImageCache m_sourcecache; // Generate a texture u32 generateTexture(const std::string &name); // Generate image based on a string like "stone.png" or "[crack:1:0". // if baseimg is NULL, it is created. Otherwise stuff is made on it. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg); // Thread-safe cache of what source images are known (true = known) MutexedMap m_source_image_existence; // A texture id is index in this array. // The first position contains a NULL texture. std::vector m_textureinfo_cache; // Maps a texture name to an index in the former. std::map m_name_to_id; // The two former containers are behind this mutex Mutex m_textureinfo_cache_mutex; // Queued texture fetches (to be processed by the main thread) RequestQueue m_get_texture_queue; // Textures that have been overwritten with other ones // but can't be deleted because the ITexture* might still be used std::vector m_texture_trash; // Cached settings needed for making textures from meshes bool m_setting_trilinear_filter; bool m_setting_bilinear_filter; bool m_setting_anisotropic_filter; }; IWritableTextureSource* createTextureSource(IrrlichtDevice *device) { return new TextureSource(device); } TextureSource::TextureSource(IrrlichtDevice *device): m_device(device) { assert(m_device); // Pre-condition m_main_thread = thr_get_current_thread_id(); // Add a NULL TextureInfo as the first index, named "" m_textureinfo_cache.push_back(TextureInfo("")); m_name_to_id[""] = 0; // Cache some settings // Note: Since this is only done once, the game must be restarted // for these settings to take effect m_setting_trilinear_filter = g_settings->getBool("trilinear_filter"); m_setting_bilinear_filter = g_settings->getBool("bilinear_filter"); m_setting_anisotropic_filter = g_settings->getBool("anisotropic_filter"); } TextureSource::~TextureSource() { video::IVideoDriver* driver = m_device->getVideoDriver(); unsigned int textures_before = driver->getTextureCount(); for (std::vector::iterator iter = m_textureinfo_cache.begin(); iter != m_textureinfo_cache.end(); ++iter) { //cleanup texture if (iter->texture) driver->removeTexture(iter->texture); } m_textureinfo_cache.clear(); for (std::vector::iterator iter = m_texture_trash.begin(); iter != m_texture_trash.end(); ++iter) { video::ITexture *t = *iter; //cleanup trashed tex (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 "guiConfirmRegistration.h" #include "client/client.h" #include "guiButton.h" #include <IGUICheckBox.h> #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include "guiEditBoxWithScrollbar.h" #include "porting.h" #ifdef HAVE_TOUCHSCREENGUI #include "client/renderingengine.h" #endif #include "gettext.h" // Continuing from guiPasswordChange.cpp const int ID_confirmPassword = 262; const int ID_confirm = 263; const int ID_intotext = 264; const int ID_cancel = 265; const int ID_message = 266; GUIConfirmRegistration::GUIConfirmRegistration(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client, const std::string &playername, const std::string &password, bool *aborted, ISimpleTextureSource *tsrc) : GUIModalMenu(env, parent, id, menumgr), m_client(client), m_playername(playername), m_password(password), m_aborted(aborted), m_tsrc(tsrc) { #ifdef HAVE_TOUCHSCREENGUI m_touchscreen_visible = false; #endif } GUIConfirmRegistration::~GUIConfirmRegistration() { removeChildren(); } void GUIConfirmRegistration::removeChildren() { const core::list<gui::IGUIElement *> &children = getChildren(); core::list<gui::IGUIElement *> children_copy; for (gui::IGUIElement *i : children) children_copy.push_back(i); for (gui::IGUIElement *i : children_copy) i->remove(); } void GUIConfirmRegistration::regenerateGui(v2u32 screensize) { acceptInput(); removeChildren(); /* Calculate new sizes and positions */ #ifdef HAVE_TOUCHSCREENGUI const float s = m_gui_scale * RenderingEngine::getDisplayDensity() / 2; #else const float s = m_gui_scale; #endif DesiredRect = core::rect<s32>( screensize.X / 2 - 600 * s / 2, screensize.Y / 2 - 360 * s / 2, screensize.X / 2 + 600 * s / 2, screensize.Y / 2 + 360 * s / 2 ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); v2s32 topleft_client(0, 0); const wchar_t *text; /* Add stuff */ s32 ypos = 30 * s; { core::rect<s32> rect2(0, 0, 540 * s, 180 * s); rect2 += topleft_client + v2s32(30 * s, ypos); static const std::string info_text_template = strgettext( "You are about to join this server with the name \"%s\" for the " "first time.\n" "If you proceed, a new account using your credentials will be " "created on this server.\n" "Please retype your password and click 'Register and Join' to " "confirm account creation, or click 'Cancel' to abort."); char info_text_buf[1024]; porting::mt_snprintf(info_text_buf, sizeof(info_text_buf), info_text_template.c_str(), m_playername.c_str()); std::wstring info_text_w = utf8_to_wide(info_text_buf); gui::IGUIEditBox *e = new GUIEditBoxWithScrollBar(info_text_w.c_str(), true, Environment, this, ID_intotext, rect2, false, true); e->drop(); e->setMultiLine(true); e->setWordWrap(true); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER); } ypos += 200 * s; { core::rect<s32> rect2(0, 0, 540 * s, 30 * s); rect2 += topleft_client + v2s32(30 * s, ypos); gui::IGUIEditBox *e = Environment->addEditBox(m_pass_confirm.c_str(), rect2, true, this, ID_confirmPassword); e->setPasswordBox(true); Environment->setFocus(e); } ypos += 50 * s; { core::rect<s32> rect2(0, 0, 230 * s, 35 * s); rect2 = rect2 + v2s32(size.X / 2 - 220 * s, ypos); text = wgettext("Register and Join"); GUIButton::addButton(Environment, rect2, m_tsrc, this, ID_confirm, text); delete[] text; } { core::rect<s32> rect2(0, 0, 120 * s, 35 * s); rect2 = rect2 + v2s32(size.X / 2 + 70 * s, ypos); text = wgettext("Cancel"); GUIButton::addButton(Environment, rect2, m_tsrc, this, ID_cancel, text); delete[] text; } { core::rect<s32> rect2(0, 0, 500 * s, 40 * s); rect2 += topleft_client + v2s32(30 * s, ypos + 40 * s); text = wgettext("Passwords do not match!"); IGUIElement *e = Environment->addStaticText( text, rect2, false, true, this, ID_message); e->setVisible(false); delete[] text; } } void GUIConfirmRegistration::drawMenu() { gui::IGUISkin *skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); #ifdef __ANDROID__ getAndroidUIInput(); #endif } void GUIConfirmRegistration::closeMenu(bool goNext) { if (goNext) { m_client->confirmRegistration(); } else { *m_aborted = true; infostream << "Connect aborted [Escape]" << std::endl; } quitMenu(); } void GUIConfirmRegistration::acceptInput() { gui::IGUIElement *e; e = getElementFromId(ID_confirmPassword); if (e) m_pass_confirm = e->getText(); } bool GUIConfirmRegistration::processInput() { if (utf8_to_wide(m_password) != m_pass_confirm) { gui::IGUIElement *e = getElementFromId(ID_message); if (e) e->setVisible(true); return false; } return true; } bool GUIConfirmRegistration::OnEvent(const SEvent &event) { if (event.EventType == EET_KEY_INPUT_EVENT) { // clang-format off if ((event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_CANCEL) && event.KeyInput.PressedDown) { closeMenu(false); return true; } // clang-format on if (event.KeyInput.Key == KEY_RETURN && event.KeyInput.PressedDown) { acceptInput(); if (processInput()) closeMenu(true); return true; } } if (event.EventType != EET_GUI_EVENT) return Parent ? Parent->OnEvent(event) : false; if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { infostream << "GUIConfirmRegistration: Not allowing focus change." << std::endl; // Returning true disables focus change return true; } } else if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { switch (event.GUIEvent.Caller->getID()) { case ID_confirm: acceptInput(); if (processInput()) closeMenu(true); return true; case ID_cancel: closeMenu(false); return true; } } else if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) { switch (event.GUIEvent.Caller->getID()) { case ID_confirmPassword: acceptInput(); if (processInput()) closeMenu(true); return true; } } return false; } #ifdef __ANDROID__ bool GUIConfirmRegistration::getAndroidUIInput() { if (!hasAndroidUIInput() || m_jni_field_name != "password") return false; // still waiting if (porting::getInputDialogState() == -1) return true; m_jni_field_name.clear(); gui::IGUIElement *e = getElementFromId(ID_confirmPassword); if (!e || e->getType() != irr::gui::EGUIET_EDIT_BOX) return false; std::string text = porting::getInputDialogValue(); e->setText(utf8_to_wide(text).c_str()); return false; } #endif if (is_number(ratio_str)) ratio = mystoi(ratio_str, 0, 255); else if (ratio_str == "alpha") keep_alpha = true; apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha); } /* [applyfiltersformesh Internal modifier */ else if (str_starts_with(part_of_name, "[applyfiltersformesh")) { // Apply the "clean transparent" filter, if configured. if (g_settings->getBool("texture_clean_transparent")) imageCleanTransparent(baseimg, 127); /* Upscale textures to user's requested minimum size. This is a trick to make * filters look as good on low-res textures as on high-res ones, by making * low-res textures BECOME high-res ones. This is helpful for worlds that * mix high- and low-res textures, or for mods with least-common-denominator * textures that don't have the resources to offer high-res alternatives. */ s32 scaleto = g_settings->getS32("texture_min_size"); if (scaleto > 1) { const core::dimension2d dim = baseimg->getDimension(); /* Calculate scaling needed to make the shortest texture dimension * equal to the target minimum. If e.g. this is a vertical frames * animation, the short dimension will be the real size. */ if ((dim.Width == 0) || (dim.Height == 0)) { errorstream << "generateImagePart(): Illegal 0 dimension " << "for part_of_name=\""<< part_of_name << "\", cancelling." << std::endl; return false; } u32 xscale = scaleto / dim.Width; u32 yscale = scaleto / dim.Height; u32 scale = (xscale > yscale) ? xscale : yscale; // Never downscale; only scale up by 2x or more. if (scale > 1) { u32 w = scale * dim.Width; u32 h = scale * dim.Height; const core::dimension2d newdim = core::dimension2d(w, h); video::IImage *newimg = driver->createImage( baseimg->getColorFormat(), newdim); baseimg->copyToScaling(newimg); baseimg->drop(); baseimg = newimg; } } } /* [resize:WxH Resizes the base image to the given dimensions */ else if (str_starts_with(part_of_name, "[resize")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\""<< part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 width = stoi(sf.next("x")); u32 height = stoi(sf.next("")); core::dimension2d dim(width, height); video::IImage* image = m_device->getVideoDriver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(image); baseimg->drop(); baseimg = image; } /* [opacity:R Makes the base image transparent according to the given ratio. R must be between 0 and 255. 0 means totally transparent. 255 means totally opaque. */ else if (str_starts_with(part_of_name, "[opacity:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 ratio = mystoi(sf.next(""), 0, 255); core::dimension2d dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) for (u32 x = 0; x < dim.Width; x++) { video::SColor c = baseimg->getPixel(x, y); c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5)); baseimg->setPixel(x, y, c); } } /* [invert:mode Inverts the given channels of the base image. Mode may contain the characters "r", "g", "b", "a". Only the channels that are mentioned in the mode string will be inverted. */ else if (str_starts_with(part_of_name, "[invert:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); std::string mode = sf.next(""); u32 mask = 0; if (mode.find("a") != std::string::npos) mask |= 0xff000000UL; if (mode.find("r") != std::string::npos) mask |= 0x00ff0000UL; if (mode.find("g") != std::string::npos) mask |= 0x0000ff00UL; if (mode.find("b") != std::string::npos) mask |= 0x000000ffUL; core::dimension2d dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) for (u32 x = 0; x < dim.Width; x++) { video::SColor c = baseimg->getPixel(x, y); c.color ^= mask; baseimg->setPixel(x, y, c); } } /* [sheet:WxH:X,Y Retrieves a tile at position X,Y (in tiles) from the base image it assumes to be a tilesheet with dimensions W,H (in tiles). */ else if (part_of_name.substr(0,7) == "[sheet:") { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 w0 = stoi(sf.next("x")); u32 h0 = stoi(sf.next(":")); u32 x0 = stoi(sf.next(",")); u32 y0 = stoi(sf.next(":")); core::dimension2d img_dim = baseimg->getDimension(); core::dimension2d tile_dim(v2u32(img_dim) / v2u32(w0, h0)); video::IImage *img = driver->createImage( video::ECF_A8R8G8B8, tile_dim); if (!img) { errorstream << "generateImagePart(): Could not create image " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } img->fill(video::SColor(0,0,0,0)); v2u32 vdim(tile_dim); core::rect rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim); baseimg->copyToWithAlpha(img, v2s32(0), rect, video::SColor(255,255,255,255), NULL); // Replace baseimg baseimg->drop(); baseimg = img; } else { errorstream << "generateImagePart(): Invalid " " modification: \"" << part_of_name << "\"" << std::endl; } } return true; } /* Draw an image on top of an another one, using the alpha channel of the source image This exists because IImage::copyToWithAlpha() doesn't seem to always work. */ static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0=0; y0getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } /* Draw an image on top of an another one, using the alpha channel of the source image; only modify fully opaque pixels in destinaion */ static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0=0; y0getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0) { dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } } // This function has been disabled because it is currently unused. // Feel free to re-enable if you find it handy. #if 0 /* Draw an image on top of an another one, using the specified ratio modify all partially-opaque pixels in the destination. */ static void blit_with_interpolate_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size, int ratio) { for (u32 y0 = 0; y0 < size.Y; y0++) for (u32 x0 = 0; x0 < size.X; x0++) { s32 src_x = src_pos.X + x0; s32 src_y = src_pos.Y + y0; s32 dst_x = dst_pos.X + x0; s32 dst_y = dst_pos.Y + y0; video::SColor src_c = src->getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); if (dst_c.getAlpha() > 0 && src_c.getAlpha() != 0) { if (ratio == -1) dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); else dst_c = src_c.getInterpolated(dst_c, (float)ratio/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } } #endif /* Apply color to destination */ static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color, int ratio, bool keep_alpha) { u32 alpha = color.getAlpha(); video::SColor dst_c; if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha dst_c = color; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { u32 dst_alpha = dst->getPixel(x, y).getAlpha(); if (dst_alpha > 0) { dst_c.setAlpha(dst_alpha * alpha / 255); dst->setPixel(x, y, dst_c); } } } else { // replace the color including the alpha for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) if (dst->getPixel(x, y).getAlpha() > 0) dst->setPixel(x, y, color); } } else { // interpolate between the color and destination float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f); for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { dst_c = dst->getPixel(x, y); if (dst_c.getAlpha() > 0) { dst_c = color.getInterpolated(dst_c, interp); dst->setPixel(x, y, dst_c); } } } } /* Apply color to destination */ static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color) { video::SColor dst_c; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { dst_c = dst->getPixel(x, y); dst_c.set( dst_c.getAlpha(), (dst_c.getRed() * color.getRed()) / 255, (dst_c.getGreen() * color.getGreen()) / 255, (dst_c.getBlue() * color.getBlue()) / 255 ); dst->setPixel(x, y, dst_c); } } /* Apply mask to destination */ static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0 = 0; y0 < size.Y; y0++) { for (u32 x0 = 0; x0 < size.X; x0++) { s32 mask_x = x0 + mask_pos.X; s32 mask_y = y0 + mask_pos.Y; s32 dst_x = x0 + dst_pos.X; s32 dst_y = y0 + dst_pos.Y; video::SColor mask_c = mask->getPixel(mask_x, mask_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); dst_c.color &= mask_c.color; dst->setPixel(dst_x, dst_y, dst_c); } } } static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, s32 frame_count, s32 progression, video::IVideoDriver *driver) { // Dimension of destination image core::dimension2d dim_dst = dst->getDimension(); // Dimension of original image core::dimension2d dim_crack = crack->getDimension(); // Count of crack stages s32 crack_count = dim_crack.Height / dim_crack.Width; // Limit frame_count if (frame_count > (s32) dim_dst.Height) frame_count = dim_dst.Height; if (frame_count < 1) frame_count = 1; // Limit progression if (progression > crack_count-1) progression = crack_count-1; // Dimension of a single crack stage core::dimension2d dim_crack_cropped( dim_crack.Width, dim_crack.Width ); // Dimension of the scaled crack stage, // which is the same as the dimension of a single destination frame core::dimension2d dim_crack_scaled( dim_dst.Width, dim_dst.Height / frame_count ); // Create cropped and scaled crack images video::IImage *crack_cropped = driver->createImage( video::ECF_A8R8G8B8, dim_crack_cropped); video::IImage *crack_scaled = driver->createImage( video::ECF_A8R8G8B8, dim_crack_scaled); if (crack_cropped && crack_scaled) { // Crop crack image v2s32 pos_crack(0, progression*dim_crack.Width); crack->copyTo(crack_cropped, v2s32(0,0), core::rect(pos_crack, dim_crack_cropped)); // Scale crack image by copying crack_cropped->copyToScaling(crack_scaled); // Copy or overlay crack image onto each frame for (s32 i = 0; i < frame_count; ++i) { v2s32 dst_pos(0, dim_crack_scaled.Height * i); if (use_overlay) { blit_with_alpha_overlay(crack_scaled, dst, v2s32(0,0), dst_pos, dim_crack_scaled); } else { blit_with_alpha(crack_scaled, dst, v2s32(0,0), dst_pos, dim_crack_scaled); } } } if (crack_scaled) crack_scaled->drop(); if (crack_cropped) crack_cropped->drop(); } void brighten(video::IImage *image) { if (image == NULL) return; core::dimension2d dim = image->getDimension(); for (u32 y=0; ygetPixel(x,y); c.setRed(0.5 * 255 + 0.5 * (float)c.getRed()); c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen()); c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue()); image->setPixel(x,y,c); } } u32 parseImageTransform(const std::string& s) { int total_transform = 0; std::string transform_names[8]; transform_names[0] = "i"; transform_names[1] = "r90"; transform_names[2] = "r180"; transform_names[3] = "r270"; transform_names[4] = "fx"; transform_names[6] = "fy"; std::size_t pos = 0; while(pos < s.size()) { int transform = -1; for (int i = 0; i <= 7; ++i) { const std::string &name_i = transform_names[i]; if (s[pos] == ('0' + i)) { transform = i; pos++; break; } else if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) { transform = i; pos += name_i.size(); break; } } if (transform < 0) break; // Multiply total_transform and transform in the group D4 int new_total = 0; if (transform < 4) new_total = (transform + total_transform) % 4; else new_total = (transform - total_transform + 8) % 4; if ((transform >= 4) ^ (total_transform >= 4)) new_total += 4; total_transform = new_total; } return total_transform; } core::dimension2d imageTransformDimension(u32 transform, core::dimension2d dim) { if (transform % 2 == 0) return dim; else return core::dimension2d(dim.Height, dim.Width); } void imageTransform(u32 transform, video::IImage *src, video::IImage *dst) { if (src == NULL || dst == NULL) return; core::dimension2d dstdim = dst->getDimension(); // Pre-conditions assert(dstdim == imageTransformDimension(transform, src->getDimension())); assert(transform <= 7); /* Compute the transformation from source coordinates (sx,sy) to destination coordinates (dx,dy). */ int sxn = 0; int syn = 2; if (transform == 0) // identity sxn = 0, syn = 2; // sx = dx, sy = dy else if (transform == 1) // rotate by 90 degrees ccw sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx else if (transform == 2) // rotate by 180 degrees sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy else if (transform == 3) // rotate by 270 degrees ccw sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx else if (transform == 4) // flip x sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy else if (transform == 5) // flip x then rotate by 90 degrees ccw sxn = 2, syn = 0; // sx = dy, sy = dx else if (transform == 6) // flip y sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy else if (transform == 7) // flip y then rotate by 90 degrees ccw sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx for (u32 dy=0; dygetPixel(sx,sy); dst->setPixel(dx,dy,c); } } video::ITexture* TextureSource::getNormalTexture(const std::string &name) { if (isKnownSourceImage("override_normal.png")) return getTexture("override_normal.png"); std::string fname_base = name; std::string normal_ext = "_normal.png"; size_t pos = fname_base.find("."); std::string fname_normal = fname_base.substr(0, pos) + normal_ext; if (isKnownSourceImage(fname_normal)) { // look for image extension and replace it size_t i = 0; while ((i = fname_base.find(".", i)) != std::string::npos) { fname_base.replace(i, 4, normal_ext); i += normal_ext.length(); } return getTexture(fname_base); } return NULL; } video::SColor TextureSource::getTextureAverageColor(const std::string &name) { video::IVideoDriver *driver = m_device->getVideoDriver(); video::SColor c(0, 0, 0, 0); video::ITexture *texture = getTexture(name); video::IImage *image = driver->createImage(texture, core::position2d(0, 0), texture->getOriginalSize()); u32 total = 0; u32 tR = 0; u32 tG = 0; u32 tB = 0; core::dimension2d dim = image->getDimension(); u16 step = 1; if (dim.Width > 16) step = dim.Width / 16; for (u16 x = 0; x < dim.Width; x += step) { for (u16 y = 0; y < dim.Width; y += step) { c = image->getPixel(x,y); if (c.getAlpha() > 0) { total++; tR += c.getRed(); tG += c.getGreen(); tB += c.getBlue(); } } } image->drop(); if (total > 0) { c.setRed(tR / total); c.setGreen(tG / total); c.setBlue(tB / total); } c.setAlpha(255); return c; } video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present) { std::string tname = "__shaderFlagsTexture"; tname += normalmap_present ? "1" : "0"; if (isKnownSourceImage(tname)) { return getTexture(tname); } else { video::IVideoDriver *driver = m_device->getVideoDriver(); video::IImage *flags_image = driver->createImage( video::ECF_A8R8G8B8, core::dimension2d(1, 1)); sanity_check(flags_image != NULL); video::SColor c(255, normalmap_present ? 255 : 0, 0, 0); flags_image->setPixel(0, 0, c); insertSourceImage(tname, flags_image); flags_image->drop(); return getTexture(tname); } }