Debian Codegraph @

common/2d/rle.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Routines to do run length encoding/decoding
23 * on bitmaps.
24 *
25 */
26
27 #include <algorithm>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31
32 #include "pstypes.h"
33 #include "u_mem.h"
34 #include "gr.h"
35 #include "dxxerror.h"
36 #include "rle.h"
37 #include "byteutil.h"
38
39 #include "compiler-range_for.h"
40 #include "d_range.h"
41
42 namespace dcx {
43
44 namespace {
45
46 struct rle_cache_element
47 {
48 const grs_bitmap *rle_bitmap;
49 grs_bitmap_ptr expanded_bitmap;
50 int last_used;
51 };
52
53 constexpr uint8_t RLE_CODE{0xe0};
54 constexpr uint8_t NOT_RLE_CODE{0x1f};
55 static_assert((RLE_CODE | NOT_RLE_CODE) == 0xff, "RLE mask error");
56
57 static uint8_t rle_cache_initialized;
58 static int rle_counter;
59 static int rle_next;
60
61 static std::array<rle_cache_element, 32> rle_cache;
62
63 static inline int IS_RLE_CODE(const uint8_t &x)
64 {
65 return (x & RLE_CODE) == RLE_CODE;
66 }
67
68 union rle_size_pun {
69 uint8_t *rle_little;
70 uint16_t *rle_big;
71 };
72
73 }
74 #define rle_stosb(_dest, _len, _color) memset(_dest,_color,_len)
75
76 uint8_t *gr_rle_decode(const color_palette_index *sb, color_palette_index *db, const rle_position_t e)
77 {
78 using std::advance;
79 using std::distance;
80 for (; sb != e.src;)
81 {
82 auto p{sb};
83 color_palette_index c;
84 for (; c = *p, !IS_RLE_CODE(c);)
85 if (++p == e.src)
86 return db;
87 const size_t count{(size_t{c} & NOT_RLE_CODE)};
88 const size_t cn{std::min<size_t>(distance(sb, p), distance(db, e.dst))};
89 memcpy(db, sb, cn);
90 advance(db, cn);
91 if (!count)
92 break;
93 advance(sb, cn);
94 if (sb == e.src || db == e.dst || count > static_cast<size_t>(distance(db, e.dst)))
95 break;
96 if (++ sb == e.src)
97 break;
98 std::fill_n(db, count, *sb++);
99 advance(db, count);
100 }
101 return db;
102 }
103
104 #if !DXX_USE_OGL
105 // Given pointer to start of one scanline of rle data, uncompress it to
106 // dest, from source pixels x1 to x2.
107 void gr_rle_expand_scanline_masked(uint8_t *dest, const uint8_t *src, const uint_fast32_t x1, const uint_fast32_t x2)
108 {
109 int i{0};
110 ubyte count;
111 uint8_t color{0};
112
113 if ( x2 < x1 ) return;
114
115 count = 0;
116 while ( i < x1 ) {
117 color = *src++;
118 if ( color == RLE_CODE ) return;
119 if ( IS_RLE_CODE(color) ) {
120 count = color & NOT_RLE_CODE;
121 color = *src++;
122 } else {
123 // unique
124 count = 1;
125 }
126 i += count;
127 }
128 count = i - x1;
129 i = x1;
130 // we know have '*count' pixels of 'color'.
131
132 if ( x1+count > x2 ) {
133 count = x2-x1+1;
134 if ( color != TRANSPARENCY_COLOR ) rle_stosb( dest, count, color );
135 return;
136 }
137
138 if ( color != TRANSPARENCY_COLOR ) rle_stosb( dest, count, color );
139 dest += count;
140 i += count;
141
142 while( i <= x2 )
143 {
144 color = *src++;
145 if ( color == RLE_CODE ) return;
146 if ( IS_RLE_CODE(color) ) {
147 count = color & NOT_RLE_CODE;
148 color = *src++;
149 } else {
150 // unique
151 count = 1;
152 }
153 // we know have '*count' pixels of 'color'.
154 if ( i+count <= x2 ) {
155 } else {
156 count = x2-i+1;
157 }
158 if ( color != 255 )rle_stosb( dest, count, color );
159 i += count;
160 dest += count;
161 }
162 }
163 #endif
164
165 void gr_rle_expand_scanline(uint8_t *dest, const uint8_t *src, const uint_fast32_t x1, const uint_fast32_t x2)
166 {
167 int i{0};
168 ubyte count;
169 uint8_t color{0};
170
171 if ( x2 < x1 ) return;
172
173 count = 0;
174 while ( i < x1 ) {
175 color = *src++;
176 if ( color == RLE_CODE ) return;
177 if ( IS_RLE_CODE(color) ) {
178 count = color & NOT_RLE_CODE;
179 color = *src++;
180 } else {
181 // unique
182 count = 1;
183 }
184 i += count;
185 }
186 count = i - x1;
187 i = x1;
188 // we know have '*count' pixels of 'color'.
189
190 if ( x1+count > x2 ) {
191 count = x2-x1+1;
192 rle_stosb( dest, count, color );
193 return;
194 }
195
196 rle_stosb( dest, count, color );
197 dest += count;
198 i += count;
199
200 while( i <= x2 ) {
201 auto color{*src++};
202 if ( color == RLE_CODE ) return;
203 if ( IS_RLE_CODE(color) ) {
204 count = color & (~RLE_CODE);
205 color = *src++;
206 } else {
207 // unique
208 count = 1;
209 }
210 // we know have '*count' pixels of 'color'.
211 if ( i+count <= x2 ) {
212 } else {
213 count = x2-i+1;
214 }
215 rle_stosb(dest, count, color);
216 i += count;
217 dest += count;
218 }
219 }
220
221 namespace {
222
223 static std::ptrdiff_t gr_rle_encode(const uint_fast32_t org_size, const uint8_t *src, uint8_t *dest)
224 {
225 if (!org_size)
226 return 0;
227 const auto dest_start{dest};
228 /* The value of count ranges from [1, (NOT_RLE_CODE - 1)], so uint8_t
229 * is sufficient to hold all values.
230 */
231 uint8_t count{1};
232 const auto flush_pending_rle_record{[&](uint8_t previous_data_byte) {
233 if (!count)
234 return;
235 /* If the count is not 1, then the count must be recorded in the
236 * stream.
237 * If the count is 1, and the data byte will be mistaken for a
238 * count, then the count of 1 must be recorded to escape the
239 * value of the data byte.
240 * Otherwise, write only the data byte.
241 */
242 if (count != 1 || IS_RLE_CODE(previous_data_byte))
243 *dest++ = count | RLE_CODE;
244 *dest++ = previous_data_byte;
245 }};
246
247 auto oc{*src++};
248 for (const auto i : xrange(org_size - 1, std::integral_constant<uint_fast32_t, 0u>(), xrange_descending()))
249 {
250 (void)i;
251 if (const auto c{*src++}; c != oc)
252 {
253 flush_pending_rle_record(std::exchange(oc, c));
254 count = 0;
255 }
256 count++;
257 if ( count == NOT_RLE_CODE ) {
258 /* If count goes any higher, it cannot be recorded properly,
259 * so record it now and reset the count. This code path
260 * would be hit for a long run of the same data value.
261 */
262 count |= RLE_CODE;
263 *dest++=count;
264 *dest++=oc;
265 count = 0;
266 }
267 }
268 flush_pending_rle_record(oc);
269 *dest++ = RLE_CODE;
270
271 return std::distance(dest_start, dest);
272 }
273
274 static unsigned gr_rle_getsize(const uint_fast32_t org_size, const uint8_t *src, const unsigned limit)
275 {
276 if (!org_size)
277 return 2;
278 unsigned dest_size{0};
279
280 uint8_t count{1};
281 const auto flush_pending_rle_record{[&](uint8_t previous_data_byte) {
282 if (!count)
283 return;
284 if (count != 1 || IS_RLE_CODE(previous_data_byte))
285 dest_size += 2;
286 else
287 ++ dest_size;
288 }};
289
290 auto oc{*src++};
291 for (const auto i : xrange(org_size - 1, std::integral_constant<uint_fast32_t, 0u>(), xrange_descending()))
292 {
293 (void)i;
294 if (const auto c{*src++}; c != oc)
295 {
296 flush_pending_rle_record(std::exchange(oc, c));
297 if (dest_size > limit)
298 return dest_size;
299 count = 0;
300 }
301 count++;
302 if ( count == NOT_RLE_CODE ) {
303 dest_size++;
304 dest_size++;
305 if (dest_size > limit)
306 return dest_size;
307 count = 0;
308 }
309 }
310 flush_pending_rle_record(oc);
311 dest_size++;
312 return dest_size;
313 }
314
315 }
316
317 void gr_bitmap_rle_compress(grs_bitmap &bmp)
318 {
319 if (bmp.get_flag_mask(BM_FLAG_PAGED_OUT))
320 return;
321 int doffset;
322
323 // first must check to see if this is large bitmap.
324
325 const uint_fast32_t bm_h{bmp.bm_h};
326 const uint_fast32_t bm_w{bmp.bm_w};
327 const auto large_rle{[&]() {
328 /* For each row, scan the contents of the row to determine how many
329 * bytes would be needed to RLE encode that row.
330 */
331 for (const uint_fast32_t y : xrange(bm_h))
332 {
333 constexpr unsigned limit{UINT8_MAX};
334 const auto d1{gr_rle_getsize(bm_w, &bmp.get_bitmap_data()[bm_w * y], limit)};
335 if (d1 > limit)
336 /* This row would need more bytes than can be recorded in a
337 * non-big RLE encoded bitmap, so switch to big mode.
338 * Once one row needs big mode, the entire bitmap will use
339 * big mode, so skip scanning any remaining rows.
340 */
341 return BM_FLAG_RLE_BIG;
342 }
343 /* Every row was checked and none required big mode, so use
344 * non-big mode.
345 */
346 return 0;
347 }()};
348
349 const auto rle_data{std::make_unique_for_overwrite<uint8_t[]>(MAX_BMP_SIZE(bm_w, bm_h))};
350 if (!large_rle)
351 doffset = 4 + bm_h;
352 else
353 doffset = 4 + (2 * bm_h); // each row of rle'd bitmap has short instead of byte offset now
354
355 const unsigned rle_size_limit{(large_rle ? 32767u : 255u)};
356 const rle_size_pun dst_line_size_ptr{&rle_data[4]};
357 range_for (const uint_fast32_t y, xrange(bm_h))
358 {
359 const auto d1{gr_rle_getsize(bm_w, &bmp.get_bitmap_data()[bm_w * y], rle_size_limit)};
360 if (d1 > rle_size_limit || doffset + d1 > bm_w * bm_h)
361 /* Encoding this row requires more space than was allocated.
362 * This bitmap is smaller when not encoded, so return and
363 * leave it in its original unencoded form.
364 *
365 * This could happen if the bitmap had a long run of
366 * varying colors, with each color encoded as a 1 byte long
367 * run.
368 */
369 return;
370 const auto d{gr_rle_encode(bmp.bm_w, &bmp.get_bitmap_data()[bmp.bm_w*y], &rle_data[doffset])};
371 Assert( d==d1 );
372 doffset += d;
373 if (large_rle)
374 PUT_INTEL_SHORT(&dst_line_size_ptr.rle_big[y], static_cast<uint16_t>(d));
375 else
376 dst_line_size_ptr.rle_little[y] = static_cast<uint8_t>(d);
377 }
378 memcpy(bmp.get_bitmap_data(), &doffset, 4);
379 memcpy(&bmp.get_bitmap_data()[4], &rle_data.get()[4], doffset - 4);
380 bmp.add_flags(BM_FLAG_RLE | large_rle);
381 }
382
383 namespace {
384
385 static void rle_cache_init()
386 {
387 rle_cache = {};
388 rle_cache_initialized = 1;
389 }
390
391 }
392
393 void rle_cache_close(void)
394 {
395 if (rle_cache_initialized) {
396 rle_cache_initialized = 0;
397 range_for (auto &i, rle_cache)
398 i.expanded_bitmap.reset();
399 }
400 }
401
402 void rle_cache_flush()
403 {
404 range_for (auto &i, rle_cache)
405 {
406 i.rle_bitmap = NULL;
407 i.last_used = 0;
408 }
409 }
410
411 namespace {
412
413 static void rle_expand_texture_sub(const grs_bitmap &bmp, grs_bitmap &rle_temp_bitmap_1)
414 {
415 auto sbits{&bmp.get_bitmap_data()[4 + bmp.bm_h]};
416 auto dbits{rle_temp_bitmap_1.get_bitmap_data()};
417
418 rle_temp_bitmap_1.set_flags(bmp.get_flags() & (~BM_FLAG_RLE));
419
420 for (int i{0}; i < bmp.bm_h; i++ ) {
421 gr_rle_decode(sbits, dbits, rle_end(bmp, rle_temp_bitmap_1));
422 sbits += static_cast<int>(bmp.bm_data[4+i]);
423 dbits += bmp.bm_w;
424 }
425 }
426
427 }
428
429 grs_bitmap *_rle_expand_texture(const grs_bitmap &bmp)
430 {
431 int lowest_count, lc;
432
433 if (!rle_cache_initialized) rle_cache_init();
434
435 Assert(!(bmp.get_flag_mask(BM_FLAG_PAGED_OUT)));
436
437 lc = rle_counter;
438 rle_counter++;
439
440 if (rle_counter < 0)
441 rle_counter = 0;
442
443 if ( rle_counter < lc ) {
444 rle_cache_flush();
445 }
446
447 lowest_count = rle_cache[rle_next].last_used;
448 auto least_recently_used{&rle_cache[rle_next]};
449 rle_next++;
450 if (rle_next >= rle_cache.size())
451 rle_next = 0;
452
453 range_for (auto &i, rle_cache)
454 {
455 if (i.rle_bitmap == &bmp)
456 {
457 i.last_used = rle_counter;
458 return i.expanded_bitmap.get();
459 }
460 if (i.last_used < lowest_count)
461 {
462 lowest_count = (least_recently_used = &i)->last_used;
463 }
464 }
465
466 least_recently_used->expanded_bitmap = gr_create_bitmap(bmp.bm_w, bmp.bm_h);
467 rle_expand_texture_sub(bmp, *least_recently_used->expanded_bitmap.get());
468 least_recently_used->rle_bitmap = &bmp;
469 least_recently_used->last_used = rle_counter;
470 return least_recently_used->expanded_bitmap.get();
471 }
472
473 #if !DXX_USE_OGL
474 void gr_rle_expand_scanline_generic(grs_canvas &canvas, grs_bitmap &dest, int dx, const int dy, const uint8_t *src, const int x1, const int x2)
475 {
476 int i{0};
477 int count;
478 uint8_t color{0};
479
480 if ( x2 < x1 ) return;
481
482 count = 0;
483 while ( i < x1 ) {
484 color = *src++;
485 if ( color == RLE_CODE ) return;
486 if ( IS_RLE_CODE(color) ) {
487 count = color & NOT_RLE_CODE;
488 color = *src++;
489 } else {
490 // unique
491 count = 1;
492 }
493 i += count;
494 }
495 count = i - x1;
496 i = x1;
497 // we know have '*count' pixels of 'color'.
498
499 if ( x1+count > x2 ) {
500 count = x2-x1+1;
501 for (int j{0}; j < count; ++j)
502 gr_bm_pixel(canvas, dest, dx++, dy, color);
503 return;
504 }
505
506 for (int j{0}; j < count; ++j)
507 gr_bm_pixel(canvas, dest, dx++, dy, color);
508 i += count;
509
510 while( i <= x2 ) {
511 color = *src++;
512 if ( color == RLE_CODE ) return;
513 if ( IS_RLE_CODE(color) ) {
514 count = color & NOT_RLE_CODE;
515 color = *src++;
516 } else {
517 // unique
518 count = 1;
519 }
520 // we know have '*count' pixels of 'color'.
521 if ( i+count <= x2 ) {
522 } else {
523 count = x2-i+1;
524 }
525 for (unsigned j{0}; j < count; ++j)
526 gr_bm_pixel(canvas, dest, dx++, dy, color);
527 i += count;
528 }
529 }
530 #endif
531
532 /*
533 * swaps entries 0 and 255 in an RLE bitmap without uncompressing it
534 */
535 void rle_swap_0_255(grs_bitmap &bmp)
536 {
537 int len, rle_big;
538 unsigned char *start;
539 unsigned short line_size;
540
541 rle_big = bmp.get_flag_mask(BM_FLAG_RLE_BIG);
542
543 const auto temp{std::make_unique_for_overwrite<uint8_t[]>(MAX_BMP_SIZE(bmp.bm_w, bmp.bm_h))};
544
545 const std::size_t pointer_offset{rle_big ? 4u + 2u * unsigned{bmp.bm_h} : 4u + unsigned{bmp.bm_h}};
546 auto ptr{&bmp.bm_data[pointer_offset]};
547 auto ptr2{&temp[pointer_offset]};
548 const rle_size_pun src_line_size_ptr{&bmp.get_bitmap_data()[4]},
549 dst_line_size_ptr{&temp[4]};
550 for (int i{0}; i < bmp.bm_h; i++) {
551 start = ptr2;
552 if (rle_big)
553 line_size = GET_INTEL_SHORT(&src_line_size_ptr.rle_big[i]);
554 else
555 line_size = src_line_size_ptr.rle_little[i];
556 for (int j{0}; j < line_size; j++) {
557 if ( ! IS_RLE_CODE(ptr[j]) ) {
558 if (ptr[j] == 0) {
559 *ptr2++ = RLE_CODE | 1;
560 *ptr2++ = 255;
561 } else
562 *ptr2++ = ptr[j];
563 } else {
564 *ptr2++ = ptr[j];
565 if ((ptr[j] & NOT_RLE_CODE) == 0)
566 break;
567 j++;
568 if (ptr[j] == 0)
569 *ptr2++ = 255;
570 else if (ptr[j] == 255)
571 *ptr2++ = 0;
572 else
573 *ptr2++ = ptr[j];
574 }
575 }
576 const auto dst_line_size{std::distance(start, ptr2)};
577 if (rle_big) // set line size
578 PUT_INTEL_SHORT(&dst_line_size_ptr.rle_big[i], static_cast<uint16_t>(dst_line_size));
579 else
580 dst_line_size_ptr.rle_little[i] = static_cast<uint8_t>(dst_line_size);
581 ptr += line_size; // go to next line
582 }
583 len = ptr2 - temp.get();
584 memcpy(bmp.get_bitmap_data(), &len, 4);
585 memcpy(&bmp.get_bitmap_data()[4], &temp.get()[4], len - 4);
586 }
587
588 /*
589 * remaps all entries using colormap in an RLE bitmap without uncompressing it
590 */
591 void rle_remap(grs_bitmap &bmp, const std::array<color_palette_index, 256> &colormap)
592 {
593 int len;
594
595 const auto rle_big{bmp.get_flag_mask(BM_FLAG_RLE_BIG)};
596 const auto temp{std::make_unique_for_overwrite<color_palette_index[]>(MAX_BMP_SIZE(bmp.bm_w, bmp.bm_h) + 30000)};
597
598 const std::size_t pointer_offset{rle_big ? 4u + 2u * unsigned{bmp.bm_h} : 4u + unsigned{bmp.bm_h}};
599 auto ptr{&bmp.get_bitmap_data()[pointer_offset]};
600 auto ptr2{&temp[pointer_offset]};
601 const rle_size_pun src_line_size_ptr{&bmp.get_bitmap_data()[4]},
602 dst_line_size_ptr{&temp[4]};
603 for (int i{0}; i < bmp.bm_h; ++i)
604 {
605 auto start{ptr2};
606 const uint16_t line_size{
607 rle_big
608 ? GET_INTEL_SHORT(&src_line_size_ptr.rle_big[i])
609 : uint16_t{src_line_size_ptr.rle_little[i]}
610 };
611 for (int j{0}; j < line_size; j++) {
612 const uint8_t v{ptr[j]};
613 if (!IS_RLE_CODE(v))
614 {
615 if (IS_RLE_CODE(colormap[v]))
616 *ptr2++ = color_palette_index{RLE_CODE | 1}; // add "escape sequence"
617 *ptr2++ = colormap[v]; // translate
618 } else {
619 *ptr2++ = ptr[j]; // just copy current rle code
620 if ((ptr[j] & NOT_RLE_CODE) == 0)
621 break;
622 j++;
623 *ptr2++ = colormap[ptr[j]]; // translate
624 }
625 }
626 const auto dst_line_size{std::distance(start, ptr2)};
627 if (rle_big) // set line size
628 PUT_INTEL_SHORT(&dst_line_size_ptr.rle_big[i], static_cast<uint16_t>(dst_line_size));
629 else
630 dst_line_size_ptr.rle_little[i] = static_cast<uint8_t>(dst_line_size);
631 ptr += line_size; // go to next line
632 }
633 len = ptr2 - temp.get();
634 memcpy(bmp.get_bitmap_data(), &len, 4);
635 memcpy(&bmp.get_bitmap_data()[4], &temp.get()[4], len - 4);
636 }
637
638 void bm_rle_src_stride::advance_src_bits()
639 {
640 /* Both bytes are always legal to read since the bitmap data
641 * is placed after the length table. Reading both, then
642 * conditionally masking out the high bits (dependent on
643 * BM_FLAG_RLE_BIG) encourages the compiler to implement
644 * this line without using branches.
645 */
646 const uintptr_t u{(ptr_src_bit_lengths[0] | (static_cast<uintptr_t>(ptr_src_bit_lengths[1]) << 8)) & src_bit_load_mask};
647 ptr_src_bit_lengths += src_bit_stride_size;
648 src_bits += u;
649 }
650
651 bm_rle_expand::step_result bm_rle_expand::step_internal(uint8_t *const begin_dbits, uint8_t *const end_dbits)
652 {
653 const auto rd{gr_rle_decode(src_bits, begin_dbits, {end_src_bm, end_dbits})};
654 /* If the destination buffer is exhausted, return without
655 * modifying the source state. This lets the caller retry
656 * with a larger buffer, if desired.
657 */
658 if (unlikely(begin_dbits == rd))
659 return dst_exhausted;
660 advance_src_bits();
661 return again;
662 }
663
664 }