AstcDecoder.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. using Ryujinx.Common.Memory;
  2. using Ryujinx.Common.Utilities;
  3. using System;
  4. using System.Buffers;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. namespace Ryujinx.Graphics.Texture.Astc
  10. {
  11. // https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp
  12. public class AstcDecoder
  13. {
  14. private ReadOnlyMemory<byte> InputBuffer { get; }
  15. private Memory<byte> OutputBuffer { get; }
  16. private int BlockSizeX { get; }
  17. private int BlockSizeY { get; }
  18. private AstcLevel[] Levels { get; }
  19. private bool Success { get; set; }
  20. public int TotalBlockCount { get; }
  21. public AstcDecoder(
  22. ReadOnlyMemory<byte> inputBuffer,
  23. Memory<byte> outputBuffer,
  24. int blockWidth,
  25. int blockHeight,
  26. int width,
  27. int height,
  28. int depth,
  29. int levels,
  30. int layers)
  31. {
  32. if ((uint)blockWidth > 12)
  33. {
  34. throw new ArgumentOutOfRangeException(nameof(blockWidth));
  35. }
  36. if ((uint)blockHeight > 12)
  37. {
  38. throw new ArgumentOutOfRangeException(nameof(blockHeight));
  39. }
  40. InputBuffer = inputBuffer;
  41. OutputBuffer = outputBuffer;
  42. BlockSizeX = blockWidth;
  43. BlockSizeY = blockHeight;
  44. Levels = new AstcLevel[levels * layers];
  45. Success = true;
  46. TotalBlockCount = 0;
  47. int currentInputBlock = 0;
  48. int currentOutputOffset = 0;
  49. for (int i = 0; i < levels; i++)
  50. {
  51. for (int j = 0; j < layers; j++)
  52. {
  53. ref AstcLevel level = ref Levels[i * layers + j];
  54. level.ImageSizeX = Math.Max(1, width >> i);
  55. level.ImageSizeY = Math.Max(1, height >> i);
  56. level.ImageSizeZ = Math.Max(1, depth >> i);
  57. level.BlockCountX = (level.ImageSizeX + blockWidth - 1) / blockWidth;
  58. level.BlockCountY = (level.ImageSizeY + blockHeight - 1) / blockHeight;
  59. level.StartBlock = currentInputBlock;
  60. level.OutputByteOffset = currentOutputOffset;
  61. currentInputBlock += level.TotalBlockCount;
  62. currentOutputOffset += level.PixelCount * 4;
  63. }
  64. }
  65. TotalBlockCount = currentInputBlock;
  66. }
  67. private struct AstcLevel
  68. {
  69. public int ImageSizeX { get; set; }
  70. public int ImageSizeY { get; set; }
  71. public int ImageSizeZ { get; set; }
  72. public int BlockCountX { get; set; }
  73. public int BlockCountY { get; set; }
  74. public int StartBlock { get; set; }
  75. public int OutputByteOffset { get; set; }
  76. public readonly int TotalBlockCount => BlockCountX * BlockCountY * ImageSizeZ;
  77. public readonly int PixelCount => ImageSizeX * ImageSizeY * ImageSizeZ;
  78. }
  79. public static int QueryDecompressedSize(int sizeX, int sizeY, int sizeZ, int levelCount, int layerCount)
  80. {
  81. int size = 0;
  82. for (int i = 0; i < levelCount; i++)
  83. {
  84. int levelSizeX = Math.Max(1, sizeX >> i);
  85. int levelSizeY = Math.Max(1, sizeY >> i);
  86. int levelSizeZ = Math.Max(1, sizeZ >> i);
  87. size += levelSizeX * levelSizeY * levelSizeZ * layerCount;
  88. }
  89. return size * 4;
  90. }
  91. public void ProcessBlock(int index)
  92. {
  93. Buffer16 inputBlock = MemoryMarshal.Cast<byte, Buffer16>(InputBuffer.Span)[index];
  94. Span<int> decompressedData = stackalloc int[144];
  95. try
  96. {
  97. DecompressBlock(inputBlock, decompressedData, BlockSizeX, BlockSizeY);
  98. }
  99. catch (Exception)
  100. {
  101. Success = false;
  102. }
  103. Span<byte> decompressedBytes = MemoryMarshal.Cast<int, byte>(decompressedData);
  104. AstcLevel levelInfo = GetLevelInfo(index);
  105. WriteDecompressedBlock(decompressedBytes, OutputBuffer.Span[levelInfo.OutputByteOffset..],
  106. index - levelInfo.StartBlock, levelInfo);
  107. }
  108. private AstcLevel GetLevelInfo(int blockIndex)
  109. {
  110. foreach (AstcLevel levelInfo in Levels)
  111. {
  112. if (blockIndex < levelInfo.StartBlock + levelInfo.TotalBlockCount)
  113. {
  114. return levelInfo;
  115. }
  116. }
  117. throw new AstcDecoderException("Invalid block index.");
  118. }
  119. private void WriteDecompressedBlock(ReadOnlySpan<byte> block, Span<byte> outputBuffer, int blockIndex, AstcLevel level)
  120. {
  121. int stride = level.ImageSizeX * 4;
  122. int blockCordX = blockIndex % level.BlockCountX;
  123. int blockCordY = blockIndex / level.BlockCountX;
  124. int pixelCordX = blockCordX * BlockSizeX;
  125. int pixelCordY = blockCordY * BlockSizeY;
  126. int outputPixelsX = Math.Min(pixelCordX + BlockSizeX, level.ImageSizeX) - pixelCordX;
  127. int outputPixelsY = Math.Min(pixelCordY + BlockSizeY, level.ImageSizeY * level.ImageSizeZ) - pixelCordY;
  128. int outputStart = pixelCordX * 4 + pixelCordY * stride;
  129. int outputOffset = outputStart;
  130. int inputOffset = 0;
  131. for (int i = 0; i < outputPixelsY; i++)
  132. {
  133. ReadOnlySpan<byte> blockRow = block.Slice(inputOffset, outputPixelsX * 4);
  134. Span<byte> outputRow = outputBuffer[outputOffset..];
  135. blockRow.CopyTo(outputRow);
  136. inputOffset += BlockSizeX * 4;
  137. outputOffset += stride;
  138. }
  139. }
  140. struct TexelWeightParams
  141. {
  142. public int Width;
  143. public int Height;
  144. public int MaxWeight;
  145. public bool DualPlane;
  146. public bool Error;
  147. public bool VoidExtentLdr;
  148. public bool VoidExtentHdr;
  149. public readonly int GetPackedBitSize()
  150. {
  151. // How many indices do we have?
  152. int indices = Height * Width;
  153. if (DualPlane)
  154. {
  155. indices *= 2;
  156. }
  157. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight);
  158. return intEncoded.GetBitLength(indices);
  159. }
  160. public readonly int GetNumWeightValues()
  161. {
  162. int ret = Width * Height;
  163. if (DualPlane)
  164. {
  165. ret *= 2;
  166. }
  167. return ret;
  168. }
  169. }
  170. public static bool TryDecodeToRgba8(
  171. ReadOnlyMemory<byte> data,
  172. int blockWidth,
  173. int blockHeight,
  174. int width,
  175. int height,
  176. int depth,
  177. int levels,
  178. int layers,
  179. out Span<byte> decoded)
  180. {
  181. byte[] output = new byte[QueryDecompressedSize(width, height, depth, levels, layers)];
  182. AstcDecoder decoder = new(data, output, blockWidth, blockHeight, width, height, depth, levels, layers);
  183. for (int i = 0; i < decoder.TotalBlockCount; i++)
  184. {
  185. decoder.ProcessBlock(i);
  186. }
  187. decoded = output;
  188. return decoder.Success;
  189. }
  190. public static bool TryDecodeToRgba8(
  191. ReadOnlyMemory<byte> data,
  192. Memory<byte> outputBuffer,
  193. int blockWidth,
  194. int blockHeight,
  195. int width,
  196. int height,
  197. int depth,
  198. int levels,
  199. int layers)
  200. {
  201. AstcDecoder decoder = new(data, outputBuffer, blockWidth, blockHeight, width, height, depth, levels, layers);
  202. for (int i = 0; i < decoder.TotalBlockCount; i++)
  203. {
  204. decoder.ProcessBlock(i);
  205. }
  206. return decoder.Success;
  207. }
  208. public static bool TryDecodeToRgba8P(
  209. ReadOnlyMemory<byte> data,
  210. Memory<byte> outputBuffer,
  211. int blockWidth,
  212. int blockHeight,
  213. int width,
  214. int height,
  215. int depth,
  216. int levels,
  217. int layers)
  218. {
  219. AstcDecoder decoder = new(data, outputBuffer, blockWidth, blockHeight, width, height, depth, levels, layers);
  220. // Lazy parallelism
  221. Enumerable.Range(0, decoder.TotalBlockCount).AsParallel().ForAll(x => decoder.ProcessBlock(x));
  222. return decoder.Success;
  223. }
  224. public static bool TryDecodeToRgba8P(
  225. ReadOnlyMemory<byte> data,
  226. int blockWidth,
  227. int blockHeight,
  228. int width,
  229. int height,
  230. int depth,
  231. int levels,
  232. int layers,
  233. out IMemoryOwner<byte> decoded)
  234. {
  235. decoded = ByteMemoryPool.Rent(QueryDecompressedSize(width, height, depth, levels, layers));
  236. AstcDecoder decoder = new(data, decoded.Memory, blockWidth, blockHeight, width, height, depth, levels, layers);
  237. Enumerable.Range(0, decoder.TotalBlockCount).AsParallel().ForAll(x => decoder.ProcessBlock(x));
  238. return decoder.Success;
  239. }
  240. public static bool DecompressBlock(
  241. Buffer16 inputBlock,
  242. Span<int> outputBuffer,
  243. int blockWidth,
  244. int blockHeight)
  245. {
  246. BitStream128 bitStream = new(inputBlock);
  247. DecodeBlockInfo(ref bitStream, out TexelWeightParams texelParams);
  248. if (texelParams.Error)
  249. {
  250. throw new AstcDecoderException("Invalid block mode");
  251. }
  252. if (texelParams.VoidExtentLdr)
  253. {
  254. FillVoidExtentLdr(ref bitStream, outputBuffer, blockWidth, blockHeight);
  255. return true;
  256. }
  257. if (texelParams.VoidExtentHdr)
  258. {
  259. throw new AstcDecoderException("HDR void extent blocks are not supported.");
  260. }
  261. if (texelParams.Width > blockWidth)
  262. {
  263. throw new AstcDecoderException("Texel weight grid width should be smaller than block width.");
  264. }
  265. if (texelParams.Height > blockHeight)
  266. {
  267. throw new AstcDecoderException("Texel weight grid height should be smaller than block height.");
  268. }
  269. // Read num partitions
  270. int numberPartitions = bitStream.ReadBits(2) + 1;
  271. Debug.Assert(numberPartitions <= 4);
  272. if (numberPartitions == 4 && texelParams.DualPlane)
  273. {
  274. throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks.");
  275. }
  276. // Based on the number of partitions, read the color endpoint mode for
  277. // each partition.
  278. // Determine partitions, partition index, and color endpoint modes
  279. int planeIndices;
  280. int partitionIndex;
  281. Span<uint> colorEndpointMode = stackalloc uint[4];
  282. BitStream128 colorEndpointStream = new();
  283. // Read extra config data...
  284. uint baseColorEndpointMode = 0;
  285. if (numberPartitions == 1)
  286. {
  287. colorEndpointMode[0] = (uint)bitStream.ReadBits(4);
  288. partitionIndex = 0;
  289. }
  290. else
  291. {
  292. partitionIndex = bitStream.ReadBits(10);
  293. baseColorEndpointMode = (uint)bitStream.ReadBits(6);
  294. }
  295. uint baseMode = (baseColorEndpointMode & 3);
  296. // Remaining bits are color endpoint data...
  297. int numberWeightBits = texelParams.GetPackedBitSize();
  298. int remainingBits = bitStream.BitsLeft - numberWeightBits;
  299. // Consider extra bits prior to texel data...
  300. uint extraColorEndpointModeBits = 0;
  301. if (baseMode != 0)
  302. {
  303. switch (numberPartitions)
  304. {
  305. case 2:
  306. extraColorEndpointModeBits += 2;
  307. break;
  308. case 3:
  309. extraColorEndpointModeBits += 5;
  310. break;
  311. case 4:
  312. extraColorEndpointModeBits += 8;
  313. break;
  314. default:
  315. Debug.Assert(false);
  316. break;
  317. }
  318. }
  319. remainingBits -= (int)extraColorEndpointModeBits;
  320. // Do we have a dual plane situation?
  321. int planeSelectorBits = 0;
  322. if (texelParams.DualPlane)
  323. {
  324. planeSelectorBits = 2;
  325. }
  326. remainingBits -= planeSelectorBits;
  327. // Read color data...
  328. int colorDataBits = remainingBits;
  329. while (remainingBits > 0)
  330. {
  331. int numberBits = Math.Min(remainingBits, 8);
  332. int bits = bitStream.ReadBits(numberBits);
  333. colorEndpointStream.WriteBits(bits, numberBits);
  334. remainingBits -= 8;
  335. }
  336. // Read the plane selection bits
  337. planeIndices = bitStream.ReadBits(planeSelectorBits);
  338. // Read the rest of the CEM
  339. if (baseMode != 0)
  340. {
  341. uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits);
  342. uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode;
  343. tempColorEndpointMode >>= 2;
  344. Span<bool> c = stackalloc bool[4];
  345. for (int i = 0; i < numberPartitions; i++)
  346. {
  347. c[i] = (tempColorEndpointMode & 1) != 0;
  348. tempColorEndpointMode >>= 1;
  349. }
  350. Span<byte> m = stackalloc byte[4];
  351. for (int i = 0; i < numberPartitions; i++)
  352. {
  353. m[i] = (byte)(tempColorEndpointMode & 3);
  354. tempColorEndpointMode >>= 2;
  355. Debug.Assert(m[i] <= 3);
  356. }
  357. for (int i = 0; i < numberPartitions; i++)
  358. {
  359. colorEndpointMode[i] = baseMode;
  360. if (!(c[i]))
  361. {
  362. colorEndpointMode[i] -= 1;
  363. }
  364. colorEndpointMode[i] <<= 2;
  365. colorEndpointMode[i] |= m[i];
  366. }
  367. }
  368. else if (numberPartitions > 1)
  369. {
  370. uint tempColorEndpointMode = baseColorEndpointMode >> 2;
  371. for (int i = 0; i < numberPartitions; i++)
  372. {
  373. colorEndpointMode[i] = tempColorEndpointMode;
  374. }
  375. }
  376. // Make sure everything up till here is sane.
  377. for (int i = 0; i < numberPartitions; i++)
  378. {
  379. Debug.Assert(colorEndpointMode[i] < 16);
  380. }
  381. Debug.Assert(bitStream.BitsLeft == texelParams.GetPackedBitSize());
  382. // Decode both color data and texel weight data
  383. Span<int> colorValues = stackalloc int[32]; // Four values * two endpoints * four maximum partitions
  384. DecodeColorValues(colorValues, ref colorEndpointStream, colorEndpointMode, numberPartitions, colorDataBits);
  385. EndPointSet endPoints;
  386. unsafe
  387. {
  388. // Skip struct initialization
  389. _ = &endPoints;
  390. }
  391. int colorValuesPosition = 0;
  392. for (int i = 0; i < numberPartitions; i++)
  393. {
  394. ComputeEndpoints(endPoints.Get(i), colorValues, colorEndpointMode[i], ref colorValuesPosition);
  395. }
  396. // Read the texel weight data.
  397. Buffer16 texelWeightData = inputBlock;
  398. // Reverse everything
  399. for (int i = 0; i < 8; i++)
  400. {
  401. byte a = ReverseByte(texelWeightData[i]);
  402. byte b = ReverseByte(texelWeightData[15 - i]);
  403. texelWeightData[i] = b;
  404. texelWeightData[15 - i] = a;
  405. }
  406. // Make sure that higher non-texel bits are set to zero
  407. int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1;
  408. texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1);
  409. int cLen = 16 - clearByteStart;
  410. for (int i = clearByteStart; i < clearByteStart + cLen; i++)
  411. {
  412. texelWeightData[i] = 0;
  413. }
  414. IntegerSequence texelWeightValues;
  415. unsafe
  416. {
  417. // Skip struct initialization
  418. _ = &texelWeightValues;
  419. }
  420. texelWeightValues.Reset();
  421. BitStream128 weightBitStream = new(texelWeightData);
  422. IntegerEncoded.DecodeIntegerSequence(ref texelWeightValues, ref weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues());
  423. // Blocks can be at most 12x12, so we can have as many as 144 weights
  424. Weights weights;
  425. unsafe
  426. {
  427. // Skip struct initialization
  428. _ = &weights;
  429. }
  430. UnquantizeTexelWeights(ref weights, ref texelWeightValues, ref texelParams, blockWidth, blockHeight);
  431. ushort[] table = Bits.Replicate8_16Table;
  432. // Now that we have endpoints and weights, we can interpolate and generate
  433. // the proper decoding...
  434. for (int j = 0; j < blockHeight; j++)
  435. {
  436. for (int i = 0; i < blockWidth; i++)
  437. {
  438. int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32));
  439. Debug.Assert(partition < numberPartitions);
  440. AstcPixel pixel = new();
  441. for (int component = 0; component < 4; component++)
  442. {
  443. int component0 = endPoints.Get(partition)[0].GetComponent(component);
  444. component0 = table[component0];
  445. int component1 = endPoints.Get(partition)[1].GetComponent(component);
  446. component1 = table[component1];
  447. int plane = 0;
  448. if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component))
  449. {
  450. plane = 1;
  451. }
  452. int weight = weights.Get(plane)[j * blockWidth + i];
  453. int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64;
  454. if (finalComponent == 65535)
  455. {
  456. pixel.SetComponent(component, 255);
  457. }
  458. else
  459. {
  460. double finalComponentFloat = finalComponent;
  461. pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5));
  462. }
  463. }
  464. outputBuffer[j * blockWidth + i] = pixel.Pack();
  465. }
  466. }
  467. return true;
  468. }
  469. // Blocks can be at most 12x12, so we can have as many as 144 weights
  470. [StructLayout(LayoutKind.Sequential, Size = 144 * sizeof(int) * Count)]
  471. private struct Weights
  472. {
  473. private int _start;
  474. public const int Count = 2;
  475. public Span<int> this[int index]
  476. {
  477. get
  478. {
  479. if ((uint)index >= Count)
  480. {
  481. throw new ArgumentOutOfRangeException(nameof(index), index, null);
  482. }
  483. ref int start = ref Unsafe.Add(ref _start, index * 144);
  484. return MemoryMarshal.CreateSpan(ref start, 144);
  485. }
  486. }
  487. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  488. public Span<int> Get(int index)
  489. {
  490. ref int start = ref Unsafe.Add(ref _start, index * 144);
  491. return MemoryMarshal.CreateSpan(ref start, 144);
  492. }
  493. }
  494. private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock)
  495. {
  496. return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock);
  497. }
  498. private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock)
  499. {
  500. if (partitionCount == 1)
  501. {
  502. return 0;
  503. }
  504. if (isSmallBlock)
  505. {
  506. x <<= 1;
  507. y <<= 1;
  508. z <<= 1;
  509. }
  510. seed += (partitionCount - 1) * 1024;
  511. int rightNum = Hash52((uint)seed);
  512. byte seed01 = (byte)(rightNum & 0xF);
  513. byte seed02 = (byte)((rightNum >> 4) & 0xF);
  514. byte seed03 = (byte)((rightNum >> 8) & 0xF);
  515. byte seed04 = (byte)((rightNum >> 12) & 0xF);
  516. byte seed05 = (byte)((rightNum >> 16) & 0xF);
  517. byte seed06 = (byte)((rightNum >> 20) & 0xF);
  518. byte seed07 = (byte)((rightNum >> 24) & 0xF);
  519. byte seed08 = (byte)((rightNum >> 28) & 0xF);
  520. byte seed09 = (byte)((rightNum >> 18) & 0xF);
  521. byte seed10 = (byte)((rightNum >> 22) & 0xF);
  522. byte seed11 = (byte)((rightNum >> 26) & 0xF);
  523. byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF);
  524. seed01 *= seed01;
  525. seed02 *= seed02;
  526. seed03 *= seed03;
  527. seed04 *= seed04;
  528. seed05 *= seed05;
  529. seed06 *= seed06;
  530. seed07 *= seed07;
  531. seed08 *= seed08;
  532. seed09 *= seed09;
  533. seed10 *= seed10;
  534. seed11 *= seed11;
  535. seed12 *= seed12;
  536. int seedHash1, seedHash2, seedHash3;
  537. if ((seed & 1) != 0)
  538. {
  539. seedHash1 = (seed & 2) != 0 ? 4 : 5;
  540. seedHash2 = (partitionCount == 3) ? 6 : 5;
  541. }
  542. else
  543. {
  544. seedHash1 = (partitionCount == 3) ? 6 : 5;
  545. seedHash2 = (seed & 2) != 0 ? 4 : 5;
  546. }
  547. seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2;
  548. seed01 >>= seedHash1;
  549. seed02 >>= seedHash2;
  550. seed03 >>= seedHash1;
  551. seed04 >>= seedHash2;
  552. seed05 >>= seedHash1;
  553. seed06 >>= seedHash2;
  554. seed07 >>= seedHash1;
  555. seed08 >>= seedHash2;
  556. seed09 >>= seedHash3;
  557. seed10 >>= seedHash3;
  558. seed11 >>= seedHash3;
  559. seed12 >>= seedHash3;
  560. int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14);
  561. int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10);
  562. int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6);
  563. int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2);
  564. a &= 0x3F;
  565. b &= 0x3F;
  566. c &= 0x3F;
  567. d &= 0x3F;
  568. if (partitionCount < 4)
  569. {
  570. d = 0;
  571. }
  572. if (partitionCount < 3)
  573. {
  574. c = 0;
  575. }
  576. if (a >= b && a >= c && a >= d)
  577. {
  578. return 0;
  579. }
  580. else if (b >= c && b >= d)
  581. {
  582. return 1;
  583. }
  584. else if (c >= d)
  585. {
  586. return 2;
  587. }
  588. return 3;
  589. }
  590. static int Hash52(uint val)
  591. {
  592. val ^= val >> 15;
  593. val -= val << 17;
  594. val += val << 7;
  595. val += val << 4;
  596. val ^= val >> 5;
  597. val += val << 16;
  598. val ^= val >> 7;
  599. val ^= val >> 3;
  600. val ^= val << 6;
  601. val ^= val >> 17;
  602. return (int)val;
  603. }
  604. static void UnquantizeTexelWeights(
  605. ref Weights outputBuffer,
  606. ref IntegerSequence weights,
  607. ref TexelWeightParams texelParams,
  608. int blockWidth,
  609. int blockHeight)
  610. {
  611. int weightIndices = 0;
  612. Weights unquantized;
  613. unsafe
  614. {
  615. // Skip struct initialization
  616. _ = &unquantized;
  617. }
  618. Span<IntegerEncoded> weightsList = weights.List;
  619. Span<int> unquantized0 = unquantized[0];
  620. Span<int> unquantized1 = unquantized[1];
  621. for (int i = 0; i < weightsList.Length; i++)
  622. {
  623. unquantized0[weightIndices] = UnquantizeTexelWeight(weightsList[i]);
  624. if (texelParams.DualPlane)
  625. {
  626. i++;
  627. unquantized1[weightIndices] = UnquantizeTexelWeight(weightsList[i]);
  628. if (i == weightsList.Length)
  629. {
  630. break;
  631. }
  632. }
  633. if (++weightIndices >= texelParams.Width * texelParams.Height)
  634. {
  635. break;
  636. }
  637. }
  638. // Do infill if necessary (Section C.2.18) ...
  639. int ds = (1024 + blockWidth / 2) / (blockWidth - 1);
  640. int dt = (1024 + blockHeight / 2) / (blockHeight - 1);
  641. int planeScale = texelParams.DualPlane ? 2 : 1;
  642. for (int plane = 0; plane < planeScale; plane++)
  643. {
  644. Span<int> unquantizedSpan = unquantized.Get(plane);
  645. Span<int> outputSpan = outputBuffer.Get(plane);
  646. for (int t = 0; t < blockHeight; t++)
  647. {
  648. for (int s = 0; s < blockWidth; s++)
  649. {
  650. int cs = ds * s;
  651. int ct = dt * t;
  652. int gs = (cs * (texelParams.Width - 1) + 32) >> 6;
  653. int gt = (ct * (texelParams.Height - 1) + 32) >> 6;
  654. int js = gs >> 4;
  655. int fs = gs & 0xF;
  656. int jt = gt >> 4;
  657. int ft = gt & 0x0F;
  658. int w11 = (fs * ft + 8) >> 4;
  659. int v0 = js + jt * texelParams.Width;
  660. int weight = 8;
  661. int wxh = texelParams.Width * texelParams.Height;
  662. if (v0 < wxh)
  663. {
  664. weight += unquantizedSpan[v0] * (16 - fs - ft + w11);
  665. if (v0 + 1 < wxh)
  666. {
  667. weight += unquantizedSpan[v0 + 1] * (fs - w11);
  668. }
  669. }
  670. if (v0 + texelParams.Width < wxh)
  671. {
  672. weight += unquantizedSpan[v0 + texelParams.Width] * (ft - w11);
  673. if (v0 + texelParams.Width + 1 < wxh)
  674. {
  675. weight += unquantizedSpan[v0 + texelParams.Width + 1] * w11;
  676. }
  677. }
  678. outputSpan[t * blockWidth + s] = weight >> 4;
  679. }
  680. }
  681. }
  682. }
  683. static int UnquantizeTexelWeight(IntegerEncoded intEncoded)
  684. {
  685. int bitValue = intEncoded.BitValue;
  686. int bitLength = intEncoded.NumberBits;
  687. int a = Bits.Replicate1_7(bitValue & 1);
  688. int b = 0, c = 0, d = 0;
  689. int result = 0;
  690. switch (intEncoded.GetEncoding())
  691. {
  692. case IntegerEncoded.EIntegerEncoding.JustBits:
  693. result = Bits.Replicate(bitValue, bitLength, 6);
  694. break;
  695. case IntegerEncoded.EIntegerEncoding.Trit:
  696. {
  697. d = intEncoded.TritValue;
  698. Debug.Assert(d < 3);
  699. switch (bitLength)
  700. {
  701. case 0:
  702. {
  703. result = d switch
  704. {
  705. 0 => 0,
  706. 1 => 32,
  707. 2 => 63,
  708. _ => 0,
  709. };
  710. break;
  711. }
  712. case 1:
  713. {
  714. c = 50;
  715. break;
  716. }
  717. case 2:
  718. {
  719. c = 23;
  720. int b2 = (bitValue >> 1) & 1;
  721. b = (b2 << 6) | (b2 << 2) | b2;
  722. break;
  723. }
  724. case 3:
  725. {
  726. c = 11;
  727. int cb = (bitValue >> 1) & 3;
  728. b = (cb << 5) | cb;
  729. break;
  730. }
  731. default:
  732. throw new AstcDecoderException("Invalid trit encoding for texel weight.");
  733. }
  734. break;
  735. }
  736. case IntegerEncoded.EIntegerEncoding.Quint:
  737. {
  738. d = intEncoded.QuintValue;
  739. Debug.Assert(d < 5);
  740. switch (bitLength)
  741. {
  742. case 0:
  743. {
  744. result = d switch
  745. {
  746. 0 => 0,
  747. 1 => 16,
  748. 2 => 32,
  749. 3 => 47,
  750. 4 => 63,
  751. _ => 0,
  752. };
  753. break;
  754. }
  755. case 1:
  756. {
  757. c = 28;
  758. break;
  759. }
  760. case 2:
  761. {
  762. c = 13;
  763. int b2 = (bitValue >> 1) & 1;
  764. b = (b2 << 6) | (b2 << 1);
  765. break;
  766. }
  767. default:
  768. throw new AstcDecoderException("Invalid quint encoding for texel weight.");
  769. }
  770. break;
  771. }
  772. }
  773. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0)
  774. {
  775. // Decode the value...
  776. result = d * c + b;
  777. result ^= a;
  778. result = (a & 0x20) | (result >> 2);
  779. }
  780. Debug.Assert(result < 64);
  781. // Change from [0,63] to [0,64]
  782. if (result > 32)
  783. {
  784. result += 1;
  785. }
  786. return result;
  787. }
  788. static byte ReverseByte(byte b)
  789. {
  790. // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits
  791. return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32);
  792. }
  793. static Span<uint> ReadUintColorValues(int number, Span<int> colorValues, ref int colorValuesPosition)
  794. {
  795. Span<int> ret = colorValues.Slice(colorValuesPosition, number);
  796. colorValuesPosition += number;
  797. return MemoryMarshal.Cast<int, uint>(ret);
  798. }
  799. static Span<int> ReadIntColorValues(int number, Span<int> colorValues, ref int colorValuesPosition)
  800. {
  801. Span<int> ret = colorValues.Slice(colorValuesPosition, number);
  802. colorValuesPosition += number;
  803. return ret;
  804. }
  805. static void ComputeEndpoints(
  806. Span<AstcPixel> endPoints,
  807. Span<int> colorValues,
  808. uint colorEndpointMode,
  809. ref int colorValuesPosition)
  810. {
  811. switch (colorEndpointMode)
  812. {
  813. case 0:
  814. {
  815. Span<uint> val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  816. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]);
  817. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]);
  818. break;
  819. }
  820. case 1:
  821. {
  822. Span<uint> val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  823. int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0));
  824. int l1 = (int)Math.Min(l0 + (val[1] & 0x3F), 0xFFU);
  825. endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0);
  826. endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1);
  827. break;
  828. }
  829. case 4:
  830. {
  831. Span<uint> val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  832. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  833. endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]);
  834. break;
  835. }
  836. case 5:
  837. {
  838. Span<int> val = ReadIntColorValues(4, colorValues, ref colorValuesPosition);
  839. Bits.BitTransferSigned(ref val[1], ref val[0]);
  840. Bits.BitTransferSigned(ref val[3], ref val[2]);
  841. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  842. endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1]));
  843. endPoints[0].ClampByte();
  844. endPoints[1].ClampByte();
  845. break;
  846. }
  847. case 6:
  848. {
  849. Span<uint> val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  850. endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  851. endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]);
  852. break;
  853. }
  854. case 8:
  855. {
  856. Span<uint> val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  857. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  858. {
  859. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  860. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  861. }
  862. else
  863. {
  864. endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  865. endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  866. }
  867. break;
  868. }
  869. case 9:
  870. {
  871. Span<int> val = ReadIntColorValues(6, colorValues, ref colorValuesPosition);
  872. Bits.BitTransferSigned(ref val[1], ref val[0]);
  873. Bits.BitTransferSigned(ref val[3], ref val[2]);
  874. Bits.BitTransferSigned(ref val[5], ref val[4]);
  875. if (val[1] + val[3] + val[5] >= 0)
  876. {
  877. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  878. endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  879. }
  880. else
  881. {
  882. endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  883. endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]);
  884. }
  885. endPoints[0].ClampByte();
  886. endPoints[1].ClampByte();
  887. break;
  888. }
  889. case 10:
  890. {
  891. Span<uint> val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  892. endPoints[0] = new AstcPixel((short)val[4], (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  893. endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]);
  894. break;
  895. }
  896. case 12:
  897. {
  898. Span<uint> val = ReadUintColorValues(8, colorValues, ref colorValuesPosition);
  899. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  900. {
  901. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  902. endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  903. }
  904. else
  905. {
  906. endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  907. endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  908. }
  909. break;
  910. }
  911. case 13:
  912. {
  913. Span<int> val = ReadIntColorValues(8, colorValues, ref colorValuesPosition);
  914. Bits.BitTransferSigned(ref val[1], ref val[0]);
  915. Bits.BitTransferSigned(ref val[3], ref val[2]);
  916. Bits.BitTransferSigned(ref val[5], ref val[4]);
  917. Bits.BitTransferSigned(ref val[7], ref val[6]);
  918. if (val[1] + val[3] + val[5] >= 0)
  919. {
  920. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  921. endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  922. }
  923. else
  924. {
  925. endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  926. endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]);
  927. }
  928. endPoints[0].ClampByte();
  929. endPoints[1].ClampByte();
  930. break;
  931. }
  932. default:
  933. throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)");
  934. }
  935. }
  936. static void DecodeColorValues(
  937. Span<int> outputValues,
  938. ref BitStream128 colorBitStream,
  939. Span<uint> modes,
  940. int numberPartitions,
  941. int numberBitsForColorData)
  942. {
  943. // First figure out how many color values we have
  944. int numberValues = 0;
  945. for (int i = 0; i < numberPartitions; i++)
  946. {
  947. numberValues += (int)((modes[i] >> 2) + 1) << 1;
  948. }
  949. // Then based on the number of values and the remaining number of bits,
  950. // figure out the max value for each of them...
  951. int range = 256;
  952. while (--range > 0)
  953. {
  954. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range);
  955. int bitLength = intEncoded.GetBitLength(numberValues);
  956. if (bitLength <= numberBitsForColorData)
  957. {
  958. // Find the smallest possible range that matches the given encoding
  959. while (--range > 0)
  960. {
  961. IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range);
  962. if (!newIntEncoded.MatchesEncoding(intEncoded))
  963. {
  964. break;
  965. }
  966. }
  967. // Return to last matching range.
  968. range++;
  969. break;
  970. }
  971. }
  972. // We now have enough to decode our integer sequence.
  973. IntegerSequence integerEncodedSequence;
  974. unsafe
  975. {
  976. // Skip struct initialization
  977. _ = &integerEncodedSequence;
  978. }
  979. integerEncodedSequence.Reset();
  980. IntegerEncoded.DecodeIntegerSequence(ref integerEncodedSequence, ref colorBitStream, range, numberValues);
  981. // Once we have the decoded values, we need to dequantize them to the 0-255 range
  982. // This procedure is outlined in ASTC spec C.2.13
  983. int outputIndices = 0;
  984. foreach (ref IntegerEncoded intEncoded in integerEncodedSequence.List)
  985. {
  986. int bitLength = intEncoded.NumberBits;
  987. int bitValue = intEncoded.BitValue;
  988. Debug.Assert(bitLength >= 1);
  989. int b = 0, c = 0, d = 0;
  990. // A is just the lsb replicated 9 times.
  991. int a = Bits.Replicate(bitValue & 1, 1, 9);
  992. switch (intEncoded.GetEncoding())
  993. {
  994. case IntegerEncoded.EIntegerEncoding.JustBits:
  995. {
  996. outputValues[outputIndices++] = Bits.Replicate(bitValue, bitLength, 8);
  997. break;
  998. }
  999. case IntegerEncoded.EIntegerEncoding.Trit:
  1000. {
  1001. d = intEncoded.TritValue;
  1002. switch (bitLength)
  1003. {
  1004. case 1:
  1005. {
  1006. c = 204;
  1007. break;
  1008. }
  1009. case 2:
  1010. {
  1011. c = 93;
  1012. // B = b000b0bb0
  1013. int b2 = (bitValue >> 1) & 1;
  1014. b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1);
  1015. break;
  1016. }
  1017. case 3:
  1018. {
  1019. c = 44;
  1020. // B = cb000cbcb
  1021. int cb = (bitValue >> 1) & 3;
  1022. b = (cb << 7) | (cb << 2) | cb;
  1023. break;
  1024. }
  1025. case 4:
  1026. {
  1027. c = 22;
  1028. // B = dcb000dcb
  1029. int dcb = (bitValue >> 1) & 7;
  1030. b = (dcb << 6) | dcb;
  1031. break;
  1032. }
  1033. case 5:
  1034. {
  1035. c = 11;
  1036. // B = edcb000ed
  1037. int edcb = (bitValue >> 1) & 0xF;
  1038. b = (edcb << 5) | (edcb >> 2);
  1039. break;
  1040. }
  1041. case 6:
  1042. {
  1043. c = 5;
  1044. // B = fedcb000f
  1045. int fedcb = (bitValue >> 1) & 0x1F;
  1046. b = (fedcb << 4) | (fedcb >> 4);
  1047. break;
  1048. }
  1049. default:
  1050. throw new AstcDecoderException("Unsupported trit encoding for color values.");
  1051. }
  1052. break;
  1053. }
  1054. case IntegerEncoded.EIntegerEncoding.Quint:
  1055. {
  1056. d = intEncoded.QuintValue;
  1057. switch (bitLength)
  1058. {
  1059. case 1:
  1060. {
  1061. c = 113;
  1062. break;
  1063. }
  1064. case 2:
  1065. {
  1066. c = 54;
  1067. // B = b0000bb00
  1068. int b2 = (bitValue >> 1) & 1;
  1069. b = (b2 << 8) | (b2 << 3) | (b2 << 2);
  1070. break;
  1071. }
  1072. case 3:
  1073. {
  1074. c = 26;
  1075. // B = cb0000cbc
  1076. int cb = (bitValue >> 1) & 3;
  1077. b = (cb << 7) | (cb << 1) | (cb >> 1);
  1078. break;
  1079. }
  1080. case 4:
  1081. {
  1082. c = 13;
  1083. // B = dcb0000dc
  1084. int dcb = (bitValue >> 1) & 7;
  1085. b = (dcb << 6) | (dcb >> 1);
  1086. break;
  1087. }
  1088. case 5:
  1089. {
  1090. c = 6;
  1091. // B = edcb0000e
  1092. int edcb = (bitValue >> 1) & 0xF;
  1093. b = (edcb << 5) | (edcb >> 3);
  1094. break;
  1095. }
  1096. default:
  1097. throw new AstcDecoderException("Unsupported quint encoding for color values.");
  1098. }
  1099. break;
  1100. }
  1101. }
  1102. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits)
  1103. {
  1104. int T = d * c + b;
  1105. T ^= a;
  1106. T = (a & 0x80) | (T >> 2);
  1107. outputValues[outputIndices++] = T;
  1108. }
  1109. }
  1110. // Make sure that each of our values is in the proper range...
  1111. for (int i = 0; i < numberValues; i++)
  1112. {
  1113. Debug.Assert(outputValues[i] <= 255);
  1114. }
  1115. }
  1116. static void FillVoidExtentLdr(ref BitStream128 bitStream, Span<int> outputBuffer, int blockWidth, int blockHeight)
  1117. {
  1118. // Don't actually care about the void extent, just read the bits...
  1119. for (int i = 0; i < 4; ++i)
  1120. {
  1121. bitStream.ReadBits(13);
  1122. }
  1123. // Decode the RGBA components and renormalize them to the range [0, 255]
  1124. ushort r = (ushort)bitStream.ReadBits(16);
  1125. ushort g = (ushort)bitStream.ReadBits(16);
  1126. ushort b = (ushort)bitStream.ReadBits(16);
  1127. ushort a = (ushort)bitStream.ReadBits(16);
  1128. int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16;
  1129. for (int j = 0; j < blockHeight; j++)
  1130. {
  1131. for (int i = 0; i < blockWidth; i++)
  1132. {
  1133. outputBuffer[j * blockWidth + i] = rgba;
  1134. }
  1135. }
  1136. }
  1137. static void DecodeBlockInfo(ref BitStream128 bitStream, out TexelWeightParams texelParams)
  1138. {
  1139. texelParams = new TexelWeightParams();
  1140. // Read the entire block mode all at once
  1141. ushort modeBits = (ushort)bitStream.ReadBits(11);
  1142. // Does this match the void extent block mode?
  1143. if ((modeBits & 0x01FF) == 0x1FC)
  1144. {
  1145. if ((modeBits & 0x200) != 0)
  1146. {
  1147. texelParams.VoidExtentHdr = true;
  1148. }
  1149. else
  1150. {
  1151. texelParams.VoidExtentLdr = true;
  1152. }
  1153. // Next two bits must be one.
  1154. if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0)
  1155. {
  1156. texelParams.Error = true;
  1157. }
  1158. return;
  1159. }
  1160. // First check if the last four bits are zero
  1161. if ((modeBits & 0xF) == 0)
  1162. {
  1163. texelParams.Error = true;
  1164. return;
  1165. }
  1166. // If the last two bits are zero, then if bits
  1167. // [6-8] are all ones, this is also reserved.
  1168. if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0)
  1169. {
  1170. texelParams.Error = true;
  1171. return;
  1172. }
  1173. // Otherwise, there is no error... Figure out the layout
  1174. // of the block mode. Layout is determined by a number
  1175. // between 0 and 9 corresponding to table C.2.8 of the
  1176. // ASTC spec.
  1177. int layout;
  1178. if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0)
  1179. {
  1180. // layout is in [0-4]
  1181. if ((modeBits & 0x8) != 0)
  1182. {
  1183. // layout is in [2-4]
  1184. if ((modeBits & 0x4) != 0)
  1185. {
  1186. // layout is in [3-4]
  1187. if ((modeBits & 0x100) != 0)
  1188. {
  1189. layout = 4;
  1190. }
  1191. else
  1192. {
  1193. layout = 3;
  1194. }
  1195. }
  1196. else
  1197. {
  1198. layout = 2;
  1199. }
  1200. }
  1201. else
  1202. {
  1203. // layout is in [0-1]
  1204. if ((modeBits & 0x4) != 0)
  1205. {
  1206. layout = 1;
  1207. }
  1208. else
  1209. {
  1210. layout = 0;
  1211. }
  1212. }
  1213. }
  1214. else
  1215. {
  1216. // layout is in [5-9]
  1217. if ((modeBits & 0x100) != 0)
  1218. {
  1219. // layout is in [7-9]
  1220. if ((modeBits & 0x80) != 0)
  1221. {
  1222. // layout is in [7-8]
  1223. Debug.Assert((modeBits & 0x40) == 0);
  1224. if ((modeBits & 0x20) != 0)
  1225. {
  1226. layout = 8;
  1227. }
  1228. else
  1229. {
  1230. layout = 7;
  1231. }
  1232. }
  1233. else
  1234. {
  1235. layout = 9;
  1236. }
  1237. }
  1238. else
  1239. {
  1240. // layout is in [5-6]
  1241. if ((modeBits & 0x80) != 0)
  1242. {
  1243. layout = 6;
  1244. }
  1245. else
  1246. {
  1247. layout = 5;
  1248. }
  1249. }
  1250. }
  1251. Debug.Assert(layout < 10);
  1252. // Determine R
  1253. int r = (modeBits >> 4) & 1;
  1254. if (layout < 5)
  1255. {
  1256. r |= (modeBits & 0x3) << 1;
  1257. }
  1258. else
  1259. {
  1260. r |= (modeBits & 0xC) >> 1;
  1261. }
  1262. Debug.Assert(2 <= r && r <= 7);
  1263. // Determine width & height
  1264. switch (layout)
  1265. {
  1266. case 0:
  1267. {
  1268. int a = (modeBits >> 5) & 0x3;
  1269. int b = (modeBits >> 7) & 0x3;
  1270. texelParams.Width = b + 4;
  1271. texelParams.Height = a + 2;
  1272. break;
  1273. }
  1274. case 1:
  1275. {
  1276. int a = (modeBits >> 5) & 0x3;
  1277. int b = (modeBits >> 7) & 0x3;
  1278. texelParams.Width = b + 8;
  1279. texelParams.Height = a + 2;
  1280. break;
  1281. }
  1282. case 2:
  1283. {
  1284. int a = (modeBits >> 5) & 0x3;
  1285. int b = (modeBits >> 7) & 0x3;
  1286. texelParams.Width = a + 2;
  1287. texelParams.Height = b + 8;
  1288. break;
  1289. }
  1290. case 3:
  1291. {
  1292. int a = (modeBits >> 5) & 0x3;
  1293. int b = (modeBits >> 7) & 0x1;
  1294. texelParams.Width = a + 2;
  1295. texelParams.Height = b + 6;
  1296. break;
  1297. }
  1298. case 4:
  1299. {
  1300. int a = (modeBits >> 5) & 0x3;
  1301. int b = (modeBits >> 7) & 0x1;
  1302. texelParams.Width = b + 2;
  1303. texelParams.Height = a + 2;
  1304. break;
  1305. }
  1306. case 5:
  1307. {
  1308. int a = (modeBits >> 5) & 0x3;
  1309. texelParams.Width = 12;
  1310. texelParams.Height = a + 2;
  1311. break;
  1312. }
  1313. case 6:
  1314. {
  1315. int a = (modeBits >> 5) & 0x3;
  1316. texelParams.Width = a + 2;
  1317. texelParams.Height = 12;
  1318. break;
  1319. }
  1320. case 7:
  1321. {
  1322. texelParams.Width = 6;
  1323. texelParams.Height = 10;
  1324. break;
  1325. }
  1326. case 8:
  1327. {
  1328. texelParams.Width = 10;
  1329. texelParams.Height = 6;
  1330. break;
  1331. }
  1332. case 9:
  1333. {
  1334. int a = (modeBits >> 5) & 0x3;
  1335. int b = (modeBits >> 9) & 0x3;
  1336. texelParams.Width = a + 6;
  1337. texelParams.Height = b + 6;
  1338. break;
  1339. }
  1340. default:
  1341. // Don't know this layout...
  1342. texelParams.Error = true;
  1343. break;
  1344. }
  1345. // Determine whether or not we're using dual planes
  1346. // and/or high precision layouts.
  1347. bool d = ((layout != 9) && ((modeBits & 0x400) != 0));
  1348. bool h = (layout != 9) && ((modeBits & 0x200) != 0);
  1349. if (h)
  1350. {
  1351. ReadOnlySpan<byte> maxWeights = new byte[] { 9, 11, 15, 19, 23, 31 };
  1352. texelParams.MaxWeight = maxWeights[r - 2];
  1353. }
  1354. else
  1355. {
  1356. ReadOnlySpan<byte> maxWeights = new byte[] { 1, 2, 3, 4, 5, 7 };
  1357. texelParams.MaxWeight = maxWeights[r - 2];
  1358. }
  1359. texelParams.DualPlane = d;
  1360. }
  1361. }
  1362. }