BsPixelUtil.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsPixelUtil.h"
  4. #include "BsBitwise.h"
  5. #include "BsColor.h"
  6. #include "BsMath.h"
  7. #include "BsException.h"
  8. #include "BsTexture.h"
  9. #include <nvtt.h>
  10. namespace bs
  11. {
  12. /**
  13. * Performs pixel data resampling using the point filter (nearest neighbor). Does not perform format conversions.
  14. *
  15. * @tparam elementSize Size of a single pixel in bytes.
  16. */
  17. template<UINT32 elementSize> struct NearestResampler
  18. {
  19. static void scale(const PixelData& source, const PixelData& dest)
  20. {
  21. UINT8* sourceData = source.getData();
  22. UINT8* destPtr = dest.getData();
  23. // Get steps for traversing source data in 16/48 fixed point format
  24. UINT64 stepX = ((UINT64)source.getWidth() << 48) / dest.getWidth();
  25. UINT64 stepY = ((UINT64)source.getHeight() << 48) / dest.getHeight();
  26. UINT64 stepZ = ((UINT64)source.getDepth() << 48) / dest.getDepth();
  27. UINT64 curZ = (stepZ >> 1) - 1; // Offset half a pixel to start at pixel center
  28. for (UINT32 z = dest.getFront(); z < dest.getBack(); z++, curZ += stepZ)
  29. {
  30. UINT32 offsetZ = (UINT32)(curZ >> 48) * source.getSlicePitch();
  31. UINT64 curY = (stepY >> 1) - 1; // Offset half a pixel to start at pixel center
  32. for (UINT32 y = dest.getTop(); y < dest.getBottom(); y++, curY += stepY)
  33. {
  34. UINT32 offsetY = (UINT32)(curY >> 48) * source.getRowPitch();
  35. UINT64 curX = (stepX >> 1) - 1; // Offset half a pixel to start at pixel center
  36. for (UINT32 x = dest.getLeft(); x < dest.getRight(); x++, curX += stepX)
  37. {
  38. UINT32 offsetX = (UINT32)(curX >> 48);
  39. UINT32 offsetBytes = elementSize*(offsetX + offsetY + offsetZ);
  40. UINT8* curSourcePtr = sourceData + offsetBytes;
  41. memcpy(destPtr, curSourcePtr, elementSize);
  42. destPtr += elementSize;
  43. }
  44. destPtr += elementSize*dest.getRowSkip();
  45. }
  46. destPtr += elementSize*dest.getSliceSkip();
  47. }
  48. }
  49. };
  50. /** Performs pixel data resampling using the box filter (linear). Performs format conversions. */
  51. struct LinearResampler
  52. {
  53. static void scale(const PixelData& source, const PixelData& dest)
  54. {
  55. UINT32 sourceElemSize = PixelUtil::getNumElemBytes(source.getFormat());
  56. UINT32 destElemSize = PixelUtil::getNumElemBytes(dest.getFormat());
  57. UINT8* sourceData = source.getData();
  58. UINT8* destPtr = dest.getData();
  59. // Get steps for traversing source data in 16/48 fixed point precision format
  60. UINT64 stepX = ((UINT64)source.getWidth() << 48) / dest.getWidth();
  61. UINT64 stepY = ((UINT64)source.getHeight() << 48) / dest.getHeight();
  62. UINT64 stepZ = ((UINT64)source.getDepth() << 48) / dest.getDepth();
  63. // Contains 16/16 fixed point precision format. Most significant
  64. // 16 bits will contain the coordinate in the source image, and the
  65. // least significant 16 bits will contain the fractional part of the coordinate
  66. // that will be used for determining the blend amount.
  67. UINT32 temp = 0;
  68. UINT64 curZ = (stepZ >> 1) - 1; // Offset half a pixel to start at pixel center
  69. for (UINT32 z = dest.getFront(); z < dest.getBack(); z++, curZ += stepZ)
  70. {
  71. temp = UINT32(curZ >> 32);
  72. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  73. UINT32 sampleCoordZ1 = temp >> 16;
  74. UINT32 sampleCoordZ2 = std::min(sampleCoordZ1 + 1, (UINT32)source.getDepth() - 1);
  75. float sampleWeightZ = (temp & 0xFFFF) / 65536.0f;
  76. UINT64 curY = (stepY >> 1) - 1; // Offset half a pixel to start at pixel center
  77. for (UINT32 y = dest.getTop(); y < dest.getBottom(); y++, curY += stepY)
  78. {
  79. temp = (UINT32)(curY >> 32);
  80. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  81. UINT32 sampleCoordY1 = temp >> 16;
  82. UINT32 sampleCoordY2 = std::min(sampleCoordY1 + 1, (UINT32)source.getHeight() - 1);
  83. float sampleWeightY = (temp & 0xFFFF) / 65536.0f;
  84. UINT64 curX = (stepX >> 1) - 1; // Offset half a pixel to start at pixel center
  85. for (UINT32 x = dest.getLeft(); x < dest.getRight(); x++, curX += stepX)
  86. {
  87. temp = (UINT32)(curX >> 32);
  88. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  89. UINT32 sampleCoordX1 = temp >> 16;
  90. UINT32 sampleCoordX2 = std::min(sampleCoordX1 + 1, (UINT32)source.getWidth() - 1);
  91. float sampleWeightX = (temp & 0xFFFF) / 65536.0f;
  92. Color x1y1z1, x2y1z1, x1y2z1, x2y2z1;
  93. Color x1y1z2, x2y1z2, x1y2z2, x2y2z2;
  94. #define GETSOURCEDATA(x, y, z) sourceData + sourceElemSize*((x)+(y)*source.getRowPitch() + (z)*source.getSlicePitch())
  95. PixelUtil::unpackColor(&x1y1z1, source.getFormat(), GETSOURCEDATA(sampleCoordX1, sampleCoordY1, sampleCoordZ1));
  96. PixelUtil::unpackColor(&x2y1z1, source.getFormat(), GETSOURCEDATA(sampleCoordX2, sampleCoordY1, sampleCoordZ1));
  97. PixelUtil::unpackColor(&x1y2z1, source.getFormat(), GETSOURCEDATA(sampleCoordX1, sampleCoordY2, sampleCoordZ1));
  98. PixelUtil::unpackColor(&x2y2z1, source.getFormat(), GETSOURCEDATA(sampleCoordX2, sampleCoordY2, sampleCoordZ1));
  99. PixelUtil::unpackColor(&x1y1z2, source.getFormat(), GETSOURCEDATA(sampleCoordX1, sampleCoordY1, sampleCoordZ2));
  100. PixelUtil::unpackColor(&x2y1z2, source.getFormat(), GETSOURCEDATA(sampleCoordX2, sampleCoordY1, sampleCoordZ2));
  101. PixelUtil::unpackColor(&x1y2z2, source.getFormat(), GETSOURCEDATA(sampleCoordX1, sampleCoordY2, sampleCoordZ2));
  102. PixelUtil::unpackColor(&x2y2z2, source.getFormat(), GETSOURCEDATA(sampleCoordX2, sampleCoordY2, sampleCoordZ2));
  103. #undef GETSOURCEDATA
  104. Color accum =
  105. x1y1z1 * ((1.0f - sampleWeightX)*(1.0f - sampleWeightY)*(1.0f - sampleWeightZ)) +
  106. x2y1z1 * ( sampleWeightX *(1.0f - sampleWeightY)*(1.0f - sampleWeightZ)) +
  107. x1y2z1 * ((1.0f - sampleWeightX)* sampleWeightY *(1.0f - sampleWeightZ)) +
  108. x2y2z1 * ( sampleWeightX * sampleWeightY *(1.0f - sampleWeightZ)) +
  109. x1y1z2 * ((1.0f - sampleWeightX)*(1.0f - sampleWeightY)* sampleWeightZ ) +
  110. x2y1z2 * ( sampleWeightX *(1.0f - sampleWeightY)* sampleWeightZ ) +
  111. x1y2z2 * ((1.0f - sampleWeightX)* sampleWeightY * sampleWeightZ ) +
  112. x2y2z2 * ( sampleWeightX * sampleWeightY * sampleWeightZ );
  113. PixelUtil::packColor(accum, dest.getFormat(), destPtr);
  114. destPtr += destElemSize;
  115. }
  116. destPtr += destElemSize * dest.getRowSkip();
  117. }
  118. destPtr += destElemSize * dest.getSliceSkip();
  119. }
  120. }
  121. };
  122. /**
  123. * Performs pixel data resampling using the box filter (linear). Only handles float RGB or RGBA pixel data (32 bits per
  124. * channel).
  125. */
  126. struct LinearResampler_Float32
  127. {
  128. static void scale(const PixelData& source, const PixelData& dest)
  129. {
  130. UINT32 numSourceChannels = PixelUtil::getNumElemBytes(source.getFormat()) / sizeof(float);
  131. UINT32 numDestChannels = PixelUtil::getNumElemBytes(dest.getFormat()) / sizeof(float);
  132. float* sourceData = (float*)source.getData();
  133. float* destPtr = (float*)dest.getData();
  134. // Get steps for traversing source data in 16/48 fixed point precision format
  135. UINT64 stepX = ((UINT64)source.getWidth() << 48) / dest.getWidth();
  136. UINT64 stepY = ((UINT64)source.getHeight() << 48) / dest.getHeight();
  137. UINT64 stepZ = ((UINT64)source.getDepth() << 48) / dest.getDepth();
  138. // Contains 16/16 fixed point precision format. Most significant
  139. // 16 bits will contain the coordinate in the source image, and the
  140. // least significant 16 bits will contain the fractional part of the coordinate
  141. // that will be used for determining the blend amount.
  142. UINT32 temp = 0;
  143. UINT64 curZ = (stepZ >> 1) - 1; // Offset half a pixel to start at pixel center
  144. for (UINT32 z = dest.getFront(); z < dest.getBack(); z++, curZ += stepZ)
  145. {
  146. temp = (UINT32)(curZ >> 32);
  147. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  148. UINT32 sampleCoordZ1 = temp >> 16;
  149. UINT32 sampleCoordZ2 = std::min(sampleCoordZ1 + 1, (UINT32)source.getDepth() - 1);
  150. float sampleWeightZ = (temp & 0xFFFF) / 65536.0f;
  151. UINT64 curY = (stepY >> 1) - 1; // Offset half a pixel to start at pixel center
  152. for (UINT32 y = dest.getTop(); y < dest.getBottom(); y++, curY += stepY)
  153. {
  154. temp = (UINT32)(curY >> 32);
  155. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  156. UINT32 sampleCoordY1 = temp >> 16;
  157. UINT32 sampleCoordY2 = std::min(sampleCoordY1 + 1, (UINT32)source.getHeight() - 1);
  158. float sampleWeightY = (temp & 0xFFFF) / 65536.0f;
  159. UINT64 curX = (stepX >> 1) - 1; // Offset half a pixel to start at pixel center
  160. for (UINT32 x = dest.getLeft(); x < dest.getRight(); x++, curX += stepX)
  161. {
  162. temp = (UINT32)(curX >> 32);
  163. temp = (temp > 0x8000)? temp - 0x8000 : 0;
  164. UINT32 sampleCoordX1 = temp >> 16;
  165. UINT32 sampleCoordX2 = std::min(sampleCoordX1 + 1, (UINT32)source.getWidth() - 1);
  166. float sampleWeightX = (temp & 0xFFFF) / 65536.0f;
  167. // process R,G,B,A simultaneously for cache coherence?
  168. float accum[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
  169. #define ACCUM3(x,y,z,factor) \
  170. { float f = factor; \
  171. UINT32 offset = (x + y*source.getRowPitch() + z*source.getSlicePitch())*numSourceChannels; \
  172. accum[0] += sourceData[offset + 0] * f; accum[1] += sourceData[offset + 1] * f; \
  173. accum[2] += sourceData[offset + 2] * f; }
  174. #define ACCUM4(x,y,z,factor) \
  175. { float f = factor; \
  176. UINT32 offset = (x + y*source.getRowPitch() + z*source.getSlicePitch())*numSourceChannels; \
  177. accum[0] += sourceData[offset + 0] * f; accum[1] += sourceData[offset + 1] * f; \
  178. accum[2] += sourceData[offset + 2] * f; accum[3] += sourceData[offset + 3] * f; }
  179. if (numSourceChannels == 3 || numDestChannels == 3)
  180. {
  181. // RGB
  182. ACCUM3(sampleCoordX1, sampleCoordY1, sampleCoordZ1, (1.0f - sampleWeightX) * (1.0f - sampleWeightY) * (1.0f - sampleWeightZ));
  183. ACCUM3(sampleCoordX2, sampleCoordY1, sampleCoordZ1, sampleWeightX * (1.0f - sampleWeightY) * (1.0f - sampleWeightZ));
  184. ACCUM3(sampleCoordX1, sampleCoordY2, sampleCoordZ1, (1.0f - sampleWeightX) * sampleWeightY * (1.0f - sampleWeightZ));
  185. ACCUM3(sampleCoordX2, sampleCoordY2, sampleCoordZ1, sampleWeightX * sampleWeightY * (1.0f - sampleWeightZ));
  186. ACCUM3(sampleCoordX1, sampleCoordY1, sampleCoordZ2, (1.0f - sampleWeightX) * (1.0f - sampleWeightY) * sampleWeightZ);
  187. ACCUM3(sampleCoordX2, sampleCoordY1, sampleCoordZ2, sampleWeightX * (1.0f - sampleWeightY) * sampleWeightZ);
  188. ACCUM3(sampleCoordX1, sampleCoordY2, sampleCoordZ2, (1.0f - sampleWeightX) * sampleWeightY * sampleWeightZ);
  189. ACCUM3(sampleCoordX2, sampleCoordY2, sampleCoordZ2, sampleWeightX * sampleWeightY * sampleWeightZ);
  190. accum[3] = 1.0f;
  191. }
  192. else
  193. {
  194. // RGBA
  195. ACCUM4(sampleCoordX1, sampleCoordY1, sampleCoordZ1, (1.0f - sampleWeightX) * (1.0f - sampleWeightY) * (1.0f - sampleWeightZ));
  196. ACCUM4(sampleCoordX2, sampleCoordY1, sampleCoordZ1, sampleWeightX * (1.0f - sampleWeightY) * (1.0f - sampleWeightZ));
  197. ACCUM4(sampleCoordX1, sampleCoordY2, sampleCoordZ1, (1.0f - sampleWeightX) * sampleWeightY * (1.0f - sampleWeightZ));
  198. ACCUM4(sampleCoordX2, sampleCoordY2, sampleCoordZ1, sampleWeightX * sampleWeightY * (1.0f - sampleWeightZ));
  199. ACCUM4(sampleCoordX1, sampleCoordY1, sampleCoordZ2, (1.0f - sampleWeightX) * (1.0f - sampleWeightY) * sampleWeightZ);
  200. ACCUM4(sampleCoordX2, sampleCoordY1, sampleCoordZ2, sampleWeightX * (1.0f - sampleWeightY) * sampleWeightZ);
  201. ACCUM4(sampleCoordX1, sampleCoordY2, sampleCoordZ2, (1.0f - sampleWeightX) * sampleWeightY * sampleWeightZ);
  202. ACCUM4(sampleCoordX2, sampleCoordY2, sampleCoordZ2, sampleWeightX * sampleWeightY * sampleWeightZ);
  203. }
  204. memcpy(destPtr, accum, sizeof(float)*numDestChannels);
  205. #undef ACCUM3
  206. #undef ACCUM4
  207. destPtr += numDestChannels;
  208. }
  209. destPtr += numDestChannels*dest.getRowSkip();
  210. }
  211. destPtr += numDestChannels*dest.getSliceSkip();
  212. }
  213. }
  214. };
  215. // byte linear resampler, does not do any format conversions.
  216. // only handles pixel formats that use 1 byte per color channel.
  217. // 2D only; punts 3D pixelboxes to default LinearResampler (slow).
  218. // templated on bytes-per-pixel to allow compiler optimizations, such
  219. // as unrolling loops and replacing multiplies with bitshifts
  220. /**
  221. * Performs pixel data resampling using the box filter (linear). Only handles pixel formats with one byte per channel.
  222. * Does not perform format conversion.
  223. *
  224. * @tparam channels Number of channels in the pixel format.
  225. */
  226. template<UINT32 channels> struct LinearResampler_Byte
  227. {
  228. static void scale(const PixelData& source, const PixelData& dest)
  229. {
  230. // Only optimized for 2D
  231. if (source.getDepth() > 1 || dest.getDepth() > 1)
  232. {
  233. LinearResampler::scale(source, dest);
  234. return;
  235. }
  236. UINT8* sourceData = (UINT8*)source.getData();
  237. UINT8* destPtr = (UINT8*)dest.getData();
  238. // Get steps for traversing source data in 16/48 fixed point precision format
  239. UINT64 stepX = ((UINT64)source.getWidth() << 48) / dest.getWidth();
  240. UINT64 stepY = ((UINT64)source.getHeight() << 48) / dest.getHeight();
  241. // Contains 16/16 fixed point precision format. Most significant
  242. // 16 bits will contain the coordinate in the source image, and the
  243. // least significant 16 bits will contain the fractional part of the coordinate
  244. // that will be used for determining the blend amount.
  245. UINT32 temp;
  246. UINT64 curY = (stepY >> 1) - 1; // Offset half a pixel to start at pixel center
  247. for (UINT32 y = dest.getTop(); y < dest.getBottom(); y++, curY += stepY)
  248. {
  249. temp = (UINT32)(curY >> 36);
  250. temp = (temp > 0x800)? temp - 0x800: 0;
  251. UINT32 sampleWeightY = temp & 0xFFF;
  252. UINT32 sampleCoordY1 = temp >> 12;
  253. UINT32 sampleCoordY2 = std::min(sampleCoordY1 + 1, (UINT32)source.getBottom() - source.getTop() - 1);
  254. UINT32 sampleY1Offset = sampleCoordY1 * source.getRowPitch();
  255. UINT32 sampleY2Offset = sampleCoordY2 * source.getRowPitch();
  256. UINT64 curX = (stepX >> 1) - 1; // Offset half a pixel to start at pixel center
  257. for (UINT32 x = dest.getLeft(); x < dest.getRight(); x++, curX += stepX)
  258. {
  259. temp = (UINT32)(curX >> 36);
  260. temp = (temp > 0x800)? temp - 0x800 : 0;
  261. UINT32 sampleWeightX = temp & 0xFFF;
  262. UINT32 sampleCoordX1 = temp >> 12;
  263. UINT32 sampleCoordX2 = std::min(sampleCoordX1 + 1, (UINT32)source.getRight() - source.getLeft() - 1);
  264. UINT32 sxfsyf = sampleWeightX*sampleWeightY;
  265. for (UINT32 k = 0; k < channels; k++)
  266. {
  267. UINT32 accum =
  268. sourceData[(sampleCoordX1 + sampleY1Offset)*channels+k]*(0x1000000-(sampleWeightX<<12)-(sampleWeightY<<12)+sxfsyf) +
  269. sourceData[(sampleCoordX2 + sampleY1Offset)*channels+k]*((sampleWeightX<<12)-sxfsyf) +
  270. sourceData[(sampleCoordX1 + sampleY2Offset)*channels+k]*((sampleWeightY<<12)-sxfsyf) +
  271. sourceData[(sampleCoordX2 + sampleY2Offset)*channels+k]*sxfsyf;
  272. // Round up to byte size
  273. *destPtr = (UINT8)((accum + 0x800000) >> 24);
  274. destPtr++;
  275. }
  276. }
  277. destPtr += channels*dest.getRowSkip();
  278. }
  279. }
  280. };
  281. /** Data describing a pixel format. */
  282. struct PixelFormatDescription
  283. {
  284. const char* name; /**< Name of the format. */
  285. UINT8 elemBytes; /**< Number of bytes one element (color value) uses. */
  286. UINT32 flags; /**< PixelFormatFlags set by the pixel format. */
  287. PixelComponentType componentType; /**< Data type of a single element of the format. */
  288. UINT8 componentCount; /**< Number of elements in the format. */
  289. UINT8 rbits, gbits, bbits, abits; /**< Number of bits per element in the format. */
  290. UINT32 rmask, gmask, bmask, amask; /**< Masks used by packers/unpackers. */
  291. UINT8 rshift, gshift, bshift, ashift; /**< Shifts used by packers/unpackers. */
  292. };
  293. /** A list of all available pixel formats. */
  294. PixelFormatDescription _pixelFormats[PF_COUNT] = {
  295. {"PF_UNKNOWN",
  296. /* Bytes per element */
  297. 0,
  298. /* Flags */
  299. 0,
  300. /* Component type and count */
  301. PCT_BYTE, 0,
  302. /* rbits, gbits, bbits, abits */
  303. 0, 0, 0, 0,
  304. /* Masks and shifts */
  305. 0, 0, 0, 0, 0, 0, 0, 0
  306. },
  307. //-----------------------------------------------------------------------
  308. {"PF_R8",
  309. /* Bytes per element */
  310. 1,
  311. /* Flags */
  312. 0,
  313. /* Component type and count */
  314. PCT_BYTE, 1,
  315. /* rbits, gbits, bbits, abits */
  316. 8, 0, 0, 0,
  317. /* Masks and shifts */
  318. 0x000000FF, 0, 0, 0,
  319. 0, 0, 0, 0
  320. },
  321. //-----------------------------------------------------------------------
  322. {"PF_R8G8",
  323. /* Bytes per element */
  324. 2,
  325. /* Flags */
  326. 0,
  327. /* Component type and count */
  328. PCT_BYTE, 2,
  329. /* rbits, gbits, bbits, abits */
  330. 8, 8, 0, 0,
  331. /* Masks and shifts */
  332. 0x000000FF, 0x0000FF00, 0, 0,
  333. 0, 8, 0, 0
  334. },
  335. //-----------------------------------------------------------------------
  336. {"PF_R8G8B8",
  337. /* Bytes per element */
  338. 3, // 24 bit integer -- special
  339. /* Flags */
  340. PFF_NATIVEENDIAN,
  341. /* Component type and count */
  342. PCT_BYTE, 3,
  343. /* rbits, gbits, bbits, abits */
  344. 8, 8, 8, 0,
  345. /* Masks and shifts */
  346. 0x000000FF, 0x0000FF00, 0x00FF0000, 0,
  347. 0, 8, 16, 0
  348. },
  349. //-----------------------------------------------------------------------
  350. {"PF_B8G8R8",
  351. /* Bytes per element */
  352. 3, // 24 bit integer -- special
  353. /* Flags */
  354. PFF_NATIVEENDIAN,
  355. /* Component type and count */
  356. PCT_BYTE, 3,
  357. /* rbits, gbits, bbits, abits */
  358. 8, 8, 8, 0,
  359. /* Masks and shifts */
  360. 0x00FF0000, 0x0000FF00, 0x000000FF, 0,
  361. 16, 8, 0, 0
  362. },
  363. //-----------------------------------------------------------------------
  364. {}, // Deleted format
  365. //-----------------------------------------------------------------------
  366. {}, // Deleted format
  367. //-----------------------------------------------------------------------
  368. {"PF_B8G8R8A8",
  369. /* Bytes per element */
  370. 4,
  371. /* Flags */
  372. PFF_HASALPHA | PFF_NATIVEENDIAN,
  373. /* Component type and count */
  374. PCT_BYTE, 4,
  375. /* rbits, gbits, bbits, abits */
  376. 8, 8, 8, 8,
  377. /* Masks and shifts */
  378. 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000,
  379. 16, 8, 0, 24
  380. },
  381. //-----------------------------------------------------------------------
  382. {"PF_R8G8B8A8",
  383. /* Bytes per element */
  384. 4,
  385. /* Flags */
  386. PFF_HASALPHA | PFF_NATIVEENDIAN,
  387. /* Component type and count */
  388. PCT_BYTE, 4,
  389. /* rbits, gbits, bbits, abits */
  390. 8, 8, 8, 8,
  391. /* Masks and shifts */
  392. 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000,
  393. 0, 8, 16, 24
  394. },
  395. //-----------------------------------------------------------------------
  396. {}, // Deleted format
  397. //-----------------------------------------------------------------------
  398. {}, // Deleted format
  399. //-----------------------------------------------------------------------
  400. {}, // Deleted format
  401. //-----------------------------------------------------------------------
  402. {}, // Deleted format
  403. //-----------------------------------------------------------------------
  404. {"PF_BC1",
  405. /* Bytes per element */
  406. 0,
  407. /* Flags */
  408. PFF_COMPRESSED | PFF_HASALPHA,
  409. /* Component type and count */
  410. PCT_BYTE, 3, // No alpha
  411. /* rbits, gbits, bbits, abits */
  412. 0, 0, 0, 0,
  413. /* Masks and shifts */
  414. 0, 0, 0, 0, 0, 0, 0, 0
  415. },
  416. //-----------------------------------------------------------------------
  417. {"PF_BC1a",
  418. /* Bytes per element */
  419. 0,
  420. /* Flags */
  421. PFF_COMPRESSED,
  422. /* Component type and count */
  423. PCT_BYTE, 3,
  424. /* rbits, gbits, bbits, abits */
  425. 0, 0, 0, 0,
  426. /* Masks and shifts */
  427. 0, 0, 0, 0, 0, 0, 0, 0
  428. },
  429. //-----------------------------------------------------------------------
  430. {"PF_BC2",
  431. /* Bytes per element */
  432. 0,
  433. /* Flags */
  434. PFF_COMPRESSED | PFF_HASALPHA,
  435. /* Component type and count */
  436. PCT_BYTE, 4,
  437. /* rbits, gbits, bbits, abits */
  438. 0, 0, 0, 0,
  439. /* Masks and shifts */
  440. 0, 0, 0, 0, 0, 0, 0, 0
  441. },
  442. //-----------------------------------------------------------------------
  443. {"PF_BC3",
  444. /* Bytes per element */
  445. 0,
  446. /* Flags */
  447. PFF_COMPRESSED | PFF_HASALPHA,
  448. /* Component type and count */
  449. PCT_BYTE, 4,
  450. /* rbits, gbits, bbits, abits */
  451. 0, 0, 0, 0,
  452. /* Masks and shifts */
  453. 0, 0, 0, 0, 0, 0, 0, 0
  454. },
  455. //-----------------------------------------------------------------------
  456. {"PF_BC4",
  457. /* Bytes per element */
  458. 0,
  459. /* Flags */
  460. PFF_COMPRESSED,
  461. /* Component type and count */
  462. PCT_BYTE, 1,
  463. /* rbits, gbits, bbits, abits */
  464. 0, 0, 0, 0,
  465. /* Masks and shifts */
  466. 0, 0, 0, 0, 0, 0, 0, 0
  467. },
  468. //-----------------------------------------------------------------------
  469. {"PF_BC5",
  470. /* Bytes per element */
  471. 0,
  472. /* Flags */
  473. PFF_COMPRESSED,
  474. /* Component type and count */
  475. PCT_BYTE, 2,
  476. /* rbits, gbits, bbits, abits */
  477. 0, 0, 0, 0,
  478. /* Masks and shifts */
  479. 0, 0, 0, 0, 0, 0, 0, 0
  480. },
  481. //-----------------------------------------------------------------------
  482. {"PF_BC6H",
  483. /* Bytes per element */
  484. 0,
  485. /* Flags */
  486. PFF_COMPRESSED,
  487. /* Component type and count */
  488. PCT_FLOAT16, 3,
  489. /* rbits, gbits, bbits, abits */
  490. 0, 0, 0, 0,
  491. /* Masks and shifts */
  492. 0, 0, 0, 0, 0, 0, 0, 0
  493. },
  494. //-----------------------------------------------------------------------
  495. {"PF_BC7",
  496. /* Bytes per element */
  497. 0,
  498. /* Flags */
  499. PFF_COMPRESSED | PFF_HASALPHA,
  500. /* Component type and count */
  501. PCT_BYTE, 4,
  502. /* rbits, gbits, bbits, abits */
  503. 0, 0, 0, 0,
  504. /* Masks and shifts */
  505. 0, 0, 0, 0, 0, 0, 0, 0
  506. },
  507. //-----------------------------------------------------------------------
  508. {"PF_FLOAT16_R",
  509. /* Bytes per element */
  510. 2,
  511. /* Flags */
  512. PFF_FLOAT,
  513. /* Component type and count */
  514. PCT_FLOAT16, 1,
  515. /* rbits, gbits, bbits, abits */
  516. 16, 0, 0, 0,
  517. /* Masks and shifts */
  518. 0, 0, 0, 0, 0, 0, 0, 0
  519. },
  520. //-----------------------------------------------------------------------
  521. {"PF_FLOAT16_RG",
  522. /* Bytes per element */
  523. 4,
  524. /* Flags */
  525. PFF_FLOAT,
  526. /* Component type and count */
  527. PCT_FLOAT16, 2,
  528. /* rbits, gbits, bbits, abits */
  529. 16, 16, 0, 0,
  530. /* Masks and shifts */
  531. 0, 0, 0, 0, 0, 0, 0, 0
  532. },
  533. //-----------------------------------------------------------------------
  534. {"PF_FLOAT16_RGB",
  535. /* Bytes per element */
  536. 6,
  537. /* Flags */
  538. PFF_FLOAT,
  539. /* Component type and count */
  540. PCT_FLOAT16, 3,
  541. /* rbits, gbits, bbits, abits */
  542. 16, 16, 16, 0,
  543. /* Masks and shifts */
  544. 0, 0, 0, 0, 0, 0, 0, 0
  545. },
  546. //-----------------------------------------------------------------------
  547. {"PF_FLOAT16_RGBA",
  548. /* Bytes per element */
  549. 8,
  550. /* Flags */
  551. PFF_FLOAT | PFF_HASALPHA,
  552. /* Component type and count */
  553. PCT_FLOAT16, 4,
  554. /* rbits, gbits, bbits, abits */
  555. 16, 16, 16, 16,
  556. /* Masks and shifts */
  557. 0, 0, 0, 0, 0, 0, 0, 0
  558. },
  559. //-----------------------------------------------------------------------
  560. {"PF_FLOAT32_R",
  561. /* Bytes per element */
  562. 4,
  563. /* Flags */
  564. PFF_FLOAT,
  565. /* Component type and count */
  566. PCT_FLOAT32, 1,
  567. /* rbits, gbits, bbits, abits */
  568. 32, 0, 0, 0,
  569. /* Masks and shifts */
  570. 0, 0, 0, 0, 0, 0, 0, 0
  571. },
  572. //-----------------------------------------------------------------------
  573. {"PF_FLOAT32_RG",
  574. /* Bytes per element */
  575. 8,
  576. /* Flags */
  577. PFF_FLOAT,
  578. /* Component type and count */
  579. PCT_FLOAT32, 2,
  580. /* rbits, gbits, bbits, abits */
  581. 32, 32, 0, 0,
  582. /* Masks and shifts */
  583. 0, 0, 0, 0, 0, 0, 0, 0
  584. },
  585. //-----------------------------------------------------------------------
  586. {"PF_FLOAT32_RGB",
  587. /* Bytes per element */
  588. 12,
  589. /* Flags */
  590. PFF_FLOAT,
  591. /* Component type and count */
  592. PCT_FLOAT32, 3,
  593. /* rbits, gbits, bbits, abits */
  594. 32, 32, 32, 0,
  595. /* Masks and shifts */
  596. 0, 0, 0, 0, 0, 0, 0, 0
  597. },
  598. //-----------------------------------------------------------------------
  599. {"PF_FLOAT32_RGBA",
  600. /* Bytes per element */
  601. 16,
  602. /* Flags */
  603. PFF_FLOAT | PFF_HASALPHA,
  604. /* Component type and count */
  605. PCT_FLOAT32, 4,
  606. /* rbits, gbits, bbits, abits */
  607. 32, 32, 32, 32,
  608. /* Masks and shifts */
  609. 0, 0, 0, 0, 0, 0, 0, 0
  610. },
  611. //-----------------------------------------------------------------------
  612. {"PF_D32_S8X24",
  613. /* Bytes per element */
  614. 8,
  615. /* Flags */
  616. PFF_DEPTH | PFF_FLOAT,
  617. /* Component type and count */
  618. PCT_FLOAT32, 2,
  619. /* rbits, gbits, bbits, abits */
  620. 0, 0, 0, 0,
  621. /* Masks and shifts */
  622. 0, 0, 0, 0, 0, 0, 0, 0
  623. },
  624. //-----------------------------------------------------------------------
  625. {"PF_D24_S8",
  626. /* Bytes per element */
  627. 4,
  628. /* Flags */
  629. PFF_DEPTH | PFF_FLOAT,
  630. /* Component type and count */
  631. PCT_FLOAT32, 1,
  632. /* rbits, gbits, bbits, abits */
  633. 0, 0, 0, 0,
  634. /* Masks and shifts */
  635. 0, 0, 0, 0, 0, 0, 0, 0
  636. },
  637. //-----------------------------------------------------------------------
  638. {"PF_D32",
  639. /* Bytes per element */
  640. 4,
  641. /* Flags */
  642. PFF_DEPTH | PFF_FLOAT,
  643. /* Component type and count */
  644. PCT_FLOAT32, 1,
  645. /* rbits, gbits, bbits, abits */
  646. 0, 0, 0, 0,
  647. /* Masks and shifts */
  648. 0, 0, 0, 0, 0, 0, 0, 0
  649. },
  650. //-----------------------------------------------------------------------
  651. {"PF_D16",
  652. /* Bytes per element */
  653. 2,
  654. /* Flags */
  655. PFF_DEPTH | PFF_FLOAT,
  656. /* Component type and count */
  657. PCT_FLOAT16, 1,
  658. /* rbits, gbits, bbits, abits */
  659. 0, 0, 0, 0,
  660. /* Masks and shifts */
  661. 0, 0, 0, 0, 0, 0, 0, 0
  662. },
  663. //-----------------------------------------------------------------------
  664. { "PF_FLOAT_R11G11B10",
  665. /* Bytes per element */
  666. 4,
  667. /* Flags */
  668. PFF_FLOAT,
  669. /* Component type and count */
  670. PCT_PACKED_R11G11B10, 1,
  671. /* rbits, gbits, bbits, abits */
  672. 11, 11, 10, 0,
  673. /* Masks and shifts */
  674. 0x000007FF, 0x003FF800, 0xFFC00000, 0,
  675. 0, 11, 22, 0
  676. },
  677. //-----------------------------------------------------------------------
  678. { "PF_UNORM_R10G10B10A2",
  679. /* Bytes per element */
  680. 4,
  681. /* Flags */
  682. PFF_FLOAT | PFF_HASALPHA,
  683. /* Component type and count */
  684. PCT_PACKED_R10G10B10A2, 1,
  685. /* rbits, gbits, bbits, abits */
  686. 10, 10, 10, 2,
  687. /* Masks and shifts */
  688. 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000,
  689. 0, 10, 20, 30
  690. },
  691. };
  692. static inline const PixelFormatDescription &getDescriptionFor(const PixelFormat fmt)
  693. {
  694. const int ord = (int)fmt;
  695. assert(ord>=0 && ord<PF_COUNT);
  696. return _pixelFormats[ord];
  697. }
  698. /** Handles compression output from NVTT library for a single image. */
  699. struct NVTTCompressOutputHandler : public nvtt::OutputHandler
  700. {
  701. NVTTCompressOutputHandler(UINT8* buffer, UINT32 sizeBytes)
  702. :buffer(buffer), bufferWritePos(buffer), bufferEnd(buffer + sizeBytes)
  703. { }
  704. virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel) override
  705. { }
  706. virtual bool writeData(const void* data, int size) override
  707. {
  708. assert((bufferWritePos + size) <= bufferEnd);
  709. memcpy(bufferWritePos, data, size);
  710. bufferWritePos += size;
  711. return true;
  712. }
  713. UINT8* buffer;
  714. UINT8* bufferWritePos;
  715. UINT8* bufferEnd;
  716. };
  717. /** Handles output from NVTT library for a mip-map chain. */
  718. struct NVTTMipmapOutputHandler : public nvtt::OutputHandler
  719. {
  720. NVTTMipmapOutputHandler(const Vector<SPtr<PixelData>>& buffers)
  721. :buffers(buffers), bufferWritePos(nullptr), bufferEnd(nullptr)
  722. { }
  723. virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)
  724. {
  725. assert(miplevel >= 0 && miplevel < (int)buffers.size());
  726. assert(size == buffers[miplevel]->getConsecutiveSize());
  727. activeBuffer = buffers[miplevel];
  728. bufferWritePos = activeBuffer->getData();
  729. bufferEnd = bufferWritePos + activeBuffer->getConsecutiveSize();
  730. }
  731. virtual bool writeData(const void* data, int size)
  732. {
  733. assert((bufferWritePos + size) <= bufferEnd);
  734. memcpy(bufferWritePos, data, size);
  735. bufferWritePos += size;
  736. return true;
  737. }
  738. Vector<SPtr<PixelData>> buffers;
  739. SPtr<PixelData> activeBuffer;
  740. UINT8* bufferWritePos;
  741. UINT8* bufferEnd;
  742. };
  743. nvtt::Format toNVTTFormat(PixelFormat format)
  744. {
  745. switch (format)
  746. {
  747. case PF_BC1:
  748. return nvtt::Format_BC1;
  749. case PF_BC1a:
  750. return nvtt::Format_BC1a;
  751. case PF_BC2:
  752. return nvtt::Format_BC2;
  753. case PF_BC3:
  754. return nvtt::Format_BC3;
  755. case PF_BC4:
  756. return nvtt::Format_BC4;
  757. case PF_BC5:
  758. return nvtt::Format_BC5;
  759. default: // Unsupported format
  760. return nvtt::Format_BC3;
  761. }
  762. }
  763. nvtt::Quality toNVTTQuality(CompressionQuality quality)
  764. {
  765. switch (quality)
  766. {
  767. case CompressionQuality::Fastest:
  768. return nvtt::Quality_Fastest;
  769. case CompressionQuality::Highest:
  770. return nvtt::Quality_Highest;
  771. case CompressionQuality::Normal:
  772. return nvtt::Quality_Normal;
  773. case CompressionQuality::Production:
  774. return nvtt::Quality_Normal;
  775. }
  776. // Unknown quality level
  777. return nvtt::Quality_Normal;
  778. }
  779. nvtt::AlphaMode toNVTTAlphaMode(AlphaMode alphaMode)
  780. {
  781. switch (alphaMode)
  782. {
  783. case AlphaMode::None:
  784. return nvtt::AlphaMode_None;
  785. case AlphaMode::Premultiplied:
  786. return nvtt::AlphaMode_Premultiplied;
  787. case AlphaMode::Transparency:
  788. return nvtt::AlphaMode_Transparency;
  789. }
  790. // Unknown alpha mode
  791. return nvtt::AlphaMode_None;
  792. }
  793. nvtt::WrapMode toNVTTWrapMode(MipMapWrapMode wrapMode)
  794. {
  795. switch (wrapMode)
  796. {
  797. case MipMapWrapMode::Clamp:
  798. return nvtt::WrapMode_Clamp;
  799. case MipMapWrapMode::Mirror:
  800. return nvtt::WrapMode_Mirror;
  801. case MipMapWrapMode::Repeat:
  802. return nvtt::WrapMode_Repeat;
  803. }
  804. // Unknown alpha mode
  805. return nvtt::WrapMode_Mirror;
  806. }
  807. UINT32 PixelUtil::getNumElemBytes(PixelFormat format)
  808. {
  809. return getDescriptionFor(format).elemBytes;
  810. }
  811. UINT32 PixelUtil::getMemorySize(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format)
  812. {
  813. if(isCompressed(format))
  814. {
  815. switch(format)
  816. {
  817. // BC formats work by dividing the image into 4x4 blocks, then encoding each
  818. // 4x4 block with a certain number of bytes.
  819. case PF_BC1:
  820. case PF_BC1a:
  821. case PF_BC4:
  822. return ((width+3)/4)*((height+3)/4)*8 * depth;
  823. case PF_BC2:
  824. case PF_BC3:
  825. case PF_BC5:
  826. case PF_BC6H:
  827. case PF_BC7:
  828. return ((width+3)/4)*((height+3)/4)*16 * depth;
  829. default:
  830. BS_EXCEPT(InvalidParametersException, "Invalid compressed pixel format");
  831. return 0;
  832. }
  833. }
  834. return width*height*depth*getNumElemBytes(format);
  835. }
  836. void PixelUtil::getPitch(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format,
  837. UINT32& rowPitch, UINT32& depthPitch)
  838. {
  839. if (isCompressed(format))
  840. {
  841. switch (format)
  842. {
  843. // BC formats work by dividing the image into 4x4 blocks, then encoding each
  844. // 4x4 block with a certain number of bytes.
  845. case PF_BC1:
  846. case PF_BC1a:
  847. case PF_BC4:
  848. case PF_BC2:
  849. case PF_BC3:
  850. case PF_BC5:
  851. case PF_BC6H:
  852. case PF_BC7:
  853. rowPitch = div(width + 3, 4).quot * 4;
  854. depthPitch = div(height + 3, 4).quot * 4 * rowPitch;
  855. return;
  856. default:
  857. BS_EXCEPT(InvalidParametersException, "Invalid compressed pixel format");
  858. return;
  859. }
  860. }
  861. rowPitch = width;
  862. depthPitch = width * height;
  863. }
  864. void PixelUtil::getSizeForMipLevel(UINT32 width, UINT32 height, UINT32 depth, UINT32 mipLevel,
  865. UINT32& mipWidth, UINT32& mipHeight, UINT32& mipDepth)
  866. {
  867. mipWidth = width;
  868. mipHeight = height;
  869. mipDepth = depth;
  870. for (UINT32 i = 0; i < mipLevel; i++)
  871. {
  872. if (mipWidth != 1) mipWidth /= 2;
  873. if (mipHeight != 1) mipHeight /= 2;
  874. if (mipDepth != 1) mipDepth /= 2;
  875. }
  876. }
  877. UINT32 PixelUtil::getNumElemBits(PixelFormat format)
  878. {
  879. return getDescriptionFor(format).elemBytes * 8;
  880. }
  881. UINT32 PixelUtil::getFlags(PixelFormat format)
  882. {
  883. return getDescriptionFor(format).flags;
  884. }
  885. bool PixelUtil::hasAlpha(PixelFormat format)
  886. {
  887. return (PixelUtil::getFlags(format) & PFF_HASALPHA) > 0;
  888. }
  889. bool PixelUtil::isFloatingPoint(PixelFormat format)
  890. {
  891. return (PixelUtil::getFlags(format) & PFF_FLOAT) > 0;
  892. }
  893. bool PixelUtil::isCompressed(PixelFormat format)
  894. {
  895. return (PixelUtil::getFlags(format) & PFF_COMPRESSED) > 0;
  896. }
  897. bool PixelUtil::isDepth(PixelFormat format)
  898. {
  899. return (PixelUtil::getFlags(format) & PFF_DEPTH) > 0;
  900. }
  901. bool PixelUtil::isNativeEndian(PixelFormat format)
  902. {
  903. return (PixelUtil::getFlags(format) & PFF_NATIVEENDIAN) > 0;
  904. }
  905. bool PixelUtil::checkFormat(PixelFormat& format, TextureType texType, int usage)
  906. {
  907. // First check just the usage since it's the most limiting factor
  908. //// Depth-stencil only supports depth formats
  909. if ((usage & TU_DEPTHSTENCIL) != 0)
  910. {
  911. if (isDepth(format))
  912. return true;
  913. format = PF_D32_S8X24;
  914. return false;
  915. }
  916. //// Render targets support everything but compressed & depth-stencil formats
  917. if ((usage & TU_RENDERTARGET) != 0)
  918. {
  919. if (!isDepth(format) && !isCompressed(format))
  920. return true;
  921. format = PF_R8G8B8A8;
  922. return false;
  923. }
  924. //// Load-store textures support everything but compressed & depth-stencil formats
  925. if ((usage & TU_LOADSTORE) != 0)
  926. {
  927. if (!isDepth(format) && !isCompressed(format))
  928. return true;
  929. format = PF_R8G8B8A8;
  930. return false;
  931. }
  932. //// Sampled texture support depends on texture type
  933. switch (texType)
  934. {
  935. case TEX_TYPE_1D:
  936. {
  937. // 1D textures support anything but depth & compressed formats
  938. if (!isDepth(format) && !isCompressed(format))
  939. return true;
  940. format = PF_R8G8B8A8;
  941. return false;
  942. }
  943. case TEX_TYPE_3D:
  944. {
  945. // 3D textures support anything but depth & compressed formats
  946. if (!isDepth(format))
  947. return true;
  948. format = PF_R8G8B8A8;
  949. return false;
  950. }
  951. default: // 2D & cube
  952. {
  953. // 2D/cube textures support anything but depth formats
  954. if (!isDepth(format))
  955. return true;
  956. format = PF_R8G8B8A8;
  957. return false;
  958. }
  959. }
  960. }
  961. bool PixelUtil::isValidExtent(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format)
  962. {
  963. if(isCompressed(format))
  964. {
  965. switch(format)
  966. {
  967. case PF_BC1:
  968. case PF_BC2:
  969. case PF_BC1a:
  970. case PF_BC3:
  971. case PF_BC4:
  972. case PF_BC5:
  973. case PF_BC6H:
  974. case PF_BC7:
  975. return ((width & 3) == 0 && (height & 3) == 0 && depth == 1);
  976. default:
  977. return true;
  978. }
  979. }
  980. else
  981. {
  982. return true;
  983. }
  984. }
  985. void PixelUtil::getBitDepths(PixelFormat format, int (&rgba)[4])
  986. {
  987. const PixelFormatDescription& des = getDescriptionFor(format);
  988. rgba[0] = des.rbits;
  989. rgba[1] = des.gbits;
  990. rgba[2] = des.bbits;
  991. rgba[3] = des.abits;
  992. }
  993. void PixelUtil::getBitMasks(PixelFormat format, UINT32 (&rgba)[4])
  994. {
  995. const PixelFormatDescription& des = getDescriptionFor(format);
  996. rgba[0] = des.rmask;
  997. rgba[1] = des.gmask;
  998. rgba[2] = des.bmask;
  999. rgba[3] = des.amask;
  1000. }
  1001. void PixelUtil::getBitShifts(PixelFormat format, UINT8 (&rgba)[4])
  1002. {
  1003. const PixelFormatDescription& des = getDescriptionFor(format);
  1004. rgba[0] = des.rshift;
  1005. rgba[1] = des.gshift;
  1006. rgba[2] = des.bshift;
  1007. rgba[3] = des.ashift;
  1008. }
  1009. String PixelUtil::getFormatName(PixelFormat srcformat)
  1010. {
  1011. return getDescriptionFor(srcformat).name;
  1012. }
  1013. bool PixelUtil::isAccessible(PixelFormat srcformat)
  1014. {
  1015. if (srcformat == PF_UNKNOWN)
  1016. return false;
  1017. UINT32 flags = getFlags(srcformat);
  1018. return !((flags & PFF_COMPRESSED) || (flags & PFF_DEPTH));
  1019. }
  1020. PixelComponentType PixelUtil::getElementType(PixelFormat format)
  1021. {
  1022. const PixelFormatDescription& des = getDescriptionFor(format);
  1023. return des.componentType;
  1024. }
  1025. UINT32 PixelUtil::getNumElements(PixelFormat format)
  1026. {
  1027. const PixelFormatDescription& des = getDescriptionFor(format);
  1028. return des.componentCount;
  1029. }
  1030. UINT32 PixelUtil::getMaxMipmaps(UINT32 width, UINT32 height, UINT32 depth, PixelFormat format)
  1031. {
  1032. UINT32 count = 0;
  1033. if((width > 0) && (height > 0))
  1034. {
  1035. while (!(width == 1 && height == 1 && depth == 1))
  1036. {
  1037. if(width>1) width = width/2;
  1038. if(height>1) height = height/2;
  1039. if(depth>1) depth = depth/2;
  1040. count ++;
  1041. }
  1042. }
  1043. return count;
  1044. }
  1045. void PixelUtil::packColor(const Color& color, PixelFormat format, void* dest)
  1046. {
  1047. packColor(color.r, color.g, color.b, color.a, format, dest);
  1048. }
  1049. void PixelUtil::packColor(UINT8 r, UINT8 g, UINT8 b, UINT8 a, PixelFormat format, void* dest)
  1050. {
  1051. const PixelFormatDescription &des = getDescriptionFor(format);
  1052. if(des.flags & PFF_NATIVEENDIAN)
  1053. {
  1054. // Shortcut for integer formats packing
  1055. UINT32 value = ((Bitwise::fixedToFixed(r, 8, des.rbits)<<des.rshift) & des.rmask) |
  1056. ((Bitwise::fixedToFixed(g, 8, des.gbits)<<des.gshift) & des.gmask) |
  1057. ((Bitwise::fixedToFixed(b, 8, des.bbits)<<des.bshift) & des.bmask) |
  1058. ((Bitwise::fixedToFixed(a, 8, des.abits)<<des.ashift) & des.amask);
  1059. // And write to memory
  1060. Bitwise::intWrite(dest, des.elemBytes, value);
  1061. }
  1062. else
  1063. {
  1064. // Convert to float
  1065. packColor((float)r/255.0f,(float)g/255.0f,(float)b/255.0f,(float)a/255.0f, format, dest);
  1066. }
  1067. }
  1068. void PixelUtil::packColor(float r, float g, float b, float a, const PixelFormat format, void* dest)
  1069. {
  1070. const PixelFormatDescription& des = getDescriptionFor(format);
  1071. if(des.flags & PFF_NATIVEENDIAN)
  1072. {
  1073. // Do the packing
  1074. const unsigned int value = ((Bitwise::floatToFixed(r, des.rbits)<<des.rshift) & des.rmask) |
  1075. ((Bitwise::floatToFixed(g, des.gbits)<<des.gshift) & des.gmask) |
  1076. ((Bitwise::floatToFixed(b, des.bbits)<<des.bshift) & des.bmask) |
  1077. ((Bitwise::floatToFixed(a, des.abits)<<des.ashift) & des.amask);
  1078. // And write to memory
  1079. Bitwise::intWrite(dest, des.elemBytes, value);
  1080. }
  1081. else
  1082. {
  1083. switch(format)
  1084. {
  1085. case PF_FLOAT32_R:
  1086. ((float*)dest)[0] = r;
  1087. break;
  1088. case PF_FLOAT32_RG:
  1089. ((float*)dest)[0] = r;
  1090. ((float*)dest)[1] = g;
  1091. break;
  1092. case PF_FLOAT32_RGB:
  1093. ((float*)dest)[0] = r;
  1094. ((float*)dest)[1] = g;
  1095. ((float*)dest)[2] = b;
  1096. break;
  1097. case PF_FLOAT32_RGBA:
  1098. ((float*)dest)[0] = r;
  1099. ((float*)dest)[1] = g;
  1100. ((float*)dest)[2] = b;
  1101. ((float*)dest)[3] = a;
  1102. break;
  1103. case PF_FLOAT16_R:
  1104. ((UINT16*)dest)[0] = Bitwise::floatToHalf(r);
  1105. break;
  1106. case PF_FLOAT16_RG:
  1107. ((UINT16*)dest)[0] = Bitwise::floatToHalf(r);
  1108. ((UINT16*)dest)[1] = Bitwise::floatToHalf(g);
  1109. break;
  1110. case PF_FLOAT16_RGB:
  1111. ((UINT16*)dest)[0] = Bitwise::floatToHalf(r);
  1112. ((UINT16*)dest)[1] = Bitwise::floatToHalf(g);
  1113. ((UINT16*)dest)[2] = Bitwise::floatToHalf(b);
  1114. break;
  1115. case PF_FLOAT16_RGBA:
  1116. ((UINT16*)dest)[0] = Bitwise::floatToHalf(r);
  1117. ((UINT16*)dest)[1] = Bitwise::floatToHalf(g);
  1118. ((UINT16*)dest)[2] = Bitwise::floatToHalf(b);
  1119. ((UINT16*)dest)[3] = Bitwise::floatToHalf(a);
  1120. break;
  1121. case PF_R8G8:
  1122. ((UINT8*)dest)[0] = (UINT8)Bitwise::floatToFixed(r, 8);
  1123. ((UINT8*)dest)[1] = (UINT8)Bitwise::floatToFixed(g, 8);
  1124. break;
  1125. case PF_R8:
  1126. ((UINT8*)dest)[0] = (UINT8)Bitwise::floatToFixed(r, 8);
  1127. break;
  1128. default:
  1129. LOGERR("Pack to " + getFormatName(format) + " not implemented");
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. void PixelUtil::unpackColor(Color* color, PixelFormat format, const void* src)
  1135. {
  1136. unpackColor(&color->r, &color->g, &color->b, &color->a, format, src);
  1137. }
  1138. void PixelUtil::unpackColor(UINT8* r, UINT8* g, UINT8* b, UINT8* a, PixelFormat format, const void* src)
  1139. {
  1140. const PixelFormatDescription &des = getDescriptionFor(format);
  1141. if(des.flags & PFF_NATIVEENDIAN)
  1142. {
  1143. // Shortcut for integer formats unpacking
  1144. const UINT32 value = Bitwise::intRead(src, des.elemBytes);
  1145. *r = (UINT8)Bitwise::fixedToFixed((value & des.rmask)>>des.rshift, des.rbits, 8);
  1146. *g = (UINT8)Bitwise::fixedToFixed((value & des.gmask)>>des.gshift, des.gbits, 8);
  1147. *b = (UINT8)Bitwise::fixedToFixed((value & des.bmask)>>des.bshift, des.bbits, 8);
  1148. if(des.flags & PFF_HASALPHA)
  1149. {
  1150. *a = (UINT8)Bitwise::fixedToFixed((value & des.amask)>>des.ashift, des.abits, 8);
  1151. }
  1152. else
  1153. {
  1154. *a = 255; // No alpha, default a component to full
  1155. }
  1156. }
  1157. else
  1158. {
  1159. // Do the operation with the more generic floating point
  1160. float rr, gg, bb, aa;
  1161. unpackColor(&rr,&gg,&bb,&aa, format, src);
  1162. *r = (UINT8)Bitwise::floatToFixed(rr, 8);
  1163. *g = (UINT8)Bitwise::floatToFixed(gg, 8);
  1164. *b = (UINT8)Bitwise::floatToFixed(bb, 8);
  1165. *a = (UINT8)Bitwise::floatToFixed(aa, 8);
  1166. }
  1167. }
  1168. void PixelUtil::unpackColor(float* r, float* g, float* b, float* a, PixelFormat format, const void* src)
  1169. {
  1170. const PixelFormatDescription &des = getDescriptionFor(format);
  1171. if(des.flags & PFF_NATIVEENDIAN)
  1172. {
  1173. // Shortcut for integer formats unpacking
  1174. const unsigned int value = Bitwise::intRead(src, des.elemBytes);
  1175. *r = Bitwise::fixedToFloat((value & des.rmask)>>des.rshift, des.rbits);
  1176. *g = Bitwise::fixedToFloat((value & des.gmask)>>des.gshift, des.gbits);
  1177. *b = Bitwise::fixedToFloat((value & des.bmask)>>des.bshift, des.bbits);
  1178. if(des.flags & PFF_HASALPHA)
  1179. {
  1180. *a = Bitwise::fixedToFloat((value & des.amask)>>des.ashift, des.abits);
  1181. }
  1182. else
  1183. {
  1184. *a = 1.0f; // No alpha, default a component to full
  1185. }
  1186. }
  1187. else
  1188. {
  1189. switch(format)
  1190. {
  1191. case PF_FLOAT32_R:
  1192. *r = *g = *b = ((float*)src)[0];
  1193. *a = 1.0f;
  1194. break;
  1195. case PF_FLOAT32_RG:
  1196. *r = ((float*)src)[0];
  1197. *g = *b = ((float*)src)[1];
  1198. *a = 1.0f;
  1199. break;
  1200. case PF_FLOAT32_RGB:
  1201. *r = ((float*)src)[0];
  1202. *g = ((float*)src)[1];
  1203. *b = ((float*)src)[2];
  1204. *a = 1.0f;
  1205. break;
  1206. case PF_FLOAT32_RGBA:
  1207. *r = ((float*)src)[0];
  1208. *g = ((float*)src)[1];
  1209. *b = ((float*)src)[2];
  1210. *a = ((float*)src)[3];
  1211. break;
  1212. case PF_FLOAT16_R:
  1213. *r = *g = *b = Bitwise::halfToFloat(((UINT16*)src)[0]);
  1214. *a = 1.0f;
  1215. break;
  1216. case PF_FLOAT16_RG:
  1217. *r = Bitwise::halfToFloat(((UINT16*)src)[0]);
  1218. *g = *b = Bitwise::halfToFloat(((UINT16*)src)[1]);
  1219. *a = 1.0f;
  1220. break;
  1221. case PF_FLOAT16_RGB:
  1222. *r = Bitwise::halfToFloat(((UINT16*)src)[0]);
  1223. *g = Bitwise::halfToFloat(((UINT16*)src)[1]);
  1224. *b = Bitwise::halfToFloat(((UINT16*)src)[2]);
  1225. *a = 1.0f;
  1226. break;
  1227. case PF_FLOAT16_RGBA:
  1228. *r = Bitwise::halfToFloat(((UINT16*)src)[0]);
  1229. *g = Bitwise::halfToFloat(((UINT16*)src)[1]);
  1230. *b = Bitwise::halfToFloat(((UINT16*)src)[2]);
  1231. *a = Bitwise::halfToFloat(((UINT16*)src)[3]);
  1232. break;
  1233. case PF_R8G8:
  1234. *r = Bitwise::fixedToFloat(((UINT8*)src)[0], 8);
  1235. *g = Bitwise::fixedToFloat(((UINT8*)src)[1], 8);
  1236. *b = 0.0f;
  1237. *a = 1.0f;
  1238. break;
  1239. case PF_R8:
  1240. *r = Bitwise::fixedToFloat(((UINT8*)src)[0], 8);
  1241. *g = 0.0f;
  1242. *b = 0.0f;
  1243. *a = 1.0f;
  1244. break;
  1245. default:
  1246. LOGERR("Unpack from " + getFormatName(format) + " not implemented");
  1247. break;
  1248. }
  1249. }
  1250. }
  1251. void PixelUtil::packDepth(float depth, const PixelFormat format, void* dest)
  1252. {
  1253. if (!isDepth(format))
  1254. {
  1255. LOGERR("Cannot convert depth to " + getFormatName(format) + ": it is not a depth format");
  1256. return;
  1257. }
  1258. LOGERR("Method is not implemented");
  1259. //TODO implement depth packing
  1260. }
  1261. float PixelUtil::unpackDepth(PixelFormat format, void* src)
  1262. {
  1263. const PixelFormatDescription &des = getDescriptionFor(format);
  1264. if (!isDepth(format))
  1265. {
  1266. LOGERR("Cannot unpack from " + getFormatName(format) + ": it is not a depth format");
  1267. return 0;
  1268. }
  1269. UINT32* color = (UINT32 *)src;
  1270. switch (format)
  1271. {
  1272. case PF_D24S8:
  1273. return static_cast<float>(*color & 0x00FFFFFF) / (float)16777216;
  1274. break;
  1275. case PF_D16:
  1276. return static_cast<float>(*color & 0xFFFF) / (float)65536;
  1277. break;
  1278. case PF_D32:
  1279. return static_cast<float>(*color & 0xFFFFFFFF) / (float)4294967296;
  1280. break;
  1281. case PF_D32_S8X24:
  1282. return static_cast<float>(*color & 0xFFFFFFFF) / (float)4294967296;
  1283. break;
  1284. default:
  1285. LOGERR("Cannot unpack from " + getFormatName(format));
  1286. return 0;
  1287. break;
  1288. }
  1289. }
  1290. void PixelUtil::bulkPixelConversion(const PixelData &src, PixelData &dst)
  1291. {
  1292. assert(src.getWidth() == dst.getWidth() &&
  1293. src.getHeight() == dst.getHeight() &&
  1294. src.getDepth() == dst.getDepth());
  1295. // Check for compressed formats, we don't support decompression
  1296. if(PixelUtil::isCompressed(src.getFormat()))
  1297. {
  1298. if(src.getFormat() == dst.getFormat())
  1299. {
  1300. memcpy(dst.getData(), src.getData(), src.getConsecutiveSize());
  1301. return;
  1302. }
  1303. else
  1304. {
  1305. LOGERR("bulkPixelConversion() cannot be used to compress or decompress images");
  1306. return;
  1307. }
  1308. }
  1309. // Check for compression
  1310. if (PixelUtil::isCompressed(dst.getFormat()))
  1311. {
  1312. if (src.getFormat() == dst.getFormat())
  1313. {
  1314. memcpy(dst.getData(), src.getData(), src.getConsecutiveSize());
  1315. return;
  1316. }
  1317. else
  1318. {
  1319. CompressionOptions co;
  1320. co.format = dst.getFormat();
  1321. compress(src, dst, co);
  1322. return;
  1323. }
  1324. }
  1325. // The easy case
  1326. if(src.getFormat() == dst.getFormat())
  1327. {
  1328. // Everything consecutive?
  1329. if(src.isConsecutive() && dst.isConsecutive())
  1330. {
  1331. memcpy(dst.getData(), src.getData(), src.getConsecutiveSize());
  1332. return;
  1333. }
  1334. const UINT32 srcPixelSize = PixelUtil::getNumElemBytes(src.getFormat());
  1335. const UINT32 dstPixelSize = PixelUtil::getNumElemBytes(dst.getFormat());
  1336. UINT8 *srcptr = static_cast<UINT8*>(src.getData())
  1337. + (src.getLeft() + src.getTop() * src.getRowPitch() + src.getFront() * src.getSlicePitch()) * srcPixelSize;
  1338. UINT8 *dstptr = static_cast<UINT8*>(dst.getData())
  1339. + (dst.getLeft() + dst.getTop() * dst.getRowPitch() + dst.getFront() * dst.getSlicePitch()) * dstPixelSize;
  1340. // Calculate pitches+skips in bytes
  1341. const UINT32 srcRowPitchBytes = src.getRowPitch()*srcPixelSize;
  1342. const UINT32 srcSliceSkipBytes = src.getSliceSkip()*srcPixelSize;
  1343. const UINT32 dstRowPitchBytes = dst.getRowPitch()*dstPixelSize;
  1344. const UINT32 dstSliceSkipBytes = dst.getSliceSkip()*dstPixelSize;
  1345. // Otherwise, copy per row
  1346. const UINT32 rowSize = src.getWidth()*srcPixelSize;
  1347. for (UINT32 z = src.getFront(); z < src.getBack(); z++)
  1348. {
  1349. for(UINT32 y = src.getTop(); y < src.getBottom(); y++)
  1350. {
  1351. memcpy(dstptr, srcptr, rowSize);
  1352. srcptr += srcRowPitchBytes;
  1353. dstptr += dstRowPitchBytes;
  1354. }
  1355. srcptr += srcSliceSkipBytes;
  1356. dstptr += dstSliceSkipBytes;
  1357. }
  1358. return;
  1359. }
  1360. const UINT32 srcPixelSize = PixelUtil::getNumElemBytes(src.getFormat());
  1361. const UINT32 dstPixelSize = PixelUtil::getNumElemBytes(dst.getFormat());
  1362. UINT8 *srcptr = static_cast<UINT8*>(src.getData())
  1363. + (src.getLeft() + src.getTop() * src.getRowPitch() + src.getFront() * src.getSlicePitch()) * srcPixelSize;
  1364. UINT8 *dstptr = static_cast<UINT8*>(dst.getData())
  1365. + (dst.getLeft() + dst.getTop() * dst.getRowPitch() + dst.getFront() * dst.getSlicePitch()) * dstPixelSize;
  1366. // Calculate pitches+skips in bytes
  1367. const UINT32 srcRowSkipBytes = src.getRowSkip()*srcPixelSize;
  1368. const UINT32 srcSliceSkipBytes = src.getSliceSkip()*srcPixelSize;
  1369. const UINT32 dstRowSkipBytes = dst.getRowSkip()*dstPixelSize;
  1370. const UINT32 dstSliceSkipBytes = dst.getSliceSkip()*dstPixelSize;
  1371. // The brute force fallback
  1372. float r,g,b,a;
  1373. for (UINT32 z = src.getFront(); z<src.getBack(); z++)
  1374. {
  1375. for (UINT32 y = src.getTop(); y < src.getBottom(); y++)
  1376. {
  1377. for (UINT32 x = src.getLeft(); x<src.getRight(); x++)
  1378. {
  1379. unpackColor(&r, &g, &b, &a, src.getFormat(), srcptr);
  1380. packColor(r, g, b, a, dst.getFormat(), dstptr);
  1381. srcptr += srcPixelSize;
  1382. dstptr += dstPixelSize;
  1383. }
  1384. srcptr += srcRowSkipBytes;
  1385. dstptr += dstRowSkipBytes;
  1386. }
  1387. srcptr += srcSliceSkipBytes;
  1388. dstptr += dstSliceSkipBytes;
  1389. }
  1390. }
  1391. void PixelUtil::scale(const PixelData& src, PixelData& scaled, Filter filter)
  1392. {
  1393. assert(PixelUtil::isAccessible(src.getFormat()));
  1394. assert(PixelUtil::isAccessible(scaled.getFormat()));
  1395. PixelData temp;
  1396. switch (filter)
  1397. {
  1398. default:
  1399. case FILTER_NEAREST:
  1400. if(src.getFormat() == scaled.getFormat())
  1401. {
  1402. // No intermediate buffer needed
  1403. temp = scaled;
  1404. }
  1405. else
  1406. {
  1407. // Allocate temporary buffer of destination size in source format
  1408. temp = PixelData(scaled.getWidth(), scaled.getHeight(), scaled.getDepth(), src.getFormat());
  1409. temp.allocateInternalBuffer();
  1410. }
  1411. // No conversion
  1412. switch (PixelUtil::getNumElemBytes(src.getFormat()))
  1413. {
  1414. case 1: NearestResampler<1>::scale(src, temp); break;
  1415. case 2: NearestResampler<2>::scale(src, temp); break;
  1416. case 3: NearestResampler<3>::scale(src, temp); break;
  1417. case 4: NearestResampler<4>::scale(src, temp); break;
  1418. case 6: NearestResampler<6>::scale(src, temp); break;
  1419. case 8: NearestResampler<8>::scale(src, temp); break;
  1420. case 12: NearestResampler<12>::scale(src, temp); break;
  1421. case 16: NearestResampler<16>::scale(src, temp); break;
  1422. default:
  1423. // Never reached
  1424. assert(false);
  1425. }
  1426. if(temp.getData() != scaled.getData())
  1427. {
  1428. // Blit temp buffer
  1429. PixelUtil::bulkPixelConversion(temp, scaled);
  1430. temp.freeInternalBuffer();
  1431. }
  1432. break;
  1433. case FILTER_LINEAR:
  1434. switch (src.getFormat())
  1435. {
  1436. case PF_R8G8:
  1437. case PF_R8G8B8: case PF_B8G8R8:
  1438. case PF_R8G8B8A8: case PF_B8G8R8A8:
  1439. if(src.getFormat() == scaled.getFormat())
  1440. {
  1441. // No intermediate buffer needed
  1442. temp = scaled;
  1443. }
  1444. else
  1445. {
  1446. // Allocate temp buffer of destination size in source format
  1447. temp = PixelData(scaled.getWidth(), scaled.getHeight(), scaled.getDepth(), src.getFormat());
  1448. temp.allocateInternalBuffer();
  1449. }
  1450. // No conversion
  1451. switch (PixelUtil::getNumElemBytes(src.getFormat()))
  1452. {
  1453. case 1: LinearResampler_Byte<1>::scale(src, temp); break;
  1454. case 2: LinearResampler_Byte<2>::scale(src, temp); break;
  1455. case 3: LinearResampler_Byte<3>::scale(src, temp); break;
  1456. case 4: LinearResampler_Byte<4>::scale(src, temp); break;
  1457. default:
  1458. // Never reached
  1459. assert(false);
  1460. }
  1461. if(temp.getData() != scaled.getData())
  1462. {
  1463. // Blit temp buffer
  1464. PixelUtil::bulkPixelConversion(temp, scaled);
  1465. temp.freeInternalBuffer();
  1466. }
  1467. break;
  1468. case PF_FLOAT32_RGB:
  1469. case PF_FLOAT32_RGBA:
  1470. if (scaled.getFormat() == PF_FLOAT32_RGB || scaled.getFormat() == PF_FLOAT32_RGBA)
  1471. {
  1472. // float32 to float32, avoid unpack/repack overhead
  1473. LinearResampler_Float32::scale(src, scaled);
  1474. break;
  1475. }
  1476. // Else, fall through
  1477. default:
  1478. // Fallback case, slow but works
  1479. LinearResampler::scale(src, scaled);
  1480. }
  1481. break;
  1482. }
  1483. }
  1484. void PixelUtil::copy(const PixelData& src, PixelData& dst, UINT32 offsetX, UINT32 offsetY, UINT32 offsetZ)
  1485. {
  1486. if(src.getFormat() != dst.getFormat())
  1487. {
  1488. LOGERR("Source format is different from destination format for copy(). This operation cannot be used for "
  1489. "a format conversion. Aborting copy.");
  1490. return;
  1491. }
  1492. UINT32 right = offsetX + dst.getWidth();
  1493. UINT32 bottom = offsetY + dst.getHeight();
  1494. UINT32 back = offsetZ + dst.getDepth();
  1495. if(right > src.getWidth() || bottom > src.getHeight() || back > src.getDepth())
  1496. {
  1497. LOGERR("Provided offset or destination size is too large and is referencing pixels that are out of bounds"
  1498. " on the source texture. Aborting copy().");
  1499. return;
  1500. }
  1501. UINT8* srcPtr = (UINT8*)src.getData() + offsetZ * src.getSlicePitch();
  1502. UINT8* dstPtr = (UINT8*)dst.getData();
  1503. UINT32 elemSize = getNumElemBytes(dst.getFormat());
  1504. UINT32 rowSize = dst.getWidth() * elemSize;
  1505. for(UINT32 z = 0; z < dst.getDepth(); z++)
  1506. {
  1507. UINT8* srcRowPtr = srcPtr + offsetY * src.getRowPitch() * elemSize;
  1508. UINT8* dstRowPtr = dstPtr;
  1509. for(UINT32 y = 0; y < dst.getHeight(); y++)
  1510. {
  1511. memcpy(dstRowPtr, srcRowPtr + offsetX * elemSize, rowSize);
  1512. srcRowPtr += src.getRowPitch() * elemSize;
  1513. dstRowPtr += dst.getRowPitch() * elemSize;
  1514. }
  1515. srcPtr += src.getSlicePitch() * elemSize;
  1516. dstPtr += dst.getSlicePitch() * elemSize;
  1517. }
  1518. }
  1519. void PixelUtil::mirror(PixelData& pixelData, MirrorMode mode)
  1520. {
  1521. UINT32 width = pixelData.getWidth();
  1522. UINT32 height = pixelData.getHeight();
  1523. UINT32 depth = pixelData.getDepth();
  1524. UINT32 elemSize = getNumElemBytes(pixelData.getFormat());
  1525. if (mode.isSet(MirrorModeBits::Z))
  1526. {
  1527. UINT32 sliceSize = width * height * elemSize;
  1528. UINT8* sliceTemp = bs_stack_alloc<UINT8>(sliceSize);
  1529. UINT8* dataPtr = pixelData.getData();
  1530. UINT32 halfDepth = depth / 2;
  1531. for (UINT32 z = 0; z < halfDepth; z++)
  1532. {
  1533. UINT32 srcZ = z * sliceSize;
  1534. UINT32 dstZ = (depth - z - 1) * sliceSize;
  1535. memcpy(sliceTemp, &dataPtr[dstZ], sliceSize);
  1536. memcpy(&dataPtr[srcZ], &dataPtr[srcZ], sliceSize);
  1537. memcpy(&dataPtr[dstZ], sliceTemp, sliceSize);
  1538. }
  1539. // Note: If flipping Y or X as well I could do it here without an extra set of memcpys
  1540. bs_stack_free(sliceTemp);
  1541. }
  1542. if(mode.isSet(MirrorModeBits::Y))
  1543. {
  1544. UINT32 rowSize = width * elemSize;
  1545. UINT8* rowTemp = bs_stack_alloc<UINT8>(rowSize);
  1546. UINT8* slicePtr = pixelData.getData();
  1547. for (UINT32 z = 0; z < depth; z++)
  1548. {
  1549. UINT32 halfHeight = height / 2;
  1550. for (UINT32 y = 0; y < halfHeight; y++)
  1551. {
  1552. UINT32 srcY = y * rowSize;
  1553. UINT32 dstY = (height - y - 1) * rowSize;
  1554. memcpy(rowTemp, &slicePtr[dstY], rowSize);
  1555. memcpy(&slicePtr[dstY], &slicePtr[srcY], rowSize);
  1556. memcpy(&slicePtr[srcY], rowTemp, rowSize);
  1557. }
  1558. // Note: If flipping X as well I could do it here without an extra set of memcpys
  1559. slicePtr += pixelData.getSlicePitch() * elemSize;
  1560. }
  1561. bs_stack_free(rowTemp);
  1562. }
  1563. if (mode.isSet(MirrorModeBits::X))
  1564. {
  1565. UINT8* elemTemp = bs_stack_alloc<UINT8>(elemSize);
  1566. UINT8* slicePtr = pixelData.getData();
  1567. for (UINT32 z = 0; z < depth; z++)
  1568. {
  1569. UINT8* rowPtr = slicePtr;
  1570. for (UINT32 y = 0; y < height; y++)
  1571. {
  1572. UINT32 halfWidth = width / 2;
  1573. for (UINT32 x = 0; x < halfWidth; x++)
  1574. {
  1575. UINT32 srcX = x * elemSize;
  1576. UINT32 dstX = (width - x - 1) * elemSize;
  1577. memcpy(elemTemp, &rowPtr[dstX], elemSize);
  1578. memcpy(&rowPtr[dstX], &rowPtr[srcX], elemSize);
  1579. memcpy(&rowPtr[srcX], elemTemp, elemSize);
  1580. }
  1581. rowPtr += pixelData.getRowPitch() * elemSize;
  1582. }
  1583. slicePtr += pixelData.getSlicePitch() * elemSize;
  1584. }
  1585. bs_stack_free(elemTemp);
  1586. }
  1587. }
  1588. void PixelUtil::applyGamma(UINT8* buffer, float gamma, UINT32 size, UINT8 bpp)
  1589. {
  1590. if(gamma == 1.0f)
  1591. return;
  1592. UINT32 stride = bpp >> 3;
  1593. for(size_t i = 0, j = size / stride; i < j; i++, buffer += stride)
  1594. {
  1595. float r = (float)buffer[0];
  1596. float g = (float)buffer[1];
  1597. float b = (float)buffer[2];
  1598. r = r * gamma;
  1599. g = g * gamma;
  1600. b = b * gamma;
  1601. float scale = 1.0f;
  1602. float tmp = 0.0f;
  1603. if(r > 255.0f && (tmp=(255.0f/r)) < scale)
  1604. scale = tmp;
  1605. if(g > 255.0f && (tmp=(255.0f/g)) < scale)
  1606. scale = tmp;
  1607. if(b > 255.0f && (tmp=(255.0f/b)) < scale)
  1608. scale = tmp;
  1609. r *= scale;
  1610. g *= scale;
  1611. b *= scale;
  1612. buffer[0] = (UINT8)r;
  1613. buffer[1] = (UINT8)g;
  1614. buffer[2] = (UINT8)b;
  1615. }
  1616. }
  1617. void PixelUtil::compress(const PixelData& src, PixelData& dst, const CompressionOptions& options)
  1618. {
  1619. if (!isCompressed(options.format))
  1620. {
  1621. LOGERR("Compression failed. Destination format is not a valid compressed format.")
  1622. return;
  1623. }
  1624. // Note: NVTT site has implementations for these two formats for when I decide to add them
  1625. if (options.format == PF_BC6H || options.format == PF_BC7)
  1626. {
  1627. LOGERR("Compression failed. BC6H and BC7 formats are currently not supported.")
  1628. return;
  1629. }
  1630. if (src.getDepth() != 1)
  1631. {
  1632. LOGERR("Compression failed. 3D texture compression not supported.")
  1633. return;
  1634. }
  1635. if (isCompressed(src.getFormat()))
  1636. {
  1637. LOGERR("Compression failed. Source data cannot be compressed.");
  1638. return;
  1639. }
  1640. PixelData bgraData(src.getWidth(), src.getHeight(), 1, PF_R8G8B8A8);
  1641. bgraData.allocateInternalBuffer();
  1642. bulkPixelConversion(src, bgraData);
  1643. nvtt::InputOptions io;
  1644. io.setTextureLayout(nvtt::TextureType_2D, src.getWidth(), src.getHeight());
  1645. io.setMipmapData(bgraData.getData(), src.getWidth(), src.getHeight());
  1646. io.setMipmapGeneration(false);
  1647. io.setAlphaMode(toNVTTAlphaMode(options.alphaMode));
  1648. io.setNormalMap(options.isNormalMap);
  1649. if (options.isSRGB)
  1650. io.setGamma(2.2f, 2.2f);
  1651. else
  1652. io.setGamma(1.0f, 1.0f);
  1653. nvtt::CompressionOptions co;
  1654. co.setFormat(toNVTTFormat(options.format));
  1655. co.setQuality(toNVTTQuality(options.quality));
  1656. NVTTCompressOutputHandler outputHandler(dst.getData(), dst.getConsecutiveSize());
  1657. nvtt::OutputOptions oo;
  1658. oo.setOutputHeader(false);
  1659. oo.setOutputHandler(&outputHandler);
  1660. nvtt::Compressor compressor;
  1661. if (!compressor.process(io, co, oo))
  1662. {
  1663. LOGERR("Compression failed. Internal error.");
  1664. return;
  1665. }
  1666. }
  1667. Vector<SPtr<PixelData>> PixelUtil::genMipmaps(const PixelData& src, const MipMapGenOptions& options)
  1668. {
  1669. Vector<SPtr<PixelData>> outputMipBuffers;
  1670. if (src.getDepth() != 1)
  1671. {
  1672. LOGERR("Mipmap generation failed. 3D texture formats not supported.")
  1673. return outputMipBuffers;
  1674. }
  1675. // Note: Add support for floating point mips, no reason they shouldn't be supported other than
  1676. // nvtt doesn't support them natively
  1677. if (isCompressed(src.getFormat()) || isFloatingPoint(src.getFormat()))
  1678. {
  1679. LOGERR("Mipmap generation failed. Source data cannot be compressed or in floating point format.")
  1680. return outputMipBuffers;
  1681. }
  1682. if (!Bitwise::isPow2(src.getWidth()) || !Bitwise::isPow2(src.getHeight()))
  1683. {
  1684. LOGERR("Mipmap generation failed. Texture width & height must be powers of 2.");
  1685. return outputMipBuffers;
  1686. }
  1687. PixelData rgbaData(src.getWidth(), src.getHeight(), 1, PF_R8G8B8A8);
  1688. rgbaData.allocateInternalBuffer();
  1689. bulkPixelConversion(src, rgbaData);
  1690. nvtt::InputOptions io;
  1691. io.setTextureLayout(nvtt::TextureType_2D, src.getWidth(), src.getHeight());
  1692. io.setMipmapData(rgbaData.getData(), src.getWidth(), src.getHeight());
  1693. io.setMipmapGeneration(true);
  1694. io.setNormalMap(options.isNormalMap);
  1695. io.setNormalizeMipmaps(options.normalizeMipmaps);
  1696. io.setWrapMode(toNVTTWrapMode(options.wrapMode));
  1697. nvtt::CompressionOptions co;
  1698. co.setFormat(nvtt::Format_RGBA);
  1699. UINT32 numMips = getMaxMipmaps(src.getWidth(), src.getHeight(), 1, src.getFormat());
  1700. Vector<SPtr<PixelData>> rgbaMipBuffers;
  1701. // Note: This can be done more effectively without creating so many temp buffers
  1702. // and working with the original formats directly, but it would complicate the code
  1703. // too much at the moment.
  1704. UINT32 curWidth = src.getWidth();
  1705. UINT32 curHeight = src.getHeight();
  1706. for (UINT32 i = 0; i < numMips; i++)
  1707. {
  1708. rgbaMipBuffers.push_back(bs_shared_ptr_new<PixelData>(curWidth, curHeight, 1, PF_R8G8B8A8));
  1709. rgbaMipBuffers.back()->allocateInternalBuffer();
  1710. if (curWidth > 1)
  1711. curWidth = curWidth / 2;
  1712. if (curHeight > 1)
  1713. curHeight = curHeight / 2;
  1714. }
  1715. rgbaMipBuffers.push_back(bs_shared_ptr_new<PixelData>(curWidth, curHeight, 1, PF_R8G8B8A8));
  1716. rgbaMipBuffers.back()->allocateInternalBuffer();
  1717. NVTTMipmapOutputHandler outputHandler(rgbaMipBuffers);
  1718. nvtt::OutputOptions oo;
  1719. oo.setOutputHeader(false);
  1720. oo.setOutputHandler(&outputHandler);
  1721. nvtt::Compressor compressor;
  1722. if (!compressor.process(io, co, oo))
  1723. {
  1724. LOGERR("Mipmap generation failed. Internal error.");
  1725. return outputMipBuffers;
  1726. }
  1727. rgbaData.freeInternalBuffer();
  1728. for (UINT32 i = 0; i < (UINT32)rgbaMipBuffers.size(); i++)
  1729. {
  1730. SPtr<PixelData> argbBuffer = rgbaMipBuffers[i];
  1731. SPtr<PixelData> outputBuffer = bs_shared_ptr_new<PixelData>(argbBuffer->getWidth(), argbBuffer->getHeight(), 1, src.getFormat());
  1732. outputBuffer->allocateInternalBuffer();
  1733. bulkPixelConversion(*argbBuffer, *outputBuffer);
  1734. argbBuffer->freeInternalBuffer();
  1735. outputMipBuffers.push_back(outputBuffer);
  1736. }
  1737. return outputMipBuffers;
  1738. }
  1739. }