image.cpp 130 KB

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