summaryrefslogtreecommitdiff
path: root/src/sdl2gfx/SDL2_rotozoom.cpp
blob: a37e1c51ef7738067cf4e8d216f625f5b2074a5b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
/*

SDL2_rotozoom.c: rotozoomer, zoomer and shrinker for 32bit or 8bit surfaces

Copyright (C) 2012-2014  Andreas Schiffler

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

3. This notice may not be removed or altered from any source
distribution.

Andreas Schiffler -- aschiffler at ferzkopp dot net

Changed for ManaPlus (C) 2013-2017  ManaPlus developers

*/

#ifdef WIN32
#include <windows.h>
#endif

#include <stdlib.h>
#include <string.h>

#include "sdl2gfx/SDL2_rotozoom.h"

#include "debug.h"

/* ---- Internally used structures */

/*!
\brief A 32 bit RGBA pixel.
*/
typedef struct tColorRGBA
{
    Uint8 r;
    Uint8 g;
    Uint8 b;
    Uint8 a;
} tColorRGBA;

/*!
\brief A 8bit Y/palette pixel.
*/
typedef struct tColorY
{
    Uint8 y;
} tColorY;

/*!
\brief Returns maximum of two numbers a and b.
*/
#define MAX(a,b)    (((a) > (b)) ? (a) : (b))

/*!
\brief Number of guard rows added to destination surfaces.

This is a simple but effective workaround for observed issues.
These rows allocate extra memory and are then hidden from the surface.
Rows are added to the end of destination surfaces when they are allocated.
This catches any potential overflows which seem to happen with
just the right src image dimensions and scale/rotation and can lead
to a situation where the program can segfault.
*/
#define GUARD_ROWS (2)

/*!
\brief Lower limit of absolute zoom factor or rotation degrees.
*/
#define VALUE_LIMIT    0.001

/*!
\brief Returns colorkey info for a surface
*/
static Uint32 _colorkey(SDL_Surface *src)
{
    Uint32 key = 0;
    SDL_GetColorKey(src, &key);
    return key;
}


/*!
\brief Internal 32 bit integer-factor averaging Shrinker.

Shrinks 32 bit RGBA/ABGR 'src' surface to 'dst' surface.
Averages color and alpha values values of src pixels to calculate dst pixels.
Assumes src and dst surfaces are of 32 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src The surface to shrink (input).
\param dst The shrunken surface (output).
\param factorx The horizontal shrinking ratio.
\param factory The vertical shrinking ratio.

\return 0 for success or -1 for error.
*/
static int _shrinkSurfaceRGBA(SDL_Surface *src,
                              SDL_Surface *dst,
                              int factorx,
                              int factory)
{
    int x, y, dx, dy, dgap, ra, ga, ba, aa;
    int n_average;
    tColorRGBA *sp, *osp, *oosp;
    tColorRGBA *dp;

    /*
    * Averaging integer shrink
    */

    /* Precalculate division factor */
    n_average = factorx*factory;

    /*
    * Scan destination
    */
    sp = static_cast<tColorRGBA *>(src->pixels);

    dp = static_cast<tColorRGBA *>(dst->pixels);
    dgap = dst->pitch - dst->w * 4;

    for (y = 0; y < dst->h; y++)
    {
        osp=sp;
        for (x = 0; x < dst->w; x++)
        {
            /* Trace out source box and accumulate */
            oosp=sp;
            ra=ga=ba=aa=0;
            for (dy=0; dy < factory; dy++)
            {
                for (dx=0; dx < factorx; dx++)
                {
                    ra += sp->r;
                    ga += sp->g;
                    ba += sp->b;
                    aa += sp->a;

                    sp++;
                }
                /* src dx loop */
                sp = reinterpret_cast<tColorRGBA *>(
                    reinterpret_cast<Uint8*>(sp) +
                    (src->pitch - 4*factorx)); // next y
            }
            /* src dy loop */

            /* next box-x */
            sp = reinterpret_cast<tColorRGBA *>(
                reinterpret_cast<Uint8*>(oosp) + 4*factorx);

            /* Store result in destination */
            dp->r = ra/n_average;
            dp->g = ga/n_average;
            dp->b = ba/n_average;
            dp->a = aa/n_average;

            /*
            * Advance destination pointer
            */
            dp++;
        }
        /* dst x loop */

        /* next box-y */
        sp = reinterpret_cast<tColorRGBA *>(reinterpret_cast<Uint8*>(osp) +
            src->pitch*factory);

        /*
        * Advance destination pointers
        */
        dp = reinterpret_cast<tColorRGBA *>(reinterpret_cast<Uint8*>(dp) +
            dgap);
    }
    /* dst y loop */

    return (0);
}

/*!
\brief Internal 8 bit integer-factor averaging shrinker.

Shrinks 8bit Y 'src' surface to 'dst' surface.
Averages color (brightness) values values of src pixels to calculate dst pixels.
Assumes src and dst surfaces are of 8 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src The surface to shrink (input).
\param dst The shrunken surface (output).
\param factorx The horizontal shrinking ratio.
\param factory The vertical shrinking ratio.

\return 0 for success or -1 for error.
*/
static int _shrinkSurfaceY(SDL_Surface *src,
                           SDL_Surface *dst,
                           int factorx,
                           int factory)
{
    int x, y, dx, dy, dgap, a;
    int n_average;
    Uint8 *sp, *osp, *oosp;
    Uint8 *dp;

    /*
    * Averaging integer shrink
    */

    /* Precalculate division factor */
    n_average = factorx*factory;

    /*
    * Scan destination
    */
    sp = static_cast<Uint8*>(src->pixels);

    dp = static_cast<Uint8*>(dst->pixels);
    dgap = dst->pitch - dst->w;

    for (y = 0; y < dst->h; y++)
    {
        osp=sp;
        for (x = 0; x < dst->w; x++)
        {
            /* Trace out source box and accumulate */
            oosp=sp;
            a=0;
            for (dy=0; dy < factory; dy++)
            {
                for (dx=0; dx < factorx; dx++)
                {
                    a += (*sp);
                    /* next x */
                    sp++;
                }
                /* end src dx loop */
                /* next y */
                sp = static_cast<Uint8*>(static_cast<Uint8*>(sp) +
                    (src->pitch - factorx));
            }
            /* end src dy loop */

            /* next box-x */
            sp = static_cast<Uint8*>(static_cast<Uint8*>(oosp) + factorx);

            /* Store result in destination */
            *dp = a/n_average;

            /*
            * Advance destination pointer
            */
            dp++;
        }
        /* end dst x loop */

        /* next box-y */
        sp = static_cast<Uint8*>(static_cast<Uint8*>(osp) +
            src->pitch*factory);

        /*
        * Advance destination pointers
        */
        dp = static_cast<Uint8*>(static_cast<Uint8*>(dp) + dgap);
    }
    /* end dst y loop */

    return (0);
}

/*!
\brief Internal 32 bit Zoomer with optional anti-aliasing by bilinear interpolation.

Zooms 32 bit RGBA/ABGR 'src' surface to 'dst' surface.
Assumes src and dst surfaces are of 32 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src The surface to zoom (input).
\param dst The zoomed surface (output).
\param flipx Flag indicating if the image should be horizontally flipped.
\param flipy Flag indicating if the image should be vertically flipped.
\param smooth Antialiasing flag; set to SMOOTHING_ON to enable.

\return 0 for success or -1 for error.
*/
static int _zoomSurfaceRGBA(SDL_Surface *src,
                            SDL_Surface *dst,
                            int flipx,
                            int flipy,
                            int smooth)
{
    int x, y, sx, sy, ssx, ssy;
    int *sax, *say, *csax, *csay, *salast;
    int csx, csy, ex, ey, cx, cy, sstep, sstepx, sstepy;
    tColorRGBA *c00, *c01, *c10, *c11;
    tColorRGBA *sp, *csp, *dp;
    int spixelgap, spixelw, spixelh, dgap, t1, t2;

    /*
    * Allocate memory for row/column increments
    */
    if ((sax = static_cast<int *>(malloc((dst->w + 1) * sizeof(Uint32)))) == nullptr)
    {
        return (-1);
    }
    if ((say = static_cast<int *>(malloc((dst->h + 1) * sizeof(Uint32)))) == nullptr)
    {
        free(sax);
        return (-1);
    }

    /*
    * Precalculate row increments
    */
    spixelw = (src->w - 1);
    spixelh = (src->h - 1);
    if (smooth)
    {
        sx = static_cast<int>(65536.0 * static_cast<float>(spixelw) /
            static_cast<float>(dst->w - 1));
        sy = static_cast<int>(65536.0 * static_cast<float>(spixelh) /
            static_cast<float>(dst->h - 1));
    }
    else
    {
        sx = static_cast<int>(65536.0 * static_cast<float>(src->w) /
            static_cast<float>(dst->w));
        sy = static_cast<int>(65536.0 * static_cast<float>(src->h) /
            static_cast<float>(dst->h));
    }

    /* Maximum scaled source size */
    ssx = (src->w << 16) - 1;
    ssy = (src->h << 16) - 1;

    /* Precalculate horizontal row increments */
    csx = 0;
    csax = sax;
    for (x = 0; x <= dst->w; x++)
    {
        *csax = csx;
        csax++;
        csx += sx;

        /* Guard from overflows */
        if (csx > ssx)
        {
            csx = ssx;
        }
    }

    /* Precalculate vertical row increments */
    csy = 0;
    csay = say;
    for (y = 0; y <= dst->h; y++)
    {
        *csay = csy;
        csay++;
        csy += sy;

        /* Guard from overflows */
        if (csy > ssy)
        {
            csy = ssy;
        }
    }

    sp = static_cast<tColorRGBA *>(src->pixels);
    dp = static_cast<tColorRGBA *>(dst->pixels);
    dgap = dst->pitch - dst->w * 4;
    spixelgap = src->pitch/4;

    if (flipx) sp += spixelw;
    if (flipy) sp += (spixelgap * spixelh);

    /*
    * Switch between interpolating and non-interpolating code
    */
    if (smooth)
    {
        /*
        * Interpolating Zoom
        */
        csay = say;
        for (y = 0; y < dst->h; y++)
        {
            csp = sp;
            csax = sax;
            for (x = 0; x < dst->w; x++)
            {
                /*
                * Setup color source pointers
                */
                ex = (*csax & 0xffff);
                ey = (*csay & 0xffff);
                cx = (*csax >> 16);
                cy = (*csay >> 16);
                sstepx = cx < spixelw;
                sstepy = cy < spixelh;
                c00 = sp;
                c01 = sp;
                c10 = sp;
                if (sstepy)
                {
                    if (flipy)
                    {
                        c10 -= spixelgap;
                    }
                    else
                    {
                        c10 += spixelgap;
                    }
                }
                c11 = c10;
                if (sstepx)
                {
                    if (flipx)
                    {
                        c01--;
                        c11--;
                    }
                    else
                    {
                        c01++;
                        c11++;
                    }
                }

                /*
                * Draw and interpolate colors
                */
                t1 = ((((c01->r - c00->r) * ex) >> 16) + c00->r) & 0xff;
                t2 = ((((c11->r - c10->r) * ex) >> 16) + c10->r) & 0xff;
                dp->r = (((t2 - t1) * ey) >> 16) + t1;
                t1 = ((((c01->g - c00->g) * ex) >> 16) + c00->g) & 0xff;
                t2 = ((((c11->g - c10->g) * ex) >> 16) + c10->g) & 0xff;
                dp->g = (((t2 - t1) * ey) >> 16) + t1;
                t1 = ((((c01->b - c00->b) * ex) >> 16) + c00->b) & 0xff;
                t2 = ((((c11->b - c10->b) * ex) >> 16) + c10->b) & 0xff;
                dp->b = (((t2 - t1) * ey) >> 16) + t1;
                t1 = ((((c01->a - c00->a) * ex) >> 16) + c00->a) & 0xff;
                t2 = ((((c11->a - c10->a) * ex) >> 16) + c10->a) & 0xff;
                dp->a = (((t2 - t1) * ey) >> 16) + t1;
                /*
                * Advance source pointer x
                */
                salast = csax;
                csax++;
                sstep = (*csax >> 16) - (*salast >> 16);
                if (flipx)
                {
                    sp -= sstep;
                }
                else
                {
                    sp += sstep;
                }

                /*
                * Advance destination pointer x
                */
                dp++;
            }
            /*
            * Advance source pointer y
            */
            salast = csay;
            csay++;
            sstep = (*csay >> 16) - (*salast >> 16);
            sstep *= spixelgap;
            if (flipy)
            {
                sp = csp - sstep;
            }
            else
            {
                sp = csp + sstep;
            }

            /*
            * Advance destination pointer y
            */
            dp = reinterpret_cast<tColorRGBA *>(
                reinterpret_cast<Uint8*>(dp) + dgap);
        }
    }
    else
    {
        /*
        * Non-Interpolating Zoom
        */
        csay = say;
        for (y = 0; y < dst->h; y++)
        {
            csp = sp;
            csax = sax;
            for (x = 0; x < dst->w; x++)
            {
                /*
                * Draw
                */
                *dp = *sp;

                /*
                * Advance source pointer x
                */
                salast = csax;
                csax++;
                sstep = (*csax >> 16) - (*salast >> 16);
                if (flipx) sstep = -sstep;
                sp += sstep;

                /*
                * Advance destination pointer x
                */
                dp++;
            }
            /*
            * Advance source pointer y
            */
            salast = csay;
            csay++;
            sstep = (*csay >> 16) - (*salast >> 16);
            sstep *= spixelgap;
            if (flipy) sstep = -sstep;
            sp = csp + sstep;

            /*
            * Advance destination pointer y
            */
            dp = reinterpret_cast<tColorRGBA *>(
                reinterpret_cast<Uint8*>(dp) + dgap);
        }
    }

    /*
    * Remove temp arrays
    */
    free(sax);
    free(say);

    return (0);
}

/*!

\brief Internal 8 bit Zoomer without smoothing.

Zooms 8bit palette/Y 'src' surface to 'dst' surface.
Assumes src and dst surfaces are of 8 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src The surface to zoom (input).
\param dst The zoomed surface (output).
\param flipx Flag indicating if the image should be horizontally flipped.
\param flipy Flag indicating if the image should be vertically flipped.

\return 0 for success or -1 for error.
*/
static int _zoomSurfaceY(SDL_Surface *src,
                         SDL_Surface *dst,
                         int flipx,
                         int flipy)
{
    int x, y;
    Uint32 *sax, *say, *csax, *csay;
    int csx, csy;
    Uint8 *sp, *dp, *csp;
    int dgap;

    /*
    * Allocate memory for row increments
    */
    if ((sax = static_cast<Uint32 *>(malloc((dst->w + 1) *
        sizeof(Uint32)))) == nullptr)
    {
        return (-1);
    }
    if ((say = static_cast<Uint32 *>(malloc((dst->h + 1) *
        sizeof(Uint32)))) == nullptr)
    {
        free(sax);
        return (-1);
    }

    /*
    * Pointer setup
    */
    sp = csp = static_cast<Uint8*>(src->pixels);
    dp = static_cast<Uint8*>(dst->pixels);
    dgap = dst->pitch - dst->w;

    if (flipx) csp += (src->w-1);
    if (flipy) csp  = (static_cast<Uint8*>(csp) + src->pitch*(src->h-1));

    /*
    * Precalculate row increments
    */
    csx = 0;
    csax = sax;
    for (x = 0; x < dst->w; x++)
    {
        csx += src->w;
        *csax = 0;
        while (csx >= dst->w)
        {
            csx -= dst->w;
            (*csax)++;
        }
        (*csax) = (*csax) * (flipx ? -1 : 1);
        csax++;
    }
    csy = 0;
    csay = say;
    for (y = 0; y < dst->h; y++)
    {
        csy += src->h;
        *csay = 0;
        while (csy >= dst->h)
        {
            csy -= dst->h;
            (*csay)++;
        }
        (*csay) = (*csay) * (flipy ? -1 : 1);
        csay++;
    }

    /*
    * Draw
    */
    csay = say;
    for (y = 0; y < dst->h; y++)
    {
        csax = sax;
        sp = csp;
        for (x = 0; x < dst->w; x++)
        {
            /*
            * Draw
            */
            *dp = *sp;
            /*
            * Advance source pointers
            */
            sp += (*csax);
            csax++;
            /*
            * Advance destination pointer
            */
            dp++;
        }
        /*
        * Advance source pointer (for row)
        */
        csp += ((*csay) * src->pitch);
        csay++;

        /*
        * Advance destination pointers
        */
        dp += dgap;
    }

    /*
    * Remove temp arrays
    */
    free(sax);
    free(say);

    return (0);
}

/*!
\brief Internal 32 bit rotozoomer with optional anti-aliasing.

Rotates and zooms 32 bit RGBA/ABGR 'src' surface to 'dst' surface based on the control
parameters by scanning the destination surface and applying optionally anti-aliasing
by bilinear interpolation.
Assumes src and dst surfaces are of 32 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src Source surface.
\param dst Destination surface.
\param cx Horizontal center coordinate.
\param cy Vertical center coordinate.
\param isin Integer version of sine of angle.
\param icos Integer version of cosine of angle.
\param flipx Flag indicating horizontal mirroring should be applied.
\param flipy Flag indicating vertical mirroring should be applied.
\param smooth Flag indicating anti-aliasing should be used.
*/
static void _transformSurfaceRGBA(SDL_Surface *src,
                                  SDL_Surface *dst,
                                  int cx,
                                  int cy,
                                  int isin,
                                  int icos,
                                  int flipx,
                                  int flipy,
                                  int smooth)
{
    int x, y, t1, t2, dx, dy, xd, yd, sdx, sdy, ax, ay, ex, ey, sw, sh;
    tColorRGBA c00, c01, c10, c11, cswap;
    tColorRGBA *pc, *sp;
    int gap;

    /*
    * Variable setup
    */
    xd = ((src->w - dst->w) << 15);
    yd = ((src->h - dst->h) << 15);
    ax = (cx << 16) - (icos * cx);
    ay = (cy << 16) - (isin * cx);
    sw = src->w - 1;
    sh = src->h - 1;
    pc = static_cast<tColorRGBA*>(dst->pixels);
    gap = dst->pitch - dst->w * 4;

    /*
    * Switch between interpolating and non-interpolating code
    */
    if (smooth)
    {
        for (y = 0; y < dst->h; y++)
        {
            dy = cy - y;
            sdx = (ax + (isin * dy)) + xd;
            sdy = (ay - (icos * dy)) + yd;
            for (x = 0; x < dst->w; x++)
            {
                dx = (sdx >> 16);
                dy = (sdy >> 16);
                if (flipx) dx = sw - dx;
                if (flipy) dy = sh - dy;
                if ((dx > -1) && (dy > -1) &&
                    (dx < (src->w-1)) && (dy < (src->h-1)))
                {
                    sp = static_cast<tColorRGBA *>(src->pixels);
                    sp += ((src->pitch/4) * dy);
                    sp += dx;
                    c00 = *sp;
                    sp += 1;
                    c01 = *sp;
                    sp += (src->pitch/4);
                    c11 = *sp;
                    sp -= 1;
                    c10 = *sp;
                    if (flipx)
                    {
                        cswap = c00; c00=c01; c01=cswap;
                        cswap = c10; c10=c11; c11=cswap;
                    }
                    if (flipy)
                    {
                        cswap = c00; c00=c10; c10=cswap;
                        cswap = c01; c01=c11; c11=cswap;
                    }
                    /*
                    * Interpolate colors
                    */
                    ex = (sdx & 0xffff);
                    ey = (sdy & 0xffff);
                    t1 = ((((c01.r - c00.r) * ex) >> 16) + c00.r) & 0xff;
                    t2 = ((((c11.r - c10.r) * ex) >> 16) + c10.r) & 0xff;
                    pc->r = (((t2 - t1) * ey) >> 16) + t1;
                    t1 = ((((c01.g - c00.g) * ex) >> 16) + c00.g) & 0xff;
                    t2 = ((((c11.g - c10.g) * ex) >> 16) + c10.g) & 0xff;
                    pc->g = (((t2 - t1) * ey) >> 16) + t1;
                    t1 = ((((c01.b - c00.b) * ex) >> 16) + c00.b) & 0xff;
                    t2 = ((((c11.b - c10.b) * ex) >> 16) + c10.b) & 0xff;
                    pc->b = (((t2 - t1) * ey) >> 16) + t1;
                    t1 = ((((c01.a - c00.a) * ex) >> 16) + c00.a) & 0xff;
                    t2 = ((((c11.a - c10.a) * ex) >> 16) + c10.a) & 0xff;
                    pc->a = (((t2 - t1) * ey) >> 16) + t1;
                }
                sdx += icos;
                sdy += isin;
                pc++;
            }
            pc = reinterpret_cast<tColorRGBA *>(
                reinterpret_cast<Uint8*>(pc) + gap);
        }
    }
    else
    {
        for (y = 0; y < dst->h; y++)
        {
            dy = cy - y;
            sdx = (ax + (isin * dy)) + xd;
            sdy = (ay - (icos * dy)) + yd;
            for (x = 0; x < dst->w; x++)
            {
                dx = static_cast<short>(sdx >> 16);
                dy = static_cast<short>(sdy >> 16);
                if (flipx) dx = (src->w-1)-dx;
                if (flipy) dy = (src->h-1)-dy;
                if ((dx >= 0) && (dy >= 0) && (dx < src->w) && (dy < src->h))
                {
                    sp = reinterpret_cast<tColorRGBA *>(
                        reinterpret_cast<Uint8*>(src->pixels) +
                        src->pitch * dy);
                    sp += dx;
                    *pc = *sp;
                }
                sdx += icos;
                sdy += isin;
                pc++;
            }
            pc = reinterpret_cast<tColorRGBA *>(
                reinterpret_cast<Uint8*>(pc) + gap);
        }
    }
}

/*!

\brief Rotates and zooms 8 bit palette/Y 'src' surface to 'dst' surface without smoothing.

Rotates and zooms 8 bit RGBA/ABGR 'src' surface to 'dst' surface based on the control
parameters by scanning the destination surface.
Assumes src and dst surfaces are of 8 bit depth.
Assumes dst surface was allocated with the correct dimensions.

\param src Source surface.
\param dst Destination surface.
\param cx Horizontal center coordinate.
\param cy Vertical center coordinate.
\param isin Integer version of sine of angle.
\param icos Integer version of cosine of angle.
\param flipx Flag indicating horizontal mirroring should be applied.
\param flipy Flag indicating vertical mirroring should be applied.
*/
static void transformSurfaceY(SDL_Surface *src,
                              SDL_Surface *dst,
                              int cx,
                              int cy,
                              int isin,
                              int icos,
                              int flipx,
                              int flipy)
{
    int x, y, dx, dy, xd, yd, sdx, sdy, ax, ay;
    tColorY *pc, *sp;
    int gap;

    /*
    * Variable setup
    */
    xd = ((src->w - dst->w) << 15);
    yd = ((src->h - dst->h) << 15);
    ax = (cx << 16) - (icos * cx);
    ay = (cy << 16) - (isin * cx);
    pc = static_cast<tColorY*>(dst->pixels);
    gap = dst->pitch - dst->w;
    /*
    * Clear surface to colorkey
    */
    memset(pc, static_cast<int>(_colorkey(src) & 0xff), dst->pitch * dst->h);
    /*
    * Iterate through destination surface
    */
    for (y = 0; y < dst->h; y++)
    {
        dy = cy - y;
        sdx = (ax + (isin * dy)) + xd;
        sdy = (ay - (icos * dy)) + yd;
        for (x = 0; x < dst->w; x++)
        {
            dx = static_cast<short>(sdx >> 16);
            dy = static_cast<short>(sdy >> 16);
            if (flipx) dx = (src->w-1)-dx;
            if (flipy) dy = (src->h-1)-dy;
            if ((dx >= 0) && (dy >= 0) && (dx < src->w) && (dy < src->h))
            {
                sp = static_cast<tColorY *>(src->pixels);
                sp += (src->pitch * dy + dx);
                *pc = *sp;
            }
            sdx += icos;
            sdy += isin;
            pc++;
        }
        pc += gap;
    }
}

/*!
\brief Rotates a 8/16/24/32 bit surface in increments of 90 degrees.

Specialized 90 degree rotator which rotates a 'src' surface in 90 degree
increments clockwise returning a new surface. Faster than rotozoomer since
no scanning or interpolation takes place. Input surface must be 8/16/24/32 bit.
(code contributed by J. Schiller, improved by C. Allport and A. Schiffler)

\param src Source surface to rotate.
\param numClockwiseTurns Number of clockwise 90 degree turns to apply to the source.

\returns The new, rotated surface; or nullptr for surfaces with incorrect input format.
*/
SDL_Surface* rotateSurface90Degrees(SDL_Surface *src,
                                    int numClockwiseTurns)
{
    int row, col, newWidth, newHeight;
    int bpp, bpr;
    SDL_Surface* dst;
    Uint8* srcBuf;
    Uint8* dstBuf;
    int normalizedClockwiseTurns;

    /* Has to be a valid surface pointer and be a Nbit surface where n is divisible by 8 */
    if (!src ||
        !src->format)
    {
        SDL_SetError("NULL source surface or source surface format");
        return nullptr;
    }

    if ((src->format->BitsPerPixel % 8) != 0)
    {
        SDL_SetError("Invalid source surface bit depth");
        return nullptr;
    }

    /* normalize numClockwiseTurns */
    normalizedClockwiseTurns = (numClockwiseTurns % 4);
    if (normalizedClockwiseTurns < 0)
    {
        normalizedClockwiseTurns += 4;
    }

    /* If turns are even, our new width/height will be the same as the source surface */
    if (normalizedClockwiseTurns % 2)
    {
        newWidth = src->h;
        newHeight = src->w;
    }
    else
    {
        newWidth = src->w;
        newHeight = src->h;
    }

    dst = SDL_CreateRGBSurface(src->flags,
        newWidth,
        newHeight,
        src->format->BitsPerPixel,
        src->format->Rmask,
        src->format->Gmask,
        src->format->Bmask,
        src->format->Amask);
    if (!dst)
    {
        SDL_SetError("Could not create destination surface");
        return nullptr;
    }

    if (SDL_MUSTLOCK(src))
    {
        SDL_LockSurface(src);
    }
    if (SDL_MUSTLOCK(dst))
    {
        SDL_LockSurface(dst);
    }

    /* Calculate byte-per-pixel */
    bpp = src->format->BitsPerPixel / 8;

    switch (normalizedClockwiseTurns)
    {
    case 0: /* Make a copy of the surface */
        {
            /* Unfortunately SDL_BlitSurface cannot be used to
            make a copy of the surface
            since it does not preserve alpha. */

            if (src->pitch == dst->pitch)
            {
                /* If the pitch is the same for both surfaces,
                the memory can be copied all at once. */
                memcpy(dst->pixels, src->pixels, (src->h * src->pitch));
            }
            else
            {
                /* If the pitch differs, copy each row separately */
                srcBuf = static_cast<Uint8*>(src->pixels);
                dstBuf = static_cast<Uint8*>(dst->pixels);
                bpr = src->w * bpp;
                for (row = 0; row < src->h; row++)
                {
                    memcpy(dstBuf, srcBuf, bpr);
                    srcBuf += src->pitch;
                    dstBuf += dst->pitch;
                }
            }
        }
        break;

        /* rotate clockwise */
    case 1: /* rotated 90 degrees clockwise */
        {
            for (row = 0; row < src->h; ++row)
            {
                srcBuf = static_cast<Uint8*>(src->pixels) +
                    (row * src->pitch);
                dstBuf = static_cast<Uint8*>(dst->pixels) +
                    (dst->w - row - 1) * bpp;
                for (col = 0; col < src->w; ++col)
                {
                    memcpy (dstBuf, srcBuf, bpp);
                    srcBuf += bpp;
                    dstBuf += dst->pitch;
                }
            }
        }
        break;

    case 2: /* rotated 180 degrees clockwise */
        {
            for (row = 0; row < src->h; ++row)
            {
                srcBuf = static_cast<Uint8*>(src->pixels) +
                    (row * src->pitch);
                dstBuf = static_cast<Uint8*>(dst->pixels) +
                    ((dst->h - row - 1) * dst->pitch) + (dst->w - 1) * bpp;
                for (col = 0; col < src->w; ++col)
                {
                    memcpy (dstBuf, srcBuf, bpp);
                    srcBuf += bpp;
                    dstBuf -= bpp;
                }
            }
        }
        break;

    case 3: /* rotated 270 degrees clockwise */
        {
            for (row = 0; row < src->h; ++row)
            {
                srcBuf = static_cast<Uint8*>(src->pixels) + (row * src->pitch);
                dstBuf = static_cast<Uint8*>(dst->pixels) +
                    (row * bpp) + (dst->h * dst->pitch);
                for (col = 0; col < src->w; ++col)
                {
                    memcpy (dstBuf, srcBuf, bpp);
                    srcBuf += bpp;
                    dstBuf -= dst->pitch;
                }
            }
        }
        break;
    default:
        break;
    }
    /* end switch */

    if (SDL_MUSTLOCK(src))
    {
        SDL_UnlockSurface(src);
    }
    if (SDL_MUSTLOCK(dst))
    {
        SDL_UnlockSurface(dst);
    }

    return dst;
}


/*!
\brief Internal target surface sizing function for rotozooms
with trig result return.

\param width The source surface width.
\param height The source surface height.
\param angle The angle to rotate in degrees.
\param zoomx The horizontal scaling factor.
\param zoomy The vertical scaling factor.
\param dstwidth The calculated width of the destination surface.
\param dstheight The calculated height of the destination surface.
\param canglezoom The sine of the angle adjusted by the zoom factor.
\param sanglezoom The cosine of the angle adjusted by the zoom factor.

*/
static void _rotozoomSurfaceSizeTrig(int width,
                                     int height,
                                     double angle,
                                     double zoomx,
                                     double zoomy,
                                     int *dstwidth,
                                     int *dstheight,
                                     double *canglezoom,
                                     double *sanglezoom)
{
    double x, y, cx, cy, sx, sy;
    double radangle;
    int dstwidthhalf, dstheighthalf;

    /*
    * Determine destination width and height by rotating a centered source box
    */
    radangle = angle * (M_PI / 180.0);
    *sanglezoom = sin(radangle);
    *canglezoom = cos(radangle);
    *sanglezoom *= zoomx;
    *canglezoom *= zoomy;
    x = static_cast<double>(width / 2);
    y = static_cast<double>(height / 2);
    cx = *canglezoom * x;
    cy = *canglezoom * y;
    sx = *sanglezoom * x;
    sy = *sanglezoom * y;

    dstwidthhalf = MAX(static_cast<int>(
        ceil(MAX(MAX(MAX(fabs(cx + sy), fabs(cx - sy)),
        fabs(-cx + sy)), fabs(-cx - sy)))), 1);
    dstheighthalf = MAX(static_cast<int>(
        ceil(MAX(MAX(MAX(fabs(sx + cy), fabs(sx - cy)),
        fabs(-sx + cy)), fabs(-sx - cy)))), 1);
    *dstwidth = 2 * dstwidthhalf;
    *dstheight = 2 * dstheighthalf;
}

/*!
\brief Returns the size of the resulting target surface for a
rotozoomSurfaceXY() call.

\param width The source surface width.
\param height The source surface height.
\param angle The angle to rotate in degrees.
\param zoomx The horizontal scaling factor.
\param zoomy The vertical scaling factor.
\param dstwidth The calculated width of the rotozoomed destination surface.
\param dstheight The calculated height of the rotozoomed destination surface.
*/
void rotozoomSurfaceSizeXY(int width,
                           int height,
                           double angle,
                           double zoomx,
                           double zoomy,
                           int *dstwidth,
                           int *dstheight)
{
    double dummy_sanglezoom, dummy_canglezoom;

    _rotozoomSurfaceSizeTrig(width, height, angle, zoomx, zoomy,
        dstwidth, dstheight, &dummy_sanglezoom, &dummy_canglezoom);
}

/*!
\brief Returns the size of the resulting target surface for a rotozoomSurface()
call.

\param width The source surface width.
\param height The source surface height.
\param angle The angle to rotate in degrees.
\param zoom The scaling factor.
\param dstwidth The calculated width of the rotozoomed destination surface.
\param dstheight The calculated height of the rotozoomed destination surface.
*/
void rotozoomSurfaceSize(int width,
                         int height,
                         double angle,
                         double zoom,
                         int *dstwidth,
                         int *dstheight)
{
    double dummy_sanglezoom, dummy_canglezoom;

    _rotozoomSurfaceSizeTrig(width, height, angle, zoom, zoom,
        dstwidth, dstheight, &dummy_sanglezoom, &dummy_canglezoom);
}

/*!
\brief Rotates and zooms a surface and optional anti-aliasing.

Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst'
surface. 'angle' is the rotation in degrees and 'zoom' a scaling factor.
If 'smooth' is set then the destination 32bit surface is anti-aliased.
If the surface is not 8bit or 32bit RGBA/ABGR it will be converted into
a 32bit RGBA format on the fly.

\param src The surface to rotozoom.
\param angle The angle to rotate in degrees.
\param zoom The scaling factor.
\param smooth Antialiasing flag; set to SMOOTHING_ON to enable.

\return The new rotozoomed surface.
*/
SDL_Surface *rotozoomSurface(SDL_Surface *src,
                             double angle,
                             double zoom,
                             int smooth)
{
    return rotozoomSurfaceXY(src, angle, zoom, zoom, smooth);
}

/*!
\brief Rotates and zooms a surface with different horizontal and
vertival scaling factors and optional anti-aliasing.

Rotates and zooms a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'angle' is the rotation in degrees, 'zoomx and 'zoomy' scaling factors.
If 'smooth' is set then the destination 32bit surface is anti-aliased.
If the surface is not 8bit or 32bit RGBA/ABGR it will be converted into
a 32bit RGBA format on the fly.

\param src The surface to rotozoom.
\param angle The angle to rotate in degrees.
\param zoomx The horizontal scaling factor.
\param zoomy The vertical scaling factor.
\param smooth Antialiasing flag; set to SMOOTHING_ON to enable.

\return The new rotozoomed surface.
*/
SDL_Surface *rotozoomSurfaceXY(SDL_Surface *src,
                               double angle,
                               double zoomx,
                               double zoomy,
                               int smooth)
{
    SDL_Surface *rz_src;
    SDL_Surface *rz_dst;
    double zoominv;
    double sanglezoom, canglezoom, sanglezoominv, canglezoominv;
    int dstwidthhalf, dstwidth, dstheighthalf, dstheight;
    int is32bit;
    int i, src_converted;
    int flipx,flipy;

    /*
    * Sanity check
    */
    if (src == nullptr)
    {
        return (nullptr);
    }

    /*
    * Determine if source surface is 32bit or 8bit
    */
    is32bit = (src->format->BitsPerPixel == 32);
    if ((is32bit) || (src->format->BitsPerPixel == 8))
    {
        /*
        * Use source surface 'as is'
        */
        rz_src = src;
        src_converted = 0;
    }
    else
    {
        /*
        * New source surface is 32bit with a defined RGBA ordering
        */
        rz_src =
            SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
#else
            0xff000000,  0x00ff0000, 0x0000ff00, 0x000000ff
#endif
            );

        SDL_BlitSurface(src, nullptr, rz_src, nullptr);

        src_converted = 1;
        is32bit = 1;
    }

    /*
    * Sanity check zoom factor
    */
    flipx = (zoomx<0.0);
    if (flipx) zoomx=-zoomx;
    flipy = (zoomy<0.0);
    if (flipy) zoomy=-zoomy;
    if (zoomx < VALUE_LIMIT) zoomx = VALUE_LIMIT;
    if (zoomy < VALUE_LIMIT) zoomy = VALUE_LIMIT;
    zoominv = 65536.0 / (zoomx * zoomx);

    /*
    * Check if we have a rotozoom or just a zoom
    */
    if (fabs(angle) > VALUE_LIMIT)
    {

        /*
        * Angle!=0: full rotozoom
        */
        /*
        * -----------------------
        */

        /* Determine target size */
        _rotozoomSurfaceSizeTrig(rz_src->w, rz_src->h, angle, zoomx, zoomy,
            &dstwidth, &dstheight, &canglezoom, &sanglezoom);

        /*
        * Calculate target factors from sin/cos and zoom
        */
        sanglezoominv = sanglezoom;
        canglezoominv = canglezoom;
        sanglezoominv *= zoominv;
        canglezoominv *= zoominv;

        /* Calculate half size */
        dstwidthhalf = dstwidth / 2;
        dstheighthalf = dstheight / 2;

        /*
        * Alloc space to completely contain the rotated surface
        */
        rz_dst = nullptr;
        if (is32bit)
        {
            /*
            * Target surface is 32bit with source RGBA/ABGR ordering
            */
            rz_dst =
                SDL_CreateRGBSurface(SDL_SWSURFACE,
                dstwidth, dstheight + GUARD_ROWS, 32,
                rz_src->format->Rmask, rz_src->format->Gmask,
                rz_src->format->Bmask, rz_src->format->Amask);
        }
        else
        {
            /*
            * Target surface is 8bit
            */
            rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth,
                dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
        }

        /* Check target */
        if (rz_dst == nullptr)
            return nullptr;

        /* Adjust for guard rows */
        rz_dst->h = dstheight;

        /*
        * Lock source surface
        */
        if (SDL_MUSTLOCK(rz_src))
        {
            SDL_LockSurface(rz_src);
        }

        /*
        * Check which kind of surface we have
        */
        if (is32bit)
        {
            /*
            * Call the 32bit transformation routine to do the rotation
            * (using alpha)
            */
            _transformSurfaceRGBA(rz_src, rz_dst, dstwidthhalf, dstheighthalf,
                static_cast<int>(sanglezoominv),
                static_cast<int>(canglezoominv),
                flipx, flipy,
                smooth);
        }
        else
        {
            /*
            * Copy palette and colorkey info
            */
            for (i = 0; i < rz_src->format->palette->ncolors; i++)
            {
                rz_dst->format->palette->colors[i] =
                    rz_src->format->palette->colors[i];
            }
            rz_dst->format->palette->ncolors =
                rz_src->format->palette->ncolors;
            /*
            * Call the 8bit transformation routine to do the rotation
            */
            transformSurfaceY(rz_src, rz_dst, dstwidthhalf, dstheighthalf,
                static_cast<int>(sanglezoominv),
                static_cast<int>(canglezoominv),
                flipx, flipy);
        }
        /*
        * Unlock source surface
        */
        if (SDL_MUSTLOCK(rz_src))
        {
            SDL_UnlockSurface(rz_src);
        }

    }
    else
    {
        /*
        * Angle=0: Just a zoom
        */
        /*
        * --------------------
        */

        /*
        * Calculate target size
        */
        zoomSurfaceSize(rz_src->w, rz_src->h, zoomx, zoomy,
            &dstwidth, &dstheight);

        /*
        * Alloc space to completely contain the zoomed surface
        */
        rz_dst = nullptr;
        if (is32bit)
        {
            /*
            * Target surface is 32bit with source RGBA/ABGR ordering
            */
            rz_dst =
                SDL_CreateRGBSurface(SDL_SWSURFACE,
                dstwidth, dstheight + GUARD_ROWS, 32,
                rz_src->format->Rmask, rz_src->format->Gmask,
                rz_src->format->Bmask, rz_src->format->Amask);
        }
        else
        {
            /*
            * Target surface is 8bit
            */
            rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE,
                dstwidth, dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
        }

        /* Check target */
        if (rz_dst == nullptr)
            return nullptr;

        /* Adjust for guard rows */
        rz_dst->h = dstheight;

        /*
        * Lock source surface
        */
        if (SDL_MUSTLOCK(rz_src))
        {
            SDL_LockSurface(rz_src);
        }

        /*
        * Check which kind of surface we have
        */
        if (is32bit)
        {
            /*
            * Call the 32bit transformation routine to do the zooming
            * (using alpha)
            */
            _zoomSurfaceRGBA(rz_src, rz_dst, flipx, flipy, smooth);

        }
        else
        {
            /*
            * Copy palette and colorkey info
            */
            for (i = 0; i < rz_src->format->palette->ncolors; i++)
            {
                rz_dst->format->palette->colors[i] =
                    rz_src->format->palette->colors[i];
            }
            rz_dst->format->palette->ncolors =
                rz_src->format->palette->ncolors;

            /*
            * Call the 8bit transformation routine to do the zooming
            */
            _zoomSurfaceY(rz_src, rz_dst, flipx, flipy);
        }

        /*
        * Unlock source surface
        */
        if (SDL_MUSTLOCK(rz_src))
        {
            SDL_UnlockSurface(rz_src);
        }
    }

    /*
    * Cleanup temp surface
    */
    if (src_converted)
    {
        SDL_FreeSurface(rz_src);
    }

    /*
    * Return destination surface
    */
    return (rz_dst);
}

/*!
\brief Calculates the size of the target surface for a zoomSurface() call.

The minimum size of the target surface is 1. The input factors
can be positive or negative.

\param width The width of the source surface to zoom.
\param height The height of the source surface to zoom.
\param zoomx The horizontal zoom factor.
\param zoomy The vertical zoom factor.
\param dstwidth Pointer to an integer to store the calculated
width of the zoomed target surface.
\param dstheight Pointer to an integer to store the calculated
height of the zoomed target surface.
*/
void zoomSurfaceSize(int width, int height,
                     double zoomx, double zoomy,
                     int *dstwidth, int *dstheight)
{
    /*
    * Make zoom factors positive
    */
    int flipx, flipy;
    flipx = (zoomx<0.0);
    if (flipx) zoomx = -zoomx;
    flipy = (zoomy<0.0);
    if (flipy) zoomy = -zoomy;

    /*
    * Sanity check zoom factors
    */
    if (zoomx < VALUE_LIMIT)
    {
        zoomx = VALUE_LIMIT;
    }
    if (zoomy < VALUE_LIMIT)
    {
        zoomy = VALUE_LIMIT;
    }

    /*
    * Calculate target size
    */
    *dstwidth = static_cast<int>(floor((static_cast<double>(
        width) * zoomx) + 0.5));
    *dstheight = static_cast<int>(floor((static_cast<double>(
        height) * zoomy) + 0.5));
    if (*dstwidth < 1)
    {
        *dstwidth = 1;
    }
    if (*dstheight < 1)
    {
        *dstheight = 1;
    }
}

/*!
\brief Zoom a surface by independent horizontal and vertical
factors with optional smoothing.

Zooms a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is on
then the destination 32bit surface is anti-aliased. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
If zoom factors are negative, the image is flipped on the axes.

\param src The surface to zoom.
\param zoomx The horizontal zoom factor.
\param zoomy The vertical zoom factor.
\param smooth Antialiasing flag; set to SMOOTHING_ON to enable.

\return The new, zoomed surface.
*/
SDL_Surface *zoomSurface(SDL_Surface *src,
                         double zoomx,
                         double zoomy,
                         int smooth)
{
    SDL_Surface *rz_src;
    SDL_Surface *rz_dst;
    int dstwidth, dstheight;
    int is32bit;
    int i, src_converted;
    int flipx, flipy;

    /*
    * Sanity check
    */
    if (src == nullptr)
        return (nullptr);

    /*
    * Determine if source surface is 32bit or 8bit
    */
    is32bit = (src->format->BitsPerPixel == 32);
    if ((is32bit) || (src->format->BitsPerPixel == 8))
    {
        /*
        * Use source surface 'as is'
        */
        rz_src = src;
        src_converted = 0;
    }
    else
    {
        /*
        * New source surface is 32bit with a defined RGBA ordering
        */
        rz_src =
            SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
#else
            0xff000000,  0x00ff0000, 0x0000ff00, 0x000000ff
#endif
            );
        if (rz_src == nullptr)
        {
            return nullptr;
        }
        SDL_BlitSurface(src, nullptr, rz_src, nullptr);
        src_converted = 1;
        is32bit = 1;
    }

    flipx = (zoomx<0.0);
    if (flipx) zoomx = -zoomx;
    flipy = (zoomy<0.0);
    if (flipy) zoomy = -zoomy;

    /* Get size if target */
    zoomSurfaceSize(rz_src->w, rz_src->h, zoomx, zoomy, &dstwidth, &dstheight);

    /*
    * Alloc space to completely contain the zoomed surface
    */
    rz_dst = nullptr;
    if (is32bit)
    {
        /*
        * Target surface is 32bit with source RGBA/ABGR ordering
        */
        rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE,
            dstwidth, dstheight + GUARD_ROWS, 32,
            rz_src->format->Rmask, rz_src->format->Gmask,
            rz_src->format->Bmask, rz_src->format->Amask);
    }
    else
    {
        /*
        * Target surface is 8bit
        */
        rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE,
            dstwidth, dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
    }

    /* Check target */
    if (rz_dst == nullptr)
    {
        /*
        * Cleanup temp surface
        */
        if (src_converted)
        {
            SDL_FreeSurface(rz_src);
        }
        return nullptr;
    }

    /* Adjust for guard rows */
    rz_dst->h = dstheight;

    /*
    * Lock source surface
    */
    if (SDL_MUSTLOCK(rz_src))
    {
        SDL_LockSurface(rz_src);
    }

    /*
    * Check which kind of surface we have
    */
    if (is32bit)
    {
        /*
        * Call the 32bit transformation routine to do the zooming (using alpha)
        */
        _zoomSurfaceRGBA(rz_src, rz_dst, flipx, flipy, smooth);
    }
    else
    {
        /*
        * Copy palette and colorkey info
        */
        for (i = 0; i < rz_src->format->palette->ncolors; i++)
        {
            rz_dst->format->palette->colors[i] =
                rz_src->format->palette->colors[i];
        }
        rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
        /*
        * Call the 8bit transformation routine to do the zooming
        */
        _zoomSurfaceY(rz_src, rz_dst, flipx, flipy);
    }
    /*
    * Unlock source surface
    */
    if (SDL_MUSTLOCK(rz_src))
    {
        SDL_UnlockSurface(rz_src);
    }

    /*
    * Cleanup temp surface
    */
    if (src_converted)
    {
        SDL_FreeSurface(rz_src);
    }

    /*
    * Return destination surface
    */
    return (rz_dst);
}

/*!
\brief Shrink a surface by an integer ratio using averaging.

Shrinks a 32bit or 8bit 'src' surface to a newly created 'dst' surface.
'factorx' and 'factory' are the shrinking ratios (i.e. 2=1/2 the size,
3=1/3 the size, etc.) The destination surface is antialiased by averaging
the source box RGBA or Y information. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
The input surface is not modified. The output surface is newly allocated.

\param src The surface to shrink.
\param factorx The horizontal shrinking ratio.
\param factory The vertical shrinking ratio.

\return The new, shrunken surface.
*/
/*@nullptr@*/
SDL_Surface *shrinkSurface(SDL_Surface *src,
                           int factorx,
                           int factory)
{
    int result;
    SDL_Surface *rz_src;
    SDL_Surface *rz_dst = nullptr;
    int dstwidth, dstheight;
    int is32bit;
    int i, src_converted = 0;
    int haveError = 0;

    /*
    * Sanity check
    */
    if (src == nullptr)
    {
        return (nullptr);
    }

    /*
    * Determine if source surface is 32bit or 8bit
    */
    is32bit = (src->format->BitsPerPixel == 32);
    if ((is32bit) || (src->format->BitsPerPixel == 8))
    {
        /*
        * Use source surface 'as is'
        */
        rz_src = src;
        src_converted = 0;
    }
    else
    {
        /*
        * New source surface is 32bit with a defined RGBA ordering
        */
        rz_src = SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
#else
            0xff000000,  0x00ff0000, 0x0000ff00, 0x000000ff
#endif
            );
        if (rz_src==nullptr)
        {
            haveError = 1;
            goto exitShrinkSurface;
        }

        SDL_BlitSurface(src, nullptr, rz_src, nullptr);
        src_converted = 1;
        is32bit = 1;
    }

    /*
    * Lock the surface
    */
    if (SDL_MUSTLOCK(rz_src))
    {
        if (SDL_LockSurface(rz_src) < 0)
        {
            haveError = 1;
            goto exitShrinkSurface;
        }
    }

    /* Get size for target */
    dstwidth=rz_src->w/factorx;
    while (dstwidth*factorx>rz_src->w)
    {
        dstwidth--;
    }
    dstheight=rz_src->h/factory;
    while (dstheight*factory>rz_src->h)
    {
        dstheight--;
    }

    /*
    * Alloc space to completely contain the shrunken surface
    * (with added guard rows)
    */
    if (is32bit==1)
    {
        /*
        * Target surface is 32bit with source RGBA/ABGR ordering
        */
        rz_dst = SDL_CreateRGBSurface(
            SDL_SWSURFACE, dstwidth, dstheight + GUARD_ROWS, 32,
            rz_src->format->Rmask, rz_src->format->Gmask,
            rz_src->format->Bmask, rz_src->format->Amask);
    }
    else
    {
        /*
        * Target surface is 8bit
        */
        rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE,
            dstwidth, dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
    }

    /* Check target */
    if (rz_dst == nullptr)
    {
        haveError = 1;
        goto exitShrinkSurface;
    }

    /* Adjust for guard rows */
    rz_dst->h = dstheight;

    /*
    * Check which kind of surface we have
    */
    if (is32bit==1)
    {
        /*
        * Call the 32bit transformation routine to do the shrinking (using alpha)
        */
        result = _shrinkSurfaceRGBA(rz_src, rz_dst, factorx, factory);
        if ((result!=0) || (rz_dst==nullptr))
        {
            haveError = 1;
            goto exitShrinkSurface;
        }
    }
    else
    {
        /*
        * Copy palette and colorkey info
        */
        for (i = 0; i < rz_src->format->palette->ncolors; i++)
        {
            rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
        }
        rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
        /*
        * Call the 8bit transformation routine to do the shrinking
        */
        result = _shrinkSurfaceY(rz_src, rz_dst, factorx, factory);
        if (result!=0)
        {
            haveError = 1;
            goto exitShrinkSurface;
        }
    }

exitShrinkSurface:
    if (rz_src!=nullptr)
    {
        /*
        * Unlock source surface
        */
        if (SDL_MUSTLOCK(rz_src))
        {
            SDL_UnlockSurface(rz_src);
        }

        /*
        * Cleanup temp surface
        */
        if (src_converted==1)
        {
            SDL_FreeSurface(rz_src);
        }
    }

    /* Check error state; maybe need to cleanup destination */
    if (haveError==1)
    {
        if (rz_dst!=nullptr)
        {
            SDL_FreeSurface(rz_dst);
        }
        rz_dst=nullptr;
    }

    /*
    * Return destination surface
    */
    return (rz_dst);
}