AstcDecoder.cs 54 KB

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