avpcl_mode1.cpp 30 KB

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