AstcDecoder.cs 57 KB

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