avpcl_mode0.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. /*
  2. Copyright 2007 nVidia, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  5. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
  6. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7. See the License for the specific language governing permissions and limitations under the License.
  8. */
  9. // Thanks to Jacob Munkberg ([email protected]) for the shortcut of using SVD to do the equivalent of principal components analysis
  10. // x1 444.1x6 16p 45b (3bi)
  11. #include "bits.h"
  12. #include "tile.h"
  13. #include "avpcl.h"
  14. #include "nvcore/debug.h"
  15. #include "nvmath/vector.inl"
  16. #include "nvmath/matrix.inl"
  17. #include "nvmath/fitting.h"
  18. #include "avpcl_utils.h"
  19. #include "endpts.h"
  20. #include <string.h>
  21. #include <float.h>
  22. #include "shapes_three.h"
  23. // use only the first 16 available shapes
  24. #undef NSHAPES
  25. #undef SHAPEBITS
  26. #define NSHAPES 16
  27. #define SHAPEBITS 4
  28. using namespace nv;
  29. using namespace AVPCL;
  30. #define NLSBMODES 4 // number of different lsb modes per region. since we have two .1 per region, that can have 4 values
  31. #define NINDICES 8
  32. #define INDEXBITS 3
  33. #define HIGH_INDEXBIT (1<<(INDEXBITS-1))
  34. #define DENOM (NINDICES-1)
  35. #define BIAS (DENOM/2)
  36. // WORK: determine optimal traversal pattern to search for best shape -- what does the error curve look like?
  37. // i.e. can we search shapes in a particular order so we can see the global error minima easily and
  38. // stop without having to touch all shapes?
  39. #define POS_TO_X(pos) ((pos)&3)
  40. #define POS_TO_Y(pos) (((pos)>>2)&3)
  41. #define NBITSIZES (NREGIONS*2)
  42. #define ABITINDEX(region) (2*(region)+0)
  43. #define BBITINDEX(region) (2*(region)+1)
  44. struct ChanBits
  45. {
  46. int nbitsizes[NBITSIZES]; // bitsizes for one channel
  47. };
  48. struct Pattern
  49. {
  50. ChanBits chan[NCHANNELS_RGB];// bit patterns used per channel
  51. int transformed; // if 0, deltas are unsigned and no transform; otherwise, signed and transformed
  52. int mode; // associated mode value
  53. int modebits; // number of mode bits
  54. const char *encoding; // verilog description of encoding for this mode
  55. };
  56. #define NPATTERNS 1
  57. static Pattern patterns[NPATTERNS] =
  58. {
  59. // red green blue xfm mode mb
  60. 4,4,4,4,4,4, 4,4,4,4,4,4, 4,4,4,4,4,4, 0, 0x1, 1, "", // really 444.1 x 6
  61. };
  62. struct RegionPrec
  63. {
  64. int endpt_a_prec[NCHANNELS_RGB];
  65. int endpt_b_prec[NCHANNELS_RGB];
  66. };
  67. struct PatternPrec
  68. {
  69. RegionPrec region_precs[NREGIONS];
  70. };
  71. // this is the precision for each channel and region
  72. // NOTE: this MUST match the corresponding data in "patterns" above -- WARNING: there is NO nvAssert to check this!
  73. static PatternPrec pattern_precs[NPATTERNS] =
  74. {
  75. 4,4,4, 4,4,4, 4,4,4, 4,4,4, 4,4,4, 4,4,4,
  76. };
  77. // return # of bits needed to store n. handle signed or unsigned cases properly
  78. static int nbits(int n, bool issigned)
  79. {
  80. int nb;
  81. if (n==0)
  82. return 0; // no bits needed for 0, signed or not
  83. else if (n > 0)
  84. {
  85. for (nb=0; n; ++nb, n>>=1) ;
  86. return nb + (issigned?1:0);
  87. }
  88. else
  89. {
  90. nvAssert (issigned);
  91. for (nb=0; n<-1; ++nb, n>>=1) ;
  92. return nb + 1;
  93. }
  94. }
  95. static void transform_forward(IntEndptsRGB_2 ep[NREGIONS])
  96. {
  97. nvUnreachable();
  98. }
  99. static void transform_inverse(IntEndptsRGB_2 ep[NREGIONS])
  100. {
  101. nvUnreachable();
  102. }
  103. // endpoints are 555,555; reduce to 444,444 and put the lsb bit majority in compr_bits
  104. static void compress_one(const IntEndptsRGB& endpts, IntEndptsRGB_2& compr_endpts)
  105. {
  106. int onescnt;
  107. onescnt = 0;
  108. for (int j=0; j<NCHANNELS_RGB; ++j)
  109. {
  110. onescnt += endpts.A[j] & 1;
  111. compr_endpts.A[j] = endpts.A[j] >> 1;
  112. nvAssert (compr_endpts.A[j] < 16);
  113. }
  114. compr_endpts.a_lsb = onescnt >= 2;
  115. onescnt = 0;
  116. for (int j=0; j<NCHANNELS_RGB; ++j)
  117. {
  118. onescnt += endpts.B[j] & 1;
  119. compr_endpts.B[j] = endpts.B[j] >> 1;
  120. nvAssert (compr_endpts.B[j] < 16);
  121. }
  122. compr_endpts.b_lsb = onescnt >= 2;
  123. }
  124. static void uncompress_one(const IntEndptsRGB_2& compr_endpts, IntEndptsRGB& endpts)
  125. {
  126. for (int j=0; j<NCHANNELS_RGB; ++j)
  127. {
  128. endpts.A[j] = (compr_endpts.A[j] << 1) | compr_endpts.a_lsb;
  129. endpts.B[j] = (compr_endpts.B[j] << 1) | compr_endpts.b_lsb;
  130. }
  131. }
  132. static void uncompress_endpoints(const IntEndptsRGB_2 compr_endpts[NREGIONS], IntEndptsRGB endpts[NREGIONS])
  133. {
  134. for (int i=0; i<NREGIONS; ++i)
  135. uncompress_one(compr_endpts[i], endpts[i]);
  136. }
  137. static void compress_endpoints(const IntEndptsRGB endpts[NREGIONS], IntEndptsRGB_2 compr_endpts[NREGIONS])
  138. {
  139. for (int i=0; i<NREGIONS; ++i)
  140. compress_one(endpts[i], compr_endpts[i]);
  141. }
  142. static void quantize_endpts(const FltEndpts endpts[NREGIONS], const PatternPrec &pattern_prec, IntEndptsRGB_2 q_endpts[NREGIONS])
  143. {
  144. IntEndptsRGB full_endpts[NREGIONS];
  145. for (int region = 0; region < NREGIONS; ++region)
  146. {
  147. full_endpts[region].A[0] = Utils::quantize(endpts[region].A.x, pattern_prec.region_precs[region].endpt_a_prec[0]+1); // +1 since we are in uncompressed space
  148. full_endpts[region].A[1] = Utils::quantize(endpts[region].A.y, pattern_prec.region_precs[region].endpt_a_prec[1]+1);
  149. full_endpts[region].A[2] = Utils::quantize(endpts[region].A.z, pattern_prec.region_precs[region].endpt_a_prec[2]+1);
  150. full_endpts[region].B[0] = Utils::quantize(endpts[region].B.x, pattern_prec.region_precs[region].endpt_b_prec[0]+1);
  151. full_endpts[region].B[1] = Utils::quantize(endpts[region].B.y, pattern_prec.region_precs[region].endpt_b_prec[1]+1);
  152. full_endpts[region].B[2] = Utils::quantize(endpts[region].B.z, pattern_prec.region_precs[region].endpt_b_prec[2]+1);
  153. compress_one(full_endpts[region], q_endpts[region]);
  154. }
  155. }
  156. // swap endpoints as needed to ensure that the indices at index_positions have a 0 high-order bit
  157. static void swap_indices(IntEndptsRGB_2 endpts[NREGIONS], int indices[Tile::TILE_H][Tile::TILE_W], int shapeindex)
  158. {
  159. for (int region = 0; region < NREGIONS; ++region)
  160. {
  161. int position = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,region);
  162. int x = POS_TO_X(position);
  163. int y = POS_TO_Y(position);
  164. nvAssert(REGION(x,y,shapeindex) == region); // double check the table
  165. if (indices[y][x] & HIGH_INDEXBIT)
  166. {
  167. // high bit is set, swap the endpts and indices for this region
  168. int t;
  169. for (int i=0; i<NCHANNELS_RGB; ++i)
  170. {
  171. t = endpts[region].A[i]; endpts[region].A[i] = endpts[region].B[i]; endpts[region].B[i] = t;
  172. }
  173. t = endpts[region].a_lsb; endpts[region].a_lsb = endpts[region].b_lsb; endpts[region].b_lsb = t;
  174. for (int y = 0; y < Tile::TILE_H; y++)
  175. for (int x = 0; x < Tile::TILE_W; x++)
  176. if (REGION(x,y,shapeindex) == region)
  177. indices[y][x] = NINDICES - 1 - indices[y][x];
  178. }
  179. }
  180. }
  181. static bool endpts_fit(IntEndptsRGB_2 endpts[NREGIONS], const Pattern &p)
  182. {
  183. return true;
  184. }
  185. static void write_header(const IntEndptsRGB_2 endpts[NREGIONS], int shapeindex, const Pattern &p, Bits &out)
  186. {
  187. out.write(p.mode, p.modebits);
  188. out.write(shapeindex, SHAPEBITS);
  189. for (int j=0; j<NCHANNELS_RGB; ++j)
  190. for (int i=0; i<NREGIONS; ++i)
  191. {
  192. out.write(endpts[i].A[j], p.chan[j].nbitsizes[ABITINDEX(i)]);
  193. out.write(endpts[i].B[j], p.chan[j].nbitsizes[BBITINDEX(i)]);
  194. }
  195. for (int i=0; i<NREGIONS; ++i)
  196. {
  197. out.write(endpts[i].a_lsb, 1);
  198. out.write(endpts[i].b_lsb, 1);
  199. }
  200. nvAssert (out.getptr() == 83);
  201. }
  202. static void read_header(Bits &in, IntEndptsRGB_2 endpts[NREGIONS], int &shapeindex, Pattern &p, int &pat_index)
  203. {
  204. int mode = AVPCL::getmode(in);
  205. pat_index = 0;
  206. nvAssert (pat_index >= 0 && pat_index < NPATTERNS);
  207. nvAssert (in.getptr() == patterns[pat_index].modebits);
  208. shapeindex = in.read(SHAPEBITS);
  209. p = patterns[pat_index];
  210. for (int j=0; j<NCHANNELS_RGB; ++j)
  211. for (int i=0; i<NREGIONS; ++i)
  212. {
  213. endpts[i].A[j] = in.read(p.chan[j].nbitsizes[ABITINDEX(i)]);
  214. endpts[i].B[j] = in.read(p.chan[j].nbitsizes[BBITINDEX(i)]);
  215. }
  216. for (int i=0; i<NREGIONS; ++i)
  217. {
  218. endpts[i].a_lsb = in.read(1);
  219. endpts[i].b_lsb = in.read(1);
  220. }
  221. nvAssert (in.getptr() == 83);
  222. }
  223. static void write_indices(const int indices[Tile::TILE_H][Tile::TILE_W], int shapeindex, Bits &out)
  224. {
  225. int positions[NREGIONS];
  226. for (int r = 0; r < NREGIONS; ++r)
  227. positions[r] = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,r);
  228. for (int pos = 0; pos < Tile::TILE_TOTAL; ++pos)
  229. {
  230. int x = POS_TO_X(pos);
  231. int y = POS_TO_Y(pos);
  232. bool match = false;
  233. for (int r = 0; r < NREGIONS; ++r)
  234. if (positions[r] == pos) { match = true; break; }
  235. out.write(indices[y][x], INDEXBITS - (match ? 1 : 0));
  236. }
  237. }
  238. static void read_indices(Bits &in, int shapeindex, int indices[Tile::TILE_H][Tile::TILE_W])
  239. {
  240. int positions[NREGIONS];
  241. for (int r = 0; r < NREGIONS; ++r)
  242. positions[r] = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,r);
  243. for (int pos = 0; pos < Tile::TILE_TOTAL; ++pos)
  244. {
  245. int x = POS_TO_X(pos);
  246. int y = POS_TO_Y(pos);
  247. bool match = false;
  248. for (int r = 0; r < NREGIONS; ++r)
  249. if (positions[r] == pos) { match = true; break; }
  250. indices[y][x]= in.read(INDEXBITS - (match ? 1 : 0));
  251. }
  252. }
  253. static void emit_block(const IntEndptsRGB_2 endpts[NREGIONS], int shapeindex, const Pattern &p, const int indices[Tile::TILE_H][Tile::TILE_W], char *block)
  254. {
  255. Bits out(block, AVPCL::BITSIZE);
  256. write_header(endpts, shapeindex, p, out);
  257. write_indices(indices, shapeindex, out);
  258. nvAssert(out.getptr() == AVPCL::BITSIZE);
  259. }
  260. static void generate_palette_quantized(const IntEndptsRGB_2 &endpts_2, const RegionPrec &region_prec, Vector4 palette[NINDICES])
  261. {
  262. IntEndptsRGB endpts;
  263. uncompress_one(endpts_2, endpts);
  264. // scale endpoints
  265. int a, b; // really need a IntVec4...
  266. a = Utils::unquantize(endpts.A[0], region_prec.endpt_a_prec[0]+1); // +1 since we are in uncompressed space
  267. b = Utils::unquantize(endpts.B[0], region_prec.endpt_b_prec[0]+1);
  268. // interpolate
  269. for (int i = 0; i < NINDICES; ++i)
  270. palette[i].x = float(Utils::lerp(a, b, i, BIAS, DENOM));
  271. a = Utils::unquantize(endpts.A[1], region_prec.endpt_a_prec[1]+1);
  272. b = Utils::unquantize(endpts.B[1], region_prec.endpt_b_prec[1]+1);
  273. // interpolate
  274. for (int i = 0; i < NINDICES; ++i)
  275. palette[i].y = float(Utils::lerp(a, b, i, BIAS, DENOM));
  276. a = Utils::unquantize(endpts.A[2], region_prec.endpt_a_prec[2]+1);
  277. b = Utils::unquantize(endpts.B[2], region_prec.endpt_b_prec[2]+1);
  278. // interpolate
  279. for (int i = 0; i < NINDICES; ++i)
  280. palette[i].z = float(Utils::lerp(a, b, i, BIAS, DENOM));
  281. // constant alpha
  282. for (int i = 0; i < NINDICES; ++i)
  283. palette[i].w = 255.0f;
  284. }
  285. static void sign_extend(Pattern &p, IntEndptsRGB_2 endpts[NREGIONS])
  286. {
  287. nvUnreachable();
  288. }
  289. void AVPCL::decompress_mode0(const char *block, Tile &t)
  290. {
  291. Bits in(block, AVPCL::BITSIZE);
  292. Pattern p;
  293. IntEndptsRGB_2 endpts[NREGIONS];
  294. int shapeindex, pat_index;
  295. read_header(in, endpts, shapeindex, p, pat_index);
  296. if (p.transformed)
  297. {
  298. sign_extend(p, endpts);
  299. transform_inverse(endpts);
  300. }
  301. Vector4 palette[NREGIONS][NINDICES];
  302. for (int r = 0; r < NREGIONS; ++r)
  303. generate_palette_quantized(endpts[r], pattern_precs[pat_index].region_precs[r], &palette[r][0]);
  304. int indices[Tile::TILE_H][Tile::TILE_W];
  305. read_indices(in, shapeindex, indices);
  306. nvAssert(in.getptr() == AVPCL::BITSIZE);
  307. // lookup
  308. for (int y = 0; y < Tile::TILE_H; y++)
  309. for (int x = 0; x < Tile::TILE_W; x++)
  310. t.data[y][x] = palette[REGION(x,y,shapeindex)][indices[y][x]];
  311. }
  312. // given a collection of colors and quantized endpoints, generate a palette, choose best entries, and return a single toterr
  313. static float map_colors(const Vector4 colors[], const float importance[], int np, const IntEndptsRGB_2 &endpts, const RegionPrec &region_prec, float current_err, int indices[Tile::TILE_TOTAL])
  314. {
  315. Vector4 palette[NINDICES];
  316. float toterr = 0;
  317. Vector4 err;
  318. generate_palette_quantized(endpts, region_prec, palette);
  319. for (int i = 0; i < np; ++i)
  320. {
  321. float besterr = FLT_MAX;
  322. for (int j = 0; j < NINDICES && besterr > 0; ++j)
  323. {
  324. float err = Utils::metric4(colors[i], palette[j]) * importance[i];
  325. if (err > besterr) // error increased, so we're done searching
  326. break;
  327. if (err < besterr)
  328. {
  329. besterr = err;
  330. indices[i] = j;
  331. }
  332. }
  333. toterr += besterr;
  334. // check for early exit
  335. if (toterr > current_err)
  336. {
  337. // fill out bogus index values so it's initialized at least
  338. for (int k = i; k < np; ++k)
  339. indices[k] = -1;
  340. return FLT_MAX;
  341. }
  342. }
  343. return toterr;
  344. }
  345. // assign indices given a tile, shape, and quantized endpoints, return toterr for each region
  346. static void assign_indices(const Tile &tile, int shapeindex, IntEndptsRGB_2 endpts[NREGIONS], const PatternPrec &pattern_prec,
  347. int indices[Tile::TILE_H][Tile::TILE_W], float toterr[NREGIONS])
  348. {
  349. // build list of possibles
  350. Vector4 palette[NREGIONS][NINDICES];
  351. for (int region = 0; region < NREGIONS; ++region)
  352. {
  353. generate_palette_quantized(endpts[region], pattern_prec.region_precs[region], &palette[region][0]);
  354. toterr[region] = 0;
  355. }
  356. Vector4 err;
  357. for (int y = 0; y < tile.size_y; y++)
  358. for (int x = 0; x < tile.size_x; x++)
  359. {
  360. int region = REGION(x,y,shapeindex);
  361. float err, besterr = FLT_MAX;
  362. for (int i = 0; i < NINDICES && besterr > 0; ++i)
  363. {
  364. err = Utils::metric4(tile.data[y][x], palette[region][i]);
  365. if (err > besterr) // error increased, so we're done searching
  366. break;
  367. if (err < besterr)
  368. {
  369. besterr = err;
  370. indices[y][x] = i;
  371. }
  372. }
  373. toterr[region] += besterr;
  374. }
  375. }
  376. // note: indices are valid only if the value returned is less than old_err; otherwise they contain -1's
  377. // this function returns either old_err or a value smaller (if it was successful in improving the error)
  378. static float perturb_one(const Vector4 colors[], const float importance[], int np, int ch, const RegionPrec &region_prec, const IntEndptsRGB_2 &old_endpts, IntEndptsRGB_2 &new_endpts,
  379. float old_err, int do_b, int indices[Tile::TILE_TOTAL])
  380. {
  381. // we have the old endpoints: old_endpts
  382. // we have the perturbed endpoints: new_endpts
  383. // we have the temporary endpoints: temp_endpts
  384. IntEndptsRGB_2 temp_endpts;
  385. float min_err = old_err; // start with the best current error
  386. int beststep;
  387. int temp_indices[Tile::TILE_TOTAL];
  388. for (int i=0; i<np; ++i)
  389. indices[i] = -1;
  390. // copy real endpoints so we can perturb them
  391. temp_endpts = new_endpts = old_endpts;
  392. int prec = do_b ? region_prec.endpt_b_prec[ch] : region_prec.endpt_a_prec[ch];
  393. // do a logarithmic search for the best error for this endpoint (which)
  394. for (int step = 1 << (prec-1); step; step >>= 1)
  395. {
  396. bool improved = false;
  397. for (int sign = -1; sign <= 1; sign += 2)
  398. {
  399. if (do_b == 0)
  400. {
  401. temp_endpts.A[ch] = new_endpts.A[ch] + sign * step;
  402. if (temp_endpts.A[ch] < 0 || temp_endpts.A[ch] >= (1 << prec))
  403. continue;
  404. }
  405. else
  406. {
  407. temp_endpts.B[ch] = new_endpts.B[ch] + sign * step;
  408. if (temp_endpts.B[ch] < 0 || temp_endpts.B[ch] >= (1 << prec))
  409. continue;
  410. }
  411. float err = map_colors(colors, importance, np, temp_endpts, region_prec, min_err, temp_indices);
  412. if (err < min_err)
  413. {
  414. improved = true;
  415. min_err = err;
  416. beststep = sign * step;
  417. for (int i=0; i<np; ++i)
  418. indices[i] = temp_indices[i];
  419. }
  420. }
  421. // if this was an improvement, move the endpoint and continue search from there
  422. if (improved)
  423. {
  424. if (do_b == 0)
  425. new_endpts.A[ch] += beststep;
  426. else
  427. new_endpts.B[ch] += beststep;
  428. }
  429. }
  430. return min_err;
  431. }
  432. // the larger the error the more time it is worth spending on an exhaustive search.
  433. // perturb the endpoints at least -3 to 3.
  434. // if err > 5000 perturb endpoints 50% of precision
  435. // if err > 1000 25%
  436. // if err > 200 12.5%
  437. // if err > 40 6.25%
  438. // for np = 16 -- adjust error thresholds as a function of np
  439. // always ensure endpoint ordering is preserved (no need to overlap the scan)
  440. // if orig_err returned from this is less than its input value, then indices[] will contain valid indices
  441. static float exhaustive(const Vector4 colors[], const float importance[], int np, int ch, const RegionPrec &region_prec, float &orig_err, IntEndptsRGB_2 &opt_endpts, int indices[Tile::TILE_TOTAL])
  442. {
  443. IntEndptsRGB_2 temp_endpts;
  444. float best_err = orig_err;
  445. int aprec = region_prec.endpt_a_prec[ch];
  446. int bprec = region_prec.endpt_b_prec[ch];
  447. int good_indices[Tile::TILE_TOTAL];
  448. int temp_indices[Tile::TILE_TOTAL];
  449. for (int i=0; i<np; ++i)
  450. indices[i] = -1;
  451. float thr_scale = (float)np / (float)Tile::TILE_TOTAL;
  452. if (orig_err == 0) return orig_err;
  453. int adelta = 0, bdelta = 0;
  454. if (orig_err > 5000.0*thr_scale) { adelta = (1 << aprec)/2; bdelta = (1 << bprec)/2; }
  455. else if (orig_err > 1000.0*thr_scale) { adelta = (1 << aprec)/4; bdelta = (1 << bprec)/4; }
  456. else if (orig_err > 200.0*thr_scale) { adelta = (1 << aprec)/8; bdelta = (1 << bprec)/8; }
  457. else if (orig_err > 40.0*thr_scale) { adelta = (1 << aprec)/16; bdelta = (1 << bprec)/16; }
  458. adelta = max(adelta, 3);
  459. bdelta = max(bdelta, 3);
  460. #ifdef DISABLE_EXHAUSTIVE
  461. adelta = bdelta = 3;
  462. #endif
  463. temp_endpts = opt_endpts;
  464. // ok figure out the range of A and B
  465. int alow = max(0, opt_endpts.A[ch] - adelta);
  466. int ahigh = min((1<<aprec)-1, opt_endpts.A[ch] + adelta);
  467. int blow = max(0, opt_endpts.B[ch] - bdelta);
  468. int bhigh = min((1<<bprec)-1, opt_endpts.B[ch] + bdelta);
  469. // now there's no need to swap the ordering of A and B
  470. bool a_le_b = opt_endpts.A[ch] <= opt_endpts.B[ch];
  471. int amin, bmin;
  472. if (opt_endpts.A[ch] <= opt_endpts.B[ch])
  473. {
  474. // keep a <= b
  475. for (int a = alow; a <= ahigh; ++a)
  476. for (int b = max(a, blow); b < bhigh; ++b)
  477. {
  478. temp_endpts.A[ch] = a;
  479. temp_endpts.B[ch] = b;
  480. float err = map_colors(colors, importance, np, temp_endpts, region_prec, best_err, temp_indices);
  481. if (err < best_err)
  482. {
  483. amin = a;
  484. bmin = b;
  485. best_err = err;
  486. for (int i=0; i<np; ++i)
  487. good_indices[i] = temp_indices[i];
  488. }
  489. }
  490. }
  491. else
  492. {
  493. // keep b <= a
  494. for (int b = blow; b < bhigh; ++b)
  495. for (int a = max(b, alow); a <= ahigh; ++a)
  496. {
  497. temp_endpts.A[ch] = a;
  498. temp_endpts.B[ch] = b;
  499. float err = map_colors(colors, importance, np, temp_endpts, region_prec, best_err, temp_indices);
  500. if (err < best_err)
  501. {
  502. amin = a;
  503. bmin = b;
  504. best_err = err;
  505. for (int i=0; i<np; ++i)
  506. good_indices[i] = temp_indices[i];
  507. }
  508. }
  509. }
  510. if (best_err < orig_err)
  511. {
  512. opt_endpts.A[ch] = amin;
  513. opt_endpts.B[ch] = bmin;
  514. orig_err = best_err;
  515. // if we actually improved, update the indices
  516. for (int i=0; i<np; ++i)
  517. indices[i] = good_indices[i];
  518. }
  519. return best_err;
  520. }
  521. static float optimize_one(const Vector4 colors[], const float importance[], int np, float orig_err, const IntEndptsRGB_2 &orig_endpts, const RegionPrec &region_prec, IntEndptsRGB_2 &opt_endpts)
  522. {
  523. float opt_err = orig_err;
  524. opt_endpts = orig_endpts;
  525. /*
  526. err0 = perturb(rgb0, delta0)
  527. err1 = perturb(rgb1, delta1)
  528. if (err0 < err1)
  529. if (err0 >= initial_error) break
  530. rgb0 += delta0
  531. next = 1
  532. else
  533. if (err1 >= initial_error) break
  534. rgb1 += delta1
  535. next = 0
  536. initial_err = map()
  537. for (;;)
  538. err = perturb(next ? rgb1:rgb0, delta)
  539. if (err >= initial_err) break
  540. next? rgb1 : rgb0 += delta
  541. initial_err = err
  542. */
  543. IntEndptsRGB_2 new_a, new_b;
  544. IntEndptsRGB_2 new_endpt;
  545. int do_b;
  546. int orig_indices[Tile::TILE_TOTAL];
  547. int new_indices[Tile::TILE_TOTAL];
  548. int temp_indices0[Tile::TILE_TOTAL];
  549. int temp_indices1[Tile::TILE_TOTAL];
  550. // now optimize each channel separately
  551. // for the first error improvement, we save the indices. then, for any later improvement, we compare the indices
  552. // if they differ, we restart the loop (which then falls back to looking for a first improvement.)
  553. for (int ch = 0; ch < NCHANNELS_RGB; ++ch)
  554. {
  555. // figure out which endpoint when perturbed gives the most improvement and start there
  556. // if we just alternate, we can easily end up in a local minima
  557. float err0 = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_a, opt_err, 0, temp_indices0); // perturb endpt A
  558. float err1 = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_b, opt_err, 1, temp_indices1); // perturb endpt B
  559. if (err0 < err1)
  560. {
  561. if (err0 >= opt_err)
  562. continue;
  563. for (int i=0; i<np; ++i)
  564. {
  565. new_indices[i] = orig_indices[i] = temp_indices0[i];
  566. nvAssert (orig_indices[i] != -1);
  567. }
  568. opt_endpts.A[ch] = new_a.A[ch];
  569. opt_err = err0;
  570. do_b = 1; // do B next
  571. }
  572. else
  573. {
  574. if (err1 >= opt_err)
  575. continue;
  576. for (int i=0; i<np; ++i)
  577. {
  578. new_indices[i] = orig_indices[i] = temp_indices1[i];
  579. nvAssert (orig_indices[i] != -1);
  580. }
  581. opt_endpts.B[ch] = new_b.B[ch];
  582. opt_err = err1;
  583. do_b = 0; // do A next
  584. }
  585. // now alternate endpoints and keep trying until there is no improvement
  586. for (;;)
  587. {
  588. float err = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_endpt, opt_err, do_b, temp_indices0);
  589. if (err >= opt_err)
  590. break;
  591. for (int i=0; i<np; ++i)
  592. {
  593. new_indices[i] = temp_indices0[i];
  594. nvAssert (new_indices[i] != -1);
  595. }
  596. if (do_b == 0)
  597. opt_endpts.A[ch] = new_endpt.A[ch];
  598. else
  599. opt_endpts.B[ch] = new_endpt.B[ch];
  600. opt_err = err;
  601. do_b = 1 - do_b; // now move the other endpoint
  602. }
  603. // see if the indices have changed
  604. int i;
  605. for (i=0; i<np; ++i)
  606. if (orig_indices[i] != new_indices[i])
  607. break;
  608. if (i<np)
  609. ch = -1; // start over
  610. }
  611. // finally, do a small exhaustive search around what we think is the global minima to be sure
  612. // note this is independent of the above search, so we don't care about the indices from the above
  613. // we don't care about the above because if they differ, so what? we've already started at ch=0
  614. bool first = true;
  615. for (int ch = 0; ch < NCHANNELS_RGB; ++ch)
  616. {
  617. float new_err = exhaustive(colors, importance, np, ch, region_prec, opt_err, opt_endpts, temp_indices0);
  618. if (new_err < opt_err)
  619. {
  620. opt_err = new_err;
  621. if (first)
  622. {
  623. for (int i=0; i<np; ++i)
  624. {
  625. orig_indices[i] = temp_indices0[i];
  626. nvAssert (orig_indices[i] != -1);
  627. }
  628. first = false;
  629. }
  630. else
  631. {
  632. // see if the indices have changed
  633. int i;
  634. for (i=0; i<np; ++i)
  635. if (orig_indices[i] != temp_indices0[i])
  636. break;
  637. if (i<np)
  638. {
  639. ch = -1; // start over
  640. first = true;
  641. }
  642. }
  643. }
  644. }
  645. return opt_err;
  646. }
  647. // this will return a valid set of endpoints in opt_endpts regardless of whether it improve orig_endpts or not
  648. static void optimize_endpts(const Tile &tile, int shapeindex, const float orig_err[NREGIONS],
  649. const IntEndptsRGB_2 orig_endpts[NREGIONS], const PatternPrec &pattern_prec, float opt_err[NREGIONS], IntEndptsRGB_2 opt_endpts[NREGIONS])
  650. {
  651. Vector4 pixels[Tile::TILE_TOTAL];
  652. float importance[Tile::TILE_TOTAL];
  653. IntEndptsRGB_2 temp_in, temp_out;
  654. int temp_indices[Tile::TILE_TOTAL];
  655. for (int region=0; region<NREGIONS; ++region)
  656. {
  657. // collect the pixels in the region
  658. int np = 0;
  659. for (int y = 0; y < tile.size_y; y++) {
  660. for (int x = 0; x < tile.size_x; x++) {
  661. if (REGION(x, y, shapeindex) == region) {
  662. pixels[np] = tile.data[y][x];
  663. importance[np] = tile.importance_map[y][x];
  664. np++;
  665. }
  666. }
  667. }
  668. opt_endpts[region] = temp_in = orig_endpts[region];
  669. opt_err[region] = orig_err[region];
  670. float best_err = orig_err[region];
  671. for (int lsbmode=0; lsbmode<NLSBMODES; ++lsbmode)
  672. {
  673. temp_in.a_lsb = lsbmode & 1;
  674. temp_in.b_lsb = (lsbmode >> 1) & 1;
  675. // make sure we have a valid error for temp_in
  676. // we use FLT_MAX here because we want an accurate temp_in_err, no shortcuts
  677. // (mapcolors will compute a mapping but will stop if the error exceeds the value passed in the FLT_MAX position)
  678. float temp_in_err = map_colors(pixels, importance, np, temp_in, pattern_prec.region_precs[region], FLT_MAX, temp_indices);
  679. // now try to optimize these endpoints
  680. float temp_out_err = optimize_one(pixels, importance, np, temp_in_err, temp_in, pattern_prec.region_precs[region], temp_out);
  681. // if we find an improvement, update the best so far and correct the output endpoints and errors
  682. if (temp_out_err < best_err)
  683. {
  684. best_err = temp_out_err;
  685. opt_err[region] = temp_out_err;
  686. opt_endpts[region] = temp_out;
  687. }
  688. }
  689. }
  690. }
  691. /* optimization algorithm
  692. for each pattern
  693. convert endpoints using pattern precision
  694. assign indices and get initial error
  695. compress indices (and possibly reorder endpoints)
  696. transform endpoints
  697. if transformed endpoints fit pattern
  698. get original endpoints back
  699. optimize endpoints, get new endpoints, new indices, and new error // new error will almost always be better
  700. compress new indices
  701. transform new endpoints
  702. if new endpoints fit pattern AND if error is improved
  703. emit compressed block with new data
  704. else
  705. emit compressed block with original data // to try to preserve maximum endpoint precision
  706. */
  707. static float refine(const Tile &tile, int shapeindex_best, const FltEndpts endpts[NREGIONS], char *block)
  708. {
  709. float orig_err[NREGIONS], opt_err[NREGIONS], orig_toterr, opt_toterr, expected_opt_err[NREGIONS];
  710. IntEndptsRGB_2 orig_endpts[NREGIONS], opt_endpts[NREGIONS];
  711. int orig_indices[Tile::TILE_H][Tile::TILE_W], opt_indices[Tile::TILE_H][Tile::TILE_W];
  712. for (int sp = 0; sp < NPATTERNS; ++sp)
  713. {
  714. quantize_endpts(endpts, pattern_precs[sp], orig_endpts);
  715. assign_indices(tile, shapeindex_best, orig_endpts, pattern_precs[sp], orig_indices, orig_err);
  716. swap_indices(orig_endpts, orig_indices, shapeindex_best);
  717. if (patterns[sp].transformed)
  718. transform_forward(orig_endpts);
  719. // apply a heuristic here -- we check if the endpoints fit before we try to optimize them.
  720. // the assumption made is that if they don't fit now, they won't fit after optimizing.
  721. if (endpts_fit(orig_endpts, patterns[sp]))
  722. {
  723. if (patterns[sp].transformed)
  724. transform_inverse(orig_endpts);
  725. optimize_endpts(tile, shapeindex_best, orig_err, orig_endpts, pattern_precs[sp], expected_opt_err, opt_endpts);
  726. assign_indices(tile, shapeindex_best, opt_endpts, pattern_precs[sp], opt_indices, opt_err);
  727. // (nreed) Commented out asserts because they go off all the time...not sure why
  728. //for (int i=0; i<NREGIONS; ++i)
  729. // nvAssert(expected_opt_err[i] == opt_err[i]);
  730. swap_indices(opt_endpts, opt_indices, shapeindex_best);
  731. if (patterns[sp].transformed)
  732. transform_forward(opt_endpts);
  733. orig_toterr = opt_toterr = 0;
  734. for (int i=0; i < NREGIONS; ++i) { orig_toterr += orig_err[i]; opt_toterr += opt_err[i]; }
  735. if (endpts_fit(opt_endpts, patterns[sp]) && opt_toterr < orig_toterr)
  736. {
  737. emit_block(opt_endpts, shapeindex_best, patterns[sp], opt_indices, block);
  738. return opt_toterr;
  739. }
  740. else
  741. {
  742. // either it stopped fitting when we optimized it, or there was no improvement
  743. // so go back to the unoptimized endpoints which we know will fit
  744. if (patterns[sp].transformed)
  745. transform_forward(orig_endpts);
  746. emit_block(orig_endpts, shapeindex_best, patterns[sp], orig_indices, block);
  747. return orig_toterr;
  748. }
  749. }
  750. }
  751. nvAssert(false); // throw "No candidate found, should never happen (mode avpcl 0).";
  752. return FLT_MAX;
  753. }
  754. static void clamp(Vector4 &v)
  755. {
  756. if (v.x < 0.0f) v.x = 0.0f;
  757. if (v.x > 255.0f) v.x = 255.0f;
  758. if (v.y < 0.0f) v.y = 0.0f;
  759. if (v.y > 255.0f) v.y = 255.0f;
  760. if (v.z < 0.0f) v.z = 0.0f;
  761. if (v.z > 255.0f) v.z = 255.0f;
  762. v.w = 255.0f;
  763. }
  764. static void generate_palette_unquantized(const FltEndpts endpts[NREGIONS], Vector4 palette[NREGIONS][NINDICES])
  765. {
  766. for (int region = 0; region < NREGIONS; ++region)
  767. for (int i = 0; i < NINDICES; ++i)
  768. palette[region][i] = Utils::lerp(endpts[region].A, endpts[region].B, i, 0, DENOM);
  769. }
  770. // generate a palette from unquantized endpoints, then pick best palette color for all pixels in each region, return toterr for all regions combined
  771. static float map_colors(const Tile &tile, int shapeindex, const FltEndpts endpts[NREGIONS])
  772. {
  773. // build list of possibles
  774. Vector4 palette[NREGIONS][NINDICES];
  775. generate_palette_unquantized(endpts, palette);
  776. float toterr = 0;
  777. Vector4 err;
  778. for (int y = 0; y < tile.size_y; y++)
  779. for (int x = 0; x < tile.size_x; x++)
  780. {
  781. int region = REGION(x,y,shapeindex);
  782. float err, besterr = FLT_MAX;
  783. for (int i = 0; i < NINDICES && besterr > 0; ++i)
  784. {
  785. err = Utils::metric4(tile.data[y][x], palette[region][i]);
  786. if (err > besterr) // error increased, so we're done searching. this works for most norms.
  787. break;
  788. if (err < besterr)
  789. besterr = err;
  790. }
  791. toterr += besterr;
  792. }
  793. return toterr;
  794. }
  795. // for this mode, we assume alpha = 255 constant and compress only the RGB portion.
  796. // however, we do the error check against the actual alpha values supplied for the tile.
  797. static float rough(const Tile &tile, int shapeindex, FltEndpts endpts[NREGIONS])
  798. {
  799. for (int region=0; region<NREGIONS; ++region)
  800. {
  801. int np = 0;
  802. Vector3 colors[Tile::TILE_TOTAL];
  803. float alphas[2];
  804. Vector4 mean(0,0,0,0);
  805. for (int y = 0; y < tile.size_y; y++)
  806. for (int x = 0; x < tile.size_x; x++)
  807. if (REGION(x,y,shapeindex) == region)
  808. {
  809. colors[np] = tile.data[y][x].xyz();
  810. if (np < 2) alphas[np] = tile.data[y][x].w;
  811. mean += tile.data[y][x];
  812. ++np;
  813. }
  814. // handle simple cases
  815. if (np == 0)
  816. {
  817. Vector4 zero(0,0,0,255.0f);
  818. endpts[region].A = zero;
  819. endpts[region].B = zero;
  820. continue;
  821. }
  822. else if (np == 1)
  823. {
  824. endpts[region].A = Vector4(colors[0], alphas[0]);
  825. endpts[region].B = Vector4(colors[0], alphas[0]);
  826. continue;
  827. }
  828. else if (np == 2)
  829. {
  830. endpts[region].A = Vector4(colors[0], alphas[0]);
  831. endpts[region].B = Vector4(colors[1], alphas[1]);
  832. continue;
  833. }
  834. mean /= float(np);
  835. Vector3 direction = Fit::computePrincipalComponent_EigenSolver(np, colors);
  836. // project each pixel value along the principal direction
  837. float minp = FLT_MAX, maxp = -FLT_MAX;
  838. for (int i = 0; i < np; i++)
  839. {
  840. float dp = dot(colors[i]-mean.xyz(), direction);
  841. if (dp < minp) minp = dp;
  842. if (dp > maxp) maxp = dp;
  843. }
  844. // choose as endpoints 2 points along the principal direction that span the projections of all of the pixel values
  845. endpts[region].A = mean + minp*Vector4(direction, 0);
  846. endpts[region].B = mean + maxp*Vector4(direction, 0);
  847. // clamp endpoints
  848. // the argument for clamping is that the actual endpoints need to be clamped and thus we need to choose the best
  849. // shape based on endpoints being clamped
  850. clamp(endpts[region].A);
  851. clamp(endpts[region].B);
  852. }
  853. return map_colors(tile, shapeindex, endpts);
  854. }
  855. static void swap(float *list1, int *list2, int i, int j)
  856. {
  857. float t = list1[i]; list1[i] = list1[j]; list1[j] = t;
  858. int t1 = list2[i]; list2[i] = list2[j]; list2[j] = t1;
  859. }
  860. float AVPCL::compress_mode0(const Tile &t, char *block)
  861. {
  862. // number of rough cases to look at. reasonable values of this are 1, NSHAPES/4, and NSHAPES
  863. // NSHAPES/4 gets nearly all the cases; you can increase that a bit (say by 3 or 4) if you really want to squeeze the last bit out
  864. const int NITEMS=NSHAPES/4;
  865. // pick the best NITEMS shapes and refine these.
  866. struct {
  867. FltEndpts endpts[NREGIONS];
  868. } all[NSHAPES];
  869. float roughmse[NSHAPES];
  870. int index[NSHAPES];
  871. char tempblock[AVPCL::BLOCKSIZE];
  872. float msebest = FLT_MAX;
  873. for (int i=0; i<NSHAPES; ++i)
  874. {
  875. roughmse[i] = rough(t, i, &all[i].endpts[0]);
  876. index[i] = i;
  877. }
  878. // bubble sort -- only need to bubble up the first NITEMS items
  879. for (int i=0; i<NITEMS; ++i)
  880. for (int j=i+1; j<NSHAPES; ++j)
  881. if (roughmse[i] > roughmse[j])
  882. swap(roughmse, index, i, j);
  883. for (int i=0; i<NITEMS && msebest>0; ++i)
  884. {
  885. int shape = index[i];
  886. float mse = refine(t, shape, &all[shape].endpts[0], tempblock);
  887. if (mse < msebest)
  888. {
  889. memcpy(block, tempblock, sizeof(tempblock));
  890. msebest = mse;
  891. }
  892. }
  893. return msebest;
  894. }