image.cpp 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754
  1. /*************************************************************************/
  2. /* image.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "image.h"
  31. #include "core/error/error_list.h"
  32. #include "core/error/error_macros.h"
  33. #include "core/io/image_loader.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/math/math_funcs.h"
  36. #include "core/string/print_string.h"
  37. #include "core/templates/hash_map.h"
  38. #include "core/variant/dictionary.h"
  39. #include <stdio.h>
  40. #include <cmath>
  41. const char *Image::format_names[Image::FORMAT_MAX] = {
  42. "Lum8", //luminance
  43. "LumAlpha8", //luminance-alpha
  44. "Red8",
  45. "RedGreen",
  46. "RGB8",
  47. "RGBA8",
  48. "RGBA4444",
  49. "RGBA5551",
  50. "RFloat", //float
  51. "RGFloat",
  52. "RGBFloat",
  53. "RGBAFloat",
  54. "RHalf", //half float
  55. "RGHalf",
  56. "RGBHalf",
  57. "RGBAHalf",
  58. "RGBE9995",
  59. "DXT1 RGB8", //s3tc
  60. "DXT3 RGBA8",
  61. "DXT5 RGBA8",
  62. "RGTC Red8",
  63. "RGTC RedGreen8",
  64. "BPTC_RGBA",
  65. "BPTC_RGBF",
  66. "BPTC_RGBFU",
  67. "ETC", //etc1
  68. "ETC2_R11", //etc2
  69. "ETC2_R11S", //signed", NOT srgb.
  70. "ETC2_RG11",
  71. "ETC2_RG11S",
  72. "ETC2_RGB8",
  73. "ETC2_RGBA8",
  74. "ETC2_RGB8A1",
  75. "ETC2_RA_AS_RG",
  76. "FORMAT_DXT5_RA_AS_RG",
  77. };
  78. SavePNGFunc Image::save_png_func = nullptr;
  79. SaveEXRFunc Image::save_exr_func = nullptr;
  80. SavePNGBufferFunc Image::save_png_buffer_func = nullptr;
  81. void Image::_put_pixelb(int p_x, int p_y, uint32_t p_pixel_size, uint8_t *p_data, const uint8_t *p_pixel) {
  82. uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
  83. memcpy(p_data + ofs, p_pixel, p_pixel_size);
  84. }
  85. void Image::_get_pixelb(int p_x, int p_y, uint32_t p_pixel_size, const uint8_t *p_data, uint8_t *p_pixel) {
  86. uint32_t ofs = (p_y * width + p_x) * p_pixel_size;
  87. memcpy(p_pixel, p_data + ofs, p_pixel_size);
  88. }
  89. int Image::get_format_pixel_size(Format p_format) {
  90. switch (p_format) {
  91. case FORMAT_L8:
  92. return 1; //luminance
  93. case FORMAT_LA8:
  94. return 2; //luminance-alpha
  95. case FORMAT_R8:
  96. return 1;
  97. case FORMAT_RG8:
  98. return 2;
  99. case FORMAT_RGB8:
  100. return 3;
  101. case FORMAT_RGBA8:
  102. return 4;
  103. case FORMAT_RGBA4444:
  104. return 2;
  105. case FORMAT_RGB565:
  106. return 2;
  107. case FORMAT_RF:
  108. return 4; //float
  109. case FORMAT_RGF:
  110. return 8;
  111. case FORMAT_RGBF:
  112. return 12;
  113. case FORMAT_RGBAF:
  114. return 16;
  115. case FORMAT_RH:
  116. return 2; //half float
  117. case FORMAT_RGH:
  118. return 4;
  119. case FORMAT_RGBH:
  120. return 6;
  121. case FORMAT_RGBAH:
  122. return 8;
  123. case FORMAT_RGBE9995:
  124. return 4;
  125. case FORMAT_DXT1:
  126. return 1; //s3tc bc1
  127. case FORMAT_DXT3:
  128. return 1; //bc2
  129. case FORMAT_DXT5:
  130. return 1; //bc3
  131. case FORMAT_RGTC_R:
  132. return 1; //bc4
  133. case FORMAT_RGTC_RG:
  134. return 1; //bc5
  135. case FORMAT_BPTC_RGBA:
  136. return 1; //btpc bc6h
  137. case FORMAT_BPTC_RGBF:
  138. return 1; //float /
  139. case FORMAT_BPTC_RGBFU:
  140. return 1; //unsigned float
  141. case FORMAT_ETC:
  142. return 1; //etc1
  143. case FORMAT_ETC2_R11:
  144. return 1; //etc2
  145. case FORMAT_ETC2_R11S:
  146. return 1; //signed: return 1; NOT srgb.
  147. case FORMAT_ETC2_RG11:
  148. return 1;
  149. case FORMAT_ETC2_RG11S:
  150. return 1;
  151. case FORMAT_ETC2_RGB8:
  152. return 1;
  153. case FORMAT_ETC2_RGBA8:
  154. return 1;
  155. case FORMAT_ETC2_RGB8A1:
  156. return 1;
  157. case FORMAT_ETC2_RA_AS_RG:
  158. return 1;
  159. case FORMAT_DXT5_RA_AS_RG:
  160. return 1;
  161. case FORMAT_MAX: {
  162. }
  163. }
  164. return 0;
  165. }
  166. void Image::get_format_min_pixel_size(Format p_format, int &r_w, int &r_h) {
  167. switch (p_format) {
  168. case FORMAT_DXT1: //s3tc bc1
  169. case FORMAT_DXT3: //bc2
  170. case FORMAT_DXT5: //bc3
  171. case FORMAT_RGTC_R: //bc4
  172. case FORMAT_RGTC_RG: { //bc5 case case FORMAT_DXT1:
  173. r_w = 4;
  174. r_h = 4;
  175. } break;
  176. case FORMAT_ETC: {
  177. r_w = 4;
  178. r_h = 4;
  179. } break;
  180. case FORMAT_BPTC_RGBA:
  181. case FORMAT_BPTC_RGBF:
  182. case FORMAT_BPTC_RGBFU: {
  183. r_w = 4;
  184. r_h = 4;
  185. } break;
  186. case FORMAT_ETC2_R11: //etc2
  187. case FORMAT_ETC2_R11S: //signed: NOT srgb.
  188. case FORMAT_ETC2_RG11:
  189. case FORMAT_ETC2_RG11S:
  190. case FORMAT_ETC2_RGB8:
  191. case FORMAT_ETC2_RGBA8:
  192. case FORMAT_ETC2_RGB8A1:
  193. case FORMAT_ETC2_RA_AS_RG:
  194. case FORMAT_DXT5_RA_AS_RG: {
  195. r_w = 4;
  196. r_h = 4;
  197. } break;
  198. default: {
  199. r_w = 1;
  200. r_h = 1;
  201. } break;
  202. }
  203. }
  204. int Image::get_format_pixel_rshift(Format p_format) {
  205. if (p_format == FORMAT_DXT1 || p_format == FORMAT_RGTC_R || p_format == FORMAT_ETC || p_format == FORMAT_ETC2_R11 || p_format == FORMAT_ETC2_R11S || p_format == FORMAT_ETC2_RGB8 || p_format == FORMAT_ETC2_RGB8A1) {
  206. return 1;
  207. } else {
  208. return 0;
  209. }
  210. }
  211. int Image::get_format_block_size(Format p_format) {
  212. switch (p_format) {
  213. case FORMAT_DXT1: //s3tc bc1
  214. case FORMAT_DXT3: //bc2
  215. case FORMAT_DXT5: //bc3
  216. case FORMAT_RGTC_R: //bc4
  217. case FORMAT_RGTC_RG: { //bc5 case case FORMAT_DXT1:
  218. return 4;
  219. }
  220. case FORMAT_ETC: {
  221. return 4;
  222. }
  223. case FORMAT_BPTC_RGBA:
  224. case FORMAT_BPTC_RGBF:
  225. case FORMAT_BPTC_RGBFU: {
  226. return 4;
  227. }
  228. case FORMAT_ETC2_R11: //etc2
  229. case FORMAT_ETC2_R11S: //signed: NOT srgb.
  230. case FORMAT_ETC2_RG11:
  231. case FORMAT_ETC2_RG11S:
  232. case FORMAT_ETC2_RGB8:
  233. case FORMAT_ETC2_RGBA8:
  234. case FORMAT_ETC2_RGB8A1:
  235. case FORMAT_ETC2_RA_AS_RG: //used to make basis universal happy
  236. case FORMAT_DXT5_RA_AS_RG: //used to make basis universal happy
  237. {
  238. return 4;
  239. }
  240. default: {
  241. }
  242. }
  243. return 1;
  244. }
  245. void Image::_get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const {
  246. int w = width;
  247. int h = height;
  248. int ofs = 0;
  249. int pixel_size = get_format_pixel_size(format);
  250. int pixel_rshift = get_format_pixel_rshift(format);
  251. int block = get_format_block_size(format);
  252. int minw, minh;
  253. get_format_min_pixel_size(format, minw, minh);
  254. for (int i = 0; i < p_mipmap; i++) {
  255. int bw = w % block != 0 ? w + (block - w % block) : w;
  256. int bh = h % block != 0 ? h + (block - h % block) : h;
  257. int s = bw * bh;
  258. s *= pixel_size;
  259. s >>= pixel_rshift;
  260. ofs += s;
  261. w = MAX(minw, w >> 1);
  262. h = MAX(minh, h >> 1);
  263. }
  264. r_offset = ofs;
  265. r_width = w;
  266. r_height = h;
  267. }
  268. int Image::get_mipmap_offset(int p_mipmap) const {
  269. ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
  270. int ofs, w, h;
  271. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  272. return ofs;
  273. }
  274. int Image::get_mipmap_byte_size(int p_mipmap) const {
  275. ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
  276. int ofs, w, h;
  277. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  278. int ofs2;
  279. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
  280. return ofs2 - ofs;
  281. }
  282. void Image::get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const {
  283. int ofs, w, h;
  284. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  285. int ofs2;
  286. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
  287. r_ofs = ofs;
  288. r_size = ofs2 - ofs;
  289. }
  290. void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const {
  291. int ofs;
  292. _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
  293. int ofs2, w2, h2;
  294. _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w2, h2);
  295. r_ofs = ofs;
  296. r_size = ofs2 - ofs;
  297. }
  298. Image::Image3DValidateError Image::validate_3d_image(Image::Format p_format, int p_width, int p_height, int p_depth, bool p_mipmaps, const Vector<Ref<Image>> &p_images) {
  299. int w = p_width;
  300. int h = p_height;
  301. int d = p_depth;
  302. int arr_ofs = 0;
  303. while (true) {
  304. for (int i = 0; i < d; i++) {
  305. int idx = i + arr_ofs;
  306. if (idx >= p_images.size()) {
  307. return VALIDATE_3D_ERR_MISSING_IMAGES;
  308. }
  309. if (p_images[idx].is_null() || p_images[idx]->is_empty()) {
  310. return VALIDATE_3D_ERR_IMAGE_EMPTY;
  311. }
  312. if (p_images[idx]->get_format() != p_format) {
  313. return VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH;
  314. }
  315. if (p_images[idx]->get_width() != w || p_images[idx]->get_height() != h) {
  316. return VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH;
  317. }
  318. if (p_images[idx]->has_mipmaps()) {
  319. return VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS;
  320. }
  321. }
  322. arr_ofs += d;
  323. if (!p_mipmaps) {
  324. break;
  325. }
  326. if (w == 1 && h == 1 && d == 1) {
  327. break;
  328. }
  329. w = MAX(1, w >> 1);
  330. h = MAX(1, h >> 1);
  331. d = MAX(1, d >> 1);
  332. }
  333. if (arr_ofs != p_images.size()) {
  334. return VALIDATE_3D_ERR_EXTRA_IMAGES;
  335. }
  336. return VALIDATE_3D_OK;
  337. }
  338. String Image::get_3d_image_validation_error_text(Image3DValidateError p_error) {
  339. switch (p_error) {
  340. case VALIDATE_3D_OK: {
  341. return "Ok";
  342. } break;
  343. case VALIDATE_3D_ERR_IMAGE_EMPTY: {
  344. return "Empty Image found";
  345. } break;
  346. case VALIDATE_3D_ERR_MISSING_IMAGES: {
  347. return "Missing Images";
  348. } break;
  349. case VALIDATE_3D_ERR_EXTRA_IMAGES: {
  350. return "Too many Images";
  351. } break;
  352. case VALIDATE_3D_ERR_IMAGE_SIZE_MISMATCH: {
  353. return "Image size mismatch";
  354. } break;
  355. case VALIDATE_3D_ERR_IMAGE_FORMAT_MISMATCH: {
  356. return "Image format mismatch";
  357. } break;
  358. case VALIDATE_3D_ERR_IMAGE_HAS_MIPMAPS: {
  359. return "Image has included mipmaps";
  360. } break;
  361. }
  362. return String();
  363. }
  364. int Image::get_width() const {
  365. return width;
  366. }
  367. int Image::get_height() const {
  368. return height;
  369. }
  370. Vector2 Image::get_size() const {
  371. return Vector2(width, height);
  372. }
  373. bool Image::has_mipmaps() const {
  374. return mipmaps;
  375. }
  376. int Image::get_mipmap_count() const {
  377. if (mipmaps) {
  378. return get_image_required_mipmaps(width, height, format);
  379. } else {
  380. return 0;
  381. }
  382. }
  383. //using template generates perfectly optimized code due to constant expression reduction and unused variable removal present in all compilers
  384. template <uint32_t read_bytes, bool read_alpha, uint32_t write_bytes, bool write_alpha, bool read_gray, bool write_gray>
  385. static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) {
  386. uint32_t max_bytes = MAX(read_bytes, write_bytes);
  387. for (int y = 0; y < p_height; y++) {
  388. for (int x = 0; x < p_width; x++) {
  389. const uint8_t *rofs = &p_src[((y * p_width) + x) * (read_bytes + (read_alpha ? 1 : 0))];
  390. uint8_t *wofs = &p_dst[((y * p_width) + x) * (write_bytes + (write_alpha ? 1 : 0))];
  391. uint8_t rgba[4] = { 0, 0, 0, 255 };
  392. if (read_gray) {
  393. rgba[0] = rofs[0];
  394. rgba[1] = rofs[0];
  395. rgba[2] = rofs[0];
  396. } else {
  397. for (uint32_t i = 0; i < max_bytes; i++) {
  398. rgba[i] = (i < read_bytes) ? rofs[i] : 0;
  399. }
  400. }
  401. if (read_alpha || write_alpha) {
  402. rgba[3] = read_alpha ? rofs[read_bytes] : 255;
  403. }
  404. if (write_gray) {
  405. //TODO: not correct grayscale, should use fixed point version of actual weights
  406. wofs[0] = uint8_t((uint16_t(rgba[0]) + uint16_t(rgba[1]) + uint16_t(rgba[2])) / 3);
  407. } else {
  408. for (uint32_t i = 0; i < write_bytes; i++) {
  409. wofs[i] = rgba[i];
  410. }
  411. }
  412. if (write_alpha) {
  413. wofs[write_bytes] = rgba[3];
  414. }
  415. }
  416. }
  417. }
  418. void Image::convert(Format p_new_format) {
  419. if (data.size() == 0) {
  420. return;
  421. }
  422. if (p_new_format == format) {
  423. return;
  424. }
  425. if (format > FORMAT_RGBE9995 || p_new_format > FORMAT_RGBE9995) {
  426. ERR_FAIL_MSG("Cannot convert to <-> from compressed formats. Use compress() and decompress() instead.");
  427. } else if (format > FORMAT_RGBA8 || p_new_format > FORMAT_RGBA8) {
  428. //use put/set pixel which is slower but works with non byte formats
  429. Image new_img(width, height, false, p_new_format);
  430. for (int i = 0; i < width; i++) {
  431. for (int j = 0; j < height; j++) {
  432. new_img.set_pixel(i, j, get_pixel(i, j));
  433. }
  434. }
  435. if (has_mipmaps()) {
  436. new_img.generate_mipmaps();
  437. }
  438. _copy_internals_from(new_img);
  439. return;
  440. }
  441. Image new_img(width, height, false, p_new_format);
  442. const uint8_t *rptr = data.ptr();
  443. uint8_t *wptr = new_img.data.ptrw();
  444. int conversion_type = format | p_new_format << 8;
  445. switch (conversion_type) {
  446. case FORMAT_L8 | (FORMAT_LA8 << 8):
  447. _convert<1, false, 1, true, true, true>(width, height, rptr, wptr);
  448. break;
  449. case FORMAT_L8 | (FORMAT_R8 << 8):
  450. _convert<1, false, 1, false, true, false>(width, height, rptr, wptr);
  451. break;
  452. case FORMAT_L8 | (FORMAT_RG8 << 8):
  453. _convert<1, false, 2, false, true, false>(width, height, rptr, wptr);
  454. break;
  455. case FORMAT_L8 | (FORMAT_RGB8 << 8):
  456. _convert<1, false, 3, false, true, false>(width, height, rptr, wptr);
  457. break;
  458. case FORMAT_L8 | (FORMAT_RGBA8 << 8):
  459. _convert<1, false, 3, true, true, false>(width, height, rptr, wptr);
  460. break;
  461. case FORMAT_LA8 | (FORMAT_L8 << 8):
  462. _convert<1, true, 1, false, true, true>(width, height, rptr, wptr);
  463. break;
  464. case FORMAT_LA8 | (FORMAT_R8 << 8):
  465. _convert<1, true, 1, false, true, false>(width, height, rptr, wptr);
  466. break;
  467. case FORMAT_LA8 | (FORMAT_RG8 << 8):
  468. _convert<1, true, 2, false, true, false>(width, height, rptr, wptr);
  469. break;
  470. case FORMAT_LA8 | (FORMAT_RGB8 << 8):
  471. _convert<1, true, 3, false, true, false>(width, height, rptr, wptr);
  472. break;
  473. case FORMAT_LA8 | (FORMAT_RGBA8 << 8):
  474. _convert<1, true, 3, true, true, false>(width, height, rptr, wptr);
  475. break;
  476. case FORMAT_R8 | (FORMAT_L8 << 8):
  477. _convert<1, false, 1, false, false, true>(width, height, rptr, wptr);
  478. break;
  479. case FORMAT_R8 | (FORMAT_LA8 << 8):
  480. _convert<1, false, 1, true, false, true>(width, height, rptr, wptr);
  481. break;
  482. case FORMAT_R8 | (FORMAT_RG8 << 8):
  483. _convert<1, false, 2, false, false, false>(width, height, rptr, wptr);
  484. break;
  485. case FORMAT_R8 | (FORMAT_RGB8 << 8):
  486. _convert<1, false, 3, false, false, false>(width, height, rptr, wptr);
  487. break;
  488. case FORMAT_R8 | (FORMAT_RGBA8 << 8):
  489. _convert<1, false, 3, true, false, false>(width, height, rptr, wptr);
  490. break;
  491. case FORMAT_RG8 | (FORMAT_L8 << 8):
  492. _convert<2, false, 1, false, false, true>(width, height, rptr, wptr);
  493. break;
  494. case FORMAT_RG8 | (FORMAT_LA8 << 8):
  495. _convert<2, false, 1, true, false, true>(width, height, rptr, wptr);
  496. break;
  497. case FORMAT_RG8 | (FORMAT_R8 << 8):
  498. _convert<2, false, 1, false, false, false>(width, height, rptr, wptr);
  499. break;
  500. case FORMAT_RG8 | (FORMAT_RGB8 << 8):
  501. _convert<2, false, 3, false, false, false>(width, height, rptr, wptr);
  502. break;
  503. case FORMAT_RG8 | (FORMAT_RGBA8 << 8):
  504. _convert<2, false, 3, true, false, false>(width, height, rptr, wptr);
  505. break;
  506. case FORMAT_RGB8 | (FORMAT_L8 << 8):
  507. _convert<3, false, 1, false, false, true>(width, height, rptr, wptr);
  508. break;
  509. case FORMAT_RGB8 | (FORMAT_LA8 << 8):
  510. _convert<3, false, 1, true, false, true>(width, height, rptr, wptr);
  511. break;
  512. case FORMAT_RGB8 | (FORMAT_R8 << 8):
  513. _convert<3, false, 1, false, false, false>(width, height, rptr, wptr);
  514. break;
  515. case FORMAT_RGB8 | (FORMAT_RG8 << 8):
  516. _convert<3, false, 2, false, false, false>(width, height, rptr, wptr);
  517. break;
  518. case FORMAT_RGB8 | (FORMAT_RGBA8 << 8):
  519. _convert<3, false, 3, true, false, false>(width, height, rptr, wptr);
  520. break;
  521. case FORMAT_RGBA8 | (FORMAT_L8 << 8):
  522. _convert<3, true, 1, false, false, true>(width, height, rptr, wptr);
  523. break;
  524. case FORMAT_RGBA8 | (FORMAT_LA8 << 8):
  525. _convert<3, true, 1, true, false, true>(width, height, rptr, wptr);
  526. break;
  527. case FORMAT_RGBA8 | (FORMAT_R8 << 8):
  528. _convert<3, true, 1, false, false, false>(width, height, rptr, wptr);
  529. break;
  530. case FORMAT_RGBA8 | (FORMAT_RG8 << 8):
  531. _convert<3, true, 2, false, false, false>(width, height, rptr, wptr);
  532. break;
  533. case FORMAT_RGBA8 | (FORMAT_RGB8 << 8):
  534. _convert<3, true, 3, false, false, false>(width, height, rptr, wptr);
  535. break;
  536. }
  537. bool gen_mipmaps = mipmaps;
  538. _copy_internals_from(new_img);
  539. if (gen_mipmaps) {
  540. generate_mipmaps();
  541. }
  542. }
  543. Image::Format Image::get_format() const {
  544. return format;
  545. }
  546. static double _bicubic_interp_kernel(double x) {
  547. x = ABS(x);
  548. double bc = 0;
  549. if (x <= 1) {
  550. bc = (1.5 * x - 2.5) * x * x + 1;
  551. } else if (x < 2) {
  552. bc = ((-0.5 * x + 2.5) * x - 4) * x + 2;
  553. }
  554. return bc;
  555. }
  556. template <int CC, class T>
  557. static void _scale_cubic(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
  558. // get source image size
  559. int width = p_src_width;
  560. int height = p_src_height;
  561. double xfac = (double)width / p_dst_width;
  562. double yfac = (double)height / p_dst_height;
  563. // coordinates of source points and coefficients
  564. double ox, oy, dx, dy, k1, k2;
  565. int ox1, oy1, ox2, oy2;
  566. // destination pixel values
  567. // width and height decreased by 1
  568. int ymax = height - 1;
  569. int xmax = width - 1;
  570. // temporary pointer
  571. for (uint32_t y = 0; y < p_dst_height; y++) {
  572. // Y coordinates
  573. oy = (double)y * yfac - 0.5f;
  574. oy1 = (int)oy;
  575. dy = oy - (double)oy1;
  576. for (uint32_t x = 0; x < p_dst_width; x++) {
  577. // X coordinates
  578. ox = (double)x * xfac - 0.5f;
  579. ox1 = (int)ox;
  580. dx = ox - (double)ox1;
  581. // initial pixel value
  582. T *__restrict dst = ((T *)p_dst) + (y * p_dst_width + x) * CC;
  583. double color[CC];
  584. for (int i = 0; i < CC; i++) {
  585. color[i] = 0;
  586. }
  587. for (int n = -1; n < 3; n++) {
  588. // get Y coefficient
  589. k1 = _bicubic_interp_kernel(dy - (double)n);
  590. oy2 = oy1 + n;
  591. if (oy2 < 0) {
  592. oy2 = 0;
  593. }
  594. if (oy2 > ymax) {
  595. oy2 = ymax;
  596. }
  597. for (int m = -1; m < 3; m++) {
  598. // get X coefficient
  599. k2 = k1 * _bicubic_interp_kernel((double)m - dx);
  600. ox2 = ox1 + m;
  601. if (ox2 < 0) {
  602. ox2 = 0;
  603. }
  604. if (ox2 > xmax) {
  605. ox2 = xmax;
  606. }
  607. // get pixel of original image
  608. const T *__restrict p = ((T *)p_src) + (oy2 * p_src_width + ox2) * CC;
  609. for (int i = 0; i < CC; i++) {
  610. if (sizeof(T) == 2) { //half float
  611. color[i] = Math::half_to_float(p[i]);
  612. } else {
  613. color[i] += p[i] * k2;
  614. }
  615. }
  616. }
  617. }
  618. for (int i = 0; i < CC; i++) {
  619. if (sizeof(T) == 1) { //byte
  620. dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 255);
  621. } else if (sizeof(T) == 2) { //half float
  622. dst[i] = Math::make_half_float(color[i]);
  623. } else {
  624. dst[i] = color[i];
  625. }
  626. }
  627. }
  628. }
  629. }
  630. template <int CC, class T>
  631. static void _scale_bilinear(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
  632. enum {
  633. FRAC_BITS = 8,
  634. FRAC_LEN = (1 << FRAC_BITS),
  635. FRAC_HALF = (FRAC_LEN >> 1),
  636. FRAC_MASK = FRAC_LEN - 1
  637. };
  638. for (uint32_t i = 0; i < p_dst_height; i++) {
  639. // Add 0.5 in order to interpolate based on pixel center
  640. uint32_t src_yofs_up_fp = (i + 0.5) * p_src_height * FRAC_LEN / p_dst_height;
  641. // Calculate nearest src pixel center above current, and truncate to get y index
  642. uint32_t src_yofs_up = src_yofs_up_fp >= FRAC_HALF ? (src_yofs_up_fp - FRAC_HALF) >> FRAC_BITS : 0;
  643. uint32_t src_yofs_down = (src_yofs_up_fp + FRAC_HALF) >> FRAC_BITS;
  644. if (src_yofs_down >= p_src_height) {
  645. src_yofs_down = p_src_height - 1;
  646. }
  647. // Calculate distance to pixel center of src_yofs_up
  648. uint32_t src_yofs_frac = src_yofs_up_fp & FRAC_MASK;
  649. src_yofs_frac = src_yofs_frac >= FRAC_HALF ? src_yofs_frac - FRAC_HALF : src_yofs_frac + FRAC_HALF;
  650. uint32_t y_ofs_up = src_yofs_up * p_src_width * CC;
  651. uint32_t y_ofs_down = src_yofs_down * p_src_width * CC;
  652. for (uint32_t j = 0; j < p_dst_width; j++) {
  653. uint32_t src_xofs_left_fp = (j + 0.5) * p_src_width * FRAC_LEN / p_dst_width;
  654. uint32_t src_xofs_left = src_xofs_left_fp >= FRAC_HALF ? (src_xofs_left_fp - FRAC_HALF) >> FRAC_BITS : 0;
  655. uint32_t src_xofs_right = (src_xofs_left_fp + FRAC_HALF) >> FRAC_BITS;
  656. if (src_xofs_right >= p_src_width) {
  657. src_xofs_right = p_src_width - 1;
  658. }
  659. uint32_t src_xofs_frac = src_xofs_left_fp & FRAC_MASK;
  660. src_xofs_frac = src_xofs_frac >= FRAC_HALF ? src_xofs_frac - FRAC_HALF : src_xofs_frac + FRAC_HALF;
  661. src_xofs_left *= CC;
  662. src_xofs_right *= CC;
  663. for (uint32_t l = 0; l < CC; l++) {
  664. if (sizeof(T) == 1) { //uint8
  665. uint32_t p00 = p_src[y_ofs_up + src_xofs_left + l] << FRAC_BITS;
  666. uint32_t p10 = p_src[y_ofs_up + src_xofs_right + l] << FRAC_BITS;
  667. uint32_t p01 = p_src[y_ofs_down + src_xofs_left + l] << FRAC_BITS;
  668. uint32_t p11 = p_src[y_ofs_down + src_xofs_right + l] << FRAC_BITS;
  669. uint32_t interp_up = p00 + (((p10 - p00) * src_xofs_frac) >> FRAC_BITS);
  670. uint32_t interp_down = p01 + (((p11 - p01) * src_xofs_frac) >> FRAC_BITS);
  671. uint32_t interp = interp_up + (((interp_down - interp_up) * src_yofs_frac) >> FRAC_BITS);
  672. interp >>= FRAC_BITS;
  673. p_dst[i * p_dst_width * CC + j * CC + l] = uint8_t(interp);
  674. } else if (sizeof(T) == 2) { //half float
  675. float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
  676. float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
  677. const T *src = ((const T *)p_src);
  678. T *dst = ((T *)p_dst);
  679. float p00 = Math::half_to_float(src[y_ofs_up + src_xofs_left + l]);
  680. float p10 = Math::half_to_float(src[y_ofs_up + src_xofs_right + l]);
  681. float p01 = Math::half_to_float(src[y_ofs_down + src_xofs_left + l]);
  682. float p11 = Math::half_to_float(src[y_ofs_down + src_xofs_right + l]);
  683. float interp_up = p00 + (p10 - p00) * xofs_frac;
  684. float interp_down = p01 + (p11 - p01) * xofs_frac;
  685. float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
  686. dst[i * p_dst_width * CC + j * CC + l] = Math::make_half_float(interp);
  687. } else if (sizeof(T) == 4) { //float
  688. float xofs_frac = float(src_xofs_frac) / (1 << FRAC_BITS);
  689. float yofs_frac = float(src_yofs_frac) / (1 << FRAC_BITS);
  690. const T *src = ((const T *)p_src);
  691. T *dst = ((T *)p_dst);
  692. float p00 = src[y_ofs_up + src_xofs_left + l];
  693. float p10 = src[y_ofs_up + src_xofs_right + l];
  694. float p01 = src[y_ofs_down + src_xofs_left + l];
  695. float p11 = src[y_ofs_down + src_xofs_right + l];
  696. float interp_up = p00 + (p10 - p00) * xofs_frac;
  697. float interp_down = p01 + (p11 - p01) * xofs_frac;
  698. float interp = interp_up + ((interp_down - interp_up) * yofs_frac);
  699. dst[i * p_dst_width * CC + j * CC + l] = interp;
  700. }
  701. }
  702. }
  703. }
  704. }
  705. template <int CC, class T>
  706. static void _scale_nearest(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
  707. for (uint32_t i = 0; i < p_dst_height; i++) {
  708. uint32_t src_yofs = i * p_src_height / p_dst_height;
  709. uint32_t y_ofs = src_yofs * p_src_width * CC;
  710. for (uint32_t j = 0; j < p_dst_width; j++) {
  711. uint32_t src_xofs = j * p_src_width / p_dst_width;
  712. src_xofs *= CC;
  713. for (uint32_t l = 0; l < CC; l++) {
  714. const T *src = ((const T *)p_src);
  715. T *dst = ((T *)p_dst);
  716. T p = src[y_ofs + src_xofs + l];
  717. dst[i * p_dst_width * CC + j * CC + l] = p;
  718. }
  719. }
  720. }
  721. }
  722. #define LANCZOS_TYPE 3
  723. static float _lanczos(float p_x) {
  724. return Math::abs(p_x) >= LANCZOS_TYPE ? 0 : Math::sincn(p_x) * Math::sincn(p_x / LANCZOS_TYPE);
  725. }
  726. template <int CC, class T>
  727. static void _scale_lanczos(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
  728. int32_t src_width = p_src_width;
  729. int32_t src_height = p_src_height;
  730. int32_t dst_height = p_dst_height;
  731. int32_t dst_width = p_dst_width;
  732. uint32_t buffer_size = src_height * dst_width * CC;
  733. float *buffer = memnew_arr(float, buffer_size); // Store the first pass in a buffer
  734. { // FIRST PASS (horizontal)
  735. float x_scale = float(src_width) / float(dst_width);
  736. float scale_factor = MAX(x_scale, 1); // A larger kernel is required only when downscaling
  737. int32_t half_kernel = LANCZOS_TYPE * scale_factor;
  738. float *kernel = memnew_arr(float, half_kernel * 2);
  739. for (int32_t buffer_x = 0; buffer_x < dst_width; buffer_x++) {
  740. // The corresponding point on the source image
  741. float src_x = (buffer_x + 0.5f) * x_scale; // Offset by 0.5 so it uses the pixel's center
  742. int32_t start_x = MAX(0, int32_t(src_x) - half_kernel + 1);
  743. int32_t end_x = MIN(src_width - 1, int32_t(src_x) + half_kernel);
  744. // Create the kernel used by all the pixels of the column
  745. for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
  746. kernel[target_x - start_x] = _lanczos((target_x + 0.5f - src_x) / scale_factor);
  747. }
  748. for (int32_t buffer_y = 0; buffer_y < src_height; buffer_y++) {
  749. float pixel[CC] = { 0 };
  750. float weight = 0;
  751. for (int32_t target_x = start_x; target_x <= end_x; target_x++) {
  752. float lanczos_val = kernel[target_x - start_x];
  753. weight += lanczos_val;
  754. const T *__restrict src_data = ((const T *)p_src) + (buffer_y * src_width + target_x) * CC;
  755. for (uint32_t i = 0; i < CC; i++) {
  756. if (sizeof(T) == 2) { //half float
  757. pixel[i] += Math::half_to_float(src_data[i]) * lanczos_val;
  758. } else {
  759. pixel[i] += src_data[i] * lanczos_val;
  760. }
  761. }
  762. }
  763. float *dst_data = ((float *)buffer) + (buffer_y * dst_width + buffer_x) * CC;
  764. for (uint32_t i = 0; i < CC; i++) {
  765. dst_data[i] = pixel[i] / weight; // Normalize the sum of all the samples
  766. }
  767. }
  768. }
  769. memdelete_arr(kernel);
  770. } // End of first pass
  771. { // SECOND PASS (vertical + result)
  772. float y_scale = float(src_height) / float(dst_height);
  773. float scale_factor = MAX(y_scale, 1);
  774. int32_t half_kernel = LANCZOS_TYPE * scale_factor;
  775. float *kernel = memnew_arr(float, half_kernel * 2);
  776. for (int32_t dst_y = 0; dst_y < dst_height; dst_y++) {
  777. float buffer_y = (dst_y + 0.5f) * y_scale;
  778. int32_t start_y = MAX(0, int32_t(buffer_y) - half_kernel + 1);
  779. int32_t end_y = MIN(src_height - 1, int32_t(buffer_y) + half_kernel);
  780. for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
  781. kernel[target_y - start_y] = _lanczos((target_y + 0.5f - buffer_y) / scale_factor);
  782. }
  783. for (int32_t dst_x = 0; dst_x < dst_width; dst_x++) {
  784. float pixel[CC] = { 0 };
  785. float weight = 0;
  786. for (int32_t target_y = start_y; target_y <= end_y; target_y++) {
  787. float lanczos_val = kernel[target_y - start_y];
  788. weight += lanczos_val;
  789. float *buffer_data = ((float *)buffer) + (target_y * dst_width + dst_x) * CC;
  790. for (uint32_t i = 0; i < CC; i++) {
  791. pixel[i] += buffer_data[i] * lanczos_val;
  792. }
  793. }
  794. T *dst_data = ((T *)p_dst) + (dst_y * dst_width + dst_x) * CC;
  795. for (uint32_t i = 0; i < CC; i++) {
  796. pixel[i] /= weight;
  797. if (sizeof(T) == 1) { //byte
  798. dst_data[i] = CLAMP(Math::fast_ftoi(pixel[i]), 0, 255);
  799. } else if (sizeof(T) == 2) { //half float
  800. dst_data[i] = Math::make_half_float(pixel[i]);
  801. } else { // float
  802. dst_data[i] = pixel[i];
  803. }
  804. }
  805. }
  806. }
  807. memdelete_arr(kernel);
  808. } // End of second pass
  809. memdelete_arr(buffer);
  810. }
  811. static void _overlay(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, float p_alpha, uint32_t p_width, uint32_t p_height, uint32_t p_pixel_size) {
  812. uint16_t alpha = MIN((uint16_t)(p_alpha * 256.0f), 256);
  813. for (uint32_t i = 0; i < p_width * p_height * p_pixel_size; i++) {
  814. p_dst[i] = (p_dst[i] * (256 - alpha) + p_src[i] * alpha) >> 8;
  815. }
  816. }
  817. bool Image::is_size_po2() const {
  818. return uint32_t(width) == next_power_of_2(width) && uint32_t(height) == next_power_of_2(height);
  819. }
  820. void Image::resize_to_po2(bool p_square, Interpolation p_interpolation) {
  821. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
  822. int w = next_power_of_2(width);
  823. int h = next_power_of_2(height);
  824. if (p_square) {
  825. w = h = MAX(w, h);
  826. }
  827. if (w == width && h == height) {
  828. if (!p_square || w == h) {
  829. return; //nothing to do
  830. }
  831. }
  832. resize(w, h, p_interpolation);
  833. }
  834. void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
  835. ERR_FAIL_COND_MSG(data.size() == 0, "Cannot resize image before creating it, use create() or create_from_data() first.");
  836. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot resize in compressed or custom image formats.");
  837. bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */;
  838. ERR_FAIL_COND_MSG(p_width <= 0, "Image width must be greater than 0.");
  839. ERR_FAIL_COND_MSG(p_height <= 0, "Image height must be greater than 0.");
  840. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH, "Image width cannot be greater than " + itos(MAX_WIDTH) + ".");
  841. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT, "Image height cannot be greater than " + itos(MAX_HEIGHT) + ".");
  842. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS, "Too many pixels for image, maximum is " + itos(MAX_PIXELS));
  843. if (p_width == width && p_height == height) {
  844. return;
  845. }
  846. Image dst(p_width, p_height, false, format);
  847. // Setup mipmap-aware scaling
  848. Image dst2;
  849. int mip1 = 0;
  850. int mip2 = 0;
  851. float mip1_weight = 0;
  852. if (mipmap_aware) {
  853. float avg_scale = ((float)p_width / width + (float)p_height / height) * 0.5f;
  854. if (avg_scale >= 1.0f) {
  855. mipmap_aware = false;
  856. } else {
  857. float level = Math::log(1.0f / avg_scale) / Math::log(2.0f);
  858. mip1 = CLAMP((int)Math::floor(level), 0, get_mipmap_count());
  859. mip2 = CLAMP((int)Math::ceil(level), 0, get_mipmap_count());
  860. mip1_weight = 1.0f - (level - mip1);
  861. }
  862. }
  863. bool interpolate_mipmaps = mipmap_aware && mip1 != mip2;
  864. if (interpolate_mipmaps) {
  865. dst2.create(p_width, p_height, false, format);
  866. }
  867. bool had_mipmaps = mipmaps;
  868. if (interpolate_mipmaps && !had_mipmaps) {
  869. generate_mipmaps();
  870. }
  871. // --
  872. const uint8_t *r = data.ptr();
  873. const unsigned char *r_ptr = r;
  874. uint8_t *w = dst.data.ptrw();
  875. unsigned char *w_ptr = w;
  876. switch (p_interpolation) {
  877. case INTERPOLATE_NEAREST: {
  878. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  879. switch (get_format_pixel_size(format)) {
  880. case 1:
  881. _scale_nearest<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  882. break;
  883. case 2:
  884. _scale_nearest<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  885. break;
  886. case 3:
  887. _scale_nearest<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  888. break;
  889. case 4:
  890. _scale_nearest<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  891. break;
  892. }
  893. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  894. switch (get_format_pixel_size(format)) {
  895. case 4:
  896. _scale_nearest<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  897. break;
  898. case 8:
  899. _scale_nearest<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  900. break;
  901. case 12:
  902. _scale_nearest<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  903. break;
  904. case 16:
  905. _scale_nearest<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  906. break;
  907. }
  908. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  909. switch (get_format_pixel_size(format)) {
  910. case 2:
  911. _scale_nearest<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  912. break;
  913. case 4:
  914. _scale_nearest<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  915. break;
  916. case 6:
  917. _scale_nearest<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  918. break;
  919. case 8:
  920. _scale_nearest<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  921. break;
  922. }
  923. }
  924. } break;
  925. case INTERPOLATE_BILINEAR:
  926. case INTERPOLATE_TRILINEAR: {
  927. for (int i = 0; i < 2; ++i) {
  928. int src_width;
  929. int src_height;
  930. const unsigned char *src_ptr;
  931. if (!mipmap_aware) {
  932. if (i == 0) {
  933. // Standard behavior
  934. src_width = width;
  935. src_height = height;
  936. src_ptr = r_ptr;
  937. } else {
  938. // No need for a second iteration
  939. break;
  940. }
  941. } else {
  942. if (i == 0) {
  943. // Read from the first mipmap that will be interpolated
  944. // (if both levels are the same, we will not interpolate, but at least we'll sample from the right level)
  945. int offs;
  946. _get_mipmap_offset_and_size(mip1, offs, src_width, src_height);
  947. src_ptr = r_ptr + offs;
  948. } else if (!interpolate_mipmaps) {
  949. // No need generate a second image
  950. break;
  951. } else {
  952. // Switch to read from the second mipmap that will be interpolated
  953. int offs;
  954. _get_mipmap_offset_and_size(mip2, offs, src_width, src_height);
  955. src_ptr = r_ptr + offs;
  956. // Switch to write to the second destination image
  957. w = dst2.data.ptrw();
  958. w_ptr = w;
  959. }
  960. }
  961. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  962. switch (get_format_pixel_size(format)) {
  963. case 1:
  964. _scale_bilinear<1, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  965. break;
  966. case 2:
  967. _scale_bilinear<2, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  968. break;
  969. case 3:
  970. _scale_bilinear<3, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  971. break;
  972. case 4:
  973. _scale_bilinear<4, uint8_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  974. break;
  975. }
  976. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  977. switch (get_format_pixel_size(format)) {
  978. case 4:
  979. _scale_bilinear<1, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  980. break;
  981. case 8:
  982. _scale_bilinear<2, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  983. break;
  984. case 12:
  985. _scale_bilinear<3, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  986. break;
  987. case 16:
  988. _scale_bilinear<4, float>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  989. break;
  990. }
  991. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  992. switch (get_format_pixel_size(format)) {
  993. case 2:
  994. _scale_bilinear<1, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  995. break;
  996. case 4:
  997. _scale_bilinear<2, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  998. break;
  999. case 6:
  1000. _scale_bilinear<3, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1001. break;
  1002. case 8:
  1003. _scale_bilinear<4, uint16_t>(src_ptr, w_ptr, src_width, src_height, p_width, p_height);
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. if (interpolate_mipmaps) {
  1009. // Switch to read again from the first scaled mipmap to overlay it over the second
  1010. r = dst.data.ptr();
  1011. _overlay(r, w, mip1_weight, p_width, p_height, get_format_pixel_size(format));
  1012. }
  1013. } break;
  1014. case INTERPOLATE_CUBIC: {
  1015. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  1016. switch (get_format_pixel_size(format)) {
  1017. case 1:
  1018. _scale_cubic<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1019. break;
  1020. case 2:
  1021. _scale_cubic<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1022. break;
  1023. case 3:
  1024. _scale_cubic<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1025. break;
  1026. case 4:
  1027. _scale_cubic<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1028. break;
  1029. }
  1030. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  1031. switch (get_format_pixel_size(format)) {
  1032. case 4:
  1033. _scale_cubic<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1034. break;
  1035. case 8:
  1036. _scale_cubic<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1037. break;
  1038. case 12:
  1039. _scale_cubic<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1040. break;
  1041. case 16:
  1042. _scale_cubic<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1043. break;
  1044. }
  1045. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  1046. switch (get_format_pixel_size(format)) {
  1047. case 2:
  1048. _scale_cubic<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1049. break;
  1050. case 4:
  1051. _scale_cubic<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1052. break;
  1053. case 6:
  1054. _scale_cubic<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1055. break;
  1056. case 8:
  1057. _scale_cubic<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1058. break;
  1059. }
  1060. }
  1061. } break;
  1062. case INTERPOLATE_LANCZOS: {
  1063. if (format >= FORMAT_L8 && format <= FORMAT_RGBA8) {
  1064. switch (get_format_pixel_size(format)) {
  1065. case 1:
  1066. _scale_lanczos<1, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1067. break;
  1068. case 2:
  1069. _scale_lanczos<2, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1070. break;
  1071. case 3:
  1072. _scale_lanczos<3, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1073. break;
  1074. case 4:
  1075. _scale_lanczos<4, uint8_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1076. break;
  1077. }
  1078. } else if (format >= FORMAT_RF && format <= FORMAT_RGBAF) {
  1079. switch (get_format_pixel_size(format)) {
  1080. case 4:
  1081. _scale_lanczos<1, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1082. break;
  1083. case 8:
  1084. _scale_lanczos<2, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1085. break;
  1086. case 12:
  1087. _scale_lanczos<3, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1088. break;
  1089. case 16:
  1090. _scale_lanczos<4, float>(r_ptr, w_ptr, width, height, p_width, p_height);
  1091. break;
  1092. }
  1093. } else if (format >= FORMAT_RH && format <= FORMAT_RGBAH) {
  1094. switch (get_format_pixel_size(format)) {
  1095. case 2:
  1096. _scale_lanczos<1, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1097. break;
  1098. case 4:
  1099. _scale_lanczos<2, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1100. break;
  1101. case 6:
  1102. _scale_lanczos<3, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1103. break;
  1104. case 8:
  1105. _scale_lanczos<4, uint16_t>(r_ptr, w_ptr, width, height, p_width, p_height);
  1106. break;
  1107. }
  1108. }
  1109. } break;
  1110. }
  1111. if (interpolate_mipmaps) {
  1112. dst._copy_internals_from(dst2);
  1113. }
  1114. if (had_mipmaps) {
  1115. dst.generate_mipmaps();
  1116. }
  1117. _copy_internals_from(dst);
  1118. }
  1119. void Image::crop_from_point(int p_x, int p_y, int p_width, int p_height) {
  1120. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot crop in compressed or custom image formats.");
  1121. ERR_FAIL_COND_MSG(p_x < 0, "Start x position cannot be smaller than 0.");
  1122. ERR_FAIL_COND_MSG(p_y < 0, "Start y position cannot be smaller than 0.");
  1123. ERR_FAIL_COND_MSG(p_width <= 0, "Width of image must be greater than 0.");
  1124. ERR_FAIL_COND_MSG(p_height <= 0, "Height of image must be greater than 0.");
  1125. ERR_FAIL_COND_MSG(p_x + p_width > MAX_WIDTH, "End x position cannot be greater than " + itos(MAX_WIDTH) + ".");
  1126. ERR_FAIL_COND_MSG(p_y + p_height > MAX_HEIGHT, "End y position cannot be greater than " + itos(MAX_HEIGHT) + ".");
  1127. /* to save memory, cropping should be done in-place, however, since this function
  1128. will most likely either not be used much, or in critical areas, for now it won't, because
  1129. it's a waste of time. */
  1130. if (p_width == width && p_height == height && p_x == 0 && p_y == 0) {
  1131. return;
  1132. }
  1133. uint8_t pdata[16]; //largest is 16
  1134. uint32_t pixel_size = get_format_pixel_size(format);
  1135. Image dst(p_width, p_height, false, format);
  1136. {
  1137. const uint8_t *r = data.ptr();
  1138. uint8_t *w = dst.data.ptrw();
  1139. int m_h = p_y + p_height;
  1140. int m_w = p_x + p_width;
  1141. for (int y = p_y; y < m_h; y++) {
  1142. for (int x = p_x; x < m_w; x++) {
  1143. if ((x >= width || y >= height)) {
  1144. for (uint32_t i = 0; i < pixel_size; i++) {
  1145. pdata[i] = 0;
  1146. }
  1147. } else {
  1148. _get_pixelb(x, y, pixel_size, r, pdata);
  1149. }
  1150. dst._put_pixelb(x - p_x, y - p_y, pixel_size, w, pdata);
  1151. }
  1152. }
  1153. }
  1154. if (has_mipmaps()) {
  1155. dst.generate_mipmaps();
  1156. }
  1157. _copy_internals_from(dst);
  1158. }
  1159. void Image::crop(int p_width, int p_height) {
  1160. crop_from_point(0, 0, p_width, p_height);
  1161. }
  1162. void Image::flip_y() {
  1163. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_y in compressed or custom image formats.");
  1164. bool used_mipmaps = has_mipmaps();
  1165. if (used_mipmaps) {
  1166. clear_mipmaps();
  1167. }
  1168. {
  1169. uint8_t *w = data.ptrw();
  1170. uint8_t up[16];
  1171. uint8_t down[16];
  1172. uint32_t pixel_size = get_format_pixel_size(format);
  1173. for (int y = 0; y < height / 2; y++) {
  1174. for (int x = 0; x < width; x++) {
  1175. _get_pixelb(x, y, pixel_size, w, up);
  1176. _get_pixelb(x, height - y - 1, pixel_size, w, down);
  1177. _put_pixelb(x, height - y - 1, pixel_size, w, up);
  1178. _put_pixelb(x, y, pixel_size, w, down);
  1179. }
  1180. }
  1181. }
  1182. if (used_mipmaps) {
  1183. generate_mipmaps();
  1184. }
  1185. }
  1186. void Image::flip_x() {
  1187. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot flip_x in compressed or custom image formats.");
  1188. bool used_mipmaps = has_mipmaps();
  1189. if (used_mipmaps) {
  1190. clear_mipmaps();
  1191. }
  1192. {
  1193. uint8_t *w = data.ptrw();
  1194. uint8_t up[16];
  1195. uint8_t down[16];
  1196. uint32_t pixel_size = get_format_pixel_size(format);
  1197. for (int y = 0; y < height; y++) {
  1198. for (int x = 0; x < width / 2; x++) {
  1199. _get_pixelb(x, y, pixel_size, w, up);
  1200. _get_pixelb(width - x - 1, y, pixel_size, w, down);
  1201. _put_pixelb(width - x - 1, y, pixel_size, w, up);
  1202. _put_pixelb(x, y, pixel_size, w, down);
  1203. }
  1204. }
  1205. }
  1206. if (used_mipmaps) {
  1207. generate_mipmaps();
  1208. }
  1209. }
  1210. /// Get mipmap size and offset.
  1211. int Image::_get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps, int *r_mm_width, int *r_mm_height) {
  1212. // Data offset in mipmaps (including the original texture).
  1213. int size = 0;
  1214. int w = p_width;
  1215. int h = p_height;
  1216. // Current mipmap index in the loop below. p_mipmaps is the target mipmap index.
  1217. // In this function, mipmap 0 represents the first mipmap instead of the original texture.
  1218. int mm = 0;
  1219. int pixsize = get_format_pixel_size(p_format);
  1220. int pixshift = get_format_pixel_rshift(p_format);
  1221. int block = get_format_block_size(p_format);
  1222. // Technically, you can still compress up to 1 px no matter the format, so commenting this.
  1223. //int minw, minh;
  1224. //get_format_min_pixel_size(p_format, minw, minh);
  1225. int minw = 1, minh = 1;
  1226. while (true) {
  1227. int bw = w % block != 0 ? w + (block - w % block) : w;
  1228. int bh = h % block != 0 ? h + (block - h % block) : h;
  1229. int s = bw * bh;
  1230. s *= pixsize;
  1231. s >>= pixshift;
  1232. size += s;
  1233. if (p_mipmaps >= 0) {
  1234. w = MAX(minw, w >> 1);
  1235. h = MAX(minh, h >> 1);
  1236. } else {
  1237. if (w == minw && h == minh) {
  1238. break;
  1239. }
  1240. w = MAX(minw, w >> 1);
  1241. h = MAX(minh, h >> 1);
  1242. }
  1243. // Set mipmap size.
  1244. if (r_mm_width) {
  1245. *r_mm_width = w;
  1246. }
  1247. if (r_mm_height) {
  1248. *r_mm_height = h;
  1249. }
  1250. // Reach target mipmap.
  1251. if (p_mipmaps >= 0 && mm == p_mipmaps) {
  1252. break;
  1253. }
  1254. mm++;
  1255. }
  1256. r_mipmaps = mm;
  1257. return size;
  1258. }
  1259. bool Image::_can_modify(Format p_format) const {
  1260. return p_format <= FORMAT_RGBE9995;
  1261. }
  1262. template <class Component, int CC, bool renormalize,
  1263. void (*average_func)(Component &, const Component &, const Component &, const Component &, const Component &),
  1264. void (*renormalize_func)(Component *)>
  1265. static void _generate_po2_mipmap(const Component *p_src, Component *p_dst, uint32_t p_width, uint32_t p_height) {
  1266. //fast power of 2 mipmap generation
  1267. uint32_t dst_w = MAX(p_width >> 1, 1u);
  1268. uint32_t dst_h = MAX(p_height >> 1, 1u);
  1269. int right_step = (p_width == 1) ? 0 : CC;
  1270. int down_step = (p_height == 1) ? 0 : (p_width * CC);
  1271. for (uint32_t i = 0; i < dst_h; i++) {
  1272. const Component *rup_ptr = &p_src[i * 2 * down_step];
  1273. const Component *rdown_ptr = rup_ptr + down_step;
  1274. Component *dst_ptr = &p_dst[i * dst_w * CC];
  1275. uint32_t count = dst_w;
  1276. while (count) {
  1277. count--;
  1278. for (int j = 0; j < CC; j++) {
  1279. average_func(dst_ptr[j], rup_ptr[j], rup_ptr[j + right_step], rdown_ptr[j], rdown_ptr[j + right_step]);
  1280. }
  1281. if (renormalize) {
  1282. renormalize_func(dst_ptr);
  1283. }
  1284. dst_ptr += CC;
  1285. rup_ptr += right_step * 2;
  1286. rdown_ptr += right_step * 2;
  1287. }
  1288. }
  1289. }
  1290. void Image::shrink_x2() {
  1291. ERR_FAIL_COND(data.size() == 0);
  1292. if (mipmaps) {
  1293. //just use the lower mipmap as base and copy all
  1294. Vector<uint8_t> new_img;
  1295. int ofs = get_mipmap_offset(1);
  1296. int new_size = data.size() - ofs;
  1297. new_img.resize(new_size);
  1298. ERR_FAIL_COND(new_img.size() == 0);
  1299. {
  1300. uint8_t *w = new_img.ptrw();
  1301. const uint8_t *r = data.ptr();
  1302. memcpy(w, &r[ofs], new_size);
  1303. }
  1304. width = MAX(width / 2, 1);
  1305. height = MAX(height / 2, 1);
  1306. data = new_img;
  1307. } else {
  1308. Vector<uint8_t> new_img;
  1309. ERR_FAIL_COND(!_can_modify(format));
  1310. int ps = get_format_pixel_size(format);
  1311. new_img.resize((width / 2) * (height / 2) * ps);
  1312. ERR_FAIL_COND(new_img.size() == 0);
  1313. ERR_FAIL_COND(data.size() == 0);
  1314. {
  1315. uint8_t *w = new_img.ptrw();
  1316. const uint8_t *r = data.ptr();
  1317. switch (format) {
  1318. case FORMAT_L8:
  1319. case FORMAT_R8:
  1320. _generate_po2_mipmap<uint8_t, 1, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1321. break;
  1322. case FORMAT_LA8:
  1323. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1324. break;
  1325. case FORMAT_RG8:
  1326. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1327. break;
  1328. case FORMAT_RGB8:
  1329. _generate_po2_mipmap<uint8_t, 3, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1330. break;
  1331. case FORMAT_RGBA8:
  1332. _generate_po2_mipmap<uint8_t, 4, false, Image::average_4_uint8, Image::renormalize_uint8>(r, w, width, height);
  1333. break;
  1334. case FORMAT_RF:
  1335. _generate_po2_mipmap<float, 1, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1336. break;
  1337. case FORMAT_RGF:
  1338. _generate_po2_mipmap<float, 2, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1339. break;
  1340. case FORMAT_RGBF:
  1341. _generate_po2_mipmap<float, 3, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1342. break;
  1343. case FORMAT_RGBAF:
  1344. _generate_po2_mipmap<float, 4, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(r), reinterpret_cast<float *>(w), width, height);
  1345. break;
  1346. case FORMAT_RH:
  1347. _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1348. break;
  1349. case FORMAT_RGH:
  1350. _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1351. break;
  1352. case FORMAT_RGBH:
  1353. _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1354. break;
  1355. case FORMAT_RGBAH:
  1356. _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r), reinterpret_cast<uint16_t *>(w), width, height);
  1357. break;
  1358. case FORMAT_RGBE9995:
  1359. _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(r), reinterpret_cast<uint32_t *>(w), width, height);
  1360. break;
  1361. default: {
  1362. }
  1363. }
  1364. }
  1365. width /= 2;
  1366. height /= 2;
  1367. data = new_img;
  1368. }
  1369. }
  1370. void Image::normalize() {
  1371. bool used_mipmaps = has_mipmaps();
  1372. if (used_mipmaps) {
  1373. clear_mipmaps();
  1374. }
  1375. for (int y = 0; y < height; y++) {
  1376. for (int x = 0; x < width; x++) {
  1377. Color c = get_pixel(x, y);
  1378. Vector3 v(c.r * 2.0 - 1.0, c.g * 2.0 - 1.0, c.b * 2.0 - 1.0);
  1379. v.normalize();
  1380. c.r = v.x * 0.5 + 0.5;
  1381. c.g = v.y * 0.5 + 0.5;
  1382. c.b = v.z * 0.5 + 0.5;
  1383. set_pixel(x, y, c);
  1384. }
  1385. }
  1386. if (used_mipmaps) {
  1387. generate_mipmaps(true);
  1388. }
  1389. }
  1390. Error Image::generate_mipmaps(bool p_renormalize) {
  1391. ERR_FAIL_COND_V_MSG(!_can_modify(format), ERR_UNAVAILABLE, "Cannot generate mipmaps in compressed or custom image formats.");
  1392. ERR_FAIL_COND_V_MSG(format == FORMAT_RGBA4444, ERR_UNAVAILABLE, "Cannot generate mipmaps from RGBA4444 format.");
  1393. ERR_FAIL_COND_V_MSG(width == 0 || height == 0, ERR_UNCONFIGURED, "Cannot generate mipmaps with width or height equal to 0.");
  1394. int mmcount;
  1395. int size = _get_dst_image_size(width, height, format, mmcount);
  1396. data.resize(size);
  1397. uint8_t *wp = data.ptrw();
  1398. int prev_ofs = 0;
  1399. int prev_h = height;
  1400. int prev_w = width;
  1401. for (int i = 1; i <= mmcount; i++) {
  1402. int ofs, w, h;
  1403. _get_mipmap_offset_and_size(i, ofs, w, h);
  1404. switch (format) {
  1405. case FORMAT_L8:
  1406. case FORMAT_R8:
  1407. _generate_po2_mipmap<uint8_t, 1, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1408. break;
  1409. case FORMAT_LA8:
  1410. case FORMAT_RG8:
  1411. _generate_po2_mipmap<uint8_t, 2, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1412. break;
  1413. case FORMAT_RGB8:
  1414. if (p_renormalize) {
  1415. _generate_po2_mipmap<uint8_t, 3, true, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1416. } else {
  1417. _generate_po2_mipmap<uint8_t, 3, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1418. }
  1419. break;
  1420. case FORMAT_RGBA8:
  1421. if (p_renormalize) {
  1422. _generate_po2_mipmap<uint8_t, 4, true, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1423. } else {
  1424. _generate_po2_mipmap<uint8_t, 4, false, Image::average_4_uint8, Image::renormalize_uint8>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h);
  1425. }
  1426. break;
  1427. case FORMAT_RF:
  1428. _generate_po2_mipmap<float, 1, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1429. break;
  1430. case FORMAT_RGF:
  1431. _generate_po2_mipmap<float, 2, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1432. break;
  1433. case FORMAT_RGBF:
  1434. if (p_renormalize) {
  1435. _generate_po2_mipmap<float, 3, true, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1436. } else {
  1437. _generate_po2_mipmap<float, 3, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1438. }
  1439. break;
  1440. case FORMAT_RGBAF:
  1441. if (p_renormalize) {
  1442. _generate_po2_mipmap<float, 4, true, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1443. } else {
  1444. _generate_po2_mipmap<float, 4, false, Image::average_4_float, Image::renormalize_float>(reinterpret_cast<const float *>(&wp[prev_ofs]), reinterpret_cast<float *>(&wp[ofs]), prev_w, prev_h);
  1445. }
  1446. break;
  1447. case FORMAT_RH:
  1448. _generate_po2_mipmap<uint16_t, 1, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1449. break;
  1450. case FORMAT_RGH:
  1451. _generate_po2_mipmap<uint16_t, 2, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1452. break;
  1453. case FORMAT_RGBH:
  1454. if (p_renormalize) {
  1455. _generate_po2_mipmap<uint16_t, 3, true, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1456. } else {
  1457. _generate_po2_mipmap<uint16_t, 3, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1458. }
  1459. break;
  1460. case FORMAT_RGBAH:
  1461. if (p_renormalize) {
  1462. _generate_po2_mipmap<uint16_t, 4, true, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1463. } else {
  1464. _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(&wp[prev_ofs]), reinterpret_cast<uint16_t *>(&wp[ofs]), prev_w, prev_h);
  1465. }
  1466. break;
  1467. case FORMAT_RGBE9995:
  1468. if (p_renormalize) {
  1469. _generate_po2_mipmap<uint32_t, 1, true, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(&wp[prev_ofs]), reinterpret_cast<uint32_t *>(&wp[ofs]), prev_w, prev_h);
  1470. } else {
  1471. _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(&wp[prev_ofs]), reinterpret_cast<uint32_t *>(&wp[ofs]), prev_w, prev_h);
  1472. }
  1473. break;
  1474. default: {
  1475. }
  1476. }
  1477. prev_ofs = ofs;
  1478. prev_w = w;
  1479. prev_h = h;
  1480. }
  1481. mipmaps = true;
  1482. return OK;
  1483. }
  1484. Error Image::generate_mipmap_roughness(RoughnessChannel p_roughness_channel, const Ref<Image> &p_normal_map) {
  1485. Vector<double> normal_sat_vec; //summed area table
  1486. double *normal_sat = nullptr; //summed area table for normal map
  1487. int normal_w = 0, normal_h = 0;
  1488. ERR_FAIL_COND_V_MSG(p_normal_map.is_null() || p_normal_map->is_empty(), ERR_INVALID_PARAMETER, "Must provide a valid normal map for roughness mipmaps");
  1489. Ref<Image> nm = p_normal_map->duplicate();
  1490. if (nm->is_compressed()) {
  1491. nm->decompress();
  1492. }
  1493. normal_w = nm->get_width();
  1494. normal_h = nm->get_height();
  1495. normal_sat_vec.resize(normal_w * normal_h * 3);
  1496. normal_sat = normal_sat_vec.ptrw();
  1497. //create summed area table
  1498. for (int y = 0; y < normal_h; y++) {
  1499. double line_sum[3] = { 0, 0, 0 };
  1500. for (int x = 0; x < normal_w; x++) {
  1501. double normal[3];
  1502. Color color = nm->get_pixel(x, y);
  1503. normal[0] = color.r * 2.0 - 1.0;
  1504. normal[1] = color.g * 2.0 - 1.0;
  1505. normal[2] = Math::sqrt(MAX(0.0, 1.0 - (normal[0] * normal[0] + normal[1] * normal[1]))); //reconstruct if missing
  1506. line_sum[0] += normal[0];
  1507. line_sum[1] += normal[1];
  1508. line_sum[2] += normal[2];
  1509. uint32_t ofs = (y * normal_w + x) * 3;
  1510. normal_sat[ofs + 0] = line_sum[0];
  1511. normal_sat[ofs + 1] = line_sum[1];
  1512. normal_sat[ofs + 2] = line_sum[2];
  1513. if (y > 0) {
  1514. uint32_t prev_ofs = ((y - 1) * normal_w + x) * 3;
  1515. normal_sat[ofs + 0] += normal_sat[prev_ofs + 0];
  1516. normal_sat[ofs + 1] += normal_sat[prev_ofs + 1];
  1517. normal_sat[ofs + 2] += normal_sat[prev_ofs + 2];
  1518. }
  1519. }
  1520. }
  1521. #if 0
  1522. {
  1523. Vector3 beg(normal_sat_vec[0], normal_sat_vec[1], normal_sat_vec[2]);
  1524. Vector3 end(normal_sat_vec[normal_sat_vec.size() - 3], normal_sat_vec[normal_sat_vec.size() - 2], normal_sat_vec[normal_sat_vec.size() - 1]);
  1525. Vector3 avg = (end - beg) / (normal_w * normal_h);
  1526. print_line("average: " + avg);
  1527. }
  1528. #endif
  1529. int mmcount;
  1530. _get_dst_image_size(width, height, format, mmcount);
  1531. uint8_t *base_ptr = data.ptrw();
  1532. for (int i = 1; i <= mmcount; i++) {
  1533. int ofs, w, h;
  1534. _get_mipmap_offset_and_size(i, ofs, w, h);
  1535. uint8_t *ptr = &base_ptr[ofs];
  1536. for (int x = 0; x < w; x++) {
  1537. for (int y = 0; y < h; y++) {
  1538. int from_x = x * normal_w / w;
  1539. int from_y = y * normal_h / h;
  1540. int to_x = (x + 1) * normal_w / w;
  1541. int to_y = (y + 1) * normal_h / h;
  1542. to_x = MIN(to_x - 1, normal_w);
  1543. to_y = MIN(to_y - 1, normal_h);
  1544. int size_x = (to_x - from_x) + 1;
  1545. int size_y = (to_y - from_y) + 1;
  1546. //summed area table version (much faster)
  1547. double avg[3] = { 0, 0, 0 };
  1548. if (from_x > 0 && from_y > 0) {
  1549. uint32_t tofs = ((from_y - 1) * normal_w + (from_x - 1)) * 3;
  1550. avg[0] += normal_sat[tofs + 0];
  1551. avg[1] += normal_sat[tofs + 1];
  1552. avg[2] += normal_sat[tofs + 2];
  1553. }
  1554. if (from_y > 0) {
  1555. uint32_t tofs = ((from_y - 1) * normal_w + to_x) * 3;
  1556. avg[0] -= normal_sat[tofs + 0];
  1557. avg[1] -= normal_sat[tofs + 1];
  1558. avg[2] -= normal_sat[tofs + 2];
  1559. }
  1560. if (from_x > 0) {
  1561. uint32_t tofs = (to_y * normal_w + (from_x - 1)) * 3;
  1562. avg[0] -= normal_sat[tofs + 0];
  1563. avg[1] -= normal_sat[tofs + 1];
  1564. avg[2] -= normal_sat[tofs + 2];
  1565. }
  1566. uint32_t tofs = (to_y * normal_w + to_x) * 3;
  1567. avg[0] += normal_sat[tofs + 0];
  1568. avg[1] += normal_sat[tofs + 1];
  1569. avg[2] += normal_sat[tofs + 2];
  1570. double div = double(size_x * size_y);
  1571. Vector3 vec(avg[0] / div, avg[1] / div, avg[2] / div);
  1572. float r = vec.length();
  1573. int pixel_ofs = y * w + x;
  1574. Color c = _get_color_at_ofs(ptr, pixel_ofs);
  1575. float roughness = 0;
  1576. switch (p_roughness_channel) {
  1577. case ROUGHNESS_CHANNEL_R: {
  1578. roughness = c.r;
  1579. } break;
  1580. case ROUGHNESS_CHANNEL_G: {
  1581. roughness = c.g;
  1582. } break;
  1583. case ROUGHNESS_CHANNEL_B: {
  1584. roughness = c.b;
  1585. } break;
  1586. case ROUGHNESS_CHANNEL_L: {
  1587. roughness = c.get_v();
  1588. } break;
  1589. case ROUGHNESS_CHANNEL_A: {
  1590. roughness = c.a;
  1591. } break;
  1592. }
  1593. float variance = 0;
  1594. if (r < 1.0f) {
  1595. float r2 = r * r;
  1596. float kappa = (3.0f * r - r * r2) / (1.0f - r2);
  1597. variance = 0.25f / kappa;
  1598. }
  1599. float threshold = 0.4;
  1600. roughness = Math::sqrt(roughness * roughness + MIN(3.0f * variance, threshold * threshold));
  1601. switch (p_roughness_channel) {
  1602. case ROUGHNESS_CHANNEL_R: {
  1603. c.r = roughness;
  1604. } break;
  1605. case ROUGHNESS_CHANNEL_G: {
  1606. c.g = roughness;
  1607. } break;
  1608. case ROUGHNESS_CHANNEL_B: {
  1609. c.b = roughness;
  1610. } break;
  1611. case ROUGHNESS_CHANNEL_L: {
  1612. c.r = roughness;
  1613. c.g = roughness;
  1614. c.b = roughness;
  1615. } break;
  1616. case ROUGHNESS_CHANNEL_A: {
  1617. c.a = roughness;
  1618. } break;
  1619. }
  1620. _set_color_at_ofs(ptr, pixel_ofs, c);
  1621. }
  1622. }
  1623. #if 0
  1624. {
  1625. int size = get_mipmap_byte_size(i);
  1626. print_line("size for mimpap " + itos(i) + ": " + itos(size));
  1627. Vector<uint8_t> imgdata;
  1628. imgdata.resize(size);
  1629. uint8_t* wr = imgdata.ptrw();
  1630. memcpy(wr.ptr(), ptr, size);
  1631. wr = uint8_t*();
  1632. Ref<Image> im;
  1633. im.instantiate();
  1634. im->create(w, h, false, format, imgdata);
  1635. im->save_png("res://mipmap_" + itos(i) + ".png");
  1636. }
  1637. #endif
  1638. }
  1639. return OK;
  1640. }
  1641. void Image::clear_mipmaps() {
  1642. if (!mipmaps) {
  1643. return;
  1644. }
  1645. if (is_empty()) {
  1646. return;
  1647. }
  1648. int ofs, w, h;
  1649. _get_mipmap_offset_and_size(1, ofs, w, h);
  1650. data.resize(ofs);
  1651. mipmaps = false;
  1652. }
  1653. bool Image::is_empty() const {
  1654. return (data.size() == 0);
  1655. }
  1656. Vector<uint8_t> Image::get_data() const {
  1657. return data;
  1658. }
  1659. void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  1660. ERR_FAIL_COND_MSG(p_width <= 0, "Image width must be greater than 0.");
  1661. ERR_FAIL_COND_MSG(p_height <= 0, "Image height must be greater than 0.");
  1662. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH, "Image width cannot be greater than " + itos(MAX_WIDTH) + ".");
  1663. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT, "Image height cannot be greater than " + itos(MAX_HEIGHT) + ".");
  1664. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS, "Too many pixels for image, maximum is " + itos(MAX_PIXELS));
  1665. ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, "Image format out of range, please see Image's Format enum.");
  1666. int mm = 0;
  1667. int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
  1668. data.resize(size);
  1669. {
  1670. uint8_t *w = data.ptrw();
  1671. memset(w, 0, size);
  1672. }
  1673. width = p_width;
  1674. height = p_height;
  1675. mipmaps = p_use_mipmaps;
  1676. format = p_format;
  1677. }
  1678. void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  1679. ERR_FAIL_COND_MSG(p_width <= 0, "Image width must be greater than 0.");
  1680. ERR_FAIL_COND_MSG(p_height <= 0, "Image height must be greater than 0.");
  1681. ERR_FAIL_COND_MSG(p_width > MAX_WIDTH, "Image width cannot be greater than " + itos(MAX_WIDTH) + ".");
  1682. ERR_FAIL_COND_MSG(p_height > MAX_HEIGHT, "Image height cannot be greater than " + itos(MAX_HEIGHT) + ".");
  1683. ERR_FAIL_COND_MSG(p_width * p_height > MAX_PIXELS, "Too many pixels for image, maximum is " + itos(MAX_PIXELS));
  1684. ERR_FAIL_INDEX_MSG(p_format, FORMAT_MAX, "Image format out of range, please see Image's Format enum.");
  1685. int mm;
  1686. int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
  1687. ERR_FAIL_COND_MSG(p_data.size() != size, "Expected data size of " + itos(size) + " bytes in Image::create(), got instead " + itos(p_data.size()) + " bytes.");
  1688. height = p_height;
  1689. width = p_width;
  1690. format = p_format;
  1691. data = p_data;
  1692. mipmaps = p_use_mipmaps;
  1693. }
  1694. void Image::create(const char **p_xpm) {
  1695. int size_width = 0;
  1696. int size_height = 0;
  1697. int pixelchars = 0;
  1698. mipmaps = false;
  1699. bool has_alpha = false;
  1700. enum Status {
  1701. READING_HEADER,
  1702. READING_COLORS,
  1703. READING_PIXELS,
  1704. DONE
  1705. };
  1706. Status status = READING_HEADER;
  1707. int line = 0;
  1708. HashMap<String, Color> colormap;
  1709. int colormap_size = 0;
  1710. uint32_t pixel_size = 0;
  1711. uint8_t *data_write = nullptr;
  1712. while (status != DONE) {
  1713. const char *line_ptr = p_xpm[line];
  1714. switch (status) {
  1715. case READING_HEADER: {
  1716. String line_str = line_ptr;
  1717. line_str.replace("\t", " ");
  1718. size_width = line_str.get_slicec(' ', 0).to_int();
  1719. size_height = line_str.get_slicec(' ', 1).to_int();
  1720. colormap_size = line_str.get_slicec(' ', 2).to_int();
  1721. pixelchars = line_str.get_slicec(' ', 3).to_int();
  1722. ERR_FAIL_COND(colormap_size > 32766);
  1723. ERR_FAIL_COND(pixelchars > 5);
  1724. ERR_FAIL_COND(size_width > 32767);
  1725. ERR_FAIL_COND(size_height > 32767);
  1726. status = READING_COLORS;
  1727. } break;
  1728. case READING_COLORS: {
  1729. String colorstring;
  1730. for (int i = 0; i < pixelchars; i++) {
  1731. colorstring += *line_ptr;
  1732. line_ptr++;
  1733. }
  1734. //skip spaces
  1735. while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
  1736. if (*line_ptr == 0) {
  1737. break;
  1738. }
  1739. line_ptr++;
  1740. }
  1741. if (*line_ptr == 'c') {
  1742. line_ptr++;
  1743. while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
  1744. if (*line_ptr == 0) {
  1745. break;
  1746. }
  1747. line_ptr++;
  1748. }
  1749. if (*line_ptr == '#') {
  1750. line_ptr++;
  1751. uint8_t col_r = 0;
  1752. uint8_t col_g = 0;
  1753. uint8_t col_b = 0;
  1754. //uint8_t col_a=255;
  1755. for (int i = 0; i < 6; i++) {
  1756. char v = line_ptr[i];
  1757. if (is_digit(v)) {
  1758. v -= '0';
  1759. } else if (v >= 'A' && v <= 'F') {
  1760. v = (v - 'A') + 10;
  1761. } else if (v >= 'a' && v <= 'f') {
  1762. v = (v - 'a') + 10;
  1763. } else {
  1764. break;
  1765. }
  1766. switch (i) {
  1767. case 0:
  1768. col_r = v << 4;
  1769. break;
  1770. case 1:
  1771. col_r |= v;
  1772. break;
  1773. case 2:
  1774. col_g = v << 4;
  1775. break;
  1776. case 3:
  1777. col_g |= v;
  1778. break;
  1779. case 4:
  1780. col_b = v << 4;
  1781. break;
  1782. case 5:
  1783. col_b |= v;
  1784. break;
  1785. }
  1786. }
  1787. // magenta mask
  1788. if (col_r == 255 && col_g == 0 && col_b == 255) {
  1789. colormap[colorstring] = Color(0, 0, 0, 0);
  1790. has_alpha = true;
  1791. } else {
  1792. colormap[colorstring] = Color(col_r / 255.0, col_g / 255.0, col_b / 255.0, 1.0);
  1793. }
  1794. }
  1795. }
  1796. if (line == colormap_size) {
  1797. status = READING_PIXELS;
  1798. create(size_width, size_height, false, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
  1799. data_write = data.ptrw();
  1800. pixel_size = has_alpha ? 4 : 3;
  1801. }
  1802. } break;
  1803. case READING_PIXELS: {
  1804. int y = line - colormap_size - 1;
  1805. for (int x = 0; x < size_width; x++) {
  1806. char pixelstr[6] = { 0, 0, 0, 0, 0, 0 };
  1807. for (int i = 0; i < pixelchars; i++) {
  1808. pixelstr[i] = line_ptr[x * pixelchars + i];
  1809. }
  1810. Color *colorptr = colormap.getptr(pixelstr);
  1811. ERR_FAIL_COND(!colorptr);
  1812. uint8_t pixel[4];
  1813. for (uint32_t i = 0; i < pixel_size; i++) {
  1814. pixel[i] = CLAMP((*colorptr)[i] * 255, 0, 255);
  1815. }
  1816. _put_pixelb(x, y, pixel_size, data_write, pixel);
  1817. }
  1818. if (y == (size_height - 1)) {
  1819. status = DONE;
  1820. }
  1821. } break;
  1822. default: {
  1823. }
  1824. }
  1825. line++;
  1826. }
  1827. }
  1828. #define DETECT_ALPHA_MAX_THRESHOLD 254
  1829. #define DETECT_ALPHA_MIN_THRESHOLD 2
  1830. #define DETECT_ALPHA(m_value) \
  1831. { \
  1832. uint8_t value = m_value; \
  1833. if (value < DETECT_ALPHA_MIN_THRESHOLD) \
  1834. bit = true; \
  1835. else if (value < DETECT_ALPHA_MAX_THRESHOLD) { \
  1836. detected = true; \
  1837. break; \
  1838. } \
  1839. }
  1840. #define DETECT_NON_ALPHA(m_value) \
  1841. { \
  1842. uint8_t value = m_value; \
  1843. if (value > 0) { \
  1844. detected = true; \
  1845. break; \
  1846. } \
  1847. }
  1848. bool Image::is_invisible() const {
  1849. if (format == FORMAT_L8 ||
  1850. format == FORMAT_RGB8 || format == FORMAT_RG8) {
  1851. return false;
  1852. }
  1853. int len = data.size();
  1854. if (len == 0) {
  1855. return true;
  1856. }
  1857. int w, h;
  1858. _get_mipmap_offset_and_size(1, len, w, h);
  1859. const uint8_t *r = data.ptr();
  1860. const unsigned char *data_ptr = r;
  1861. bool detected = false;
  1862. switch (format) {
  1863. case FORMAT_LA8: {
  1864. for (int i = 0; i < (len >> 1); i++) {
  1865. DETECT_NON_ALPHA(data_ptr[(i << 1) + 1]);
  1866. }
  1867. } break;
  1868. case FORMAT_RGBA8: {
  1869. for (int i = 0; i < (len >> 2); i++) {
  1870. DETECT_NON_ALPHA(data_ptr[(i << 2) + 3])
  1871. }
  1872. } break;
  1873. case FORMAT_DXT3:
  1874. case FORMAT_DXT5: {
  1875. detected = true;
  1876. } break;
  1877. default: {
  1878. }
  1879. }
  1880. return !detected;
  1881. }
  1882. Image::AlphaMode Image::detect_alpha() const {
  1883. int len = data.size();
  1884. if (len == 0) {
  1885. return ALPHA_NONE;
  1886. }
  1887. int w, h;
  1888. _get_mipmap_offset_and_size(1, len, w, h);
  1889. const uint8_t *r = data.ptr();
  1890. const unsigned char *data_ptr = r;
  1891. bool bit = false;
  1892. bool detected = false;
  1893. switch (format) {
  1894. case FORMAT_LA8: {
  1895. for (int i = 0; i < (len >> 1); i++) {
  1896. DETECT_ALPHA(data_ptr[(i << 1) + 1]);
  1897. }
  1898. } break;
  1899. case FORMAT_RGBA8: {
  1900. for (int i = 0; i < (len >> 2); i++) {
  1901. DETECT_ALPHA(data_ptr[(i << 2) + 3])
  1902. }
  1903. } break;
  1904. case FORMAT_DXT3:
  1905. case FORMAT_DXT5: {
  1906. detected = true;
  1907. } break;
  1908. default: {
  1909. }
  1910. }
  1911. if (detected) {
  1912. return ALPHA_BLEND;
  1913. } else if (bit) {
  1914. return ALPHA_BIT;
  1915. } else {
  1916. return ALPHA_NONE;
  1917. }
  1918. }
  1919. Error Image::load(const String &p_path) {
  1920. #ifdef DEBUG_ENABLED
  1921. if (p_path.begins_with("res://") && ResourceLoader::exists(p_path)) {
  1922. WARN_PRINT("Loaded resource as image file, this will not work on export: '" + p_path + "'. Instead, import the image file as an Image resource and load it normally as a resource.");
  1923. }
  1924. #endif
  1925. return ImageLoader::load_image(p_path, this);
  1926. }
  1927. Error Image::save_png(const String &p_path) const {
  1928. if (save_png_func == nullptr) {
  1929. return ERR_UNAVAILABLE;
  1930. }
  1931. return save_png_func(p_path, Ref<Image>((Image *)this));
  1932. }
  1933. Vector<uint8_t> Image::save_png_to_buffer() const {
  1934. if (save_png_buffer_func == nullptr) {
  1935. return Vector<uint8_t>();
  1936. }
  1937. return save_png_buffer_func(Ref<Image>((Image *)this));
  1938. }
  1939. Error Image::save_exr(const String &p_path, bool p_grayscale) const {
  1940. if (save_exr_func == nullptr) {
  1941. return ERR_UNAVAILABLE;
  1942. }
  1943. return save_exr_func(p_path, Ref<Image>((Image *)this), p_grayscale);
  1944. }
  1945. int Image::get_image_data_size(int p_width, int p_height, Format p_format, bool p_mipmaps) {
  1946. int mm;
  1947. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps ? -1 : 0);
  1948. }
  1949. int Image::get_image_required_mipmaps(int p_width, int p_height, Format p_format) {
  1950. int mm;
  1951. _get_dst_image_size(p_width, p_height, p_format, mm, -1);
  1952. return mm;
  1953. }
  1954. Size2i Image::get_image_mipmap_size(int p_width, int p_height, Format p_format, int p_mipmap) {
  1955. int mm;
  1956. Size2i ret;
  1957. _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap, &ret.x, &ret.y);
  1958. return ret;
  1959. }
  1960. int Image::get_image_mipmap_offset(int p_width, int p_height, Format p_format, int p_mipmap) {
  1961. if (p_mipmap <= 0) {
  1962. return 0;
  1963. }
  1964. int mm;
  1965. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1);
  1966. }
  1967. int Image::get_image_mipmap_offset_and_dimensions(int p_width, int p_height, Format p_format, int p_mipmap, int &r_w, int &r_h) {
  1968. if (p_mipmap <= 0) {
  1969. r_w = p_width;
  1970. r_h = p_height;
  1971. return 0;
  1972. }
  1973. int mm;
  1974. return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmap - 1, &r_w, &r_h);
  1975. }
  1976. bool Image::is_compressed() const {
  1977. return format > FORMAT_RGBE9995;
  1978. }
  1979. Error Image::decompress() {
  1980. if (((format >= FORMAT_DXT1 && format <= FORMAT_RGTC_RG) || (format == FORMAT_DXT5_RA_AS_RG)) && _image_decompress_bc) {
  1981. _image_decompress_bc(this);
  1982. } else if (format >= FORMAT_BPTC_RGBA && format <= FORMAT_BPTC_RGBFU && _image_decompress_bptc) {
  1983. _image_decompress_bptc(this);
  1984. } else if (format == FORMAT_ETC && _image_decompress_etc1) {
  1985. _image_decompress_etc1(this);
  1986. } else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RA_AS_RG && _image_decompress_etc2) {
  1987. _image_decompress_etc2(this);
  1988. } else {
  1989. return ERR_UNAVAILABLE;
  1990. }
  1991. return OK;
  1992. }
  1993. Error Image::compress(CompressMode p_mode, CompressSource p_source, float p_lossy_quality) {
  1994. ERR_FAIL_INDEX_V_MSG(p_mode, COMPRESS_MAX, ERR_INVALID_PARAMETER, "Invalid compress mode.");
  1995. ERR_FAIL_INDEX_V_MSG(p_source, COMPRESS_SOURCE_MAX, ERR_INVALID_PARAMETER, "Invalid compress source.");
  1996. return compress_from_channels(p_mode, detect_used_channels(p_source), p_lossy_quality);
  1997. }
  1998. Error Image::compress_from_channels(CompressMode p_mode, UsedChannels p_channels, float p_lossy_quality) {
  1999. switch (p_mode) {
  2000. case COMPRESS_S3TC: {
  2001. ERR_FAIL_COND_V(!_image_compress_bc_func, ERR_UNAVAILABLE);
  2002. _image_compress_bc_func(this, p_lossy_quality, p_channels);
  2003. } break;
  2004. case COMPRESS_ETC: {
  2005. ERR_FAIL_COND_V(!_image_compress_etc1_func, ERR_UNAVAILABLE);
  2006. _image_compress_etc1_func(this, p_lossy_quality);
  2007. } break;
  2008. case COMPRESS_ETC2: {
  2009. ERR_FAIL_COND_V(!_image_compress_etc2_func, ERR_UNAVAILABLE);
  2010. _image_compress_etc2_func(this, p_lossy_quality, p_channels);
  2011. } break;
  2012. case COMPRESS_BPTC: {
  2013. ERR_FAIL_COND_V(!_image_compress_bptc_func, ERR_UNAVAILABLE);
  2014. _image_compress_bptc_func(this, p_lossy_quality, p_channels);
  2015. } break;
  2016. case COMPRESS_MAX: {
  2017. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  2018. } break;
  2019. }
  2020. return OK;
  2021. }
  2022. Image::Image(const char **p_xpm) {
  2023. width = 0;
  2024. height = 0;
  2025. mipmaps = false;
  2026. format = FORMAT_L8;
  2027. create(p_xpm);
  2028. }
  2029. Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
  2030. width = 0;
  2031. height = 0;
  2032. mipmaps = p_use_mipmaps;
  2033. format = FORMAT_L8;
  2034. create(p_width, p_height, p_use_mipmaps, p_format);
  2035. }
  2036. Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const Vector<uint8_t> &p_data) {
  2037. width = 0;
  2038. height = 0;
  2039. mipmaps = p_mipmaps;
  2040. format = FORMAT_L8;
  2041. create(p_width, p_height, p_mipmaps, p_format, p_data);
  2042. }
  2043. Rect2 Image::get_used_rect() const {
  2044. if (format != FORMAT_LA8 && format != FORMAT_RGBA8 && format != FORMAT_RGBAF && format != FORMAT_RGBAH && format != FORMAT_RGBA4444 && format != FORMAT_RGB565) {
  2045. return Rect2(Point2(), Size2(width, height));
  2046. }
  2047. int len = data.size();
  2048. if (len == 0) {
  2049. return Rect2();
  2050. }
  2051. int minx = 0xFFFFFF, miny = 0xFFFFFFF;
  2052. int maxx = -1, maxy = -1;
  2053. for (int j = 0; j < height; j++) {
  2054. for (int i = 0; i < width; i++) {
  2055. if (!(get_pixel(i, j).a > 0)) {
  2056. continue;
  2057. }
  2058. if (i > maxx) {
  2059. maxx = i;
  2060. }
  2061. if (j > maxy) {
  2062. maxy = j;
  2063. }
  2064. if (i < minx) {
  2065. minx = i;
  2066. }
  2067. if (j < miny) {
  2068. miny = j;
  2069. }
  2070. }
  2071. }
  2072. if (maxx == -1) {
  2073. return Rect2();
  2074. } else {
  2075. return Rect2(minx, miny, maxx - minx + 1, maxy - miny + 1);
  2076. }
  2077. }
  2078. Ref<Image> Image::get_rect(const Rect2 &p_area) const {
  2079. Ref<Image> img = memnew(Image(p_area.size.x, p_area.size.y, mipmaps, format));
  2080. img->blit_rect(Ref<Image>((Image *)this), p_area, Point2(0, 0));
  2081. return img;
  2082. }
  2083. void Image::_get_clipped_src_and_dest_rects(const Ref<Image> &p_src, const Rect2i &p_src_rect, const Point2i &p_dest, Rect2i &r_clipped_src_rect, Rect2i &r_clipped_dest_rect) const {
  2084. r_clipped_dest_rect.position = p_dest;
  2085. r_clipped_src_rect = p_src_rect;
  2086. if (r_clipped_src_rect.position.x < 0) {
  2087. r_clipped_dest_rect.position.x -= r_clipped_src_rect.position.x;
  2088. r_clipped_src_rect.size.x += r_clipped_src_rect.position.x;
  2089. r_clipped_src_rect.position.x = 0;
  2090. }
  2091. if (r_clipped_src_rect.position.y < 0) {
  2092. r_clipped_dest_rect.position.y -= r_clipped_src_rect.position.y;
  2093. r_clipped_src_rect.size.y += r_clipped_src_rect.position.y;
  2094. r_clipped_src_rect.position.y = 0;
  2095. }
  2096. if (r_clipped_dest_rect.position.x < 0) {
  2097. r_clipped_src_rect.position.x -= r_clipped_dest_rect.position.x;
  2098. r_clipped_src_rect.size.x += r_clipped_dest_rect.position.x;
  2099. r_clipped_dest_rect.position.x = 0;
  2100. }
  2101. if (r_clipped_dest_rect.position.y < 0) {
  2102. r_clipped_src_rect.position.y -= r_clipped_dest_rect.position.y;
  2103. r_clipped_src_rect.size.y += r_clipped_dest_rect.position.y;
  2104. r_clipped_dest_rect.position.y = 0;
  2105. }
  2106. r_clipped_src_rect.size.x = MAX(0, MIN(r_clipped_src_rect.size.x, MIN(p_src->width - r_clipped_src_rect.position.x, width - r_clipped_dest_rect.position.x)));
  2107. r_clipped_src_rect.size.y = MAX(0, MIN(r_clipped_src_rect.size.y, MIN(p_src->height - r_clipped_src_rect.position.y, height - r_clipped_dest_rect.position.y)));
  2108. r_clipped_dest_rect.size.x = r_clipped_src_rect.size.x;
  2109. r_clipped_dest_rect.size.y = r_clipped_src_rect.size.y;
  2110. }
  2111. void Image::blit_rect(const Ref<Image> &p_src, const Rect2 &p_src_rect, const Point2 &p_dest) {
  2112. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2113. int dsize = data.size();
  2114. int srcdsize = p_src->data.size();
  2115. ERR_FAIL_COND(dsize == 0);
  2116. ERR_FAIL_COND(srcdsize == 0);
  2117. ERR_FAIL_COND(format != p_src->format);
  2118. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot blit_rect in compressed or custom image formats.");
  2119. Rect2i src_rect;
  2120. Rect2i dest_rect;
  2121. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2122. if (src_rect.has_no_area() || dest_rect.has_no_area()) {
  2123. return;
  2124. }
  2125. uint8_t *wp = data.ptrw();
  2126. uint8_t *dst_data_ptr = wp;
  2127. const uint8_t *rp = p_src->data.ptr();
  2128. const uint8_t *src_data_ptr = rp;
  2129. int pixel_size = get_format_pixel_size(format);
  2130. for (int i = 0; i < dest_rect.size.y; i++) {
  2131. for (int j = 0; j < dest_rect.size.x; j++) {
  2132. int src_x = src_rect.position.x + j;
  2133. int src_y = src_rect.position.y + i;
  2134. int dst_x = dest_rect.position.x + j;
  2135. int dst_y = dest_rect.position.y + i;
  2136. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2137. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2138. for (int k = 0; k < pixel_size; k++) {
  2139. dst[k] = src[k];
  2140. }
  2141. }
  2142. }
  2143. }
  2144. void Image::blit_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2 &p_src_rect, const Point2 &p_dest) {
  2145. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2146. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2147. int dsize = data.size();
  2148. int srcdsize = p_src->data.size();
  2149. int maskdsize = p_mask->data.size();
  2150. ERR_FAIL_COND(dsize == 0);
  2151. ERR_FAIL_COND(srcdsize == 0);
  2152. ERR_FAIL_COND(maskdsize == 0);
  2153. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2154. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2155. ERR_FAIL_COND(format != p_src->format);
  2156. Rect2i src_rect;
  2157. Rect2i dest_rect;
  2158. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2159. if (src_rect.has_no_area() || dest_rect.has_no_area()) {
  2160. return;
  2161. }
  2162. uint8_t *wp = data.ptrw();
  2163. uint8_t *dst_data_ptr = wp;
  2164. const uint8_t *rp = p_src->data.ptr();
  2165. const uint8_t *src_data_ptr = rp;
  2166. int pixel_size = get_format_pixel_size(format);
  2167. Ref<Image> msk = p_mask;
  2168. for (int i = 0; i < dest_rect.size.y; i++) {
  2169. for (int j = 0; j < dest_rect.size.x; j++) {
  2170. int src_x = src_rect.position.x + j;
  2171. int src_y = src_rect.position.y + i;
  2172. if (msk->get_pixel(src_x, src_y).a != 0) {
  2173. int dst_x = dest_rect.position.x + j;
  2174. int dst_y = dest_rect.position.y + i;
  2175. const uint8_t *src = &src_data_ptr[(src_y * p_src->width + src_x) * pixel_size];
  2176. uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
  2177. for (int k = 0; k < pixel_size; k++) {
  2178. dst[k] = src[k];
  2179. }
  2180. }
  2181. }
  2182. }
  2183. }
  2184. void Image::blend_rect(const Ref<Image> &p_src, const Rect2 &p_src_rect, const Point2 &p_dest) {
  2185. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2186. int dsize = data.size();
  2187. int srcdsize = p_src->data.size();
  2188. ERR_FAIL_COND(dsize == 0);
  2189. ERR_FAIL_COND(srcdsize == 0);
  2190. ERR_FAIL_COND(format != p_src->format);
  2191. Rect2i src_rect;
  2192. Rect2i dest_rect;
  2193. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2194. if (src_rect.has_no_area() || dest_rect.has_no_area()) {
  2195. return;
  2196. }
  2197. Ref<Image> img = p_src;
  2198. for (int i = 0; i < dest_rect.size.y; i++) {
  2199. for (int j = 0; j < dest_rect.size.x; j++) {
  2200. int src_x = src_rect.position.x + j;
  2201. int src_y = src_rect.position.y + i;
  2202. int dst_x = dest_rect.position.x + j;
  2203. int dst_y = dest_rect.position.y + i;
  2204. Color sc = img->get_pixel(src_x, src_y);
  2205. if (sc.a != 0) {
  2206. Color dc = get_pixel(dst_x, dst_y);
  2207. dc = dc.blend(sc);
  2208. set_pixel(dst_x, dst_y, dc);
  2209. }
  2210. }
  2211. }
  2212. }
  2213. void Image::blend_rect_mask(const Ref<Image> &p_src, const Ref<Image> &p_mask, const Rect2 &p_src_rect, const Point2 &p_dest) {
  2214. ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object.");
  2215. ERR_FAIL_COND_MSG(p_mask.is_null(), "It's not a reference to a valid Image object.");
  2216. int dsize = data.size();
  2217. int srcdsize = p_src->data.size();
  2218. int maskdsize = p_mask->data.size();
  2219. ERR_FAIL_COND(dsize == 0);
  2220. ERR_FAIL_COND(srcdsize == 0);
  2221. ERR_FAIL_COND(maskdsize == 0);
  2222. ERR_FAIL_COND_MSG(p_src->width != p_mask->width, "Source image width is different from mask width.");
  2223. ERR_FAIL_COND_MSG(p_src->height != p_mask->height, "Source image height is different from mask height.");
  2224. ERR_FAIL_COND(format != p_src->format);
  2225. Rect2i src_rect;
  2226. Rect2i dest_rect;
  2227. _get_clipped_src_and_dest_rects(p_src, p_src_rect, p_dest, src_rect, dest_rect);
  2228. if (src_rect.has_no_area() || dest_rect.has_no_area()) {
  2229. return;
  2230. }
  2231. Ref<Image> img = p_src;
  2232. Ref<Image> msk = p_mask;
  2233. for (int i = 0; i < dest_rect.size.y; i++) {
  2234. for (int j = 0; j < dest_rect.size.x; j++) {
  2235. int src_x = src_rect.position.x + j;
  2236. int src_y = src_rect.position.y + i;
  2237. // If the mask's pixel is transparent then we skip it
  2238. //Color c = msk->get_pixel(src_x, src_y);
  2239. //if (c.a == 0) continue;
  2240. if (msk->get_pixel(src_x, src_y).a != 0) {
  2241. int dst_x = dest_rect.position.x + j;
  2242. int dst_y = dest_rect.position.y + i;
  2243. Color sc = img->get_pixel(src_x, src_y);
  2244. if (sc.a != 0) {
  2245. Color dc = get_pixel(dst_x, dst_y);
  2246. dc = dc.blend(sc);
  2247. set_pixel(dst_x, dst_y, dc);
  2248. }
  2249. }
  2250. }
  2251. }
  2252. }
  2253. // Repeats `p_pixel` `p_count` times in consecutive memory.
  2254. // Results in the original pixel and `p_count - 1` subsequent copies of it.
  2255. void Image::_repeat_pixel_over_subsequent_memory(uint8_t *p_pixel, int p_pixel_size, int p_count) {
  2256. int offset = 1;
  2257. for (int stride = 1; offset + stride <= p_count; stride *= 2) {
  2258. memcpy(p_pixel + offset * p_pixel_size, p_pixel, stride * p_pixel_size);
  2259. offset += stride;
  2260. }
  2261. if (offset < p_count) {
  2262. memcpy(p_pixel + offset * p_pixel_size, p_pixel, (p_count - offset) * p_pixel_size);
  2263. }
  2264. }
  2265. void Image::fill(const Color &p_color) {
  2266. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill in compressed or custom image formats.");
  2267. uint8_t *dst_data_ptr = data.ptrw();
  2268. int pixel_size = get_format_pixel_size(format);
  2269. // Put first pixel with the format-aware API.
  2270. _set_color_at_ofs(dst_data_ptr, 0, p_color);
  2271. _repeat_pixel_over_subsequent_memory(dst_data_ptr, pixel_size, width * height);
  2272. }
  2273. void Image::fill_rect(const Rect2 &p_rect, const Color &p_color) {
  2274. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot fill rect in compressed or custom image formats.");
  2275. Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect.abs());
  2276. if (r.has_no_area()) {
  2277. return;
  2278. }
  2279. uint8_t *dst_data_ptr = data.ptrw();
  2280. int pixel_size = get_format_pixel_size(format);
  2281. // Put first pixel with the format-aware API.
  2282. uint8_t *rect_first_pixel_ptr = &dst_data_ptr[(r.position.y * width + r.position.x) * pixel_size];
  2283. _set_color_at_ofs(rect_first_pixel_ptr, 0, p_color);
  2284. if (r.size.x == width) {
  2285. // No need to fill rows separately.
  2286. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, width * r.size.y);
  2287. } else {
  2288. _repeat_pixel_over_subsequent_memory(rect_first_pixel_ptr, pixel_size, r.size.x);
  2289. for (int y = 1; y < r.size.y; y++) {
  2290. memcpy(rect_first_pixel_ptr + y * width * pixel_size, rect_first_pixel_ptr, r.size.x * pixel_size);
  2291. }
  2292. }
  2293. }
  2294. ImageMemLoadFunc Image::_png_mem_loader_func = nullptr;
  2295. ImageMemLoadFunc Image::_jpg_mem_loader_func = nullptr;
  2296. ImageMemLoadFunc Image::_webp_mem_loader_func = nullptr;
  2297. ImageMemLoadFunc Image::_tga_mem_loader_func = nullptr;
  2298. ImageMemLoadFunc Image::_bmp_mem_loader_func = nullptr;
  2299. void (*Image::_image_compress_bc_func)(Image *, float, Image::UsedChannels) = nullptr;
  2300. void (*Image::_image_compress_bptc_func)(Image *, float, Image::UsedChannels) = nullptr;
  2301. void (*Image::_image_compress_etc1_func)(Image *, float) = nullptr;
  2302. void (*Image::_image_compress_etc2_func)(Image *, float, Image::UsedChannels) = nullptr;
  2303. void (*Image::_image_decompress_bc)(Image *) = nullptr;
  2304. void (*Image::_image_decompress_bptc)(Image *) = nullptr;
  2305. void (*Image::_image_decompress_etc1)(Image *) = nullptr;
  2306. void (*Image::_image_decompress_etc2)(Image *) = nullptr;
  2307. Vector<uint8_t> (*Image::webp_lossy_packer)(const Ref<Image> &, float) = nullptr;
  2308. Vector<uint8_t> (*Image::webp_lossless_packer)(const Ref<Image> &) = nullptr;
  2309. Ref<Image> (*Image::webp_unpacker)(const Vector<uint8_t> &) = nullptr;
  2310. Vector<uint8_t> (*Image::png_packer)(const Ref<Image> &) = nullptr;
  2311. Ref<Image> (*Image::png_unpacker)(const Vector<uint8_t> &) = nullptr;
  2312. Vector<uint8_t> (*Image::basis_universal_packer)(const Ref<Image> &, Image::UsedChannels) = nullptr;
  2313. Ref<Image> (*Image::basis_universal_unpacker)(const Vector<uint8_t> &) = nullptr;
  2314. Ref<Image> (*Image::basis_universal_unpacker_ptr)(const uint8_t *, int) = nullptr;
  2315. void Image::_set_data(const Dictionary &p_data) {
  2316. ERR_FAIL_COND(!p_data.has("width"));
  2317. ERR_FAIL_COND(!p_data.has("height"));
  2318. ERR_FAIL_COND(!p_data.has("format"));
  2319. ERR_FAIL_COND(!p_data.has("mipmaps"));
  2320. ERR_FAIL_COND(!p_data.has("data"));
  2321. int dwidth = p_data["width"];
  2322. int dheight = p_data["height"];
  2323. String dformat = p_data["format"];
  2324. bool dmipmaps = p_data["mipmaps"];
  2325. Vector<uint8_t> ddata = p_data["data"];
  2326. Format ddformat = FORMAT_MAX;
  2327. for (int i = 0; i < FORMAT_MAX; i++) {
  2328. if (dformat == get_format_name(Format(i))) {
  2329. ddformat = Format(i);
  2330. break;
  2331. }
  2332. }
  2333. ERR_FAIL_COND(ddformat == FORMAT_MAX);
  2334. create(dwidth, dheight, dmipmaps, ddformat, ddata);
  2335. }
  2336. Dictionary Image::_get_data() const {
  2337. Dictionary d;
  2338. d["width"] = width;
  2339. d["height"] = height;
  2340. d["format"] = get_format_name(format);
  2341. d["mipmaps"] = mipmaps;
  2342. d["data"] = data;
  2343. return d;
  2344. }
  2345. Color Image::get_pixelv(const Point2i &p_point) const {
  2346. return get_pixel(p_point.x, p_point.y);
  2347. }
  2348. Color Image::_get_color_at_ofs(const uint8_t *ptr, uint32_t ofs) const {
  2349. switch (format) {
  2350. case FORMAT_L8: {
  2351. float l = ptr[ofs] / 255.0;
  2352. return Color(l, l, l, 1);
  2353. }
  2354. case FORMAT_LA8: {
  2355. float l = ptr[ofs * 2 + 0] / 255.0;
  2356. float a = ptr[ofs * 2 + 1] / 255.0;
  2357. return Color(l, l, l, a);
  2358. }
  2359. case FORMAT_R8: {
  2360. float r = ptr[ofs] / 255.0;
  2361. return Color(r, 0, 0, 1);
  2362. }
  2363. case FORMAT_RG8: {
  2364. float r = ptr[ofs * 2 + 0] / 255.0;
  2365. float g = ptr[ofs * 2 + 1] / 255.0;
  2366. return Color(r, g, 0, 1);
  2367. }
  2368. case FORMAT_RGB8: {
  2369. float r = ptr[ofs * 3 + 0] / 255.0;
  2370. float g = ptr[ofs * 3 + 1] / 255.0;
  2371. float b = ptr[ofs * 3 + 2] / 255.0;
  2372. return Color(r, g, b, 1);
  2373. }
  2374. case FORMAT_RGBA8: {
  2375. float r = ptr[ofs * 4 + 0] / 255.0;
  2376. float g = ptr[ofs * 4 + 1] / 255.0;
  2377. float b = ptr[ofs * 4 + 2] / 255.0;
  2378. float a = ptr[ofs * 4 + 3] / 255.0;
  2379. return Color(r, g, b, a);
  2380. }
  2381. case FORMAT_RGBA4444: {
  2382. uint16_t u = ((uint16_t *)ptr)[ofs];
  2383. float r = ((u >> 12) & 0xF) / 15.0;
  2384. float g = ((u >> 8) & 0xF) / 15.0;
  2385. float b = ((u >> 4) & 0xF) / 15.0;
  2386. float a = (u & 0xF) / 15.0;
  2387. return Color(r, g, b, a);
  2388. }
  2389. case FORMAT_RGB565: {
  2390. uint16_t u = ((uint16_t *)ptr)[ofs];
  2391. float r = (u & 0x1F) / 31.0;
  2392. float g = ((u >> 5) & 0x3F) / 63.0;
  2393. float b = ((u >> 11) & 0x1F) / 31.0;
  2394. return Color(r, g, b, 1.0);
  2395. }
  2396. case FORMAT_RF: {
  2397. float r = ((float *)ptr)[ofs];
  2398. return Color(r, 0, 0, 1);
  2399. }
  2400. case FORMAT_RGF: {
  2401. float r = ((float *)ptr)[ofs * 2 + 0];
  2402. float g = ((float *)ptr)[ofs * 2 + 1];
  2403. return Color(r, g, 0, 1);
  2404. }
  2405. case FORMAT_RGBF: {
  2406. float r = ((float *)ptr)[ofs * 3 + 0];
  2407. float g = ((float *)ptr)[ofs * 3 + 1];
  2408. float b = ((float *)ptr)[ofs * 3 + 2];
  2409. return Color(r, g, b, 1);
  2410. }
  2411. case FORMAT_RGBAF: {
  2412. float r = ((float *)ptr)[ofs * 4 + 0];
  2413. float g = ((float *)ptr)[ofs * 4 + 1];
  2414. float b = ((float *)ptr)[ofs * 4 + 2];
  2415. float a = ((float *)ptr)[ofs * 4 + 3];
  2416. return Color(r, g, b, a);
  2417. }
  2418. case FORMAT_RH: {
  2419. uint16_t r = ((uint16_t *)ptr)[ofs];
  2420. return Color(Math::half_to_float(r), 0, 0, 1);
  2421. }
  2422. case FORMAT_RGH: {
  2423. uint16_t r = ((uint16_t *)ptr)[ofs * 2 + 0];
  2424. uint16_t g = ((uint16_t *)ptr)[ofs * 2 + 1];
  2425. return Color(Math::half_to_float(r), Math::half_to_float(g), 0, 1);
  2426. }
  2427. case FORMAT_RGBH: {
  2428. uint16_t r = ((uint16_t *)ptr)[ofs * 3 + 0];
  2429. uint16_t g = ((uint16_t *)ptr)[ofs * 3 + 1];
  2430. uint16_t b = ((uint16_t *)ptr)[ofs * 3 + 2];
  2431. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), 1);
  2432. }
  2433. case FORMAT_RGBAH: {
  2434. uint16_t r = ((uint16_t *)ptr)[ofs * 4 + 0];
  2435. uint16_t g = ((uint16_t *)ptr)[ofs * 4 + 1];
  2436. uint16_t b = ((uint16_t *)ptr)[ofs * 4 + 2];
  2437. uint16_t a = ((uint16_t *)ptr)[ofs * 4 + 3];
  2438. return Color(Math::half_to_float(r), Math::half_to_float(g), Math::half_to_float(b), Math::half_to_float(a));
  2439. }
  2440. case FORMAT_RGBE9995: {
  2441. return Color::from_rgbe9995(((uint32_t *)ptr)[ofs]);
  2442. }
  2443. default: {
  2444. ERR_FAIL_V_MSG(Color(), "Can't get_pixel() on compressed image, sorry.");
  2445. }
  2446. }
  2447. }
  2448. void Image::_set_color_at_ofs(uint8_t *ptr, uint32_t ofs, const Color &p_color) {
  2449. switch (format) {
  2450. case FORMAT_L8: {
  2451. ptr[ofs] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2452. } break;
  2453. case FORMAT_LA8: {
  2454. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.get_v() * 255.0, 0, 255));
  2455. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2456. } break;
  2457. case FORMAT_R8: {
  2458. ptr[ofs] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2459. } break;
  2460. case FORMAT_RG8: {
  2461. ptr[ofs * 2 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2462. ptr[ofs * 2 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2463. } break;
  2464. case FORMAT_RGB8: {
  2465. ptr[ofs * 3 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2466. ptr[ofs * 3 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2467. ptr[ofs * 3 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2468. } break;
  2469. case FORMAT_RGBA8: {
  2470. ptr[ofs * 4 + 0] = uint8_t(CLAMP(p_color.r * 255.0, 0, 255));
  2471. ptr[ofs * 4 + 1] = uint8_t(CLAMP(p_color.g * 255.0, 0, 255));
  2472. ptr[ofs * 4 + 2] = uint8_t(CLAMP(p_color.b * 255.0, 0, 255));
  2473. ptr[ofs * 4 + 3] = uint8_t(CLAMP(p_color.a * 255.0, 0, 255));
  2474. } break;
  2475. case FORMAT_RGBA4444: {
  2476. uint16_t rgba = 0;
  2477. rgba = uint16_t(CLAMP(p_color.r * 15.0, 0, 15)) << 12;
  2478. rgba |= uint16_t(CLAMP(p_color.g * 15.0, 0, 15)) << 8;
  2479. rgba |= uint16_t(CLAMP(p_color.b * 15.0, 0, 15)) << 4;
  2480. rgba |= uint16_t(CLAMP(p_color.a * 15.0, 0, 15));
  2481. ((uint16_t *)ptr)[ofs] = rgba;
  2482. } break;
  2483. case FORMAT_RGB565: {
  2484. uint16_t rgba = 0;
  2485. rgba = uint16_t(CLAMP(p_color.r * 31.0, 0, 31));
  2486. rgba |= uint16_t(CLAMP(p_color.g * 63.0, 0, 33)) << 5;
  2487. rgba |= uint16_t(CLAMP(p_color.b * 31.0, 0, 31)) << 11;
  2488. ((uint16_t *)ptr)[ofs] = rgba;
  2489. } break;
  2490. case FORMAT_RF: {
  2491. ((float *)ptr)[ofs] = p_color.r;
  2492. } break;
  2493. case FORMAT_RGF: {
  2494. ((float *)ptr)[ofs * 2 + 0] = p_color.r;
  2495. ((float *)ptr)[ofs * 2 + 1] = p_color.g;
  2496. } break;
  2497. case FORMAT_RGBF: {
  2498. ((float *)ptr)[ofs * 3 + 0] = p_color.r;
  2499. ((float *)ptr)[ofs * 3 + 1] = p_color.g;
  2500. ((float *)ptr)[ofs * 3 + 2] = p_color.b;
  2501. } break;
  2502. case FORMAT_RGBAF: {
  2503. ((float *)ptr)[ofs * 4 + 0] = p_color.r;
  2504. ((float *)ptr)[ofs * 4 + 1] = p_color.g;
  2505. ((float *)ptr)[ofs * 4 + 2] = p_color.b;
  2506. ((float *)ptr)[ofs * 4 + 3] = p_color.a;
  2507. } break;
  2508. case FORMAT_RH: {
  2509. ((uint16_t *)ptr)[ofs] = Math::make_half_float(p_color.r);
  2510. } break;
  2511. case FORMAT_RGH: {
  2512. ((uint16_t *)ptr)[ofs * 2 + 0] = Math::make_half_float(p_color.r);
  2513. ((uint16_t *)ptr)[ofs * 2 + 1] = Math::make_half_float(p_color.g);
  2514. } break;
  2515. case FORMAT_RGBH: {
  2516. ((uint16_t *)ptr)[ofs * 3 + 0] = Math::make_half_float(p_color.r);
  2517. ((uint16_t *)ptr)[ofs * 3 + 1] = Math::make_half_float(p_color.g);
  2518. ((uint16_t *)ptr)[ofs * 3 + 2] = Math::make_half_float(p_color.b);
  2519. } break;
  2520. case FORMAT_RGBAH: {
  2521. ((uint16_t *)ptr)[ofs * 4 + 0] = Math::make_half_float(p_color.r);
  2522. ((uint16_t *)ptr)[ofs * 4 + 1] = Math::make_half_float(p_color.g);
  2523. ((uint16_t *)ptr)[ofs * 4 + 2] = Math::make_half_float(p_color.b);
  2524. ((uint16_t *)ptr)[ofs * 4 + 3] = Math::make_half_float(p_color.a);
  2525. } break;
  2526. case FORMAT_RGBE9995: {
  2527. ((uint32_t *)ptr)[ofs] = p_color.to_rgbe9995();
  2528. } break;
  2529. default: {
  2530. ERR_FAIL_MSG("Can't set_pixel() on compressed image, sorry.");
  2531. }
  2532. }
  2533. }
  2534. Color Image::get_pixel(int p_x, int p_y) const {
  2535. #ifdef DEBUG_ENABLED
  2536. ERR_FAIL_INDEX_V(p_x, width, Color());
  2537. ERR_FAIL_INDEX_V(p_y, height, Color());
  2538. #endif
  2539. uint32_t ofs = p_y * width + p_x;
  2540. return _get_color_at_ofs(data.ptr(), ofs);
  2541. }
  2542. void Image::set_pixelv(const Point2i &p_point, const Color &p_color) {
  2543. set_pixel(p_point.x, p_point.y, p_color);
  2544. }
  2545. void Image::set_pixel(int p_x, int p_y, const Color &p_color) {
  2546. #ifdef DEBUG_ENABLED
  2547. ERR_FAIL_INDEX(p_x, width);
  2548. ERR_FAIL_INDEX(p_y, height);
  2549. #endif
  2550. uint32_t ofs = p_y * width + p_x;
  2551. _set_color_at_ofs(data.ptrw(), ofs, p_color);
  2552. }
  2553. void Image::adjust_bcs(float p_brightness, float p_contrast, float p_saturation) {
  2554. ERR_FAIL_COND_MSG(!_can_modify(format), "Cannot adjust_bcs in compressed or custom image formats.");
  2555. uint8_t *w = data.ptrw();
  2556. uint32_t pixel_size = get_format_pixel_size(format);
  2557. uint32_t pixel_count = data.size() / pixel_size;
  2558. for (uint32_t i = 0; i < pixel_count; i++) {
  2559. Color c = _get_color_at_ofs(w, i);
  2560. Vector3 rgb(c.r, c.g, c.b);
  2561. rgb *= p_brightness;
  2562. rgb = Vector3(0.5, 0.5, 0.5).lerp(rgb, p_contrast);
  2563. float center = (rgb.x + rgb.y + rgb.z) / 3.0;
  2564. rgb = Vector3(center, center, center).lerp(rgb, p_saturation);
  2565. c.r = rgb.x;
  2566. c.g = rgb.y;
  2567. c.b = rgb.z;
  2568. _set_color_at_ofs(w, i, c);
  2569. }
  2570. }
  2571. Image::UsedChannels Image::detect_used_channels(CompressSource p_source) const {
  2572. ERR_FAIL_COND_V(data.size() == 0, USED_CHANNELS_RGBA);
  2573. ERR_FAIL_COND_V(is_compressed(), USED_CHANNELS_RGBA);
  2574. bool r = false, g = false, b = false, a = false, c = false;
  2575. const uint8_t *data_ptr = data.ptr();
  2576. uint32_t data_total = width * height;
  2577. for (uint32_t i = 0; i < data_total; i++) {
  2578. Color col = _get_color_at_ofs(data_ptr, i);
  2579. if (col.r > 0.001) {
  2580. r = true;
  2581. }
  2582. if (col.g > 0.001) {
  2583. g = true;
  2584. }
  2585. if (col.b > 0.001) {
  2586. b = true;
  2587. }
  2588. if (col.a < 0.999) {
  2589. a = true;
  2590. }
  2591. if (col.r != col.b || col.r != col.g || col.b != col.g) {
  2592. c = true;
  2593. }
  2594. }
  2595. UsedChannels used_channels;
  2596. if (!c && !a) {
  2597. used_channels = USED_CHANNELS_L;
  2598. } else if (!c && a) {
  2599. used_channels = USED_CHANNELS_LA;
  2600. } else if (r && !g && !b && !a) {
  2601. used_channels = USED_CHANNELS_R;
  2602. } else if (r && g && !b && !a) {
  2603. used_channels = USED_CHANNELS_RG;
  2604. } else if (r && g && b && !a) {
  2605. used_channels = USED_CHANNELS_RGB;
  2606. } else {
  2607. used_channels = USED_CHANNELS_RGBA;
  2608. }
  2609. if (p_source == COMPRESS_SOURCE_SRGB && (used_channels == USED_CHANNELS_R || used_channels == USED_CHANNELS_RG)) {
  2610. //R and RG do not support SRGB
  2611. used_channels = USED_CHANNELS_RGB;
  2612. }
  2613. if (p_source == COMPRESS_SOURCE_NORMAL) {
  2614. //use RG channels only for normal
  2615. used_channels = USED_CHANNELS_RG;
  2616. }
  2617. return used_channels;
  2618. }
  2619. void Image::optimize_channels() {
  2620. switch (detect_used_channels()) {
  2621. case USED_CHANNELS_L:
  2622. convert(FORMAT_L8);
  2623. break;
  2624. case USED_CHANNELS_LA:
  2625. convert(FORMAT_LA8);
  2626. break;
  2627. case USED_CHANNELS_R:
  2628. convert(FORMAT_R8);
  2629. break;
  2630. case USED_CHANNELS_RG:
  2631. convert(FORMAT_RG8);
  2632. break;
  2633. case USED_CHANNELS_RGB:
  2634. convert(FORMAT_RGB8);
  2635. break;
  2636. case USED_CHANNELS_RGBA:
  2637. convert(FORMAT_RGBA8);
  2638. break;
  2639. }
  2640. }
  2641. void Image::_bind_methods() {
  2642. ClassDB::bind_method(D_METHOD("get_width"), &Image::get_width);
  2643. ClassDB::bind_method(D_METHOD("get_height"), &Image::get_height);
  2644. ClassDB::bind_method(D_METHOD("get_size"), &Image::get_size);
  2645. ClassDB::bind_method(D_METHOD("has_mipmaps"), &Image::has_mipmaps);
  2646. ClassDB::bind_method(D_METHOD("get_format"), &Image::get_format);
  2647. ClassDB::bind_method(D_METHOD("get_data"), &Image::get_data);
  2648. ClassDB::bind_method(D_METHOD("convert", "format"), &Image::convert);
  2649. ClassDB::bind_method(D_METHOD("get_mipmap_offset", "mipmap"), &Image::get_mipmap_offset);
  2650. ClassDB::bind_method(D_METHOD("resize_to_po2", "square", "interpolation"), &Image::resize_to_po2, DEFVAL(false), DEFVAL(INTERPOLATE_BILINEAR));
  2651. ClassDB::bind_method(D_METHOD("resize", "width", "height", "interpolation"), &Image::resize, DEFVAL(INTERPOLATE_BILINEAR));
  2652. ClassDB::bind_method(D_METHOD("shrink_x2"), &Image::shrink_x2);
  2653. ClassDB::bind_method(D_METHOD("crop", "width", "height"), &Image::crop);
  2654. ClassDB::bind_method(D_METHOD("flip_x"), &Image::flip_x);
  2655. ClassDB::bind_method(D_METHOD("flip_y"), &Image::flip_y);
  2656. ClassDB::bind_method(D_METHOD("generate_mipmaps", "renormalize"), &Image::generate_mipmaps, DEFVAL(false));
  2657. ClassDB::bind_method(D_METHOD("clear_mipmaps"), &Image::clear_mipmaps);
  2658. ClassDB::bind_method(D_METHOD("create", "width", "height", "use_mipmaps", "format"), &Image::create_empty);
  2659. ClassDB::bind_method(D_METHOD("create_from_data", "width", "height", "use_mipmaps", "format", "data"), &Image::create_from_data);
  2660. ClassDB::bind_method(D_METHOD("is_empty"), &Image::is_empty);
  2661. ClassDB::bind_method(D_METHOD("load", "path"), &Image::load);
  2662. ClassDB::bind_method(D_METHOD("save_png", "path"), &Image::save_png);
  2663. ClassDB::bind_method(D_METHOD("save_png_to_buffer"), &Image::save_png_to_buffer);
  2664. ClassDB::bind_method(D_METHOD("save_exr", "path", "grayscale"), &Image::save_exr, DEFVAL(false));
  2665. ClassDB::bind_method(D_METHOD("detect_alpha"), &Image::detect_alpha);
  2666. ClassDB::bind_method(D_METHOD("is_invisible"), &Image::is_invisible);
  2667. ClassDB::bind_method(D_METHOD("detect_used_channels", "source"), &Image::detect_used_channels, DEFVAL(COMPRESS_SOURCE_GENERIC));
  2668. ClassDB::bind_method(D_METHOD("compress", "mode", "source", "lossy_quality"), &Image::compress, DEFVAL(COMPRESS_SOURCE_GENERIC), DEFVAL(0.7));
  2669. ClassDB::bind_method(D_METHOD("compress_from_channels", "mode", "channels", "lossy_quality"), &Image::compress_from_channels, DEFVAL(0.7));
  2670. ClassDB::bind_method(D_METHOD("decompress"), &Image::decompress);
  2671. ClassDB::bind_method(D_METHOD("is_compressed"), &Image::is_compressed);
  2672. ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &Image::fix_alpha_edges);
  2673. ClassDB::bind_method(D_METHOD("premultiply_alpha"), &Image::premultiply_alpha);
  2674. ClassDB::bind_method(D_METHOD("srgb_to_linear"), &Image::srgb_to_linear);
  2675. ClassDB::bind_method(D_METHOD("normal_map_to_xy"), &Image::normal_map_to_xy);
  2676. ClassDB::bind_method(D_METHOD("rgbe_to_srgb"), &Image::rgbe_to_srgb);
  2677. ClassDB::bind_method(D_METHOD("bump_map_to_normal_map", "bump_scale"), &Image::bump_map_to_normal_map, DEFVAL(1.0));
  2678. ClassDB::bind_method(D_METHOD("compute_image_metrics", "compared_image", "use_luma"), &Image::compute_image_metrics);
  2679. ClassDB::bind_method(D_METHOD("blit_rect", "src", "src_rect", "dst"), &Image::blit_rect);
  2680. ClassDB::bind_method(D_METHOD("blit_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blit_rect_mask);
  2681. ClassDB::bind_method(D_METHOD("blend_rect", "src", "src_rect", "dst"), &Image::blend_rect);
  2682. ClassDB::bind_method(D_METHOD("blend_rect_mask", "src", "mask", "src_rect", "dst"), &Image::blend_rect_mask);
  2683. ClassDB::bind_method(D_METHOD("fill", "color"), &Image::fill);
  2684. ClassDB::bind_method(D_METHOD("fill_rect", "rect", "color"), &Image::fill_rect);
  2685. ClassDB::bind_method(D_METHOD("get_used_rect"), &Image::get_used_rect);
  2686. ClassDB::bind_method(D_METHOD("get_rect", "rect"), &Image::get_rect);
  2687. ClassDB::bind_method(D_METHOD("copy_from", "src"), &Image::copy_internals_from);
  2688. ClassDB::bind_method(D_METHOD("_set_data", "data"), &Image::_set_data);
  2689. ClassDB::bind_method(D_METHOD("_get_data"), &Image::_get_data);
  2690. ClassDB::bind_method(D_METHOD("get_pixelv", "point"), &Image::get_pixelv);
  2691. ClassDB::bind_method(D_METHOD("get_pixel", "x", "y"), &Image::get_pixel);
  2692. ClassDB::bind_method(D_METHOD("set_pixelv", "point", "color"), &Image::set_pixelv);
  2693. ClassDB::bind_method(D_METHOD("set_pixel", "x", "y", "color"), &Image::set_pixel);
  2694. ClassDB::bind_method(D_METHOD("adjust_bcs", "brightness", "contrast", "saturation"), &Image::adjust_bcs);
  2695. ClassDB::bind_method(D_METHOD("load_png_from_buffer", "buffer"), &Image::load_png_from_buffer);
  2696. ClassDB::bind_method(D_METHOD("load_jpg_from_buffer", "buffer"), &Image::load_jpg_from_buffer);
  2697. ClassDB::bind_method(D_METHOD("load_webp_from_buffer", "buffer"), &Image::load_webp_from_buffer);
  2698. ClassDB::bind_method(D_METHOD("load_tga_from_buffer", "buffer"), &Image::load_tga_from_buffer);
  2699. ClassDB::bind_method(D_METHOD("load_bmp_from_buffer", "buffer"), &Image::load_bmp_from_buffer);
  2700. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "_set_data", "_get_data");
  2701. BIND_CONSTANT(MAX_WIDTH);
  2702. BIND_CONSTANT(MAX_HEIGHT);
  2703. BIND_ENUM_CONSTANT(FORMAT_L8); //luminance
  2704. BIND_ENUM_CONSTANT(FORMAT_LA8); //luminance-alpha
  2705. BIND_ENUM_CONSTANT(FORMAT_R8);
  2706. BIND_ENUM_CONSTANT(FORMAT_RG8);
  2707. BIND_ENUM_CONSTANT(FORMAT_RGB8);
  2708. BIND_ENUM_CONSTANT(FORMAT_RGBA8);
  2709. BIND_ENUM_CONSTANT(FORMAT_RGBA4444);
  2710. BIND_ENUM_CONSTANT(FORMAT_RGB565);
  2711. BIND_ENUM_CONSTANT(FORMAT_RF); //float
  2712. BIND_ENUM_CONSTANT(FORMAT_RGF);
  2713. BIND_ENUM_CONSTANT(FORMAT_RGBF);
  2714. BIND_ENUM_CONSTANT(FORMAT_RGBAF);
  2715. BIND_ENUM_CONSTANT(FORMAT_RH); //half float
  2716. BIND_ENUM_CONSTANT(FORMAT_RGH);
  2717. BIND_ENUM_CONSTANT(FORMAT_RGBH);
  2718. BIND_ENUM_CONSTANT(FORMAT_RGBAH);
  2719. BIND_ENUM_CONSTANT(FORMAT_RGBE9995);
  2720. BIND_ENUM_CONSTANT(FORMAT_DXT1); //s3tc bc1
  2721. BIND_ENUM_CONSTANT(FORMAT_DXT3); //bc2
  2722. BIND_ENUM_CONSTANT(FORMAT_DXT5); //bc3
  2723. BIND_ENUM_CONSTANT(FORMAT_RGTC_R);
  2724. BIND_ENUM_CONSTANT(FORMAT_RGTC_RG);
  2725. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBA); //btpc bc6h
  2726. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBF); //float /
  2727. BIND_ENUM_CONSTANT(FORMAT_BPTC_RGBFU); //unsigned float
  2728. BIND_ENUM_CONSTANT(FORMAT_ETC); //etc1
  2729. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11); //etc2
  2730. BIND_ENUM_CONSTANT(FORMAT_ETC2_R11S); //signed ); NOT srgb.
  2731. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11);
  2732. BIND_ENUM_CONSTANT(FORMAT_ETC2_RG11S);
  2733. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8);
  2734. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGBA8);
  2735. BIND_ENUM_CONSTANT(FORMAT_ETC2_RGB8A1);
  2736. BIND_ENUM_CONSTANT(FORMAT_ETC2_RA_AS_RG);
  2737. BIND_ENUM_CONSTANT(FORMAT_DXT5_RA_AS_RG);
  2738. BIND_ENUM_CONSTANT(FORMAT_MAX);
  2739. BIND_ENUM_CONSTANT(INTERPOLATE_NEAREST);
  2740. BIND_ENUM_CONSTANT(INTERPOLATE_BILINEAR);
  2741. BIND_ENUM_CONSTANT(INTERPOLATE_CUBIC);
  2742. BIND_ENUM_CONSTANT(INTERPOLATE_TRILINEAR);
  2743. BIND_ENUM_CONSTANT(INTERPOLATE_LANCZOS);
  2744. BIND_ENUM_CONSTANT(ALPHA_NONE);
  2745. BIND_ENUM_CONSTANT(ALPHA_BIT);
  2746. BIND_ENUM_CONSTANT(ALPHA_BLEND);
  2747. BIND_ENUM_CONSTANT(COMPRESS_S3TC);
  2748. BIND_ENUM_CONSTANT(COMPRESS_ETC);
  2749. BIND_ENUM_CONSTANT(COMPRESS_ETC2);
  2750. BIND_ENUM_CONSTANT(COMPRESS_BPTC);
  2751. BIND_ENUM_CONSTANT(USED_CHANNELS_L);
  2752. BIND_ENUM_CONSTANT(USED_CHANNELS_LA);
  2753. BIND_ENUM_CONSTANT(USED_CHANNELS_R);
  2754. BIND_ENUM_CONSTANT(USED_CHANNELS_RG);
  2755. BIND_ENUM_CONSTANT(USED_CHANNELS_RGB);
  2756. BIND_ENUM_CONSTANT(USED_CHANNELS_RGBA);
  2757. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_GENERIC);
  2758. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_SRGB);
  2759. BIND_ENUM_CONSTANT(COMPRESS_SOURCE_NORMAL);
  2760. }
  2761. void Image::set_compress_bc_func(void (*p_compress_func)(Image *, float, UsedChannels)) {
  2762. _image_compress_bc_func = p_compress_func;
  2763. }
  2764. void Image::set_compress_bptc_func(void (*p_compress_func)(Image *, float, UsedChannels)) {
  2765. _image_compress_bptc_func = p_compress_func;
  2766. }
  2767. void Image::normal_map_to_xy() {
  2768. convert(Image::FORMAT_RGBA8);
  2769. {
  2770. int len = data.size() / 4;
  2771. uint8_t *data_ptr = data.ptrw();
  2772. for (int i = 0; i < len; i++) {
  2773. data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w
  2774. data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz
  2775. data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1];
  2776. }
  2777. }
  2778. convert(Image::FORMAT_LA8);
  2779. }
  2780. Ref<Image> Image::rgbe_to_srgb() {
  2781. if (data.size() == 0) {
  2782. return Ref<Image>();
  2783. }
  2784. ERR_FAIL_COND_V(format != FORMAT_RGBE9995, Ref<Image>());
  2785. Ref<Image> new_image;
  2786. new_image.instantiate();
  2787. new_image->create(width, height, false, Image::FORMAT_RGB8);
  2788. for (int row = 0; row < height; row++) {
  2789. for (int col = 0; col < width; col++) {
  2790. new_image->set_pixel(col, row, get_pixel(col, row).linear_to_srgb());
  2791. }
  2792. }
  2793. if (has_mipmaps()) {
  2794. new_image->generate_mipmaps();
  2795. }
  2796. return new_image;
  2797. }
  2798. Ref<Image> Image::get_image_from_mipmap(int p_mipamp) const {
  2799. int ofs, size, w, h;
  2800. get_mipmap_offset_size_and_dimensions(p_mipamp, ofs, size, w, h);
  2801. Vector<uint8_t> new_data;
  2802. new_data.resize(size);
  2803. {
  2804. uint8_t *wr = new_data.ptrw();
  2805. const uint8_t *rd = data.ptr();
  2806. memcpy(wr, rd + ofs, size);
  2807. }
  2808. Ref<Image> image;
  2809. image.instantiate();
  2810. image->width = w;
  2811. image->height = h;
  2812. image->format = format;
  2813. image->data = new_data;
  2814. image->mipmaps = false;
  2815. return image;
  2816. }
  2817. void Image::bump_map_to_normal_map(float bump_scale) {
  2818. ERR_FAIL_COND(!_can_modify(format));
  2819. convert(Image::FORMAT_RF);
  2820. Vector<uint8_t> result_image; //rgba output
  2821. result_image.resize(width * height * 4);
  2822. {
  2823. const uint8_t *rp = data.ptr();
  2824. uint8_t *wp = result_image.ptrw();
  2825. ERR_FAIL_COND(!rp);
  2826. unsigned char *write_ptr = wp;
  2827. float *read_ptr = (float *)rp;
  2828. for (int ty = 0; ty < height; ty++) {
  2829. int py = ty + 1;
  2830. if (py >= height) {
  2831. py -= height;
  2832. }
  2833. for (int tx = 0; tx < width; tx++) {
  2834. int px = tx + 1;
  2835. if (px >= width) {
  2836. px -= width;
  2837. }
  2838. float here = read_ptr[ty * width + tx];
  2839. float to_right = read_ptr[ty * width + px];
  2840. float above = read_ptr[py * width + tx];
  2841. Vector3 up = Vector3(0, 1, (here - above) * bump_scale);
  2842. Vector3 across = Vector3(1, 0, (to_right - here) * bump_scale);
  2843. Vector3 normal = across.cross(up);
  2844. normal.normalize();
  2845. write_ptr[((ty * width + tx) << 2) + 0] = (127.5 + normal.x * 127.5);
  2846. write_ptr[((ty * width + tx) << 2) + 1] = (127.5 + normal.y * 127.5);
  2847. write_ptr[((ty * width + tx) << 2) + 2] = (127.5 + normal.z * 127.5);
  2848. write_ptr[((ty * width + tx) << 2) + 3] = 255;
  2849. }
  2850. }
  2851. }
  2852. format = FORMAT_RGBA8;
  2853. data = result_image;
  2854. }
  2855. void Image::srgb_to_linear() {
  2856. if (data.size() == 0) {
  2857. return;
  2858. }
  2859. static const uint8_t srgb2lin[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252, 255 };
  2860. ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
  2861. if (format == FORMAT_RGBA8) {
  2862. int len = data.size() / 4;
  2863. uint8_t *data_ptr = data.ptrw();
  2864. for (int i = 0; i < len; i++) {
  2865. data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]];
  2866. data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]];
  2867. data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]];
  2868. }
  2869. } else if (format == FORMAT_RGB8) {
  2870. int len = data.size() / 3;
  2871. uint8_t *data_ptr = data.ptrw();
  2872. for (int i = 0; i < len; i++) {
  2873. data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]];
  2874. data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]];
  2875. data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]];
  2876. }
  2877. }
  2878. }
  2879. void Image::premultiply_alpha() {
  2880. if (data.size() == 0) {
  2881. return;
  2882. }
  2883. if (format != FORMAT_RGBA8) {
  2884. return; //not needed
  2885. }
  2886. uint8_t *data_ptr = data.ptrw();
  2887. for (int i = 0; i < height; i++) {
  2888. for (int j = 0; j < width; j++) {
  2889. uint8_t *ptr = &data_ptr[(i * width + j) * 4];
  2890. ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3])) >> 8;
  2891. ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3])) >> 8;
  2892. ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3])) >> 8;
  2893. }
  2894. }
  2895. }
  2896. void Image::fix_alpha_edges() {
  2897. if (data.size() == 0) {
  2898. return;
  2899. }
  2900. if (format != FORMAT_RGBA8) {
  2901. return; //not needed
  2902. }
  2903. Vector<uint8_t> dcopy = data;
  2904. const uint8_t *srcptr = dcopy.ptr();
  2905. uint8_t *data_ptr = data.ptrw();
  2906. const int max_radius = 4;
  2907. const int alpha_threshold = 20;
  2908. const int max_dist = 0x7FFFFFFF;
  2909. for (int i = 0; i < height; i++) {
  2910. for (int j = 0; j < width; j++) {
  2911. const uint8_t *rptr = &srcptr[(i * width + j) * 4];
  2912. uint8_t *wptr = &data_ptr[(i * width + j) * 4];
  2913. if (rptr[3] >= alpha_threshold) {
  2914. continue;
  2915. }
  2916. int closest_dist = max_dist;
  2917. uint8_t closest_color[3];
  2918. int from_x = MAX(0, j - max_radius);
  2919. int to_x = MIN(width - 1, j + max_radius);
  2920. int from_y = MAX(0, i - max_radius);
  2921. int to_y = MIN(height - 1, i + max_radius);
  2922. for (int k = from_y; k <= to_y; k++) {
  2923. for (int l = from_x; l <= to_x; l++) {
  2924. int dy = i - k;
  2925. int dx = j - l;
  2926. int dist = dy * dy + dx * dx;
  2927. if (dist >= closest_dist) {
  2928. continue;
  2929. }
  2930. const uint8_t *rp2 = &srcptr[(k * width + l) << 2];
  2931. if (rp2[3] < alpha_threshold) {
  2932. continue;
  2933. }
  2934. closest_dist = dist;
  2935. closest_color[0] = rp2[0];
  2936. closest_color[1] = rp2[1];
  2937. closest_color[2] = rp2[2];
  2938. }
  2939. }
  2940. if (closest_dist != max_dist) {
  2941. wptr[0] = closest_color[0];
  2942. wptr[1] = closest_color[1];
  2943. wptr[2] = closest_color[2];
  2944. }
  2945. }
  2946. }
  2947. }
  2948. String Image::get_format_name(Format p_format) {
  2949. ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String());
  2950. return format_names[p_format];
  2951. }
  2952. Error Image::load_png_from_buffer(const Vector<uint8_t> &p_array) {
  2953. return _load_from_buffer(p_array, _png_mem_loader_func);
  2954. }
  2955. Error Image::load_jpg_from_buffer(const Vector<uint8_t> &p_array) {
  2956. return _load_from_buffer(p_array, _jpg_mem_loader_func);
  2957. }
  2958. Error Image::load_webp_from_buffer(const Vector<uint8_t> &p_array) {
  2959. return _load_from_buffer(p_array, _webp_mem_loader_func);
  2960. }
  2961. Error Image::load_tga_from_buffer(const Vector<uint8_t> &p_array) {
  2962. ERR_FAIL_NULL_V_MSG(
  2963. _tga_mem_loader_func,
  2964. ERR_UNAVAILABLE,
  2965. "The TGA module isn't enabled. Recompile the Godot editor or export template binary with the `module_tga_enabled=yes` SCons option.");
  2966. return _load_from_buffer(p_array, _tga_mem_loader_func);
  2967. }
  2968. Error Image::load_bmp_from_buffer(const Vector<uint8_t> &p_array) {
  2969. ERR_FAIL_NULL_V_MSG(
  2970. _bmp_mem_loader_func,
  2971. ERR_UNAVAILABLE,
  2972. "The BMP module isn't enabled. Recompile the Godot editor or export template binary with the `module_bmp_enabled=yes` SCons option.");
  2973. return _load_from_buffer(p_array, _bmp_mem_loader_func);
  2974. }
  2975. void Image::convert_rg_to_ra_rgba8() {
  2976. ERR_FAIL_COND(format != FORMAT_RGBA8);
  2977. ERR_FAIL_COND(!data.size());
  2978. int s = data.size();
  2979. uint8_t *w = data.ptrw();
  2980. for (int i = 0; i < s; i += 4) {
  2981. w[i + 3] = w[i + 1];
  2982. w[i + 1] = 0;
  2983. w[i + 2] = 0;
  2984. }
  2985. }
  2986. void Image::convert_ra_rgba8_to_rg() {
  2987. ERR_FAIL_COND(format != FORMAT_RGBA8);
  2988. ERR_FAIL_COND(!data.size());
  2989. int s = data.size();
  2990. uint8_t *w = data.ptrw();
  2991. for (int i = 0; i < s; i += 4) {
  2992. w[i + 1] = w[i + 3];
  2993. w[i + 2] = 0;
  2994. w[i + 3] = 255;
  2995. }
  2996. }
  2997. Error Image::_load_from_buffer(const Vector<uint8_t> &p_array, ImageMemLoadFunc p_loader) {
  2998. int buffer_size = p_array.size();
  2999. ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER);
  3000. ERR_FAIL_COND_V(!p_loader, ERR_INVALID_PARAMETER);
  3001. const uint8_t *r = p_array.ptr();
  3002. Ref<Image> image = p_loader(r, buffer_size);
  3003. ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR);
  3004. copy_internals_from(image);
  3005. return OK;
  3006. }
  3007. void Image::average_4_uint8(uint8_t &p_out, const uint8_t &p_a, const uint8_t &p_b, const uint8_t &p_c, const uint8_t &p_d) {
  3008. p_out = static_cast<uint8_t>((p_a + p_b + p_c + p_d + 2) >> 2);
  3009. }
  3010. void Image::average_4_float(float &p_out, const float &p_a, const float &p_b, const float &p_c, const float &p_d) {
  3011. p_out = (p_a + p_b + p_c + p_d) * 0.25f;
  3012. }
  3013. void Image::average_4_half(uint16_t &p_out, const uint16_t &p_a, const uint16_t &p_b, const uint16_t &p_c, const uint16_t &p_d) {
  3014. p_out = Math::make_half_float((Math::half_to_float(p_a) + Math::half_to_float(p_b) + Math::half_to_float(p_c) + Math::half_to_float(p_d)) * 0.25f);
  3015. }
  3016. void Image::average_4_rgbe9995(uint32_t &p_out, const uint32_t &p_a, const uint32_t &p_b, const uint32_t &p_c, const uint32_t &p_d) {
  3017. p_out = ((Color::from_rgbe9995(p_a) + Color::from_rgbe9995(p_b) + Color::from_rgbe9995(p_c) + Color::from_rgbe9995(p_d)) * 0.25f).to_rgbe9995();
  3018. }
  3019. void Image::renormalize_uint8(uint8_t *p_rgb) {
  3020. Vector3 n(p_rgb[0] / 255.0, p_rgb[1] / 255.0, p_rgb[2] / 255.0);
  3021. n *= 2.0;
  3022. n -= Vector3(1, 1, 1);
  3023. n.normalize();
  3024. n += Vector3(1, 1, 1);
  3025. n *= 0.5;
  3026. n *= 255;
  3027. p_rgb[0] = CLAMP(int(n.x), 0, 255);
  3028. p_rgb[1] = CLAMP(int(n.y), 0, 255);
  3029. p_rgb[2] = CLAMP(int(n.z), 0, 255);
  3030. }
  3031. void Image::renormalize_float(float *p_rgb) {
  3032. Vector3 n(p_rgb[0], p_rgb[1], p_rgb[2]);
  3033. n.normalize();
  3034. p_rgb[0] = n.x;
  3035. p_rgb[1] = n.y;
  3036. p_rgb[2] = n.z;
  3037. }
  3038. void Image::renormalize_half(uint16_t *p_rgb) {
  3039. Vector3 n(Math::half_to_float(p_rgb[0]), Math::half_to_float(p_rgb[1]), Math::half_to_float(p_rgb[2]));
  3040. n.normalize();
  3041. p_rgb[0] = Math::make_half_float(n.x);
  3042. p_rgb[1] = Math::make_half_float(n.y);
  3043. p_rgb[2] = Math::make_half_float(n.z);
  3044. }
  3045. void Image::renormalize_rgbe9995(uint32_t *p_rgb) {
  3046. // Never used
  3047. }
  3048. Image::Image(const uint8_t *p_mem_png_jpg, int p_len) {
  3049. width = 0;
  3050. height = 0;
  3051. mipmaps = false;
  3052. format = FORMAT_L8;
  3053. if (_png_mem_loader_func) {
  3054. copy_internals_from(_png_mem_loader_func(p_mem_png_jpg, p_len));
  3055. }
  3056. if (is_empty() && _jpg_mem_loader_func) {
  3057. copy_internals_from(_jpg_mem_loader_func(p_mem_png_jpg, p_len));
  3058. }
  3059. if (is_empty() && _webp_mem_loader_func) {
  3060. copy_internals_from(_webp_mem_loader_func(p_mem_png_jpg, p_len));
  3061. }
  3062. }
  3063. Ref<Resource> Image::duplicate(bool p_subresources) const {
  3064. Ref<Image> copy;
  3065. copy.instantiate();
  3066. copy->_copy_internals_from(*this);
  3067. return copy;
  3068. }
  3069. void Image::set_as_black() {
  3070. memset(data.ptrw(), 0, data.size());
  3071. }
  3072. Dictionary Image::compute_image_metrics(const Ref<Image> p_compared_image, bool p_luma_metric) {
  3073. // https://github.com/richgel999/bc7enc_rdo/blob/master/LICENSE
  3074. //
  3075. // This is free and unencumbered software released into the public domain.
  3076. // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  3077. // software, either in source code form or as a compiled binary, for any purpose,
  3078. // commercial or non - commercial, and by any means.
  3079. // In jurisdictions that recognize copyright laws, the author or authors of this
  3080. // software dedicate any and all copyright interest in the software to the public
  3081. // domain. We make this dedication for the benefit of the public at large and to
  3082. // the detriment of our heirs and successors. We intend this dedication to be an
  3083. // overt act of relinquishment in perpetuity of all present and future rights to
  3084. // this software under copyright law.
  3085. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3086. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3087. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  3088. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  3089. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  3090. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  3091. Dictionary result;
  3092. result["max"] = INFINITY;
  3093. result["mean"] = INFINITY;
  3094. result["mean_squared"] = INFINITY;
  3095. result["root_mean_squared"] = INFINITY;
  3096. result["peak_snr"] = 0.0f;
  3097. ERR_FAIL_NULL_V(p_compared_image, result);
  3098. Error err = OK;
  3099. Ref<Image> compared_image = duplicate(true);
  3100. if (compared_image->is_compressed()) {
  3101. err = compared_image->decompress();
  3102. }
  3103. ERR_FAIL_COND_V(err != OK, result);
  3104. Ref<Image> source_image = p_compared_image->duplicate(true);
  3105. if (source_image->is_compressed()) {
  3106. err = source_image->decompress();
  3107. }
  3108. ERR_FAIL_COND_V(err != OK, result);
  3109. ERR_FAIL_COND_V(err != OK, result);
  3110. ERR_FAIL_COND_V_MSG((compared_image->get_format() >= Image::FORMAT_RH) && (compared_image->get_format() <= Image::FORMAT_RGBE9995), result, "Metrics on HDR images are not supported.");
  3111. ERR_FAIL_COND_V_MSG((source_image->get_format() >= Image::FORMAT_RH) && (source_image->get_format() <= Image::FORMAT_RGBE9995), result, "Metrics on HDR images are not supported.");
  3112. double image_metric_max, image_metric_mean, image_metric_mean_squared, image_metric_root_mean_squared, image_metric_peak_snr = 0.0;
  3113. const bool average_component_error = true;
  3114. const uint32_t width = MIN(compared_image->get_width(), source_image->get_width());
  3115. const uint32_t height = MIN(compared_image->get_height(), source_image->get_height());
  3116. // Histogram approach originally due to Charles Bloom.
  3117. double hist[256];
  3118. memset(hist, 0, sizeof(hist));
  3119. for (uint32_t y = 0; y < height; y++) {
  3120. for (uint32_t x = 0; x < width; x++) {
  3121. const Color color_a = compared_image->get_pixel(x, y);
  3122. const Color color_b = source_image->get_pixel(x, y);
  3123. if (!p_luma_metric) {
  3124. ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3125. ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3126. hist[Math::abs(color_a.get_r8() - color_b.get_r8())]++;
  3127. ERR_FAIL_COND_V_MSG(color_a.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3128. ERR_FAIL_COND_V_MSG(color_b.g > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3129. hist[Math::abs(color_a.get_g8() - color_b.get_g8())]++;
  3130. ERR_FAIL_COND_V_MSG(color_a.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3131. ERR_FAIL_COND_V_MSG(color_b.b > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3132. hist[Math::abs(color_a.get_b8() - color_b.get_b8())]++;
  3133. ERR_FAIL_COND_V_MSG(color_a.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3134. ERR_FAIL_COND_V_MSG(color_b.a > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3135. hist[Math::abs(color_a.get_a8() - color_b.get_a8())]++;
  3136. } else {
  3137. ERR_FAIL_COND_V_MSG(color_a.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3138. ERR_FAIL_COND_V_MSG(color_b.r > 1.0f, Dictionary(), "Can't compare HDR colors.");
  3139. // REC709 weightings
  3140. int luma_a = (13938U * color_a.get_r8() + 46869U * color_a.get_g8() + 4729U * color_a.get_b8() + 32768U) >> 16U;
  3141. int luma_b = (13938U * color_b.get_r8() + 46869U * color_b.get_g8() + 4729U * color_b.get_b8() + 32768U) >> 16U;
  3142. hist[Math::abs(luma_a - luma_b)]++;
  3143. }
  3144. }
  3145. }
  3146. image_metric_max = 0;
  3147. double sum = 0.0f, sum2 = 0.0f;
  3148. for (uint32_t i = 0; i < 256; i++) {
  3149. if (!hist[i]) {
  3150. continue;
  3151. }
  3152. image_metric_max = MAX(image_metric_max, i);
  3153. double x = i * hist[i];
  3154. sum += x;
  3155. sum2 += i * x;
  3156. }
  3157. // See http://richg42.blogspot.com/2016/09/how-to-compute-psnr-from-old-berkeley.html
  3158. double total_values = width * height;
  3159. if (average_component_error) {
  3160. total_values *= 4;
  3161. }
  3162. image_metric_mean = CLAMP(sum / total_values, 0.0f, 255.0f);
  3163. image_metric_mean_squared = CLAMP(sum2 / total_values, 0.0f, 255.0f * 255.0f);
  3164. image_metric_root_mean_squared = sqrt(image_metric_mean_squared);
  3165. if (!image_metric_root_mean_squared) {
  3166. image_metric_peak_snr = 1e+10f;
  3167. } else {
  3168. image_metric_peak_snr = CLAMP(log10(255.0f / image_metric_root_mean_squared) * 20.0f, 0.0f, 500.0f);
  3169. }
  3170. result["max"] = image_metric_max;
  3171. result["mean"] = image_metric_mean;
  3172. result["mean_squared"] = image_metric_mean_squared;
  3173. result["root_mean_squared"] = image_metric_root_mean_squared;
  3174. result["peak_snr"] = image_metric_peak_snr;
  3175. return result;
  3176. }