image.cpp 127 KB

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