image.cpp 123 KB

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