tile.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "tile.h"
  17. #include <ICameraSceneNode.h>
  18. #include "util/string.h"
  19. #include "util/container.h"
  20. #include "util/thread.h"
  21. #include "filesys.h"
  22. #include "settings.h"
  23. #include "mesh.h"
  24. #include "gamedef.h"
  25. #include "util/strfnd.h"
  26. #include "imagefilters.h"
  27. #include "guiscalingfilter.h"
  28. #include "renderingengine.h"
  29. #ifdef __ANDROID__
  30. #include <GLES/gl.h>
  31. #endif
  32. /*
  33. A cache from texture name to texture path
  34. */
  35. MutexedMap<std::string, std::string> g_texturename_to_path_cache;
  36. /*
  37. Replaces the filename extension.
  38. eg:
  39. std::string image = "a/image.png"
  40. replace_ext(image, "jpg")
  41. -> image = "a/image.jpg"
  42. Returns true on success.
  43. */
  44. static bool replace_ext(std::string &path, const char *ext)
  45. {
  46. if (ext == NULL)
  47. return false;
  48. // Find place of last dot, fail if \ or / found.
  49. s32 last_dot_i = -1;
  50. for (s32 i=path.size()-1; i>=0; i--)
  51. {
  52. if (path[i] == '.')
  53. {
  54. last_dot_i = i;
  55. break;
  56. }
  57. if (path[i] == '\\' || path[i] == '/')
  58. break;
  59. }
  60. // If not found, return an empty string
  61. if (last_dot_i == -1)
  62. return false;
  63. // Else make the new path
  64. path = path.substr(0, last_dot_i+1) + ext;
  65. return true;
  66. }
  67. /*
  68. Find out the full path of an image by trying different filename
  69. extensions.
  70. If failed, return "".
  71. */
  72. std::string getImagePath(std::string path)
  73. {
  74. // A NULL-ended list of possible image extensions
  75. const char *extensions[] = {
  76. "png", "jpg", "bmp", "tga",
  77. "pcx", "ppm", "psd", "wal", "rgb",
  78. NULL
  79. };
  80. // If there is no extension, add one
  81. if (removeStringEnd(path, extensions).empty())
  82. path = path + ".png";
  83. // Check paths until something is found to exist
  84. const char **ext = extensions;
  85. do{
  86. bool r = replace_ext(path, *ext);
  87. if (!r)
  88. return "";
  89. if (fs::PathExists(path))
  90. return path;
  91. }
  92. while((++ext) != NULL);
  93. return "";
  94. }
  95. /*
  96. Gets the path to a texture by first checking if the texture exists
  97. in texture_path and if not, using the data path.
  98. Checks all supported extensions by replacing the original extension.
  99. If not found, returns "".
  100. Utilizes a thread-safe cache.
  101. */
  102. std::string getTexturePath(const std::string &filename)
  103. {
  104. std::string fullpath;
  105. /*
  106. Check from cache
  107. */
  108. bool incache = g_texturename_to_path_cache.get(filename, &fullpath);
  109. if (incache)
  110. return fullpath;
  111. /*
  112. Check from texture_path
  113. */
  114. for (const auto &path : getTextureDirs()) {
  115. std::string testpath = path + DIR_DELIM + filename;
  116. // Check all filename extensions. Returns "" if not found.
  117. fullpath = getImagePath(testpath);
  118. if (!fullpath.empty())
  119. break;
  120. }
  121. /*
  122. Check from default data directory
  123. */
  124. if (fullpath.empty())
  125. {
  126. std::string base_path = porting::path_share + DIR_DELIM + "textures"
  127. + DIR_DELIM + "base" + DIR_DELIM + "pack";
  128. std::string testpath = base_path + DIR_DELIM + filename;
  129. // Check all filename extensions. Returns "" if not found.
  130. fullpath = getImagePath(testpath);
  131. }
  132. // Add to cache (also an empty result is cached)
  133. g_texturename_to_path_cache.set(filename, fullpath);
  134. // Finally return it
  135. return fullpath;
  136. }
  137. void clearTextureNameCache()
  138. {
  139. g_texturename_to_path_cache.clear();
  140. }
  141. /*
  142. Stores internal information about a texture.
  143. */
  144. struct TextureInfo
  145. {
  146. std::string name;
  147. video::ITexture *texture;
  148. TextureInfo(
  149. const std::string &name_,
  150. video::ITexture *texture_=NULL
  151. ):
  152. name(name_),
  153. texture(texture_)
  154. {
  155. }
  156. };
  157. /*
  158. SourceImageCache: A cache used for storing source images.
  159. */
  160. class SourceImageCache
  161. {
  162. public:
  163. ~SourceImageCache() {
  164. for (auto &m_image : m_images) {
  165. m_image.second->drop();
  166. }
  167. m_images.clear();
  168. }
  169. void insert(const std::string &name, video::IImage *img, bool prefer_local)
  170. {
  171. assert(img); // Pre-condition
  172. // Remove old image
  173. std::map<std::string, video::IImage*>::iterator n;
  174. n = m_images.find(name);
  175. if (n != m_images.end()){
  176. if (n->second)
  177. n->second->drop();
  178. }
  179. video::IImage* toadd = img;
  180. bool need_to_grab = true;
  181. // Try to use local texture instead if asked to
  182. if (prefer_local){
  183. std::string path = getTexturePath(name);
  184. if (!path.empty()) {
  185. video::IImage *img2 = RenderingEngine::get_video_driver()->
  186. createImageFromFile(path.c_str());
  187. if (img2){
  188. toadd = img2;
  189. need_to_grab = false;
  190. }
  191. }
  192. }
  193. if (need_to_grab)
  194. toadd->grab();
  195. m_images[name] = toadd;
  196. }
  197. video::IImage* get(const std::string &name)
  198. {
  199. std::map<std::string, video::IImage*>::iterator n;
  200. n = m_images.find(name);
  201. if (n != m_images.end())
  202. return n->second;
  203. return NULL;
  204. }
  205. // Primarily fetches from cache, secondarily tries to read from filesystem
  206. video::IImage *getOrLoad(const std::string &name)
  207. {
  208. std::map<std::string, video::IImage*>::iterator n;
  209. n = m_images.find(name);
  210. if (n != m_images.end()){
  211. n->second->grab(); // Grab for caller
  212. return n->second;
  213. }
  214. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  215. std::string path = getTexturePath(name);
  216. if (path.empty()) {
  217. infostream<<"SourceImageCache::getOrLoad(): No path found for \""
  218. <<name<<"\""<<std::endl;
  219. return NULL;
  220. }
  221. infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path
  222. <<"\""<<std::endl;
  223. video::IImage *img = driver->createImageFromFile(path.c_str());
  224. if (img){
  225. m_images[name] = img;
  226. img->grab(); // Grab for caller
  227. }
  228. return img;
  229. }
  230. private:
  231. std::map<std::string, video::IImage*> m_images;
  232. };
  233. /*
  234. TextureSource
  235. */
  236. class TextureSource : public IWritableTextureSource
  237. {
  238. public:
  239. TextureSource();
  240. virtual ~TextureSource();
  241. /*
  242. Example case:
  243. Now, assume a texture with the id 1 exists, and has the name
  244. "stone.png^mineral1".
  245. Then a random thread calls getTextureId for a texture called
  246. "stone.png^mineral1^crack0".
  247. ...Now, WTF should happen? Well:
  248. - getTextureId strips off stuff recursively from the end until
  249. the remaining part is found, or nothing is left when
  250. something is stripped out
  251. But it is slow to search for textures by names and modify them
  252. like that?
  253. - ContentFeatures is made to contain ids for the basic plain
  254. textures
  255. - Crack textures can be slow by themselves, but the framework
  256. must be fast.
  257. Example case #2:
  258. - Assume a texture with the id 1 exists, and has the name
  259. "stone.png^mineral_coal.png".
  260. - Now getNodeTile() stumbles upon a node which uses
  261. texture id 1, and determines that MATERIAL_FLAG_CRACK
  262. must be applied to the tile
  263. - MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and
  264. has received the current crack level 0 from the client. It
  265. finds out the name of the texture with getTextureName(1),
  266. appends "^crack0" to it and gets a new texture id with
  267. getTextureId("stone.png^mineral_coal.png^crack0").
  268. */
  269. /*
  270. Gets a texture id from cache or
  271. - if main thread, generates the texture, adds to cache and returns id.
  272. - if other thread, adds to request queue and waits for main thread.
  273. The id 0 points to a NULL texture. It is returned in case of error.
  274. */
  275. u32 getTextureId(const std::string &name);
  276. // Finds out the name of a cached texture.
  277. std::string getTextureName(u32 id);
  278. /*
  279. If texture specified by the name pointed by the id doesn't
  280. exist, create it, then return the cached texture.
  281. Can be called from any thread. If called from some other thread
  282. and not found in cache, the call is queued to the main thread
  283. for processing.
  284. */
  285. video::ITexture* getTexture(u32 id);
  286. video::ITexture* getTexture(const std::string &name, u32 *id = NULL);
  287. /*
  288. Get a texture specifically intended for mesh
  289. application, i.e. not HUD, compositing, or other 2D
  290. use. This texture may be a different size and may
  291. have had additional filters applied.
  292. */
  293. video::ITexture* getTextureForMesh(const std::string &name, u32 *id);
  294. virtual Palette* getPalette(const std::string &name);
  295. bool isKnownSourceImage(const std::string &name)
  296. {
  297. bool is_known = false;
  298. bool cache_found = m_source_image_existence.get(name, &is_known);
  299. if (cache_found)
  300. return is_known;
  301. // Not found in cache; find out if a local file exists
  302. is_known = (!getTexturePath(name).empty());
  303. m_source_image_existence.set(name, is_known);
  304. return is_known;
  305. }
  306. // Processes queued texture requests from other threads.
  307. // Shall be called from the main thread.
  308. void processQueue();
  309. // Insert an image into the cache without touching the filesystem.
  310. // Shall be called from the main thread.
  311. void insertSourceImage(const std::string &name, video::IImage *img);
  312. // Rebuild images and textures from the current set of source images
  313. // Shall be called from the main thread.
  314. void rebuildImagesAndTextures();
  315. // Render a mesh to a texture.
  316. // Returns NULL if render-to-texture failed.
  317. // Shall be called from the main thread.
  318. video::ITexture* generateTextureFromMesh(
  319. const TextureFromMeshParams &params);
  320. video::ITexture* getNormalTexture(const std::string &name);
  321. video::SColor getTextureAverageColor(const std::string &name);
  322. video::ITexture *getShaderFlagsTexture(bool normamap_present);
  323. private:
  324. // The id of the thread that is allowed to use irrlicht directly
  325. std::thread::id m_main_thread;
  326. // Cache of source images
  327. // This should be only accessed from the main thread
  328. SourceImageCache m_sourcecache;
  329. // Generate a texture
  330. u32 generateTexture(const std::string &name);
  331. // Generate image based on a string like "stone.png" or "[crack:1:0".
  332. // if baseimg is NULL, it is created. Otherwise stuff is made on it.
  333. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg);
  334. /*! Generates an image from a full string like
  335. * "stone.png^mineral_coal.png^[crack:1:0".
  336. * Shall be called from the main thread.
  337. * The returned Image should be dropped.
  338. */
  339. video::IImage* generateImage(const std::string &name);
  340. // Thread-safe cache of what source images are known (true = known)
  341. MutexedMap<std::string, bool> m_source_image_existence;
  342. // A texture id is index in this array.
  343. // The first position contains a NULL texture.
  344. std::vector<TextureInfo> m_textureinfo_cache;
  345. // Maps a texture name to an index in the former.
  346. std::map<std::string, u32> m_name_to_id;
  347. // The two former containers are behind this mutex
  348. std::mutex m_textureinfo_cache_mutex;
  349. // Queued texture fetches (to be processed by the main thread)
  350. RequestQueue<std::string, u32, u8, u8> m_get_texture_queue;
  351. // Textures that have been overwritten with other ones
  352. // but can't be deleted because the ITexture* might still be used
  353. std::vector<video::ITexture*> m_texture_trash;
  354. // Maps image file names to loaded palettes.
  355. std::unordered_map<std::string, Palette> m_palettes;
  356. // Cached settings needed for making textures from meshes
  357. bool m_setting_trilinear_filter;
  358. bool m_setting_bilinear_filter;
  359. bool m_setting_anisotropic_filter;
  360. };
  361. IWritableTextureSource *createTextureSource()
  362. {
  363. return new TextureSource();
  364. }
  365. TextureSource::TextureSource()
  366. {
  367. m_main_thread = std::this_thread::get_id();
  368. // Add a NULL TextureInfo as the first index, named ""
  369. m_textureinfo_cache.emplace_back("");
  370. m_name_to_id[""] = 0;
  371. // Cache some settings
  372. // Note: Since this is only done once, the game must be restarted
  373. // for these settings to take effect
  374. m_setting_trilinear_filter = g_settings->getBool("trilinear_filter");
  375. m_setting_bilinear_filter = g_settings->getBool("bilinear_filter");
  376. m_setting_anisotropic_filter = g_settings->getBool("anisotropic_filter");
  377. }
  378. TextureSource::~TextureSource()
  379. {
  380. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  381. unsigned int textures_before = driver->getTextureCount();
  382. for (const auto &iter : m_textureinfo_cache) {
  383. //cleanup texture
  384. if (iter.texture)
  385. driver->removeTexture(iter.texture);
  386. }
  387. m_textureinfo_cache.clear();
  388. for (auto t : m_texture_trash) {
  389. //cleanup trashed texture
  390. driver->removeTexture(t);
  391. }
  392. infostream << "~TextureSource() "<< textures_before << "/"
  393. << driver->getTextureCount() << std::endl;
  394. }
  395. u32 TextureSource::getTextureId(const std::string &name)
  396. {
  397. //infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;
  398. {
  399. /*
  400. See if texture already exists
  401. */
  402. MutexAutoLock lock(m_textureinfo_cache_mutex);
  403. std::map<std::string, u32>::iterator n;
  404. n = m_name_to_id.find(name);
  405. if (n != m_name_to_id.end())
  406. {
  407. return n->second;
  408. }
  409. }
  410. /*
  411. Get texture
  412. */
  413. if (std::this_thread::get_id() == m_main_thread) {
  414. return generateTexture(name);
  415. }
  416. infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
  417. // We're gonna ask the result to be put into here
  418. static ResultQueue<std::string, u32, u8, u8> result_queue;
  419. // Throw a request in
  420. m_get_texture_queue.add(name, 0, 0, &result_queue);
  421. try {
  422. while(true) {
  423. // Wait result for a second
  424. GetResult<std::string, u32, u8, u8>
  425. result = result_queue.pop_front(1000);
  426. if (result.key == name) {
  427. return result.item;
  428. }
  429. }
  430. } catch(ItemNotFoundException &e) {
  431. errorstream << "Waiting for texture " << name << " timed out." << std::endl;
  432. return 0;
  433. }
  434. infostream << "getTextureId(): Failed" << std::endl;
  435. return 0;
  436. }
  437. // Draw an image on top of an another one, using the alpha channel of the
  438. // source image
  439. static void blit_with_alpha(video::IImage *src, video::IImage *dst,
  440. v2s32 src_pos, v2s32 dst_pos, v2u32 size);
  441. // Like blit_with_alpha, but only modifies destination pixels that
  442. // are fully opaque
  443. static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
  444. v2s32 src_pos, v2s32 dst_pos, v2u32 size);
  445. // Apply a color to an image. Uses an int (0-255) to calculate the ratio.
  446. // If the ratio is 255 or -1 and keep_alpha is true, then it multiples the
  447. // color alpha with the destination alpha.
  448. // Otherwise, any pixels that are not fully transparent get the color alpha.
  449. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  450. const video::SColor &color, int ratio, bool keep_alpha);
  451. // paint a texture using the given color
  452. static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  453. const video::SColor &color);
  454. // Apply a mask to an image
  455. static void apply_mask(video::IImage *mask, video::IImage *dst,
  456. v2s32 mask_pos, v2s32 dst_pos, v2u32 size);
  457. // Draw or overlay a crack
  458. static void draw_crack(video::IImage *crack, video::IImage *dst,
  459. bool use_overlay, s32 frame_count, s32 progression,
  460. video::IVideoDriver *driver, u8 tiles = 1);
  461. // Brighten image
  462. void brighten(video::IImage *image);
  463. // Parse a transform name
  464. u32 parseImageTransform(const std::string& s);
  465. // Apply transform to image dimension
  466. core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim);
  467. // Apply transform to image data
  468. void imageTransform(u32 transform, video::IImage *src, video::IImage *dst);
  469. /*
  470. This method generates all the textures
  471. */
  472. u32 TextureSource::generateTexture(const std::string &name)
  473. {
  474. //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl;
  475. // Empty name means texture 0
  476. if (name.empty()) {
  477. infostream<<"generateTexture(): name is empty"<<std::endl;
  478. return 0;
  479. }
  480. {
  481. /*
  482. See if texture already exists
  483. */
  484. MutexAutoLock lock(m_textureinfo_cache_mutex);
  485. std::map<std::string, u32>::iterator n;
  486. n = m_name_to_id.find(name);
  487. if (n != m_name_to_id.end()) {
  488. return n->second;
  489. }
  490. }
  491. /*
  492. Calling only allowed from main thread
  493. */
  494. if (std::this_thread::get_id() != m_main_thread) {
  495. errorstream<<"TextureSource::generateTexture() "
  496. "called not from main thread"<<std::endl;
  497. return 0;
  498. }
  499. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  500. sanity_check(driver);
  501. video::IImage *img = generateImage(name);
  502. video::ITexture *tex = NULL;
  503. if (img != NULL) {
  504. #ifdef __ANDROID__
  505. img = Align2Npot2(img, driver);
  506. #endif
  507. // Create texture from resulting image
  508. tex = driver->addTexture(name.c_str(), img);
  509. guiScalingCache(io::path(name.c_str()), driver, img);
  510. img->drop();
  511. }
  512. /*
  513. Add texture to caches (add NULL textures too)
  514. */
  515. MutexAutoLock lock(m_textureinfo_cache_mutex);
  516. u32 id = m_textureinfo_cache.size();
  517. TextureInfo ti(name, tex);
  518. m_textureinfo_cache.push_back(ti);
  519. m_name_to_id[name] = id;
  520. return id;
  521. }
  522. std::string TextureSource::getTextureName(u32 id)
  523. {
  524. MutexAutoLock lock(m_textureinfo_cache_mutex);
  525. if (id >= m_textureinfo_cache.size())
  526. {
  527. errorstream<<"TextureSource::getTextureName(): id="<<id
  528. <<" >= m_textureinfo_cache.size()="
  529. <<m_textureinfo_cache.size()<<std::endl;
  530. return "";
  531. }
  532. return m_textureinfo_cache[id].name;
  533. }
  534. video::ITexture* TextureSource::getTexture(u32 id)
  535. {
  536. MutexAutoLock lock(m_textureinfo_cache_mutex);
  537. if (id >= m_textureinfo_cache.size())
  538. return NULL;
  539. return m_textureinfo_cache[id].texture;
  540. }
  541. video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id)
  542. {
  543. u32 actual_id = getTextureId(name);
  544. if (id){
  545. *id = actual_id;
  546. }
  547. return getTexture(actual_id);
  548. }
  549. video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id)
  550. {
  551. return getTexture(name + "^[applyfiltersformesh", id);
  552. }
  553. Palette* TextureSource::getPalette(const std::string &name)
  554. {
  555. // Only the main thread may load images
  556. sanity_check(std::this_thread::get_id() == m_main_thread);
  557. if (name.empty())
  558. return NULL;
  559. auto it = m_palettes.find(name);
  560. if (it == m_palettes.end()) {
  561. // Create palette
  562. video::IImage *img = generateImage(name);
  563. if (!img) {
  564. warningstream << "TextureSource::getPalette(): palette \"" << name
  565. << "\" could not be loaded." << std::endl;
  566. return NULL;
  567. }
  568. Palette new_palette;
  569. u32 w = img->getDimension().Width;
  570. u32 h = img->getDimension().Height;
  571. // Real area of the image
  572. u32 area = h * w;
  573. if (area == 0)
  574. return NULL;
  575. if (area > 256) {
  576. warningstream << "TextureSource::getPalette(): the specified"
  577. << " palette image \"" << name << "\" is larger than 256"
  578. << " pixels, using the first 256." << std::endl;
  579. area = 256;
  580. } else if (256 % area != 0)
  581. warningstream << "TextureSource::getPalette(): the "
  582. << "specified palette image \"" << name << "\" does not "
  583. << "contain power of two pixels." << std::endl;
  584. // We stretch the palette so it will fit 256 values
  585. // This many param2 values will have the same color
  586. u32 step = 256 / area;
  587. // For each pixel in the image
  588. for (u32 i = 0; i < area; i++) {
  589. video::SColor c = img->getPixel(i % w, i / w);
  590. // Fill in palette with 'step' colors
  591. for (u32 j = 0; j < step; j++)
  592. new_palette.push_back(c);
  593. }
  594. img->drop();
  595. // Fill in remaining elements
  596. while (new_palette.size() < 256)
  597. new_palette.emplace_back(0xFFFFFFFF);
  598. m_palettes[name] = new_palette;
  599. it = m_palettes.find(name);
  600. }
  601. if (it != m_palettes.end())
  602. return &((*it).second);
  603. return NULL;
  604. }
  605. void TextureSource::processQueue()
  606. {
  607. /*
  608. Fetch textures
  609. */
  610. //NOTE this is only thread safe for ONE consumer thread!
  611. if (!m_get_texture_queue.empty())
  612. {
  613. GetRequest<std::string, u32, u8, u8>
  614. request = m_get_texture_queue.pop();
  615. /*infostream<<"TextureSource::processQueue(): "
  616. <<"got texture request with "
  617. <<"name=\""<<request.key<<"\""
  618. <<std::endl;*/
  619. m_get_texture_queue.pushResult(request, generateTexture(request.key));
  620. }
  621. }
  622. void TextureSource::insertSourceImage(const std::string &name, video::IImage *img)
  623. {
  624. //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
  625. sanity_check(std::this_thread::get_id() == m_main_thread);
  626. m_sourcecache.insert(name, img, true);
  627. m_source_image_existence.set(name, true);
  628. }
  629. void TextureSource::rebuildImagesAndTextures()
  630. {
  631. MutexAutoLock lock(m_textureinfo_cache_mutex);
  632. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  633. sanity_check(driver);
  634. // Recreate textures
  635. for (TextureInfo &ti : m_textureinfo_cache) {
  636. video::IImage *img = generateImage(ti.name);
  637. #ifdef __ANDROID__
  638. img = Align2Npot2(img, driver);
  639. #endif
  640. // Create texture from resulting image
  641. video::ITexture *t = NULL;
  642. if (img) {
  643. t = driver->addTexture(ti.name.c_str(), img);
  644. guiScalingCache(io::path(ti.name.c_str()), driver, img);
  645. img->drop();
  646. }
  647. video::ITexture *t_old = ti.texture;
  648. // Replace texture
  649. ti.texture = t;
  650. if (t_old)
  651. m_texture_trash.push_back(t_old);
  652. }
  653. }
  654. video::ITexture* TextureSource::generateTextureFromMesh(
  655. const TextureFromMeshParams &params)
  656. {
  657. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  658. sanity_check(driver);
  659. #ifdef __ANDROID__
  660. const GLubyte* renderstr = glGetString(GL_RENDERER);
  661. std::string renderer((char*) renderstr);
  662. // use no render to texture hack
  663. if (
  664. (renderer.find("Adreno") != std::string::npos) ||
  665. (renderer.find("Mali") != std::string::npos) ||
  666. (renderer.find("Immersion") != std::string::npos) ||
  667. (renderer.find("Tegra") != std::string::npos) ||
  668. g_settings->getBool("inventory_image_hack")
  669. ) {
  670. // Get a scene manager
  671. scene::ISceneManager *smgr_main = RenderingEngine::get_raw_device()->getSceneManager();
  672. sanity_check(smgr_main);
  673. scene::ISceneManager *smgr = smgr_main->createNewSceneManager();
  674. sanity_check(smgr);
  675. const float scaling = 0.2;
  676. scene::IMeshSceneNode* meshnode =
  677. smgr->addMeshSceneNode(params.mesh, NULL,
  678. -1, v3f(0,0,0), v3f(0,0,0),
  679. v3f(1.0 * scaling,1.0 * scaling,1.0 * scaling), true);
  680. meshnode->setMaterialFlag(video::EMF_LIGHTING, true);
  681. meshnode->setMaterialFlag(video::EMF_ANTI_ALIASING, true);
  682. meshnode->setMaterialFlag(video::EMF_TRILINEAR_FILTER, m_setting_trilinear_filter);
  683. meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, m_setting_bilinear_filter);
  684. meshnode->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, m_setting_anisotropic_filter);
  685. scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(0,
  686. params.camera_position, params.camera_lookat);
  687. // second parameter of setProjectionMatrix (isOrthogonal) is ignored
  688. camera->setProjectionMatrix(params.camera_projection_matrix, false);
  689. smgr->setAmbientLight(params.ambient_light);
  690. smgr->addLightSceneNode(0,
  691. params.light_position,
  692. params.light_color,
  693. params.light_radius*scaling);
  694. core::dimension2d<u32> screen = driver->getScreenSize();
  695. // Render scene
  696. driver->beginScene(true, true, video::SColor(0,0,0,0));
  697. driver->clearZBuffer();
  698. smgr->drawAll();
  699. core::dimension2d<u32> partsize(screen.Width * scaling,screen.Height * scaling);
  700. irr::video::IImage* rawImage =
  701. driver->createImage(irr::video::ECF_A8R8G8B8, partsize);
  702. u8* pixels = static_cast<u8*>(rawImage->lock());
  703. if (!pixels)
  704. {
  705. rawImage->drop();
  706. return NULL;
  707. }
  708. core::rect<s32> source(
  709. screen.Width /2 - (screen.Width * (scaling / 2)),
  710. screen.Height/2 - (screen.Height * (scaling / 2)),
  711. screen.Width /2 + (screen.Width * (scaling / 2)),
  712. screen.Height/2 + (screen.Height * (scaling / 2))
  713. );
  714. glReadPixels(source.UpperLeftCorner.X, source.UpperLeftCorner.Y,
  715. partsize.Width, partsize.Height, GL_RGBA,
  716. GL_UNSIGNED_BYTE, pixels);
  717. driver->endScene();
  718. // Drop scene manager
  719. smgr->drop();
  720. unsigned int pixelcount = partsize.Width*partsize.Height;
  721. u8* runptr = pixels;
  722. for (unsigned int i=0; i < pixelcount; i++) {
  723. u8 B = *runptr;
  724. u8 G = *(runptr+1);
  725. u8 R = *(runptr+2);
  726. u8 A = *(runptr+3);
  727. //BGRA -> RGBA
  728. *runptr = R;
  729. runptr ++;
  730. *runptr = G;
  731. runptr ++;
  732. *runptr = B;
  733. runptr ++;
  734. *runptr = A;
  735. runptr ++;
  736. }
  737. video::IImage* inventory_image =
  738. driver->createImage(irr::video::ECF_A8R8G8B8, params.dim);
  739. rawImage->copyToScaling(inventory_image);
  740. rawImage->drop();
  741. guiScalingCache(io::path(params.rtt_texture_name.c_str()), driver, inventory_image);
  742. video::ITexture *rtt = driver->addTexture(params.rtt_texture_name.c_str(), inventory_image);
  743. inventory_image->drop();
  744. if (rtt == NULL) {
  745. errorstream << "TextureSource::generateTextureFromMesh(): failed to recreate texture from image: " << params.rtt_texture_name << std::endl;
  746. return NULL;
  747. }
  748. driver->makeColorKeyTexture(rtt, v2s32(0,0));
  749. if (params.delete_texture_on_shutdown)
  750. m_texture_trash.push_back(rtt);
  751. return rtt;
  752. }
  753. #endif
  754. if (!driver->queryFeature(video::EVDF_RENDER_TO_TARGET)) {
  755. static bool warned = false;
  756. if (!warned)
  757. {
  758. errorstream<<"TextureSource::generateTextureFromMesh(): "
  759. <<"EVDF_RENDER_TO_TARGET not supported."<<std::endl;
  760. warned = true;
  761. }
  762. return NULL;
  763. }
  764. // Create render target texture
  765. video::ITexture *rtt = driver->addRenderTargetTexture(
  766. params.dim, params.rtt_texture_name.c_str(),
  767. video::ECF_A8R8G8B8);
  768. if (rtt == NULL)
  769. {
  770. errorstream<<"TextureSource::generateTextureFromMesh(): "
  771. <<"addRenderTargetTexture returned NULL."<<std::endl;
  772. return NULL;
  773. }
  774. // Set render target
  775. if (!driver->setRenderTarget(rtt, false, true, video::SColor(0,0,0,0))) {
  776. driver->removeTexture(rtt);
  777. errorstream<<"TextureSource::generateTextureFromMesh(): "
  778. <<"failed to set render target"<<std::endl;
  779. return NULL;
  780. }
  781. // Get a scene manager
  782. scene::ISceneManager *smgr_main = RenderingEngine::get_scene_manager();
  783. assert(smgr_main);
  784. scene::ISceneManager *smgr = smgr_main->createNewSceneManager();
  785. assert(smgr);
  786. scene::IMeshSceneNode* meshnode =
  787. smgr->addMeshSceneNode(params.mesh, NULL,
  788. -1, v3f(0,0,0), v3f(0,0,0), v3f(1,1,1), true);
  789. meshnode->setMaterialFlag(video::EMF_LIGHTING, true);
  790. meshnode->setMaterialFlag(video::EMF_ANTI_ALIASING, true);
  791. meshnode->setMaterialFlag(video::EMF_TRILINEAR_FILTER, m_setting_trilinear_filter);
  792. meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, m_setting_bilinear_filter);
  793. meshnode->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, m_setting_anisotropic_filter);
  794. scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(0,
  795. params.camera_position, params.camera_lookat);
  796. // second parameter of setProjectionMatrix (isOrthogonal) is ignored
  797. camera->setProjectionMatrix(params.camera_projection_matrix, false);
  798. smgr->setAmbientLight(params.ambient_light);
  799. smgr->addLightSceneNode(0,
  800. params.light_position,
  801. params.light_color,
  802. params.light_radius);
  803. // Render scene
  804. driver->beginScene(true, true, video::SColor(0,0,0,0));
  805. smgr->drawAll();
  806. driver->endScene();
  807. // Drop scene manager
  808. smgr->drop();
  809. // Unset render target
  810. driver->setRenderTarget(0, false, true, video::SColor(0,0,0,0));
  811. if (params.delete_texture_on_shutdown)
  812. m_texture_trash.push_back(rtt);
  813. return rtt;
  814. }
  815. video::IImage* TextureSource::generateImage(const std::string &name)
  816. {
  817. // Get the base image
  818. const char separator = '^';
  819. const char escape = '\\';
  820. const char paren_open = '(';
  821. const char paren_close = ')';
  822. // Find last separator in the name
  823. s32 last_separator_pos = -1;
  824. u8 paren_bal = 0;
  825. for (s32 i = name.size() - 1; i >= 0; i--) {
  826. if (i > 0 && name[i-1] == escape)
  827. continue;
  828. switch (name[i]) {
  829. case separator:
  830. if (paren_bal == 0) {
  831. last_separator_pos = i;
  832. i = -1; // break out of loop
  833. }
  834. break;
  835. case paren_open:
  836. if (paren_bal == 0) {
  837. errorstream << "generateImage(): unbalanced parentheses"
  838. << "(extranous '(') while generating texture \""
  839. << name << "\"" << std::endl;
  840. return NULL;
  841. }
  842. paren_bal--;
  843. break;
  844. case paren_close:
  845. paren_bal++;
  846. break;
  847. default:
  848. break;
  849. }
  850. }
  851. if (paren_bal > 0) {
  852. errorstream << "generateImage(): unbalanced parentheses"
  853. << "(missing matching '(') while generating texture \""
  854. << name << "\"" << std::endl;
  855. return NULL;
  856. }
  857. video::IImage *baseimg = NULL;
  858. /*
  859. If separator was found, make the base image
  860. using a recursive call.
  861. */
  862. if (last_separator_pos != -1) {
  863. baseimg = generateImage(name.substr(0, last_separator_pos));
  864. }
  865. /*
  866. Parse out the last part of the name of the image and act
  867. according to it
  868. */
  869. std::string last_part_of_name = name.substr(last_separator_pos + 1);
  870. /*
  871. If this name is enclosed in parentheses, generate it
  872. and blit it onto the base image
  873. */
  874. if (last_part_of_name[0] == paren_open
  875. && last_part_of_name[last_part_of_name.size() - 1] == paren_close) {
  876. std::string name2 = last_part_of_name.substr(1,
  877. last_part_of_name.size() - 2);
  878. video::IImage *tmp = generateImage(name2);
  879. if (!tmp) {
  880. errorstream << "generateImage(): "
  881. "Failed to generate \"" << name2 << "\""
  882. << std::endl;
  883. return NULL;
  884. }
  885. core::dimension2d<u32> dim = tmp->getDimension();
  886. if (baseimg) {
  887. blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim);
  888. tmp->drop();
  889. } else {
  890. baseimg = tmp;
  891. }
  892. } else if (!generateImagePart(last_part_of_name, baseimg)) {
  893. // Generate image according to part of name
  894. errorstream << "generateImage(): "
  895. "Failed to generate \"" << last_part_of_name << "\""
  896. << std::endl;
  897. }
  898. // If no resulting image, print a warning
  899. if (baseimg == NULL) {
  900. errorstream << "generateImage(): baseimg is NULL (attempted to"
  901. " create texture \"" << name << "\")" << std::endl;
  902. }
  903. return baseimg;
  904. }
  905. #ifdef __ANDROID__
  906. #include <GLES/gl.h>
  907. /**
  908. * Check and align image to npot2 if required by hardware
  909. * @param image image to check for npot2 alignment
  910. * @param driver driver to use for image operations
  911. * @return image or copy of image aligned to npot2
  912. */
  913. inline u16 get_GL_major_version()
  914. {
  915. const GLubyte *gl_version = glGetString(GL_VERSION);
  916. return (u16) (gl_version[0] - '0');
  917. }
  918. video::IImage * Align2Npot2(video::IImage * image,
  919. video::IVideoDriver* driver)
  920. {
  921. if (image == NULL) {
  922. return image;
  923. }
  924. core::dimension2d<u32> dim = image->getDimension();
  925. std::string extensions = (char*) glGetString(GL_EXTENSIONS);
  926. // Only GLES2 is trusted to correctly report npot support
  927. if (get_GL_major_version() > 1 &&
  928. extensions.find("GL_OES_texture_npot") != std::string::npos) {
  929. return image;
  930. }
  931. unsigned int height = npot2(dim.Height);
  932. unsigned int width = npot2(dim.Width);
  933. if ((dim.Height == height) &&
  934. (dim.Width == width)) {
  935. return image;
  936. }
  937. if (dim.Height > height) {
  938. height *= 2;
  939. }
  940. if (dim.Width > width) {
  941. width *= 2;
  942. }
  943. video::IImage *targetimage =
  944. driver->createImage(video::ECF_A8R8G8B8,
  945. core::dimension2d<u32>(width, height));
  946. if (targetimage != NULL) {
  947. image->copyToScaling(targetimage);
  948. }
  949. image->drop();
  950. return targetimage;
  951. }
  952. #endif
  953. static std::string unescape_string(const std::string &str, const char esc = '\\')
  954. {
  955. std::string out;
  956. size_t pos = 0, cpos;
  957. out.reserve(str.size());
  958. while (1) {
  959. cpos = str.find_first_of(esc, pos);
  960. if (cpos == std::string::npos) {
  961. out += str.substr(pos);
  962. break;
  963. }
  964. out += str.substr(pos, cpos - pos) + str[cpos + 1];
  965. pos = cpos + 2;
  966. }
  967. return out;
  968. }
  969. bool TextureSource::generateImagePart(std::string part_of_name,
  970. video::IImage *& baseimg)
  971. {
  972. const char escape = '\\'; // same as in generateImage()
  973. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  974. sanity_check(driver);
  975. // Stuff starting with [ are special commands
  976. if (part_of_name.empty() || part_of_name[0] != '[') {
  977. video::IImage *image = m_sourcecache.getOrLoad(part_of_name);
  978. #ifdef __ANDROID__
  979. image = Align2Npot2(image, driver);
  980. #endif
  981. if (image == NULL) {
  982. if (!part_of_name.empty()) {
  983. // Do not create normalmap dummies
  984. if (part_of_name.find("_normal.png") != std::string::npos) {
  985. warningstream << "generateImage(): Could not load normal map \""
  986. << part_of_name << "\"" << std::endl;
  987. return true;
  988. }
  989. errorstream << "generateImage(): Could not load image \""
  990. << part_of_name << "\" while building texture; "
  991. "Creating a dummy image" << std::endl;
  992. }
  993. // Just create a dummy image
  994. //core::dimension2d<u32> dim(2,2);
  995. core::dimension2d<u32> dim(1,1);
  996. image = driver->createImage(video::ECF_A8R8G8B8, dim);
  997. sanity_check(image != NULL);
  998. /*image->setPixel(0,0, video::SColor(255,255,0,0));
  999. image->setPixel(1,0, video::SColor(255,0,255,0));
  1000. image->setPixel(0,1, video::SColor(255,0,0,255));
  1001. image->setPixel(1,1, video::SColor(255,255,0,255));*/
  1002. image->setPixel(0,0, video::SColor(255,myrand()%256,
  1003. myrand()%256,myrand()%256));
  1004. /*image->setPixel(1,0, video::SColor(255,myrand()%256,
  1005. myrand()%256,myrand()%256));
  1006. image->setPixel(0,1, video::SColor(255,myrand()%256,
  1007. myrand()%256,myrand()%256));
  1008. image->setPixel(1,1, video::SColor(255,myrand()%256,
  1009. myrand()%256,myrand()%256));*/
  1010. }
  1011. // If base image is NULL, load as base.
  1012. if (baseimg == NULL)
  1013. {
  1014. //infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
  1015. /*
  1016. Copy it this way to get an alpha channel.
  1017. Otherwise images with alpha cannot be blitted on
  1018. images that don't have alpha in the original file.
  1019. */
  1020. core::dimension2d<u32> dim = image->getDimension();
  1021. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1022. image->copyTo(baseimg);
  1023. }
  1024. // Else blit on base.
  1025. else
  1026. {
  1027. //infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
  1028. // Size of the copied area
  1029. core::dimension2d<u32> dim = image->getDimension();
  1030. //core::dimension2d<u32> dim(16,16);
  1031. // Position to copy the blitted to in the base image
  1032. core::position2d<s32> pos_to(0,0);
  1033. // Position to copy the blitted from in the blitted image
  1034. core::position2d<s32> pos_from(0,0);
  1035. // Blit
  1036. /*image->copyToWithAlpha(baseimg, pos_to,
  1037. core::rect<s32>(pos_from, dim),
  1038. video::SColor(255,255,255,255),
  1039. NULL);*/
  1040. core::dimension2d<u32> dim_dst = baseimg->getDimension();
  1041. if (dim == dim_dst) {
  1042. blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
  1043. } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) {
  1044. // Upscale overlying image
  1045. video::IImage *scaled_image = RenderingEngine::get_video_driver()->
  1046. createImage(video::ECF_A8R8G8B8, dim_dst);
  1047. image->copyToScaling(scaled_image);
  1048. blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, dim_dst);
  1049. scaled_image->drop();
  1050. } else {
  1051. // Upscale base image
  1052. video::IImage *scaled_base = RenderingEngine::get_video_driver()->
  1053. createImage(video::ECF_A8R8G8B8, dim);
  1054. baseimg->copyToScaling(scaled_base);
  1055. baseimg->drop();
  1056. baseimg = scaled_base;
  1057. blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
  1058. }
  1059. }
  1060. //cleanup
  1061. image->drop();
  1062. }
  1063. else
  1064. {
  1065. // A special texture modification
  1066. /*infostream<<"generateImage(): generating special "
  1067. <<"modification \""<<part_of_name<<"\""
  1068. <<std::endl;*/
  1069. /*
  1070. [crack:N:P
  1071. [cracko:N:P
  1072. Adds a cracking texture
  1073. N = animation frame count, P = crack progression
  1074. */
  1075. if (str_starts_with(part_of_name, "[crack"))
  1076. {
  1077. if (baseimg == NULL) {
  1078. errorstream<<"generateImagePart(): baseimg == NULL "
  1079. <<"for part_of_name=\""<<part_of_name
  1080. <<"\", cancelling."<<std::endl;
  1081. return false;
  1082. }
  1083. // Crack image number and overlay option
  1084. // Format: crack[o][:<tiles>]:<frame_count>:<frame>
  1085. bool use_overlay = (part_of_name[6] == 'o');
  1086. Strfnd sf(part_of_name);
  1087. sf.next(":");
  1088. s32 frame_count = stoi(sf.next(":"));
  1089. s32 progression = stoi(sf.next(":"));
  1090. s32 tiles = 1;
  1091. // Check whether there is the <tiles> argument, that is,
  1092. // whether there are 3 arguments. If so, shift values
  1093. // as the first and not the last argument is optional.
  1094. auto s = sf.next(":");
  1095. if (!s.empty()) {
  1096. tiles = frame_count;
  1097. frame_count = progression;
  1098. progression = stoi(s);
  1099. }
  1100. if (progression >= 0) {
  1101. /*
  1102. Load crack image.
  1103. It is an image with a number of cracking stages
  1104. horizontally tiled.
  1105. */
  1106. video::IImage *img_crack = m_sourcecache.getOrLoad(
  1107. "crack_anylength.png");
  1108. if (img_crack) {
  1109. draw_crack(img_crack, baseimg,
  1110. use_overlay, frame_count,
  1111. progression, driver, tiles);
  1112. img_crack->drop();
  1113. }
  1114. }
  1115. }
  1116. /*
  1117. [combine:WxH:X,Y=filename:X,Y=filename2
  1118. Creates a bigger texture from any amount of smaller ones
  1119. */
  1120. else if (str_starts_with(part_of_name, "[combine"))
  1121. {
  1122. Strfnd sf(part_of_name);
  1123. sf.next(":");
  1124. u32 w0 = stoi(sf.next("x"));
  1125. u32 h0 = stoi(sf.next(":"));
  1126. core::dimension2d<u32> dim(w0,h0);
  1127. if (baseimg == NULL) {
  1128. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1129. baseimg->fill(video::SColor(0,0,0,0));
  1130. }
  1131. while (!sf.at_end()) {
  1132. u32 x = stoi(sf.next(","));
  1133. u32 y = stoi(sf.next("="));
  1134. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1135. infostream<<"Adding \""<<filename
  1136. <<"\" to combined ("<<x<<","<<y<<")"
  1137. <<std::endl;
  1138. video::IImage *img = generateImage(filename);
  1139. if (img) {
  1140. core::dimension2d<u32> dim = img->getDimension();
  1141. infostream<<"Size "<<dim.Width
  1142. <<"x"<<dim.Height<<std::endl;
  1143. core::position2d<s32> pos_base(x, y);
  1144. video::IImage *img2 =
  1145. driver->createImage(video::ECF_A8R8G8B8, dim);
  1146. img->copyTo(img2);
  1147. img->drop();
  1148. /*img2->copyToWithAlpha(baseimg, pos_base,
  1149. core::rect<s32>(v2s32(0,0), dim),
  1150. video::SColor(255,255,255,255),
  1151. NULL);*/
  1152. blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim);
  1153. img2->drop();
  1154. } else {
  1155. errorstream << "generateImagePart(): Failed to load image \""
  1156. << filename << "\" for [combine" << std::endl;
  1157. }
  1158. }
  1159. }
  1160. /*
  1161. [brighten
  1162. */
  1163. else if (str_starts_with(part_of_name, "[brighten"))
  1164. {
  1165. if (baseimg == NULL) {
  1166. errorstream<<"generateImagePart(): baseimg==NULL "
  1167. <<"for part_of_name=\""<<part_of_name
  1168. <<"\", cancelling."<<std::endl;
  1169. return false;
  1170. }
  1171. brighten(baseimg);
  1172. }
  1173. /*
  1174. [noalpha
  1175. Make image completely opaque.
  1176. Used for the leaves texture when in old leaves mode, so
  1177. that the transparent parts don't look completely black
  1178. when simple alpha channel is used for rendering.
  1179. */
  1180. else if (str_starts_with(part_of_name, "[noalpha"))
  1181. {
  1182. if (baseimg == NULL){
  1183. errorstream<<"generateImagePart(): baseimg==NULL "
  1184. <<"for part_of_name=\""<<part_of_name
  1185. <<"\", cancelling."<<std::endl;
  1186. return false;
  1187. }
  1188. core::dimension2d<u32> dim = baseimg->getDimension();
  1189. // Set alpha to full
  1190. for (u32 y=0; y<dim.Height; y++)
  1191. for (u32 x=0; x<dim.Width; x++)
  1192. {
  1193. video::SColor c = baseimg->getPixel(x,y);
  1194. c.setAlpha(255);
  1195. baseimg->setPixel(x,y,c);
  1196. }
  1197. }
  1198. /*
  1199. [makealpha:R,G,B
  1200. Convert one color to transparent.
  1201. */
  1202. else if (str_starts_with(part_of_name, "[makealpha:"))
  1203. {
  1204. if (baseimg == NULL) {
  1205. errorstream<<"generateImagePart(): baseimg == NULL "
  1206. <<"for part_of_name=\""<<part_of_name
  1207. <<"\", cancelling."<<std::endl;
  1208. return false;
  1209. }
  1210. Strfnd sf(part_of_name.substr(11));
  1211. u32 r1 = stoi(sf.next(","));
  1212. u32 g1 = stoi(sf.next(","));
  1213. u32 b1 = stoi(sf.next(""));
  1214. core::dimension2d<u32> dim = baseimg->getDimension();
  1215. /*video::IImage *oldbaseimg = baseimg;
  1216. baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
  1217. oldbaseimg->copyTo(baseimg);
  1218. oldbaseimg->drop();*/
  1219. // Set alpha to full
  1220. for (u32 y=0; y<dim.Height; y++)
  1221. for (u32 x=0; x<dim.Width; x++)
  1222. {
  1223. video::SColor c = baseimg->getPixel(x,y);
  1224. u32 r = c.getRed();
  1225. u32 g = c.getGreen();
  1226. u32 b = c.getBlue();
  1227. if (!(r == r1 && g == g1 && b == b1))
  1228. continue;
  1229. c.setAlpha(0);
  1230. baseimg->setPixel(x,y,c);
  1231. }
  1232. }
  1233. /*
  1234. [transformN
  1235. Rotates and/or flips the image.
  1236. N can be a number (between 0 and 7) or a transform name.
  1237. Rotations are counter-clockwise.
  1238. 0 I identity
  1239. 1 R90 rotate by 90 degrees
  1240. 2 R180 rotate by 180 degrees
  1241. 3 R270 rotate by 270 degrees
  1242. 4 FX flip X
  1243. 5 FXR90 flip X then rotate by 90 degrees
  1244. 6 FY flip Y
  1245. 7 FYR90 flip Y then rotate by 90 degrees
  1246. Note: Transform names can be concatenated to produce
  1247. their product (applies the first then the second).
  1248. The resulting transform will be equivalent to one of the
  1249. eight existing ones, though (see: dihedral group).
  1250. */
  1251. else if (str_starts_with(part_of_name, "[transform"))
  1252. {
  1253. if (baseimg == NULL) {
  1254. errorstream<<"generateImagePart(): baseimg == NULL "
  1255. <<"for part_of_name=\""<<part_of_name
  1256. <<"\", cancelling."<<std::endl;
  1257. return false;
  1258. }
  1259. u32 transform = parseImageTransform(part_of_name.substr(10));
  1260. core::dimension2d<u32> dim = imageTransformDimension(
  1261. transform, baseimg->getDimension());
  1262. video::IImage *image = driver->createImage(
  1263. baseimg->getColorFormat(), dim);
  1264. sanity_check(image != NULL);
  1265. imageTransform(transform, baseimg, image);
  1266. baseimg->drop();
  1267. baseimg = image;
  1268. }
  1269. /*
  1270. [inventorycube{topimage{leftimage{rightimage
  1271. In every subimage, replace ^ with &.
  1272. Create an "inventory cube".
  1273. NOTE: This should be used only on its own.
  1274. Example (a grass block (not actually used in game):
  1275. "[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
  1276. */
  1277. else if (str_starts_with(part_of_name, "[inventorycube"))
  1278. {
  1279. if (baseimg != NULL){
  1280. errorstream<<"generateImagePart(): baseimg != NULL "
  1281. <<"for part_of_name=\""<<part_of_name
  1282. <<"\", cancelling."<<std::endl;
  1283. return false;
  1284. }
  1285. str_replace(part_of_name, '&', '^');
  1286. Strfnd sf(part_of_name);
  1287. sf.next("{");
  1288. std::string imagename_top = sf.next("{");
  1289. std::string imagename_left = sf.next("{");
  1290. std::string imagename_right = sf.next("{");
  1291. // Generate images for the faces of the cube
  1292. video::IImage *img_top = generateImage(imagename_top);
  1293. video::IImage *img_left = generateImage(imagename_left);
  1294. video::IImage *img_right = generateImage(imagename_right);
  1295. if (img_top == NULL || img_left == NULL || img_right == NULL) {
  1296. errorstream << "generateImagePart(): Failed to create textures"
  1297. << " for inventorycube \"" << part_of_name << "\""
  1298. << std::endl;
  1299. baseimg = generateImage(imagename_top);
  1300. return true;
  1301. }
  1302. #ifdef __ANDROID__
  1303. assert(img_top->getDimension().Height == npot2(img_top->getDimension().Height));
  1304. assert(img_top->getDimension().Width == npot2(img_top->getDimension().Width));
  1305. assert(img_left->getDimension().Height == npot2(img_left->getDimension().Height));
  1306. assert(img_left->getDimension().Width == npot2(img_left->getDimension().Width));
  1307. assert(img_right->getDimension().Height == npot2(img_right->getDimension().Height));
  1308. assert(img_right->getDimension().Width == npot2(img_right->getDimension().Width));
  1309. #endif
  1310. // Create textures from images
  1311. video::ITexture *texture_top = driver->addTexture(
  1312. (imagename_top + "__temp__").c_str(), img_top);
  1313. video::ITexture *texture_left = driver->addTexture(
  1314. (imagename_left + "__temp__").c_str(), img_left);
  1315. video::ITexture *texture_right = driver->addTexture(
  1316. (imagename_right + "__temp__").c_str(), img_right);
  1317. FATAL_ERROR_IF(!(texture_top && texture_left && texture_right), "");
  1318. // Drop images
  1319. img_top->drop();
  1320. img_left->drop();
  1321. img_right->drop();
  1322. /*
  1323. Draw a cube mesh into a render target texture
  1324. */
  1325. scene::IMesh* cube = createCubeMesh(v3f(1, 1, 1));
  1326. setMeshColor(cube, video::SColor(255, 255, 255, 255));
  1327. cube->getMeshBuffer(0)->getMaterial().setTexture(0, texture_top);
  1328. cube->getMeshBuffer(1)->getMaterial().setTexture(0, texture_top);
  1329. cube->getMeshBuffer(2)->getMaterial().setTexture(0, texture_right);
  1330. cube->getMeshBuffer(3)->getMaterial().setTexture(0, texture_right);
  1331. cube->getMeshBuffer(4)->getMaterial().setTexture(0, texture_left);
  1332. cube->getMeshBuffer(5)->getMaterial().setTexture(0, texture_left);
  1333. TextureFromMeshParams params;
  1334. params.mesh = cube;
  1335. params.dim.set(64, 64);
  1336. params.rtt_texture_name = part_of_name + "_RTT";
  1337. // We will delete the rtt texture ourselves
  1338. params.delete_texture_on_shutdown = false;
  1339. params.camera_position.set(0, 1.0, -1.5);
  1340. params.camera_position.rotateXZBy(45);
  1341. params.camera_lookat.set(0, 0, 0);
  1342. // Set orthogonal projection
  1343. params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
  1344. 1.65, 1.65, 0, 100);
  1345. params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
  1346. params.light_position.set(10, 100, -50);
  1347. params.light_color.set(1.0, 0.5, 0.5, 0.5);
  1348. params.light_radius = 1000;
  1349. video::ITexture *rtt = generateTextureFromMesh(params);
  1350. // Drop mesh
  1351. cube->drop();
  1352. // Free textures
  1353. driver->removeTexture(texture_top);
  1354. driver->removeTexture(texture_left);
  1355. driver->removeTexture(texture_right);
  1356. if (rtt == NULL) {
  1357. baseimg = generateImage(imagename_top);
  1358. return true;
  1359. }
  1360. // Create image of render target
  1361. video::IImage *image = driver->createImage(rtt, v2s32(0, 0), params.dim);
  1362. FATAL_ERROR_IF(!image, "Could not create image of render target");
  1363. // Cleanup texture
  1364. driver->removeTexture(rtt);
  1365. baseimg = driver->createImage(video::ECF_A8R8G8B8, params.dim);
  1366. if (image) {
  1367. image->copyTo(baseimg);
  1368. image->drop();
  1369. }
  1370. }
  1371. /*
  1372. [lowpart:percent:filename
  1373. Adds the lower part of a texture
  1374. */
  1375. else if (str_starts_with(part_of_name, "[lowpart:"))
  1376. {
  1377. Strfnd sf(part_of_name);
  1378. sf.next(":");
  1379. u32 percent = stoi(sf.next(":"));
  1380. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1381. if (baseimg == NULL)
  1382. baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16));
  1383. video::IImage *img = generateImage(filename);
  1384. if (img)
  1385. {
  1386. core::dimension2d<u32> dim = img->getDimension();
  1387. core::position2d<s32> pos_base(0, 0);
  1388. video::IImage *img2 =
  1389. driver->createImage(video::ECF_A8R8G8B8, dim);
  1390. img->copyTo(img2);
  1391. img->drop();
  1392. core::position2d<s32> clippos(0, 0);
  1393. clippos.Y = dim.Height * (100-percent) / 100;
  1394. core::dimension2d<u32> clipdim = dim;
  1395. clipdim.Height = clipdim.Height * percent / 100 + 1;
  1396. core::rect<s32> cliprect(clippos, clipdim);
  1397. img2->copyToWithAlpha(baseimg, pos_base,
  1398. core::rect<s32>(v2s32(0,0), dim),
  1399. video::SColor(255,255,255,255),
  1400. &cliprect);
  1401. img2->drop();
  1402. }
  1403. }
  1404. /*
  1405. [verticalframe:N:I
  1406. Crops a frame of a vertical animation.
  1407. N = frame count, I = frame index
  1408. */
  1409. else if (str_starts_with(part_of_name, "[verticalframe:"))
  1410. {
  1411. Strfnd sf(part_of_name);
  1412. sf.next(":");
  1413. u32 frame_count = stoi(sf.next(":"));
  1414. u32 frame_index = stoi(sf.next(":"));
  1415. if (baseimg == NULL){
  1416. errorstream<<"generateImagePart(): baseimg != NULL "
  1417. <<"for part_of_name=\""<<part_of_name
  1418. <<"\", cancelling."<<std::endl;
  1419. return false;
  1420. }
  1421. v2u32 frame_size = baseimg->getDimension();
  1422. frame_size.Y /= frame_count;
  1423. video::IImage *img = driver->createImage(video::ECF_A8R8G8B8,
  1424. frame_size);
  1425. if (!img){
  1426. errorstream<<"generateImagePart(): Could not create image "
  1427. <<"for part_of_name=\""<<part_of_name
  1428. <<"\", cancelling."<<std::endl;
  1429. return false;
  1430. }
  1431. // Fill target image with transparency
  1432. img->fill(video::SColor(0,0,0,0));
  1433. core::dimension2d<u32> dim = frame_size;
  1434. core::position2d<s32> pos_dst(0, 0);
  1435. core::position2d<s32> pos_src(0, frame_index * frame_size.Y);
  1436. baseimg->copyToWithAlpha(img, pos_dst,
  1437. core::rect<s32>(pos_src, dim),
  1438. video::SColor(255,255,255,255),
  1439. NULL);
  1440. // Replace baseimg
  1441. baseimg->drop();
  1442. baseimg = img;
  1443. }
  1444. /*
  1445. [mask:filename
  1446. Applies a mask to an image
  1447. */
  1448. else if (str_starts_with(part_of_name, "[mask:"))
  1449. {
  1450. if (baseimg == NULL) {
  1451. errorstream << "generateImage(): baseimg == NULL "
  1452. << "for part_of_name=\"" << part_of_name
  1453. << "\", cancelling." << std::endl;
  1454. return false;
  1455. }
  1456. Strfnd sf(part_of_name);
  1457. sf.next(":");
  1458. std::string filename = unescape_string(sf.next_esc(":", escape), escape);
  1459. video::IImage *img = generateImage(filename);
  1460. if (img) {
  1461. apply_mask(img, baseimg, v2s32(0, 0), v2s32(0, 0),
  1462. img->getDimension());
  1463. img->drop();
  1464. } else {
  1465. errorstream << "generateImage(): Failed to load \""
  1466. << filename << "\".";
  1467. }
  1468. }
  1469. /*
  1470. [multiply:color
  1471. multiplys a given color to any pixel of an image
  1472. color = color as ColorString
  1473. */
  1474. else if (str_starts_with(part_of_name, "[multiply:")) {
  1475. Strfnd sf(part_of_name);
  1476. sf.next(":");
  1477. std::string color_str = sf.next(":");
  1478. if (baseimg == NULL) {
  1479. errorstream << "generateImagePart(): baseimg != NULL "
  1480. << "for part_of_name=\"" << part_of_name
  1481. << "\", cancelling." << std::endl;
  1482. return false;
  1483. }
  1484. video::SColor color;
  1485. if (!parseColorString(color_str, color, false))
  1486. return false;
  1487. apply_multiplication(baseimg, v2u32(0, 0), baseimg->getDimension(), color);
  1488. }
  1489. /*
  1490. [colorize:color
  1491. Overlays image with given color
  1492. color = color as ColorString
  1493. */
  1494. else if (str_starts_with(part_of_name, "[colorize:"))
  1495. {
  1496. Strfnd sf(part_of_name);
  1497. sf.next(":");
  1498. std::string color_str = sf.next(":");
  1499. std::string ratio_str = sf.next(":");
  1500. if (baseimg == NULL) {
  1501. errorstream << "generateImagePart(): baseimg != NULL "
  1502. << "for part_of_name=\"" << part_of_name
  1503. << "\", cancelling." << std::endl;
  1504. return false;
  1505. }
  1506. video::SColor color;
  1507. int ratio = -1;
  1508. bool keep_alpha = false;
  1509. if (!parseColorString(color_str, color, false))
  1510. return false;
  1511. if (is_number(ratio_str))
  1512. ratio = mystoi(ratio_str, 0, 255);
  1513. else if (ratio_str == "alpha")
  1514. keep_alpha = true;
  1515. apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha);
  1516. }
  1517. /*
  1518. [applyfiltersformesh
  1519. Internal modifier
  1520. */
  1521. else if (str_starts_with(part_of_name, "[applyfiltersformesh"))
  1522. {
  1523. // Apply the "clean transparent" filter, if configured.
  1524. if (g_settings->getBool("texture_clean_transparent"))
  1525. imageCleanTransparent(baseimg, 127);
  1526. /* Upscale textures to user's requested minimum size. This is a trick to make
  1527. * filters look as good on low-res textures as on high-res ones, by making
  1528. * low-res textures BECOME high-res ones. This is helpful for worlds that
  1529. * mix high- and low-res textures, or for mods with least-common-denominator
  1530. * textures that don't have the resources to offer high-res alternatives.
  1531. */
  1532. const bool filter = m_setting_trilinear_filter || m_setting_bilinear_filter;
  1533. const s32 scaleto = filter ? g_settings->getS32("texture_min_size") : 1;
  1534. if (scaleto > 1) {
  1535. const core::dimension2d<u32> dim = baseimg->getDimension();
  1536. /* Calculate scaling needed to make the shortest texture dimension
  1537. * equal to the target minimum. If e.g. this is a vertical frames
  1538. * animation, the short dimension will be the real size.
  1539. */
  1540. if ((dim.Width == 0) || (dim.Height == 0)) {
  1541. errorstream << "generateImagePart(): Illegal 0 dimension "
  1542. << "for part_of_name=\""<< part_of_name
  1543. << "\", cancelling." << std::endl;
  1544. return false;
  1545. }
  1546. u32 xscale = scaleto / dim.Width;
  1547. u32 yscale = scaleto / dim.Height;
  1548. u32 scale = (xscale > yscale) ? xscale : yscale;
  1549. // Never downscale; only scale up by 2x or more.
  1550. if (scale > 1) {
  1551. u32 w = scale * dim.Width;
  1552. u32 h = scale * dim.Height;
  1553. const core::dimension2d<u32> newdim = core::dimension2d<u32>(w, h);
  1554. video::IImage *newimg = driver->createImage(
  1555. baseimg->getColorFormat(), newdim);
  1556. baseimg->copyToScaling(newimg);
  1557. baseimg->drop();
  1558. baseimg = newimg;
  1559. }
  1560. }
  1561. }
  1562. /*
  1563. [resize:WxH
  1564. Resizes the base image to the given dimensions
  1565. */
  1566. else if (str_starts_with(part_of_name, "[resize"))
  1567. {
  1568. if (baseimg == NULL) {
  1569. errorstream << "generateImagePart(): baseimg == NULL "
  1570. << "for part_of_name=\""<< part_of_name
  1571. << "\", cancelling." << std::endl;
  1572. return false;
  1573. }
  1574. Strfnd sf(part_of_name);
  1575. sf.next(":");
  1576. u32 width = stoi(sf.next("x"));
  1577. u32 height = stoi(sf.next(""));
  1578. core::dimension2d<u32> dim(width, height);
  1579. video::IImage *image = RenderingEngine::get_video_driver()->
  1580. createImage(video::ECF_A8R8G8B8, dim);
  1581. baseimg->copyToScaling(image);
  1582. baseimg->drop();
  1583. baseimg = image;
  1584. }
  1585. /*
  1586. [opacity:R
  1587. Makes the base image transparent according to the given ratio.
  1588. R must be between 0 and 255.
  1589. 0 means totally transparent.
  1590. 255 means totally opaque.
  1591. */
  1592. else if (str_starts_with(part_of_name, "[opacity:")) {
  1593. if (baseimg == NULL) {
  1594. errorstream << "generateImagePart(): baseimg == NULL "
  1595. << "for part_of_name=\"" << part_of_name
  1596. << "\", cancelling." << std::endl;
  1597. return false;
  1598. }
  1599. Strfnd sf(part_of_name);
  1600. sf.next(":");
  1601. u32 ratio = mystoi(sf.next(""), 0, 255);
  1602. core::dimension2d<u32> dim = baseimg->getDimension();
  1603. for (u32 y = 0; y < dim.Height; y++)
  1604. for (u32 x = 0; x < dim.Width; x++)
  1605. {
  1606. video::SColor c = baseimg->getPixel(x, y);
  1607. c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5));
  1608. baseimg->setPixel(x, y, c);
  1609. }
  1610. }
  1611. /*
  1612. [invert:mode
  1613. Inverts the given channels of the base image.
  1614. Mode may contain the characters "r", "g", "b", "a".
  1615. Only the channels that are mentioned in the mode string
  1616. will be inverted.
  1617. */
  1618. else if (str_starts_with(part_of_name, "[invert:")) {
  1619. if (baseimg == NULL) {
  1620. errorstream << "generateImagePart(): baseimg == NULL "
  1621. << "for part_of_name=\"" << part_of_name
  1622. << "\", cancelling." << std::endl;
  1623. return false;
  1624. }
  1625. Strfnd sf(part_of_name);
  1626. sf.next(":");
  1627. std::string mode = sf.next("");
  1628. u32 mask = 0;
  1629. if (mode.find('a') != std::string::npos)
  1630. mask |= 0xff000000UL;
  1631. if (mode.find('r') != std::string::npos)
  1632. mask |= 0x00ff0000UL;
  1633. if (mode.find('g') != std::string::npos)
  1634. mask |= 0x0000ff00UL;
  1635. if (mode.find('b') != std::string::npos)
  1636. mask |= 0x000000ffUL;
  1637. core::dimension2d<u32> dim = baseimg->getDimension();
  1638. for (u32 y = 0; y < dim.Height; y++)
  1639. for (u32 x = 0; x < dim.Width; x++)
  1640. {
  1641. video::SColor c = baseimg->getPixel(x, y);
  1642. c.color ^= mask;
  1643. baseimg->setPixel(x, y, c);
  1644. }
  1645. }
  1646. /*
  1647. [sheet:WxH:X,Y
  1648. Retrieves a tile at position X,Y (in tiles)
  1649. from the base image it assumes to be a
  1650. tilesheet with dimensions W,H (in tiles).
  1651. */
  1652. else if (part_of_name.substr(0,7) == "[sheet:") {
  1653. if (baseimg == NULL) {
  1654. errorstream << "generateImagePart(): baseimg != NULL "
  1655. << "for part_of_name=\"" << part_of_name
  1656. << "\", cancelling." << std::endl;
  1657. return false;
  1658. }
  1659. Strfnd sf(part_of_name);
  1660. sf.next(":");
  1661. u32 w0 = stoi(sf.next("x"));
  1662. u32 h0 = stoi(sf.next(":"));
  1663. u32 x0 = stoi(sf.next(","));
  1664. u32 y0 = stoi(sf.next(":"));
  1665. core::dimension2d<u32> img_dim = baseimg->getDimension();
  1666. core::dimension2d<u32> tile_dim(v2u32(img_dim) / v2u32(w0, h0));
  1667. video::IImage *img = driver->createImage(
  1668. video::ECF_A8R8G8B8, tile_dim);
  1669. if (!img) {
  1670. errorstream << "generateImagePart(): Could not create image "
  1671. << "for part_of_name=\"" << part_of_name
  1672. << "\", cancelling." << std::endl;
  1673. return false;
  1674. }
  1675. img->fill(video::SColor(0,0,0,0));
  1676. v2u32 vdim(tile_dim);
  1677. core::rect<s32> rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim);
  1678. baseimg->copyToWithAlpha(img, v2s32(0), rect,
  1679. video::SColor(255,255,255,255), NULL);
  1680. // Replace baseimg
  1681. baseimg->drop();
  1682. baseimg = img;
  1683. }
  1684. else
  1685. {
  1686. errorstream << "generateImagePart(): Invalid "
  1687. " modification: \"" << part_of_name << "\"" << std::endl;
  1688. }
  1689. }
  1690. return true;
  1691. }
  1692. /*
  1693. Draw an image on top of an another one, using the alpha channel of the
  1694. source image
  1695. This exists because IImage::copyToWithAlpha() doesn't seem to always
  1696. work.
  1697. */
  1698. static void blit_with_alpha(video::IImage *src, video::IImage *dst,
  1699. v2s32 src_pos, v2s32 dst_pos, v2u32 size)
  1700. {
  1701. for (u32 y0=0; y0<size.Y; y0++)
  1702. for (u32 x0=0; x0<size.X; x0++)
  1703. {
  1704. s32 src_x = src_pos.X + x0;
  1705. s32 src_y = src_pos.Y + y0;
  1706. s32 dst_x = dst_pos.X + x0;
  1707. s32 dst_y = dst_pos.Y + y0;
  1708. video::SColor src_c = src->getPixel(src_x, src_y);
  1709. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1710. dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f);
  1711. dst->setPixel(dst_x, dst_y, dst_c);
  1712. }
  1713. }
  1714. /*
  1715. Draw an image on top of an another one, using the alpha channel of the
  1716. source image; only modify fully opaque pixels in destinaion
  1717. */
  1718. static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
  1719. v2s32 src_pos, v2s32 dst_pos, v2u32 size)
  1720. {
  1721. for (u32 y0=0; y0<size.Y; y0++)
  1722. for (u32 x0=0; x0<size.X; x0++)
  1723. {
  1724. s32 src_x = src_pos.X + x0;
  1725. s32 src_y = src_pos.Y + y0;
  1726. s32 dst_x = dst_pos.X + x0;
  1727. s32 dst_y = dst_pos.Y + y0;
  1728. video::SColor src_c = src->getPixel(src_x, src_y);
  1729. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1730. if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0)
  1731. {
  1732. dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f);
  1733. dst->setPixel(dst_x, dst_y, dst_c);
  1734. }
  1735. }
  1736. }
  1737. // This function has been disabled because it is currently unused.
  1738. // Feel free to re-enable if you find it handy.
  1739. #if 0
  1740. /*
  1741. Draw an image on top of an another one, using the specified ratio
  1742. modify all partially-opaque pixels in the destination.
  1743. */
  1744. static void blit_with_interpolate_overlay(video::IImage *src, video::IImage *dst,
  1745. v2s32 src_pos, v2s32 dst_pos, v2u32 size, int ratio)
  1746. {
  1747. for (u32 y0 = 0; y0 < size.Y; y0++)
  1748. for (u32 x0 = 0; x0 < size.X; x0++)
  1749. {
  1750. s32 src_x = src_pos.X + x0;
  1751. s32 src_y = src_pos.Y + y0;
  1752. s32 dst_x = dst_pos.X + x0;
  1753. s32 dst_y = dst_pos.Y + y0;
  1754. video::SColor src_c = src->getPixel(src_x, src_y);
  1755. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1756. if (dst_c.getAlpha() > 0 && src_c.getAlpha() != 0)
  1757. {
  1758. if (ratio == -1)
  1759. dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f);
  1760. else
  1761. dst_c = src_c.getInterpolated(dst_c, (float)ratio/255.0f);
  1762. dst->setPixel(dst_x, dst_y, dst_c);
  1763. }
  1764. }
  1765. }
  1766. #endif
  1767. /*
  1768. Apply color to destination
  1769. */
  1770. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  1771. const video::SColor &color, int ratio, bool keep_alpha)
  1772. {
  1773. u32 alpha = color.getAlpha();
  1774. video::SColor dst_c;
  1775. if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color
  1776. if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha
  1777. dst_c = color;
  1778. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1779. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1780. u32 dst_alpha = dst->getPixel(x, y).getAlpha();
  1781. if (dst_alpha > 0) {
  1782. dst_c.setAlpha(dst_alpha * alpha / 255);
  1783. dst->setPixel(x, y, dst_c);
  1784. }
  1785. }
  1786. } else { // replace the color including the alpha
  1787. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1788. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++)
  1789. if (dst->getPixel(x, y).getAlpha() > 0)
  1790. dst->setPixel(x, y, color);
  1791. }
  1792. } else { // interpolate between the color and destination
  1793. float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f);
  1794. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1795. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1796. dst_c = dst->getPixel(x, y);
  1797. if (dst_c.getAlpha() > 0) {
  1798. dst_c = color.getInterpolated(dst_c, interp);
  1799. dst->setPixel(x, y, dst_c);
  1800. }
  1801. }
  1802. }
  1803. }
  1804. /*
  1805. Apply color to destination
  1806. */
  1807. static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
  1808. const video::SColor &color)
  1809. {
  1810. video::SColor dst_c;
  1811. for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
  1812. for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
  1813. dst_c = dst->getPixel(x, y);
  1814. dst_c.set(
  1815. dst_c.getAlpha(),
  1816. (dst_c.getRed() * color.getRed()) / 255,
  1817. (dst_c.getGreen() * color.getGreen()) / 255,
  1818. (dst_c.getBlue() * color.getBlue()) / 255
  1819. );
  1820. dst->setPixel(x, y, dst_c);
  1821. }
  1822. }
  1823. /*
  1824. Apply mask to destination
  1825. */
  1826. static void apply_mask(video::IImage *mask, video::IImage *dst,
  1827. v2s32 mask_pos, v2s32 dst_pos, v2u32 size)
  1828. {
  1829. for (u32 y0 = 0; y0 < size.Y; y0++) {
  1830. for (u32 x0 = 0; x0 < size.X; x0++) {
  1831. s32 mask_x = x0 + mask_pos.X;
  1832. s32 mask_y = y0 + mask_pos.Y;
  1833. s32 dst_x = x0 + dst_pos.X;
  1834. s32 dst_y = y0 + dst_pos.Y;
  1835. video::SColor mask_c = mask->getPixel(mask_x, mask_y);
  1836. video::SColor dst_c = dst->getPixel(dst_x, dst_y);
  1837. dst_c.color &= mask_c.color;
  1838. dst->setPixel(dst_x, dst_y, dst_c);
  1839. }
  1840. }
  1841. }
  1842. video::IImage *create_crack_image(video::IImage *crack, s32 frame_index,
  1843. core::dimension2d<u32> size, u8 tiles, video::IVideoDriver *driver)
  1844. {
  1845. core::dimension2d<u32> strip_size = crack->getDimension();
  1846. core::dimension2d<u32> frame_size(strip_size.Width, strip_size.Width);
  1847. core::dimension2d<u32> tile_size(size / tiles);
  1848. s32 frame_count = strip_size.Height / strip_size.Width;
  1849. if (frame_index >= frame_count)
  1850. frame_index = frame_count - 1;
  1851. core::rect<s32> frame(v2s32(0, frame_index * frame_size.Height), frame_size);
  1852. video::IImage *result = nullptr;
  1853. // extract crack frame
  1854. video::IImage *crack_tile = driver->createImage(video::ECF_A8R8G8B8, tile_size);
  1855. if (!crack_tile)
  1856. return nullptr;
  1857. if (tile_size == frame_size) {
  1858. crack->copyTo(crack_tile, v2s32(0, 0), frame);
  1859. } else {
  1860. video::IImage *crack_frame = driver->createImage(video::ECF_A8R8G8B8, frame_size);
  1861. if (!crack_frame)
  1862. goto exit__has_tile;
  1863. crack->copyTo(crack_frame, v2s32(0, 0), frame);
  1864. crack_frame->copyToScaling(crack_tile);
  1865. crack_frame->drop();
  1866. }
  1867. if (tiles == 1)
  1868. return crack_tile;
  1869. // tile it
  1870. result = driver->createImage(video::ECF_A8R8G8B8, size);
  1871. if (!result)
  1872. goto exit__has_tile;
  1873. result->fill({});
  1874. for (u8 i = 0; i < tiles; i++)
  1875. for (u8 j = 0; j < tiles; j++)
  1876. crack_tile->copyTo(result, v2s32(i * tile_size.Width, j * tile_size.Height));
  1877. exit__has_tile:
  1878. crack_tile->drop();
  1879. return result;
  1880. }
  1881. static void draw_crack(video::IImage *crack, video::IImage *dst,
  1882. bool use_overlay, s32 frame_count, s32 progression,
  1883. video::IVideoDriver *driver, u8 tiles)
  1884. {
  1885. // Dimension of destination image
  1886. core::dimension2d<u32> dim_dst = dst->getDimension();
  1887. // Limit frame_count
  1888. if (frame_count > (s32) dim_dst.Height)
  1889. frame_count = dim_dst.Height;
  1890. if (frame_count < 1)
  1891. frame_count = 1;
  1892. // Dimension of the scaled crack stage,
  1893. // which is the same as the dimension of a single destination frame
  1894. core::dimension2d<u32> frame_size(
  1895. dim_dst.Width,
  1896. dim_dst.Height / frame_count
  1897. );
  1898. video::IImage *crack_scaled = create_crack_image(crack, progression,
  1899. frame_size, tiles, driver);
  1900. if (!crack_scaled)
  1901. return;
  1902. auto blit = use_overlay ? blit_with_alpha_overlay : blit_with_alpha;
  1903. for (s32 i = 0; i < frame_count; ++i) {
  1904. v2s32 dst_pos(0, frame_size.Height * i);
  1905. blit(crack_scaled, dst, v2s32(0,0), dst_pos, frame_size);
  1906. }
  1907. crack_scaled->drop();
  1908. }
  1909. void brighten(video::IImage *image)
  1910. {
  1911. if (image == NULL)
  1912. return;
  1913. core::dimension2d<u32> dim = image->getDimension();
  1914. for (u32 y=0; y<dim.Height; y++)
  1915. for (u32 x=0; x<dim.Width; x++)
  1916. {
  1917. video::SColor c = image->getPixel(x,y);
  1918. c.setRed(0.5 * 255 + 0.5 * (float)c.getRed());
  1919. c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen());
  1920. c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue());
  1921. image->setPixel(x,y,c);
  1922. }
  1923. }
  1924. u32 parseImageTransform(const std::string& s)
  1925. {
  1926. int total_transform = 0;
  1927. std::string transform_names[8];
  1928. transform_names[0] = "i";
  1929. transform_names[1] = "r90";
  1930. transform_names[2] = "r180";
  1931. transform_names[3] = "r270";
  1932. transform_names[4] = "fx";
  1933. transform_names[6] = "fy";
  1934. std::size_t pos = 0;
  1935. while(pos < s.size())
  1936. {
  1937. int transform = -1;
  1938. for (int i = 0; i <= 7; ++i)
  1939. {
  1940. const std::string &name_i = transform_names[i];
  1941. if (s[pos] == ('0' + i))
  1942. {
  1943. transform = i;
  1944. pos++;
  1945. break;
  1946. }
  1947. if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) {
  1948. transform = i;
  1949. pos += name_i.size();
  1950. break;
  1951. }
  1952. }
  1953. if (transform < 0)
  1954. break;
  1955. // Multiply total_transform and transform in the group D4
  1956. int new_total = 0;
  1957. if (transform < 4)
  1958. new_total = (transform + total_transform) % 4;
  1959. else
  1960. new_total = (transform - total_transform + 8) % 4;
  1961. if ((transform >= 4) ^ (total_transform >= 4))
  1962. new_total += 4;
  1963. total_transform = new_total;
  1964. }
  1965. return total_transform;
  1966. }
  1967. core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim)
  1968. {
  1969. if (transform % 2 == 0)
  1970. return dim;
  1971. return core::dimension2d<u32>(dim.Height, dim.Width);
  1972. }
  1973. void imageTransform(u32 transform, video::IImage *src, video::IImage *dst)
  1974. {
  1975. if (src == NULL || dst == NULL)
  1976. return;
  1977. core::dimension2d<u32> dstdim = dst->getDimension();
  1978. // Pre-conditions
  1979. assert(dstdim == imageTransformDimension(transform, src->getDimension()));
  1980. assert(transform <= 7);
  1981. /*
  1982. Compute the transformation from source coordinates (sx,sy)
  1983. to destination coordinates (dx,dy).
  1984. */
  1985. int sxn = 0;
  1986. int syn = 2;
  1987. if (transform == 0) // identity
  1988. sxn = 0, syn = 2; // sx = dx, sy = dy
  1989. else if (transform == 1) // rotate by 90 degrees ccw
  1990. sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx
  1991. else if (transform == 2) // rotate by 180 degrees
  1992. sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy
  1993. else if (transform == 3) // rotate by 270 degrees ccw
  1994. sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx
  1995. else if (transform == 4) // flip x
  1996. sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy
  1997. else if (transform == 5) // flip x then rotate by 90 degrees ccw
  1998. sxn = 2, syn = 0; // sx = dy, sy = dx
  1999. else if (transform == 6) // flip y
  2000. sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy
  2001. else if (transform == 7) // flip y then rotate by 90 degrees ccw
  2002. sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx
  2003. for (u32 dy=0; dy<dstdim.Height; dy++)
  2004. for (u32 dx=0; dx<dstdim.Width; dx++)
  2005. {
  2006. u32 entries[4] = {dx, dstdim.Width-1-dx, dy, dstdim.Height-1-dy};
  2007. u32 sx = entries[sxn];
  2008. u32 sy = entries[syn];
  2009. video::SColor c = src->getPixel(sx,sy);
  2010. dst->setPixel(dx,dy,c);
  2011. }
  2012. }
  2013. video::ITexture* TextureSource::getNormalTexture(const std::string &name)
  2014. {
  2015. if (isKnownSourceImage("override_normal.png"))
  2016. return getTexture("override_normal.png");
  2017. std::string fname_base = name;
  2018. static const char *normal_ext = "_normal.png";
  2019. static const u32 normal_ext_size = strlen(normal_ext);
  2020. size_t pos = fname_base.find('.');
  2021. std::string fname_normal = fname_base.substr(0, pos) + normal_ext;
  2022. if (isKnownSourceImage(fname_normal)) {
  2023. // look for image extension and replace it
  2024. size_t i = 0;
  2025. while ((i = fname_base.find('.', i)) != std::string::npos) {
  2026. fname_base.replace(i, 4, normal_ext);
  2027. i += normal_ext_size;
  2028. }
  2029. return getTexture(fname_base);
  2030. }
  2031. return NULL;
  2032. }
  2033. video::SColor TextureSource::getTextureAverageColor(const std::string &name)
  2034. {
  2035. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  2036. video::SColor c(0, 0, 0, 0);
  2037. video::ITexture *texture = getTexture(name);
  2038. video::IImage *image = driver->createImage(texture,
  2039. core::position2d<s32>(0, 0),
  2040. texture->getOriginalSize());
  2041. u32 total = 0;
  2042. u32 tR = 0;
  2043. u32 tG = 0;
  2044. u32 tB = 0;
  2045. core::dimension2d<u32> dim = image->getDimension();
  2046. u16 step = 1;
  2047. if (dim.Width > 16)
  2048. step = dim.Width / 16;
  2049. for (u16 x = 0; x < dim.Width; x += step) {
  2050. for (u16 y = 0; y < dim.Width; y += step) {
  2051. c = image->getPixel(x,y);
  2052. if (c.getAlpha() > 0) {
  2053. total++;
  2054. tR += c.getRed();
  2055. tG += c.getGreen();
  2056. tB += c.getBlue();
  2057. }
  2058. }
  2059. }
  2060. image->drop();
  2061. if (total > 0) {
  2062. c.setRed(tR / total);
  2063. c.setGreen(tG / total);
  2064. c.setBlue(tB / total);
  2065. }
  2066. c.setAlpha(255);
  2067. return c;
  2068. }
  2069. video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present)
  2070. {
  2071. std::string tname = "__shaderFlagsTexture";
  2072. tname += normalmap_present ? "1" : "0";
  2073. if (isKnownSourceImage(tname)) {
  2074. return getTexture(tname);
  2075. }
  2076. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  2077. video::IImage *flags_image = driver->createImage(
  2078. video::ECF_A8R8G8B8, core::dimension2d<u32>(1, 1));
  2079. sanity_check(flags_image != NULL);
  2080. video::SColor c(255, normalmap_present ? 255 : 0, 0, 0);
  2081. flags_image->setPixel(0, 0, c);
  2082. insertSourceImage(tname, flags_image);
  2083. flags_image->drop();
  2084. return getTexture(tname);
  2085. }
  2086. std::vector<std::string> getTextureDirs()
  2087. {
  2088. return fs::GetRecursiveDirs(g_settings->get("texture_path"));
  2089. }