image.cpp 130 KB

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