summaryrefslogtreecommitdiff
path: root/drawinglayer/source/processor2d/d2dpixelprocessor2d.cxx
blob: 21a441783ca64214a4913ccfd6f2aae5b1b75b62 (plain)
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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>

// win-specific
#include <prewin.h>
#include <d2d1.h>
#include <d2d1_1.h>
#include <postwin.h>

#include <drawinglayer/processor2d/d2dpixelprocessor2d.hxx>
#include <drawinglayer/processor2d/SDPRProcessor2dTools.hxx>
#include <sal/log.hxx>
#include <vcl/outdev.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx>
#include <drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx>
#include <drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx>
#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx>
#include <drawinglayer/primitive2d/fillgraphicprimitive2d.hxx>
#include <drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx>
#include <drawinglayer/primitive2d/backgroundcolorprimitive2d.hxx>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <drawinglayer/primitive2d/markerarrayprimitive2d.hxx>
#include <drawinglayer/primitive2d/maskprimitive2d.hxx>
#include <drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx>
#include <drawinglayer/primitive2d/pointarrayprimitive2d.hxx>
#include <drawinglayer/primitive2d/PolygonStrokePrimitive2D.hxx>
#include <drawinglayer/primitive2d/Tools.hxx>
#include <drawinglayer/primitive2d/transformprimitive2d.hxx>
#include <drawinglayer/primitive2d/transparenceprimitive2d.hxx>
#include <drawinglayer/converters.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>
#include <basegfx/utils/systemdependentdata.hxx>
#include <vcl/BitmapReadAccess.hxx>
#include <vcl/svapp.hxx>

using namespace com::sun::star;

namespace
{
class ID2D1GlobalFactoryProvider
{
    sal::systools::COMReference<ID2D1Factory> mpD2DFactory;

public:
    ID2D1GlobalFactoryProvider()
        : mpD2DFactory(nullptr)
    {
        const HRESULT hr(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,
                                           __uuidof(ID2D1Factory), nullptr,
                                           reinterpret_cast<void**>(&mpD2DFactory)));

        if (!SUCCEEDED(hr))
            mpD2DFactory.clear();
    }

    sal::systools::COMReference<ID2D1Factory>& getID2D1Factory() { return mpD2DFactory; }
};

ID2D1GlobalFactoryProvider aID2D1GlobalFactoryProvider;

class ID2D1GlobalRenderTargetProvider
{
    sal::systools::COMReference<ID2D1DCRenderTarget> mpID2D1DCRenderTarget;

public:
    ID2D1GlobalRenderTargetProvider()
        : mpID2D1DCRenderTarget()
    {
    }

    sal::systools::COMReference<ID2D1DCRenderTarget>& getID2D1DCRenderTarget()
    {
        if (!mpID2D1DCRenderTarget && aID2D1GlobalFactoryProvider.getID2D1Factory())
        {
            const D2D1_RENDER_TARGET_PROPERTIES aRTProps(D2D1::RenderTargetProperties(
                D2D1_RENDER_TARGET_TYPE_DEFAULT,
                D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
                                  D2D1_ALPHA_MODE_IGNORE), //D2D1_ALPHA_MODE_PREMULTIPLIED),
                0, 0, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_DEFAULT));

            const HRESULT hr(aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateDCRenderTarget(
                &aRTProps, &mpID2D1DCRenderTarget));

            // interestingly this ID2D1DCRenderTarget already works and can hold
            // created ID2D1Bitmap(s) in RenderTarget-specific form, *without*
            // any call to "BindDC", thus *without* the need of a real HDC - nice :-)
            // When that would be needed, Application::GetDefaultDevice() would need
            // to have a HDC that is valid during LO's lifetime.

            if (!SUCCEEDED(hr))
                mpID2D1DCRenderTarget.clear();
        }

        return mpID2D1DCRenderTarget;
    }
};

ID2D1GlobalRenderTargetProvider aID2D1GlobalRenderTargetProvider;

class SystemDependentData_ID2D1PathGeometry : public basegfx::SystemDependentData
{
private:
    sal::systools::COMReference<ID2D1PathGeometry> mpID2D1PathGeometry;

public:
    SystemDependentData_ID2D1PathGeometry(
        sal::systools::COMReference<ID2D1PathGeometry>& rID2D1PathGeometry)
        : basegfx::SystemDependentData(Application::GetSystemDependentDataManager())
        , mpID2D1PathGeometry(rID2D1PathGeometry)
    {
    }

    const sal::systools::COMReference<ID2D1PathGeometry>& getID2D1PathGeometry() const
    {
        return mpID2D1PathGeometry;
    }
    virtual sal_Int64 estimateUsageInBytes() const override;
};

sal_Int64 SystemDependentData_ID2D1PathGeometry::estimateUsageInBytes() const
{
    sal_Int64 aRetval(0);

    if (getID2D1PathGeometry())
    {
        UINT32 nCount(0);
        const HRESULT hr(getID2D1PathGeometry()->GetSegmentCount(&nCount));

        if (SUCCEEDED(hr))
        {
            // without completely receiving and tracing the GeometrySink
            // do a rough estimation - each segment is 2D, so has two doubles.
            // Some are beziers, so add some guessed buffer for two additional
            // control points
            aRetval = static_cast<sal_Int64>(nCount) * (6 * sizeof(double));
        }
    }

    return aRetval;
}

basegfx::B2DPoint impPixelSnap(const basegfx::B2DPolygon& rPolygon,
                               const drawinglayer::geometry::ViewInformation2D& rViewInformation,
                               sal_uInt32 nIndex)
{
    const sal_uInt32 nCount(rPolygon.count());

    // get the data
    const basegfx::B2ITuple aPrevTuple(
        basegfx::fround(rViewInformation.getObjectToViewTransformation()
                        * rPolygon.getB2DPoint((nIndex + nCount - 1) % nCount)));
    const basegfx::B2DPoint aCurrPoint(rViewInformation.getObjectToViewTransformation()
                                       * rPolygon.getB2DPoint(nIndex));
    const basegfx::B2ITuple aCurrTuple(basegfx::fround(aCurrPoint));
    const basegfx::B2ITuple aNextTuple(
        basegfx::fround(rViewInformation.getObjectToViewTransformation()
                        * rPolygon.getB2DPoint((nIndex + 1) % nCount)));

    // get the states
    const bool bPrevVertical(aPrevTuple.getX() == aCurrTuple.getX());
    const bool bNextVertical(aNextTuple.getX() == aCurrTuple.getX());
    const bool bPrevHorizontal(aPrevTuple.getY() == aCurrTuple.getY());
    const bool bNextHorizontal(aNextTuple.getY() == aCurrTuple.getY());
    const bool bSnapX(bPrevVertical || bNextVertical);
    const bool bSnapY(bPrevHorizontal || bNextHorizontal);

    if (bSnapX || bSnapY)
    {
        basegfx::B2DPoint aSnappedPoint(bSnapX ? aCurrTuple.getX() : aCurrPoint.getX(),
                                        bSnapY ? aCurrTuple.getY() : aCurrPoint.getY());

        aSnappedPoint *= rViewInformation.getInverseObjectToViewTransformation();

        return aSnappedPoint;
    }

    return rPolygon.getB2DPoint(nIndex);
}

void addB2DPolygonToPathGeometry(sal::systools::COMReference<ID2D1GeometrySink>& rSink,
                                 const basegfx::B2DPolygon& rPolygon,
                                 const drawinglayer::geometry::ViewInformation2D* pViewInformation)
{
    const sal_uInt32 nPointCount(rPolygon.count());
    const sal_uInt32 nEdgeCount(rPolygon.isClosed() ? nPointCount : nPointCount - 1);
    basegfx::B2DCubicBezier aEdge;

    for (sal_uInt32 a(0); a < nEdgeCount; a++)
    {
        rPolygon.getBezierSegment(a, aEdge);

        const basegfx::B2DPoint aEndPoint(
            nullptr == pViewInformation
                ? aEdge.getEndPoint()
                : impPixelSnap(rPolygon, *pViewInformation, (a + 1) % nPointCount));

        if (aEdge.isBezier())
        {
            rSink->AddBezier(
                D2D1::BezierSegment(D2D1::Point2F(aEdge.getControlPointA().getX(),
                                                  aEdge.getControlPointA().getY()), //C1
                                    D2D1::Point2F(aEdge.getControlPointB().getX(),
                                                  aEdge.getControlPointB().getY()), //c2
                                    D2D1::Point2F(aEndPoint.getX(), aEndPoint.getY()))); //end
        }
        else
        {
            rSink->AddLine(D2D1::Point2F(aEndPoint.getX(), aEndPoint.getY()));
        }
    }
}

std::shared_ptr<SystemDependentData_ID2D1PathGeometry>
getOrCreatePathGeometry(const basegfx::B2DPolygon& rPolygon,
                        const drawinglayer::geometry::ViewInformation2D& rViewInformation)
{
    // try to access buffered data
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1PathGeometry(
        rPolygon.getSystemDependentData<SystemDependentData_ID2D1PathGeometry>());

    if (pSystemDependentData_ID2D1PathGeometry)
    {
        if (rViewInformation.getPixelSnapHairline())
        {
            // do not buffer when PixelSnap is active
            pSystemDependentData_ID2D1PathGeometry.reset();
        }
        else
        {
            // use and return buffered data
            return pSystemDependentData_ID2D1PathGeometry;
        }
    }

    sal::systools::COMReference<ID2D1PathGeometry> pID2D1PathGeometry;
    HRESULT hr(
        aID2D1GlobalFactoryProvider.getID2D1Factory()->CreatePathGeometry(&pID2D1PathGeometry));
    const sal_uInt32 nPointCount(rPolygon.count());

    if (SUCCEEDED(hr) && nPointCount)
    {
        sal::systools::COMReference<ID2D1GeometrySink> pSink;
        hr = pID2D1PathGeometry->Open(&pSink);

        if (SUCCEEDED(hr) && pSink)
        {
            const basegfx::B2DPoint aStart(rViewInformation.getPixelSnapHairline()
                                               ? rPolygon.getB2DPoint(0)
                                               : impPixelSnap(rPolygon, rViewInformation, 0));

            pSink->BeginFigure(D2D1::Point2F(aStart.getX(), aStart.getY()),
                               D2D1_FIGURE_BEGIN_HOLLOW);
            addB2DPolygonToPathGeometry(pSink, rPolygon, &rViewInformation);
            pSink->EndFigure(rPolygon.isClosed() ? D2D1_FIGURE_END_CLOSED : D2D1_FIGURE_END_OPEN);
            pSink->Close();
        }
    }

    // add to buffering mechanism
    if (pID2D1PathGeometry)
    {
        if (rViewInformation.getPixelSnapHairline() || nPointCount <= 4)
        {
            // do not buffer when PixelSnap is active or small polygon
            return std::make_shared<SystemDependentData_ID2D1PathGeometry>(pID2D1PathGeometry);
        }
        else
        {
            return rPolygon.addOrReplaceSystemDependentData<SystemDependentData_ID2D1PathGeometry>(
                pID2D1PathGeometry);
        }
    }

    return std::shared_ptr<SystemDependentData_ID2D1PathGeometry>();
}

std::shared_ptr<SystemDependentData_ID2D1PathGeometry>
getOrCreateFillGeometry(const basegfx::B2DPolyPolygon& rPolyPolygon)
{
    // try to access buffered data
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1PathGeometry(
        rPolyPolygon.getSystemDependentData<SystemDependentData_ID2D1PathGeometry>());

    if (pSystemDependentData_ID2D1PathGeometry)
    {
        // use and return buffered data
        return pSystemDependentData_ID2D1PathGeometry;
    }

    sal::systools::COMReference<ID2D1PathGeometry> pID2D1PathGeometry;
    HRESULT hr(
        aID2D1GlobalFactoryProvider.getID2D1Factory()->CreatePathGeometry(&pID2D1PathGeometry));
    const sal_uInt32 nCount(rPolyPolygon.count());

    if (SUCCEEDED(hr) && nCount)
    {
        sal::systools::COMReference<ID2D1GeometrySink> pSink;
        hr = pID2D1PathGeometry->Open(&pSink);

        if (SUCCEEDED(hr) && pSink)
        {
            for (sal_uInt32 a(0); a < nCount; a++)
            {
                const basegfx::B2DPolygon& rPolygon(rPolyPolygon.getB2DPolygon(a));
                const sal_uInt32 nPointCount(rPolygon.count());

                if (nPointCount)
                {
                    const basegfx::B2DPoint aStart(rPolygon.getB2DPoint(0));

                    pSink->BeginFigure(D2D1::Point2F(aStart.getX(), aStart.getY()),
                                       D2D1_FIGURE_BEGIN_FILLED);
                    addB2DPolygonToPathGeometry(pSink, rPolygon, nullptr);
                    pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
                }
            }

            pSink->Close();
        }
    }

    // add to buffering mechanism
    if (pID2D1PathGeometry)
    {
        return rPolyPolygon.addOrReplaceSystemDependentData<SystemDependentData_ID2D1PathGeometry>(
            pID2D1PathGeometry);
    }

    return std::shared_ptr<SystemDependentData_ID2D1PathGeometry>();
}

class SystemDependentData_ID2D1Bitmap : public basegfx::SystemDependentData
{
private:
    sal::systools::COMReference<ID2D1Bitmap> mpD2DBitmap;
    const std::shared_ptr<SalBitmap> maAssociatedAlpha;

public:
    SystemDependentData_ID2D1Bitmap(sal::systools::COMReference<ID2D1Bitmap>& rD2DBitmap,
                                    const std::shared_ptr<SalBitmap>& rAssociatedAlpha)
        : basegfx::SystemDependentData(Application::GetSystemDependentDataManager())
        , mpD2DBitmap(rD2DBitmap)
        , maAssociatedAlpha(rAssociatedAlpha)
    {
    }

    const sal::systools::COMReference<ID2D1Bitmap>& getID2D1Bitmap() const { return mpD2DBitmap; }
    const std::shared_ptr<SalBitmap>& getAssociatedAlpha() const { return maAssociatedAlpha; }

    virtual sal_Int64 estimateUsageInBytes() const override;
};

sal_Int64 SystemDependentData_ID2D1Bitmap::estimateUsageInBytes() const
{
    sal_Int64 aRetval(0);

    if (getID2D1Bitmap())
    {
        // use factor 4 for RGBA_8 as estimation
        const D2D1_SIZE_U aSizePixel(getID2D1Bitmap()->GetPixelSize());
        aRetval = static_cast<sal_Int64>(aSizePixel.width)
                  * static_cast<sal_Int64>(aSizePixel.height) * 4;
    }

    return aRetval;
}

sal::systools::COMReference<ID2D1Bitmap> createB2DBitmap(const BitmapEx& rBitmapEx)
{
    const Size& rSizePixel(rBitmapEx.GetSizePixel());
    const bool bAlpha(rBitmapEx.IsAlpha());
    const sal_uInt32 nPixelCount(rSizePixel.Width() * rSizePixel.Height());
    std::unique_ptr<sal_uInt32[]> aData(new sal_uInt32[nPixelCount]);
    sal_uInt32* pTarget = aData.get();

    if (bAlpha)
    {
        Bitmap aSrcAlpha(rBitmapEx.GetAlphaMask().GetBitmap());
        Bitmap::ScopedReadAccess pReadAccess(const_cast<Bitmap&>(rBitmapEx.GetBitmap()));
        Bitmap::ScopedReadAccess pAlphaReadAccess(aSrcAlpha.AcquireReadAccess(), aSrcAlpha);
        const tools::Long nHeight(pReadAccess->Height());
        const tools::Long nWidth(pReadAccess->Width());

        for (tools::Long y = 0; y < nHeight; ++y)
        {
            for (tools::Long x = 0; x < nWidth; ++x)
            {
                const BitmapColor aColor(pReadAccess->GetColor(y, x));
                const BitmapColor aAlpha(pAlphaReadAccess->GetColor(y, x));
                const sal_uInt16 nAlpha(255 - aAlpha.GetRed());

                *pTarget++ = sal_uInt32(BitmapColor(
                    ColorAlpha, sal_uInt8((sal_uInt16(aColor.GetRed()) * nAlpha) >> 8),
                    sal_uInt8((sal_uInt16(aColor.GetGreen()) * nAlpha) >> 8),
                    sal_uInt8((sal_uInt16(aColor.GetBlue()) * nAlpha) >> 8), aAlpha.GetRed()));
            }
        }
    }
    else
    {
        Bitmap::ScopedReadAccess pReadAccess(const_cast<Bitmap&>(rBitmapEx.GetBitmap()));
        const tools::Long nHeight(pReadAccess->Height());
        const tools::Long nWidth(pReadAccess->Width());

        for (tools::Long y = 0; y < nHeight; ++y)
        {
            for (tools::Long x = 0; x < nWidth; ++x)
            {
                const BitmapColor aColor(pReadAccess->GetColor(y, x));
                *pTarget++ = sal_uInt32(aColor);
            }
        }
    }

    // use GlobalRenderTarget to allow usage combined with
    // the Direct2D CreateSharedBitmap-mechanism. This is needed
    // since ID2D1Bitmap is a ID2D1RenderTarget-dependent resource
    // and thus - in principle - would have to be re-created for
    // *each* new ID2D1RenderTarget, that means for *each* new
    // target HDC, resp. OutputDevice
    sal::systools::COMReference<ID2D1Bitmap> pID2D1Bitmap;

    if (aID2D1GlobalRenderTargetProvider.getID2D1DCRenderTarget())
    {
        const HRESULT hr(aID2D1GlobalRenderTargetProvider.getID2D1DCRenderTarget()->CreateBitmap(
            D2D1::SizeU(rSizePixel.Width(), rSizePixel.Height()), &aData[0],
            rSizePixel.Width() * sizeof(sal_uInt32),
            D2D1::BitmapProperties(
                D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, // DXGI_FORMAT
                                  bAlpha ? D2D1_ALPHA_MODE_PREMULTIPLIED
                                         : D2D1_ALPHA_MODE_IGNORE)), // D2D1_ALPHA_MODE
            &pID2D1Bitmap));

        if (!SUCCEEDED(hr))
            pID2D1Bitmap.clear();
    }

    return pID2D1Bitmap;
}

sal::systools::COMReference<ID2D1Bitmap>
getOrCreateB2DBitmap(sal::systools::COMReference<ID2D1RenderTarget>& rRT, const BitmapEx& rBitmapEx)
{
    const basegfx::SystemDependentDataHolder* pHolder(
        rBitmapEx.GetBitmap().accessSystemDependentDataHolder());
    std::shared_ptr<SystemDependentData_ID2D1Bitmap> pSystemDependentData_ID2D1Bitmap;

    if (nullptr != pHolder)
    {
        // try to access SystemDependentDataHolder and buffered data
        pSystemDependentData_ID2D1Bitmap
            = std::static_pointer_cast<SystemDependentData_ID2D1Bitmap>(
                pHolder->getSystemDependentData(
                    typeid(SystemDependentData_ID2D1Bitmap).hash_code()));

        // check data validity for associated Alpha
        if (pSystemDependentData_ID2D1Bitmap
            && pSystemDependentData_ID2D1Bitmap->getAssociatedAlpha()
                   != rBitmapEx.GetAlphaMask().GetBitmap().ImplGetSalBitmap())
        {
            // AssociatedAlpha did change, data invalid
            pSystemDependentData_ID2D1Bitmap.reset();
        }
    }

    if (!pSystemDependentData_ID2D1Bitmap)
    {
        // have to create newly
        sal::systools::COMReference<ID2D1Bitmap> pID2D1Bitmap(createB2DBitmap(rBitmapEx));

        if (pID2D1Bitmap)
        {
            // creation worked, create SystemDependentData_ID2D1Bitmap
            pSystemDependentData_ID2D1Bitmap = std::make_shared<SystemDependentData_ID2D1Bitmap>(
                pID2D1Bitmap, rBitmapEx.GetAlphaMask().GetBitmap().ImplGetSalBitmap());

            // only add if feasible
            if (nullptr != pHolder
                && pSystemDependentData_ID2D1Bitmap->calculateCombinedHoldCyclesInSeconds() > 0)
            {
                basegfx::SystemDependentData_SharedPtr r2(pSystemDependentData_ID2D1Bitmap);
                const_cast<basegfx::SystemDependentDataHolder*>(pHolder)
                    ->addOrReplaceSystemDependentData(r2);
            }
        }
    }

    sal::systools::COMReference<ID2D1Bitmap> pWrappedD2DBitmap;

    if (pSystemDependentData_ID2D1Bitmap)
    {
        // embed to CreateSharedBitmap, that makes it usable on
        // the specified RenderTarget
        const HRESULT hr(rRT->CreateSharedBitmap(
            __uuidof(ID2D1Bitmap),
            static_cast<void*>(pSystemDependentData_ID2D1Bitmap->getID2D1Bitmap()), nullptr,
            &pWrappedD2DBitmap));

        if (!SUCCEEDED(hr))
            pWrappedD2DBitmap.clear();
    }

    return pWrappedD2DBitmap;
}

// This is a simple local derivation of D2DPixelProcessor2D to be used
// when sub-content needs to be rendered to pixels. Hand over the adapted
// ViewInformation2D, a pixel size and the parent RenderTarget. It will
// locally create and use a ID2D1BitmapRenderTarget to render the stuff
// (you need to call process() with the primitives to be painted of
// course). Then use the local helper getID2D1Bitmap() to access the
// ID2D1Bitmap which was the target of that operation.
class D2DBitmapPixelProcessor2D final : public drawinglayer::processor2d::D2DPixelProcessor2D
{
    // the local ID2D1BitmapRenderTarget
    sal::systools::COMReference<ID2D1BitmapRenderTarget> mpBitmapRenderTarget;

public:
    // helper class to create another instance of D2DPixelProcessor2D for
    // creating helper-ID2D1Bitmap's for a given ID2D1RenderTarget
    D2DBitmapPixelProcessor2D(const drawinglayer::geometry::ViewInformation2D& rViewInformation,
                              sal_uInt32 nWidth, sal_uInt32 nHeight,
                              sal::systools::COMReference<ID2D1RenderTarget>& rParent)
        : drawinglayer::processor2d::D2DPixelProcessor2D(rViewInformation)
        , mpBitmapRenderTarget()
    {
        if (0 == nWidth || 0 == nHeight)
        {
            // no width/height, done
            increaseError();
        }

        if (!hasError())
        {
            // Allocate compatible RGBA render target
            const D2D1_SIZE_U aRenderTargetSizePixel(D2D1::SizeU(nWidth, nHeight));
            const HRESULT hr(rParent->CreateCompatibleRenderTarget(
                nullptr, &aRenderTargetSizePixel, nullptr,
                D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE, &mpBitmapRenderTarget));

            if (!SUCCEEDED(hr) || nullptr == mpBitmapRenderTarget)
            {
                // did not work, done
                increaseError();
            }
            else
            {
                sal::systools::COMReference<ID2D1RenderTarget> pRT;
                mpBitmapRenderTarget->QueryInterface(__uuidof(ID2D1RenderTarget),
                                                     reinterpret_cast<void**>(&pRT));
                setRenderTarget(pRT);
            }
        }

        if (hasRenderTarget())
        {
            // set Viewort if none was given. We have a fixed pixel target, s we know the
            // exact Viewport to work on
            if (getViewInformation2D().getViewport().isEmpty())
            {
                drawinglayer::geometry::ViewInformation2D aViewInformation(getViewInformation2D());
                basegfx::B2DRange aViewport(0.0, 0.0, nWidth, nHeight);
                basegfx::B2DHomMatrix aInvViewTransform(aViewInformation.getViewTransformation());

                aInvViewTransform.invert();
                aViewport.transform(aInvViewTransform);
                aViewInformation.setViewport(aViewport);
                updateViewInformation(aViewInformation);
            }

            // clear as render preparation
            getRenderTarget()->BeginDraw();
            getRenderTarget()->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
            getRenderTarget()->EndDraw();
        }
    }

    sal::systools::COMReference<ID2D1Bitmap> getID2D1Bitmap() const
    {
        sal::systools::COMReference<ID2D1Bitmap> pResult;

        // access the resulting bitmap if exists
        if (mpBitmapRenderTarget)
        {
            mpBitmapRenderTarget->GetBitmap(&pResult);
        }

        return pResult;
    }
};
}

namespace drawinglayer::processor2d
{
D2DPixelProcessor2D::D2DPixelProcessor2D(const geometry::ViewInformation2D& rViewInformation)
    : BaseProcessor2D(rViewInformation)
    , maBColorModifierStack()
    , mpRT()
    , mnRecursionCounter(0)
    , mnErrorCounter(0)
{
}

D2DPixelProcessor2D::D2DPixelProcessor2D(const geometry::ViewInformation2D& rViewInformation,
                                         HDC aHdc)
    : BaseProcessor2D(rViewInformation)
    , maBColorModifierStack()
    , mpRT()
    , mnRecursionCounter(0)
    , mnErrorCounter(0)
{
    sal::systools::COMReference<ID2D1DCRenderTarget> pDCRT;
    tools::Long aOutWidth(0), aOutHeight(0);

    if (aHdc)
    {
        aOutWidth = GetDeviceCaps(aHdc, HORZRES);
        aOutHeight = GetDeviceCaps(aHdc, VERTRES);
    }

    if (aOutWidth > 0 && aOutHeight > 0 && aID2D1GlobalFactoryProvider.getID2D1Factory())
    {
        const D2D1_RENDER_TARGET_PROPERTIES aRTProps(D2D1::RenderTargetProperties(
            D2D1_RENDER_TARGET_TYPE_DEFAULT,
            D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
                              D2D1_ALPHA_MODE_IGNORE), //D2D1_ALPHA_MODE_PREMULTIPLIED),
            0, 0, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_DEFAULT));

        const HRESULT hr(
            aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateDCRenderTarget(&aRTProps, &pDCRT));

        if (!SUCCEEDED(hr))
            pDCRT.clear();
    }

    if (pDCRT)
    {
        const RECT rc(
            { 0, 0, o3tl::narrowing<LONG>(aOutWidth), o3tl::narrowing<LONG>(aOutHeight) });
        const HRESULT hr(pDCRT->BindDC(aHdc, &rc));

        if (!SUCCEEDED(hr))
            pDCRT.clear();
    }

    if (pDCRT)
    {
        if (rViewInformation.getUseAntiAliasing())
        {
            D2D1_ANTIALIAS_MODE eAAMode = D2D1_ANTIALIAS_MODE_PER_PRIMITIVE;
            pDCRT->SetAntialiasMode(eAAMode);
        }
        else
        {
            D2D1_ANTIALIAS_MODE eAAMode = D2D1_ANTIALIAS_MODE_ALIASED;
            pDCRT->SetAntialiasMode(eAAMode);
        }

        // since ID2D1DCRenderTarget depends on the transformation
        // set at hdc, be careful and reset it to identity
        XFORM aXForm;
        aXForm.eM11 = 1.0;
        aXForm.eM12 = 0.0;
        aXForm.eM21 = 0.0;
        aXForm.eM22 = 1.0;
        aXForm.eDx = 0.0;
        aXForm.eDy = 0.0;
        SetWorldTransform(aHdc, &aXForm);
    }

    if (pDCRT)
    {
        sal::systools::COMReference<ID2D1RenderTarget> pRT;
        pDCRT->QueryInterface(__uuidof(ID2D1RenderTarget), reinterpret_cast<void**>(&pRT));
        setRenderTarget(pRT);
    }
    else
    {
        increaseError();
    }
}

void D2DPixelProcessor2D::processPolygonHairlinePrimitive2D(
    const primitive2d::PolygonHairlinePrimitive2D& rPolygonHairlinePrimitive2D)
{
    const basegfx::B2DPolygon& rPolygon(rPolygonHairlinePrimitive2D.getB2DPolygon());

    if (!rPolygon.count())
    {
        // no geometry, done
        return;
    }

    bool bDone(false);
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1PathGeometry(
        getOrCreatePathGeometry(rPolygon, getViewInformation2D()));

    if (pSystemDependentData_ID2D1PathGeometry)
    {
        sal::systools::COMReference<ID2D1TransformedGeometry> pTransformedGeometry;
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        const basegfx::B2DHomMatrix& rObjectToView(
            getViewInformation2D().getObjectToViewTransformation());
        HRESULT hr(aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateTransformedGeometry(
            pSystemDependentData_ID2D1PathGeometry->getID2D1PathGeometry(),
            D2D1::Matrix3x2F(rObjectToView.a(), rObjectToView.b(), rObjectToView.c(),
                             rObjectToView.d(), rObjectToView.e() + fAAOffset,
                             rObjectToView.f() + fAAOffset),
            &pTransformedGeometry));

        if (SUCCEEDED(hr) && pTransformedGeometry)
        {
            const basegfx::BColor aHairlineColor(
                maBColorModifierStack.getModifiedColor(rPolygonHairlinePrimitive2D.getBColor()));
            const D2D1::ColorF aD2DColor(aHairlineColor.getRed(), aHairlineColor.getGreen(),
                                         aHairlineColor.getBlue());
            sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
            hr = getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush);

            if (SUCCEEDED(hr) && pColorBrush)
            {
                getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
                // TODO: Unfortunately Direct2D paint of one pixel wide lines does not
                // correctly and completely blend 100% over the background. Experimenting
                // shows that a value around/slightly below 2.0 is needed which hints that
                // alpha blending the half-shifted lines (see fAAOffset above) is involved.
                // To get correct blending I try to use just wider hairlines for now. This
                // may need to be improved - or balanced (trying sqrt(2) now...)
                getRenderTarget()->DrawGeometry(pTransformedGeometry, pColorBrush, 1.44f);
                bDone = true;
            }
        }
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processPolyPolygonColorPrimitive2D(
    const primitive2d::PolyPolygonColorPrimitive2D& rPolyPolygonColorPrimitive2D)
{
    const basegfx::B2DPolyPolygon& rPolyPolygon(rPolyPolygonColorPrimitive2D.getB2DPolyPolygon());
    const sal_uInt32 nCount(rPolyPolygon.count());

    if (!nCount)
    {
        // no geometry, done
        return;
    }

    bool bDone(false);
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1PathGeometry(
        getOrCreateFillGeometry(rPolyPolygon));

    if (pSystemDependentData_ID2D1PathGeometry)
    {
        sal::systools::COMReference<ID2D1TransformedGeometry> pTransformedGeometry;
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        const basegfx::B2DHomMatrix& rObjectToView(
            getViewInformation2D().getObjectToViewTransformation());
        HRESULT hr(aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateTransformedGeometry(
            pSystemDependentData_ID2D1PathGeometry->getID2D1PathGeometry(),
            D2D1::Matrix3x2F(rObjectToView.a(), rObjectToView.b(), rObjectToView.c(),
                             rObjectToView.d(), rObjectToView.e() + fAAOffset,
                             rObjectToView.f() + fAAOffset),
            &pTransformedGeometry));

        if (SUCCEEDED(hr) && pTransformedGeometry)
        {
            const basegfx::BColor aFillColor(
                maBColorModifierStack.getModifiedColor(rPolyPolygonColorPrimitive2D.getBColor()));
            const D2D1::ColorF aD2DColor(aFillColor.getRed(), aFillColor.getGreen(),
                                         aFillColor.getBlue());

            sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
            hr = getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush);

            if (SUCCEEDED(hr) && pColorBrush)
            {
                getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
                getRenderTarget()->FillGeometry(pTransformedGeometry, pColorBrush);
                bDone = true;
            }
        }
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processBitmapPrimitive2D(
    const primitive2d::BitmapPrimitive2D& rBitmapCandidate)
{
    // check if graphic content is inside discrete local ViewPort
    const basegfx::B2DRange& rDiscreteViewPort(getViewInformation2D().getDiscreteViewport());
    const basegfx::B2DHomMatrix aLocalTransform(
        getViewInformation2D().getObjectToViewTransformation() * rBitmapCandidate.getTransform());

    if (!rDiscreteViewPort.isEmpty())
    {
        basegfx::B2DRange aUnitRange(0.0, 0.0, 1.0, 1.0);

        aUnitRange.transform(aLocalTransform);

        if (!aUnitRange.overlaps(rDiscreteViewPort))
        {
            // content is outside discrete local ViewPort, done
            return;
        }
    }

    BitmapEx aBitmapEx(rBitmapCandidate.getBitmap());

    if (aBitmapEx.IsEmpty() || aBitmapEx.GetSizePixel().IsEmpty())
    {
        // no pixel data, done
        return;
    }

    if (maBColorModifierStack.count())
    {
        // need to apply ColorModifier to Bitmap data
        aBitmapEx = aBitmapEx.ModifyBitmapEx(maBColorModifierStack);

        if (aBitmapEx.IsEmpty())
        {
            // color gets completely replaced, get it (any input works)
            const basegfx::BColor aModifiedColor(
                maBColorModifierStack.getModifiedColor(basegfx::BColor()));

            // use unit geometry as fallback object geometry. Do *not*
            // transform, the below used method will use the already
            // correctly initialized local ViewInformation
            basegfx::B2DPolygon aPolygon(basegfx::utils::createUnitPolygon());

            rtl::Reference<primitive2d::PolyPolygonColorPrimitive2D> aTemp(
                new primitive2d::PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon),
                                                             aModifiedColor));

            // draw as Polygon, done
            processPolyPolygonColorPrimitive2D(*aTemp);
            return;
        }
    }

    bool bDone(false);
    sal::systools::COMReference<ID2D1Bitmap> pD2DBitmap(
        getOrCreateB2DBitmap(getRenderTarget(), aBitmapEx));

    if (pD2DBitmap)
    {
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F(
            aLocalTransform.a(), aLocalTransform.b(), aLocalTransform.c(), aLocalTransform.d(),
            aLocalTransform.e() + fAAOffset, aLocalTransform.f() + fAAOffset));

        // destinationRectangle is part of transformation above, so use UnitRange
        getRenderTarget()->DrawBitmap(pD2DBitmap, D2D1::RectF(0.0, 0.0, 1.0, 1.0));
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

sal::systools::COMReference<ID2D1Bitmap> D2DPixelProcessor2D::implCreateAlpha_Direct(
    const primitive2d::TransparencePrimitive2D& rTransCandidate,
    const basegfx::B2DRange& rVisibleRange)
{
    // Try if we can use ID2D1DeviceContext/d2d1_1 by querying for interface.
    // Only then can we use ID2D1Effect/CLSID_D2D1LuminanceToAlpha and it makes
    // sense to try to do it this way in this implementation
    sal::systools::COMReference<ID2D1DeviceContext> pID2D1DeviceContext;
    getRenderTarget()->QueryInterface(__uuidof(ID2D1DeviceContext),
                                      reinterpret_cast<void**>(&pID2D1DeviceContext));
    sal::systools::COMReference<ID2D1Bitmap> pRetval;

    if (!pID2D1DeviceContext)
    {
        // no, done - tell caller to use fallback by returning empty - we have
        // not the preconditions for this
        return pRetval;
    }

    // Release early, was only a test and I saw comments in docu thatQueryInterface
    // does already increase that refcount
    pID2D1DeviceContext.clear();

    // I had a former version (call it 'a') where I directly painted to a
    // alpha-only bitmap target, see aAlphaFormat below and refer to
    // refs/changes/87/141087/21 for details.
    // To do that this class had a member mbTargetAlpha and all other
    // impls of ::process*Primitive2D of this renderer had to take care
    // of it when true by setting used colors to their LuminanceToAlpha values,
    // so another necessity similar and besides a possible ColorModifierStack.
    // That worked okay, since for now this is not complex to do since only
    // gradients (decomposed to Polygons) get rendered for now when a
    // TransparencePrimitive2D is processed, so it would work as long as only
    // polygons are treated correctly.
    // But the definition of TransparencePrimitive2D is (see include\
    // drawinglayer\primitive2d\transparenceprimitive2d.hxx) is more dynamic:
    //
    //    The basic definition is to use the transparence content as transparence-Mask by
    //    interpreting the transparence-content not as RGB, but as Luminance transparence mask
    //    using the common RGB_to_luminance definition as e.g. used by VCL.
    //
    // And it is good and necessary to be defined that way to be able to
    // define *any* content as alpha channel for this primitive, now and in the
    // future. Thus, more complex stuff like Bitmaps(RBGA) and sub-contents
    // themselves, containing transparence, may be used in the future, and the
    // former solution (a) would create errors.
    // To solve this, it is necessary to unchanged draw that sub-content as
    // RGB and convert the complete result to luminance, so being independent
    // of painting already as luminance-based alpha channel, so I created this
    // method 'b'.
    // This is possible using ID2D1Effect and CLSID_D2D1LuminanceToAlpha when
    // a Direct2D is in place that supports this (else fallback to
    // implCreateAlpha_B2DBitmap, see there). I thoroughly compared a and b
    // in a windows pro build, there are only minimal differences, so equal
    // in performance. Thus I choose (b) over (a) for less complexity & more
    // security, esp. for the future to avoid errors.
    //
    // NOTE: This is also a good example for future impls how to use the
    // ID2D1Effect mechanism of Direct2D, e.g. for our glow/softEdge/shadow
    // stuff...

    // Use a temporary second instance of a D2DBitmapPixelProcessor2D with adapted
    // ViewInformation2D, it will create the needed ID2D1BitmapRenderTarget
    // locally and Clear() it (see class def above).
    // That way it is not necessary to patch/relocate all the local variables (safer)
    // and the renderer has no real overhead itself
    geometry::ViewInformation2D aAdaptedViewInformation2D(getViewInformation2D());
    const double fTargetWidth(ceil(rVisibleRange.getWidth()));
    const double fTargetHeight(ceil(rVisibleRange.getHeight()));

    {
        // create adapted ViewTransform, needs to be offset in discrete coordinates,
        // so multiply from left
        basegfx::B2DHomMatrix aAdapted(basegfx::utils::createTranslateB2DHomMatrix(
                                           -rVisibleRange.getMinX(), -rVisibleRange.getMinY())
                                       * getViewInformation2D().getViewTransformation());
        aAdaptedViewInformation2D.setViewTransformation(aAdapted);

        // reset Viewport (world coordinates), so the helper renderer will create it's
        // own based on it's given internal discrete size
        aAdaptedViewInformation2D.setViewport(basegfx::B2DRange());
    }

    D2DBitmapPixelProcessor2D aSubContentRenderer(aAdaptedViewInformation2D, fTargetWidth,
                                                  fTargetHeight, getRenderTarget());

    if (!aSubContentRenderer.valid())
    {
        // did not work, done
        return pRetval;
    }

    // render sub-content recursively
    aSubContentRenderer.process(rTransCandidate.getTransparence());

    // grab Bitmap & prepare results from RGBA content rendering
    sal::systools::COMReference<ID2D1Bitmap> pInBetweenResult(aSubContentRenderer.getID2D1Bitmap());

    // Now we need a target to render this to, using the ID2D1Effect tooling.
    // We can directly apply the effect to an alpha-only 8bit target here,
    // so create one (no RGBA needed for this).
    // We need another render target: I tried to render pInBetweenResult
    // to pContent again, but that does not work due to the bitmap
    // fetched being probably only an internal reference to the
    // ID2D1BitmapRenderTarget, thus it would draw onto itself -> chaos
    sal::systools::COMReference<ID2D1BitmapRenderTarget> pContent;
    const D2D1_PIXEL_FORMAT aAlphaFormat(
        D2D1::PixelFormat(DXGI_FORMAT_A8_UNORM, D2D1_ALPHA_MODE_STRAIGHT));
    const D2D1_SIZE_U aRenderTargetSizePixel(
        D2D1::SizeU(ceil(rVisibleRange.getWidth()), ceil(rVisibleRange.getHeight())));
    const HRESULT hr(getRenderTarget()->CreateCompatibleRenderTarget(
        nullptr, &aRenderTargetSizePixel, &aAlphaFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE,
        &pContent));

    if (SUCCEEDED(hr) && pContent)
    {
        // try to access ID2D1DeviceContext of that target, we need that *now*
        pContent->QueryInterface(__uuidof(ID2D1DeviceContext),
                                 reinterpret_cast<void**>(&pID2D1DeviceContext));

        if (pID2D1DeviceContext)
        {
            // create the effect
            sal::systools::COMReference<ID2D1Effect> pLuminanceToAlpha;
            pID2D1DeviceContext->CreateEffect(CLSID_D2D1LuminanceToAlpha, &pLuminanceToAlpha);

            if (pLuminanceToAlpha)
            {
                // chain effect stuff together & paint it
                pLuminanceToAlpha->SetInput(0, pInBetweenResult);

                pID2D1DeviceContext->BeginDraw();
                pID2D1DeviceContext->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
                pID2D1DeviceContext->DrawImage(pLuminanceToAlpha);
                pID2D1DeviceContext->EndDraw();

                // grab result
                pContent->GetBitmap(&pRetval);
            }
        }
    }

    return pRetval;
}

sal::systools::COMReference<ID2D1Bitmap> D2DPixelProcessor2D::implCreateAlpha_B2DBitmap(
    const primitive2d::TransparencePrimitive2D& rTransCandidate,
    const basegfx::B2DRange& rVisibleRange, D2D1_MATRIX_3X2_F& rMaskScale)
{
    // Use this fallback that will also use a pixel processor indirectly,
    // but allows to get the AlphaMask as vcl Bitmap using existing tooling
    const sal_uInt32 nDiscreteClippedWidth(ceil(rVisibleRange.getWidth()));
    const sal_uInt32 nDiscreteClippedHeight(ceil(rVisibleRange.getHeight()));
    const sal_uInt32 nMaximumQuadraticPixels(250000);

    // Embed content graphics to TransformPrimitive2D
    const basegfx::B2DHomMatrix aAlphaEmbedding(
        basegfx::utils::createTranslateB2DHomMatrix(-rVisibleRange.getMinX(),
                                                    -rVisibleRange.getMinY())
        * getViewInformation2D().getObjectToViewTransformation());
    const primitive2d::Primitive2DReference xAlphaEmbedRef(new primitive2d::TransformPrimitive2D(
        aAlphaEmbedding,
        drawinglayer::primitive2d::Primitive2DContainer(rTransCandidate.getTransparence())));
    drawinglayer::primitive2d::Primitive2DContainer xEmbedSeq{ xAlphaEmbedRef };

    // use empty ViewInformation to have neutral transformation
    const geometry::ViewInformation2D aEmptyViewInformation2D;

    // use new mode to create AlphaChannel (not just AlphaMask) for transparency channel
    const AlphaMask aAlpha(::drawinglayer::createAlphaMask(
        std::move(xEmbedSeq), aEmptyViewInformation2D, nDiscreteClippedWidth,
        nDiscreteClippedHeight, nMaximumQuadraticPixels, true));
    sal::systools::COMReference<ID2D1Bitmap> pRetval;

    if (aAlpha.IsEmpty())
    {
        // if we have no content we are done
        return pRetval;
    }

    // use alpha data to create the ID2D1Bitmap
    const Size& rSizePixel(aAlpha.GetSizePixel());
    const sal_uInt32 nPixelCount(rSizePixel.Width() * rSizePixel.Height());
    std::unique_ptr<sal_uInt8[]> aData(new sal_uInt8[nPixelCount]);
    sal_uInt8* pTarget = aData.get();
    Bitmap aSrcAlpha(aAlpha.GetBitmap());
    Bitmap::ScopedReadAccess pReadAccess(aSrcAlpha.AcquireReadAccess(), aSrcAlpha);
    const tools::Long nHeight(pReadAccess->Height());
    const tools::Long nWidth(pReadAccess->Width());

    for (tools::Long y = 0; y < nHeight; ++y)
    {
        for (tools::Long x = 0; x < nWidth; ++x)
        {
            const BitmapColor aColor(pReadAccess->GetColor(y, x));
            *pTarget++ = aColor.GetLuminance();
        }
    }

    const D2D1_BITMAP_PROPERTIES aBmProps(D2D1::BitmapProperties(
        D2D1::PixelFormat(DXGI_FORMAT_A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)));
    const HRESULT hr(getRenderTarget()->CreateBitmap(
        D2D1::SizeU(rSizePixel.Width(), rSizePixel.Height()), &aData[0],
        rSizePixel.Width() * sizeof(sal_uInt8), &aBmProps, &pRetval));

    if (!SUCCEEDED(hr) || !pRetval)
    {
        // did not work, done
        return pRetval;
    }

    // create needed adapted transformation for alpha brush.
    // We may have to take a corrective scaling into account when the
    // MaximumQuadraticPixel limit was used/triggered
    const Size& rBitmapExSizePixel(aAlpha.GetSizePixel());

    if (static_cast<sal_uInt32>(rBitmapExSizePixel.Width()) != nDiscreteClippedWidth
        || static_cast<sal_uInt32>(rBitmapExSizePixel.Height()) != nDiscreteClippedHeight)
    {
        // scale in X and Y should be the same (see fReduceFactor in createAlphaMask),
        // so adapt numerically to a single scale value, they are integer rounded values
        const double fScaleX(static_cast<double>(rBitmapExSizePixel.Width())
                             / static_cast<double>(nDiscreteClippedWidth));
        const double fScaleY(static_cast<double>(rBitmapExSizePixel.Height())
                             / static_cast<double>(nDiscreteClippedHeight));

        const double fScale(1.0 / ((fScaleX + fScaleY) * 0.5));
        rMaskScale = D2D1::Matrix3x2F::Scale(fScale, fScale);
    }

    return pRetval;
}

void D2DPixelProcessor2D::processTransparencePrimitive2D(
    const primitive2d::TransparencePrimitive2D& rTransCandidate)
{
    if (rTransCandidate.getChildren().empty())
    {
        // no content, done
        return;
    }

    if (rTransCandidate.getTransparence().empty())
    {
        // no mask (so nothing visible), done
        return;
    }

    // calculate visible range, create only for that range
    basegfx::B2DRange aDiscreteRange(
        rTransCandidate.getChildren().getB2DRange(getViewInformation2D()));
    aDiscreteRange.transform(getViewInformation2D().getObjectToViewTransformation());
    const basegfx::B2DRange& rDiscreteViewPort(getViewInformation2D().getDiscreteViewport());
    basegfx::B2DRange aVisibleRange(aDiscreteRange);

    if (!rDiscreteViewPort.isEmpty())
    {
        aVisibleRange.intersect(rDiscreteViewPort);

        if (aVisibleRange.isEmpty())
        {
            // not visible, done
            return;
        }
    }

    // try to create directly, this needs the current mpRT to be a ID2D1DeviceContext/d2d1_1
    // what is not guaranteed but usually works for more modern windows (after 7)
    sal::systools::COMReference<ID2D1Bitmap> pAlphaBitmap(
        implCreateAlpha_Direct(rTransCandidate, aVisibleRange));
    D2D1_MATRIX_3X2_F aMaskScale(D2D1::Matrix3x2F::Identity());

    if (!pAlphaBitmap)
    {
        // did not work, use more expensive fallback to existing tooling
        pAlphaBitmap = implCreateAlpha_B2DBitmap(rTransCandidate, aVisibleRange, aMaskScale);
    }

    if (!pAlphaBitmap)
    {
        // could not create alpha channel, error
        increaseError();
        return;
    }

    sal::systools::COMReference<ID2D1Layer> pLayer;
    HRESULT hr(getRenderTarget()->CreateLayer(nullptr, &pLayer));
    bool bDone(false);

    if (SUCCEEDED(hr) && pLayer)
    {
        sal::systools::COMReference<ID2D1BitmapBrush> pBitmapBrush;
        hr = getRenderTarget()->CreateBitmapBrush(pAlphaBitmap, &pBitmapBrush);

        if (SUCCEEDED(hr) && pBitmapBrush)
        {
            // apply MaskScale to Brush, maybe used if implCreateAlpha_B2DBitmap was needed
            pBitmapBrush->SetTransform(aMaskScale);

            // need to set transform offset for Layer initialization, we work
            // in discrete device coordinates
            getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Translation(
                floor(aVisibleRange.getMinX()), floor(aVisibleRange.getMinY())));

            getRenderTarget()->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), nullptr,
                                                               D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
                                                               D2D1::Matrix3x2F::Identity(), 1.0,
                                                               pBitmapBrush),
                                         pLayer);

            // ... but need to reset to paint content unchanged
            getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());

            // draw content recursively
            process(rTransCandidate.getChildren());

            getRenderTarget()->PopLayer();
            bDone = true;
        }
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processUnifiedTransparencePrimitive2D(
    const primitive2d::UnifiedTransparencePrimitive2D& rTransCandidate)
{
    if (rTransCandidate.getChildren().empty())
    {
        // no content, done
        return;
    }

    if (0.0 == rTransCandidate.getTransparence())
    {
        // not transparent at all, use content
        process(rTransCandidate.getChildren());
        return;
    }

    if (rTransCandidate.getTransparence() < 0.0 || rTransCandidate.getTransparence() > 1.0)
    {
        // invalid transparence, done
        return;
    }

    basegfx::B2DRange aTransparencyRange(
        rTransCandidate.getChildren().getB2DRange(getViewInformation2D()));
    aTransparencyRange.transform(getViewInformation2D().getObjectToViewTransformation());
    const basegfx::B2DRange& rDiscreteViewPort(getViewInformation2D().getDiscreteViewport());

    if (!rDiscreteViewPort.isEmpty() && !rDiscreteViewPort.overlaps(aTransparencyRange))
    {
        // we have a Viewport and visible range of geometry is outside -> not visible, done
        return;
    }

    bool bDone(false);
    sal::systools::COMReference<ID2D1Layer> pLayer;
    const HRESULT hr(getRenderTarget()->CreateLayer(nullptr, &pLayer));

    if (SUCCEEDED(hr) && pLayer)
    {
        // need to set correct transform for Layer initialization, we work
        // in discrete device coordinates
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
        getRenderTarget()->PushLayer(
            D2D1::LayerParameters(D2D1::InfiniteRect(), nullptr, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
                                  D2D1::IdentityMatrix(),
                                  1.0 - rTransCandidate.getTransparence()), // opacity
            pLayer);
        process(rTransCandidate.getChildren());
        getRenderTarget()->PopLayer();
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processMaskPrimitive2DPixel(
    const primitive2d::MaskPrimitive2D& rMaskCandidate)
{
    if (rMaskCandidate.getChildren().empty())
    {
        // no content, done
        return;
    }

    basegfx::B2DPolyPolygon aMask(rMaskCandidate.getMask());

    if (!aMask.count())
    {
        // no mask (so nothing inside), done
        return;
    }

    basegfx::B2DRange aMaskRange(aMask.getB2DRange());
    aMaskRange.transform(getViewInformation2D().getObjectToViewTransformation());
    const basegfx::B2DRange& rDiscreteViewPort(getViewInformation2D().getDiscreteViewport());

    if (!rDiscreteViewPort.isEmpty() && !rDiscreteViewPort.overlaps(aMaskRange))
    {
        // we have a Viewport and visible range of geometry is outside -> not visible, done
        return;
    }

    bool bDone(false);
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1MaskGeometry(
        getOrCreateFillGeometry(rMaskCandidate.getMask()));

    if (pSystemDependentData_ID2D1MaskGeometry)
    {
        sal::systools::COMReference<ID2D1TransformedGeometry> pTransformedMaskGeometry;
        const basegfx::B2DHomMatrix& rObjectToView(
            getViewInformation2D().getObjectToViewTransformation());
        HRESULT hr(aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateTransformedGeometry(
            pSystemDependentData_ID2D1MaskGeometry->getID2D1PathGeometry(),
            D2D1::Matrix3x2F(rObjectToView.a(), rObjectToView.b(), rObjectToView.c(),
                             rObjectToView.d(), rObjectToView.e(), rObjectToView.f()),
            &pTransformedMaskGeometry));

        if (SUCCEEDED(hr) && pTransformedMaskGeometry)
        {
            sal::systools::COMReference<ID2D1Layer> pLayer;
            hr = getRenderTarget()->CreateLayer(nullptr, &pLayer);

            if (SUCCEEDED(hr) && pLayer)
            {
                // need to set correct transform for Layer initialization, we work
                // in discrete device coordinates
                getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
                getRenderTarget()->PushLayer(
                    D2D1::LayerParameters(D2D1::InfiniteRect(), pTransformedMaskGeometry), pLayer);
                process(rMaskCandidate.getChildren());
                getRenderTarget()->PopLayer();
                bDone = true;
            }
        }
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processPointArrayPrimitive2D(
    const primitive2d::PointArrayPrimitive2D& rPointArrayCandidate)
{
    const std::vector<basegfx::B2DPoint>& rPositions(rPointArrayCandidate.getPositions());

    if (rPositions.empty())
    {
        // no geometry, done
        return;
    }

    const basegfx::BColor aPointColor(
        maBColorModifierStack.getModifiedColor(rPointArrayCandidate.getRGBColor()));
    sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
    D2D1::ColorF aD2DColor(aPointColor.getRed(), aPointColor.getGreen(), aPointColor.getBlue());
    const HRESULT hr(getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush));
    bool bDone(false);

    if (SUCCEEDED(hr) && pColorBrush)
    {
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());

        // To really paint a single pixel I found nothing better than
        // switch off AA and draw a pixel-aligned rectangle
        const D2D1_ANTIALIAS_MODE aOldAAMode(getRenderTarget()->GetAntialiasMode());
        getRenderTarget()->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);

        for (auto const& pos : rPositions)
        {
            const basegfx::B2DPoint aDiscretePos(
                getViewInformation2D().getObjectToViewTransformation() * pos);
            const double fX(ceil(aDiscretePos.getX()));
            const double fY(ceil(aDiscretePos.getY()));
            const D2D1_RECT_F rect = { FLOAT(fX), FLOAT(fY), FLOAT(fX), FLOAT(fY) };

            getRenderTarget()->DrawRectangle(&rect, pColorBrush);
        }

        getRenderTarget()->SetAntialiasMode(aOldAAMode);
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processMarkerArrayPrimitive2D(
    const primitive2d::MarkerArrayPrimitive2D& rMarkerArrayCandidate)
{
    const std::vector<basegfx::B2DPoint>& rPositions(rMarkerArrayCandidate.getPositions());

    if (rPositions.empty())
    {
        // no geometry, done
        return;
    }

    const BitmapEx& rMarker(rMarkerArrayCandidate.getMarker());

    if (rMarker.IsEmpty())
    {
        // no marker defined, done
        return;
    }

    sal::systools::COMReference<ID2D1Bitmap> pD2DBitmap(
        getOrCreateB2DBitmap(getRenderTarget(), rMarker));
    bool bDone(false);

    if (pD2DBitmap)
    {
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
        const Size& rSizePixel(rMarker.GetSizePixel());
        const tools::Long nMiX((rSizePixel.Width() / 2) + 1);
        const tools::Long nMiY((rSizePixel.Height() / 2) + 1);
        const tools::Long nPlX(rSizePixel.Width() - nMiX);
        const tools::Long nPlY(rSizePixel.Height() - nMiY);

        // draw with non-AA to show unhampered, clear, non-scaled marker
        const D2D1_ANTIALIAS_MODE aOldAAMode(getRenderTarget()->GetAntialiasMode());
        getRenderTarget()->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);

        for (auto const& pos : rPositions)
        {
            const basegfx::B2DPoint aDiscretePos(
                getViewInformation2D().getObjectToViewTransformation() * pos);
            const double fX(ceil(aDiscretePos.getX()));
            const double fY(ceil(aDiscretePos.getY()));
            const D2D1_RECT_F rect
                = { FLOAT(fX - nMiX), FLOAT(fY - nMiY), FLOAT(fX + nPlX), FLOAT(fY + nPlY) };

            getRenderTarget()->DrawBitmap(pD2DBitmap, &rect);
        }

        getRenderTarget()->SetAntialiasMode(aOldAAMode);
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processBackgroundColorPrimitive2D(
    const primitive2d::BackgroundColorPrimitive2D& rBackgroundColorCandidate)
{
    // check for allowed range [0.0 .. 1.0[
    if (rBackgroundColorCandidate.getTransparency() < 0.0
        || rBackgroundColorCandidate.getTransparency() >= 1.0)
        return;

    const D2D1::ColorF aD2DColor(rBackgroundColorCandidate.getBColor().getRed(),
                                 rBackgroundColorCandidate.getBColor().getGreen(),
                                 rBackgroundColorCandidate.getBColor().getBlue(),
                                 1.0 - rBackgroundColorCandidate.getTransparency());

    getRenderTarget()->Clear(aD2DColor);
}

void D2DPixelProcessor2D::processModifiedColorPrimitive2D(
    const primitive2d::ModifiedColorPrimitive2D& rModifiedCandidate)
{
    if (!rModifiedCandidate.getChildren().empty())
    {
        maBColorModifierStack.push(rModifiedCandidate.getColorModifier());
        process(rModifiedCandidate.getChildren());
        maBColorModifierStack.pop();
    }
}

void D2DPixelProcessor2D::processTransformPrimitive2D(
    const primitive2d::TransformPrimitive2D& rTransformCandidate)
{
    // remember current transformation and ViewInformation
    const geometry::ViewInformation2D aLastViewInformation2D(getViewInformation2D());

    // create new transformations for local ViewInformation2D
    geometry::ViewInformation2D aViewInformation2D(getViewInformation2D());
    aViewInformation2D.setObjectTransformation(getViewInformation2D().getObjectTransformation()
                                               * rTransformCandidate.getTransformation());
    updateViewInformation(aViewInformation2D);

    // process content
    process(rTransformCandidate.getChildren());

    // restore transformations
    updateViewInformation(aLastViewInformation2D);
}

void D2DPixelProcessor2D::processPolygonStrokePrimitive2D(
    const primitive2d::PolygonStrokePrimitive2D& rPolygonStrokeCandidate)
{
    const basegfx::B2DPolygon& rPolygon(rPolygonStrokeCandidate.getB2DPolygon());
    const attribute::LineAttribute& rLineAttribute(rPolygonStrokeCandidate.getLineAttribute());

    if (!rPolygon.count() || rLineAttribute.getWidth() < 0.0)
    {
        // no geometry, done
        return;
    }

    // get some values early that might be used for decisions
    const bool bHairline(0.0 == rLineAttribute.getWidth());
    const basegfx::B2DHomMatrix& rObjectToView(
        getViewInformation2D().getObjectToViewTransformation());
    const double fDiscreteLineWidth(
        bHairline
            ? 1.0
            : (rObjectToView * basegfx::B2DVector(rLineAttribute.getWidth(), 0.0)).getLength());

    // Here for every combination which the system-specific implementation is not
    // capable of visualizing, use the (for decomposable Primitives always possible)
    // fallback to the decomposition.
    if (basegfx::B2DLineJoin::NONE == rLineAttribute.getLineJoin() && fDiscreteLineWidth > 1.5)
    {
        // basegfx::B2DLineJoin::NONE is special for our office, no other GraphicSystem
        // knows that (so far), so fallback to decomposition. This is only needed if
        // LineJoin will be used, so also check for discrete LineWidth before falling back
        process(rPolygonStrokeCandidate);
        return;
    }

    // This is a method every system-specific implementation of a decomposable Primitive
    // can use to allow simple optical control of paint implementation:
    // Create a copy, e.g. change color to 'red' as here and paint before the system
    // paints it using the decomposition. That way you can - if active - directly
    // optically compare if the system-specific solution is geometrically identical to
    // the decomposition (which defines our interpretation that we need to visualize).
    // Look below in the impl for bRenderDecomposeForCompareInRed to see that in that case
    // we create a half-transparent paint to better support visual control
    static bool bRenderDecomposeForCompareInRed(false);

    if (bRenderDecomposeForCompareInRed)
    {
        const attribute::LineAttribute aRed(
            basegfx::BColor(1.0, 0.0, 0.0), rLineAttribute.getWidth(), rLineAttribute.getLineJoin(),
            rLineAttribute.getLineCap(), rLineAttribute.getMiterMinimumAngle());
        rtl::Reference<primitive2d::PolygonStrokePrimitive2D> aCopy(
            new primitive2d::PolygonStrokePrimitive2D(
                rPolygonStrokeCandidate.getB2DPolygon(), aRed,
                rPolygonStrokeCandidate.getStrokeAttribute()));
        process(*aCopy);
    }

    bool bDone(false);
    std::shared_ptr<SystemDependentData_ID2D1PathGeometry> pSystemDependentData_ID2D1PathGeometry(
        getOrCreatePathGeometry(rPolygon, getViewInformation2D()));

    if (pSystemDependentData_ID2D1PathGeometry)
    {
        sal::systools::COMReference<ID2D1TransformedGeometry> pTransformedGeometry;
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        HRESULT hr(aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateTransformedGeometry(
            pSystemDependentData_ID2D1PathGeometry->getID2D1PathGeometry(),
            D2D1::Matrix3x2F(rObjectToView.a(), rObjectToView.b(), rObjectToView.c(),
                             rObjectToView.d(), rObjectToView.e() + fAAOffset,
                             rObjectToView.f() + fAAOffset),
            &pTransformedGeometry));

        if (SUCCEEDED(hr) && pTransformedGeometry)
        {
            const basegfx::BColor aLineColor(
                maBColorModifierStack.getModifiedColor(rLineAttribute.getColor()));
            D2D1::ColorF aD2DColor(aLineColor.getRed(), aLineColor.getGreen(),
                                   aLineColor.getBlue());

            if (bRenderDecomposeForCompareInRed)
            {
                aD2DColor.a = 0.5;
            }

            sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
            hr = getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush);

            if (SUCCEEDED(hr) && pColorBrush)
            {
                sal::systools::COMReference<ID2D1StrokeStyle> pStrokeStyle;
                D2D1_CAP_STYLE aCapStyle(D2D1_CAP_STYLE_FLAT);
                D2D1_LINE_JOIN aLineJoin(D2D1_LINE_JOIN_MITER);
                const attribute::StrokeAttribute& rStrokeAttribute(
                    rPolygonStrokeCandidate.getStrokeAttribute());
                const bool bDashUsed(!rStrokeAttribute.isDefault()
                                     && !rStrokeAttribute.getDotDashArray().empty()
                                     && 0.0 < rStrokeAttribute.getFullDotDashLen());
                D2D1_DASH_STYLE aDashStyle(bDashUsed ? D2D1_DASH_STYLE_CUSTOM
                                                     : D2D1_DASH_STYLE_SOLID);
                std::vector<float> dashes;
                float miterLimit(1.0);

                switch (rLineAttribute.getLineCap())
                {
                    case css::drawing::LineCap_ROUND:
                        aCapStyle = D2D1_CAP_STYLE_ROUND;
                        break;
                    case css::drawing::LineCap_SQUARE:
                        aCapStyle = D2D1_CAP_STYLE_SQUARE;
                        break;
                    default:
                        break;
                }

                switch (rLineAttribute.getLineJoin())
                {
                    case basegfx::B2DLineJoin::NONE:
                        break;
                    case basegfx::B2DLineJoin::Bevel:
                        aLineJoin = D2D1_LINE_JOIN_BEVEL;
                        break;
                    case basegfx::B2DLineJoin::Miter:
                    {
                        // for basegfx::B2DLineJoin::Miter there are two problems:
                        // (1) MS uses D2D1_LINE_JOIN_MITER which handles the cut-off when MiterLimit is hit not by
                        //     fallback to Bevel, but by cutting miter geometry at the defined distance. That is
                        //     nice, but not what we need or is the standard for other graphic systems. Luckily there
                        //     is also D2D1_LINE_JOIN_MITER_OR_BEVEL and (after some search) the page
                        //     https://learn.microsoft.com/en-us/windows/win32/api/d2d1/ne-d2d1-d2d1_line_join
                        //     which gives some explanation, so that is what we need to use here.
                        // (2) Instead of using an angle in radians (15 deg default) MS uses
                        //     "miterLimit is relative to 1/2 LineWidth", so a length. After some experimenting
                        //     it shows that the (better understandable) angle has to be converted to the length
                        //     that a miter prolongation would have at that angle, so use some trigonometry.
                        //     Unfortunately there is also some'precision' problem (probably), so I had to
                        //     experimentally come to a correction value around 0.9925. Since that seems to
                        //     be no obvious numerical value involved somehow (and as long as I find no other
                        //     explanation) I will have to use that.
                        // NOTE: To find that correction value I usd that handy bRenderDecomposeForCompareInRed
                        //       and changes in debugger - as work tipp
                        // With both done I can use Direct2D for Miter completely - what is good for speed.
                        aLineJoin = D2D1_LINE_JOIN_MITER_OR_BEVEL;

                        // snap absolute value of angle in radians to [0.0 .. PI]
                        double fVal(::basegfx::snapToZeroRange(
                            fabs(rLineAttribute.getMiterMinimumAngle()), M_PI));

                        // cut at 0.0 and PI since sin would be zero ('endless' miter)
                        const double fSmallValue(M_PI * 0.0000001);
                        fVal = std::max(fSmallValue, fVal);
                        fVal = std::min(M_PI - fSmallValue, fVal);

                        // get relative length
                        fVal = 1.0 / sin(fVal);

                        // use for miterLimit, we need factor 2.0 (relative to double LineWidth)
                        // and the correction mentioned in (2) above
                        const double fCorrector(2.0 * 0.9925);

                        miterLimit = fVal * fCorrector;
                        break;
                    }
                    case basegfx::B2DLineJoin::Round:
                        aLineJoin = D2D1_LINE_JOIN_ROUND;
                        break;
                    default:
                        break;
                }

                if (bDashUsed)
                {
                    // dashes need to be discrete and relative to LineWidth
                    for (auto& value : rStrokeAttribute.getDotDashArray())
                    {
                        dashes.push_back(
                            (rObjectToView * basegfx::B2DVector(value, 0.0)).getLength()
                            / fDiscreteLineWidth);
                    }
                }

                hr = aID2D1GlobalFactoryProvider.getID2D1Factory()->CreateStrokeStyle(
                    D2D1::StrokeStyleProperties(aCapStyle, // startCap
                                                aCapStyle, // endCap
                                                aCapStyle, // dashCap
                                                aLineJoin, // lineJoin
                                                miterLimit, // miterLimit
                                                aDashStyle, // dashStyle
                                                0.0f), // dashOffset
                    bDashUsed ? dashes.data() : nullptr, bDashUsed ? dashes.size() : 0,
                    &pStrokeStyle);

                if (SUCCEEDED(hr) && pStrokeStyle)
                {
                    getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
                    getRenderTarget()->DrawGeometry(
                        pTransformedGeometry, pColorBrush,
                        // TODO: Hairline LineWidth, see comment at processPolygonHairlinePrimitive2D
                        bHairline ? 1.44 : fDiscreteLineWidth, pStrokeStyle);
                    bDone = true;
                }
            }
        }
    }

    if (!bDone)
    {
        // fallback to decomposition
        process(rPolygonStrokeCandidate);
    }
}

void D2DPixelProcessor2D::processLineRectanglePrimitive2D(
    const primitive2d::LineRectanglePrimitive2D& rLineRectanglePrimitive2D)
{
    if (rLineRectanglePrimitive2D.getB2DRange().isEmpty())
    {
        // no geometry, done
        return;
    }

    const basegfx::BColor aHairlineColor(
        maBColorModifierStack.getModifiedColor(rLineRectanglePrimitive2D.getBColor()));
    const D2D1::ColorF aD2DColor(aHairlineColor.getRed(), aHairlineColor.getGreen(),
                                 aHairlineColor.getBlue());
    sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
    const HRESULT hr(getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush));
    bool bDone(false);

    if (SUCCEEDED(hr) && pColorBrush)
    {
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        const basegfx::B2DHomMatrix aLocalTransform(
            getViewInformation2D().getObjectToViewTransformation());
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F(
            aLocalTransform.a(), aLocalTransform.b(), aLocalTransform.c(), aLocalTransform.d(),
            aLocalTransform.e() + fAAOffset, aLocalTransform.f() + fAAOffset));
        const basegfx::B2DRange& rRange(rLineRectanglePrimitive2D.getB2DRange());
        const D2D1_RECT_F rect = { FLOAT(rRange.getMinX()), FLOAT(rRange.getMinY()),
                                   FLOAT(rRange.getMaxX()), FLOAT(rRange.getMaxY()) };
        const double fDiscreteLineWidth(
            (getViewInformation2D().getInverseObjectToViewTransformation()
             * basegfx::B2DVector(1.44, 0.0))
                .getLength());

        getRenderTarget()->DrawRectangle(&rect, pColorBrush, fDiscreteLineWidth);
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processFilledRectanglePrimitive2D(
    const primitive2d::FilledRectanglePrimitive2D& rFilledRectanglePrimitive2D)
{
    if (rFilledRectanglePrimitive2D.getB2DRange().isEmpty())
    {
        // no geometry, done
        return;
    }

    const basegfx::BColor aFillColor(
        maBColorModifierStack.getModifiedColor(rFilledRectanglePrimitive2D.getBColor()));
    const D2D1::ColorF aD2DColor(aFillColor.getRed(), aFillColor.getGreen(), aFillColor.getBlue());
    sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
    const HRESULT hr(getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush));
    bool bDone(false);

    if (SUCCEEDED(hr) && pColorBrush)
    {
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        const basegfx::B2DHomMatrix aLocalTransform(
            getViewInformation2D().getObjectToViewTransformation());
        getRenderTarget()->SetTransform(D2D1::Matrix3x2F(
            aLocalTransform.a(), aLocalTransform.b(), aLocalTransform.c(), aLocalTransform.d(),
            aLocalTransform.e() + fAAOffset, aLocalTransform.f() + fAAOffset));
        const basegfx::B2DRange& rRange(rFilledRectanglePrimitive2D.getB2DRange());
        const D2D1_RECT_F rect = { FLOAT(rRange.getMinX()), FLOAT(rRange.getMinY()),
                                   FLOAT(rRange.getMaxX()), FLOAT(rRange.getMaxY()) };

        getRenderTarget()->FillRectangle(&rect, pColorBrush);
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processSingleLinePrimitive2D(
    const primitive2d::SingleLinePrimitive2D& rSingleLinePrimitive2D)
{
    const basegfx::BColor aLineColor(
        maBColorModifierStack.getModifiedColor(rSingleLinePrimitive2D.getBColor()));
    const D2D1::ColorF aD2DColor(aLineColor.getRed(), aLineColor.getGreen(), aLineColor.getBlue());
    sal::systools::COMReference<ID2D1SolidColorBrush> pColorBrush;
    const HRESULT hr(getRenderTarget()->CreateSolidColorBrush(aD2DColor, &pColorBrush));
    bool bDone(false);

    if (SUCCEEDED(hr) && pColorBrush)
    {
        const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
        basegfx::B2DHomMatrix aLocalTransform(
            getViewInformation2D().getObjectToViewTransformation());
        const basegfx::B2DPoint aStart(aLocalTransform * rSingleLinePrimitive2D.getStart());
        const basegfx::B2DPoint aEnd(aLocalTransform * rSingleLinePrimitive2D.getEnd());

        getRenderTarget()->SetTransform(D2D1::Matrix3x2F::Identity());
        const D2D1_POINT_2F aD2D1Start
            = { FLOAT(aStart.getX() + fAAOffset), FLOAT(aStart.getY() + fAAOffset) };
        const D2D1_POINT_2F aD2D1End
            = { FLOAT(aEnd.getX() + fAAOffset), FLOAT(aEnd.getY() + fAAOffset) };

        getRenderTarget()->DrawLine(aD2D1Start, aD2D1End, pColorBrush, 1.44f);
        bDone = true;
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processFillGraphicPrimitive2D(
    const primitive2d::FillGraphicPrimitive2D& rFillGraphicPrimitive2D)
{
    BitmapEx aPreparedBitmap;
    basegfx::B2DRange aFillUnitRange(rFillGraphicPrimitive2D.getFillGraphic().getGraphicRange());
    static double fBigDiscreteArea(300.0 * 300.0);

    // use tooling to do various checks and prepare tiled rendering, see
    // description of method, parameters and return value there
    if (!prepareBitmapForDirectRender(rFillGraphicPrimitive2D, getViewInformation2D(),
                                      aPreparedBitmap, aFillUnitRange, fBigDiscreteArea))
    {
        // no output needed, done
        return;
    }

    if (aPreparedBitmap.IsEmpty())
    {
        // output needed and Bitmap data empty, so no bitmap data based
        // tiled rendering is suggested. Use fallback for paint (decomposition)
        process(rFillGraphicPrimitive2D);
        return;
    }

    // render tiled using the prepared Bitmap data
    if (maBColorModifierStack.count())
    {
        // need to apply ColorModifier to Bitmap data
        aPreparedBitmap = aPreparedBitmap.ModifyBitmapEx(maBColorModifierStack);

        if (aPreparedBitmap.IsEmpty())
        {
            // color gets completely replaced, get it (any input works)
            const basegfx::BColor aModifiedColor(
                maBColorModifierStack.getModifiedColor(basegfx::BColor()));

            // use unit geometry as fallback object geometry. Do *not*
            // transform, the below used method will use the already
            // correctly initialized local ViewInformation
            basegfx::B2DPolygon aPolygon(basegfx::utils::createUnitPolygon());

            // what we still need to apply is the object transform from the
            // local primitive, that is not part of DisplayInfo yet
            aPolygon.transform(rFillGraphicPrimitive2D.getTransformation());

            rtl::Reference<primitive2d::PolyPolygonColorPrimitive2D> aTemp(
                new primitive2d::PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon),
                                                             aModifiedColor));

            // draw as colored Polygon, done
            processPolyPolygonColorPrimitive2D(*aTemp);
            return;
        }
    }

    bool bDone(false);
    sal::systools::COMReference<ID2D1Bitmap> pD2DBitmap(
        getOrCreateB2DBitmap(getRenderTarget(), aPreparedBitmap));

    if (pD2DBitmap)
    {
        sal::systools::COMReference<ID2D1BitmapBrush> pBitmapBrush;
        const HRESULT hr(getRenderTarget()->CreateBitmapBrush(pD2DBitmap, &pBitmapBrush));

        if (SUCCEEDED(hr) && pBitmapBrush)
        {
            // set extended to repeat/wrap AKA tiling
            pBitmapBrush->SetExtendModeX(D2D1_EXTEND_MODE_WRAP);
            pBitmapBrush->SetExtendModeY(D2D1_EXTEND_MODE_WRAP);

            // set interpolation mode
            // NOTE: This uses D2D1_BITMAP_INTERPOLATION_MODE, but there seem to be
            //       advanced modes when using D2D1_INTERPOLATION_MODE, but that needs
            //       D2D1_BITMAP_BRUSH_PROPERTIES1 and ID2D1BitmapBrush1
            sal::systools::COMReference<ID2D1BitmapBrush1> pBrush1;
            pBitmapBrush->QueryInterface(__uuidof(ID2D1BitmapBrush1),
                                         reinterpret_cast<void**>(&pBrush1));

            if (pBrush1)
            {
                pBrush1->SetInterpolationMode1(D2D1_INTERPOLATION_MODE_MULTI_SAMPLE_LINEAR);
            }
            else
            {
                pBitmapBrush->SetInterpolationMode(D2D1_BITMAP_INTERPOLATION_MODE_LINEAR);
            }

            // set BitmapBrush transformation relative to it's PixelSize and
            // the used FillUnitRange. Since we use unit coordinates here this
            // is pretty simple
            const D2D1_SIZE_U aBMSPixel(pD2DBitmap->GetPixelSize());
            const double fScaleX((aFillUnitRange.getMaxX() - aFillUnitRange.getMinX())
                                 / aBMSPixel.width);
            const double fScaleY((aFillUnitRange.getMaxY() - aFillUnitRange.getMinY())
                                 / aBMSPixel.height);
            const D2D1_MATRIX_3X2_F aBTrans(D2D1::Matrix3x2F(
                fScaleX, 0.0, 0.0, fScaleY, aFillUnitRange.getMinX(), aFillUnitRange.getMinY()));
            pBitmapBrush->SetTransform(&aBTrans);

            // set transform to ObjectToWorld to be able to paint in unit coordinates, so
            // evtl. shear/rotate in that transform is used and does not influence the
            // orthogonal and unit-oriented brush handling
            const double fAAOffset(getViewInformation2D().getUseAntiAliasing() ? 0.5 : 0.0);
            const basegfx::B2DHomMatrix aLocalTransform(
                getViewInformation2D().getObjectToViewTransformation()
                * rFillGraphicPrimitive2D.getTransformation());
            getRenderTarget()->SetTransform(D2D1::Matrix3x2F(
                aLocalTransform.a(), aLocalTransform.b(), aLocalTransform.c(), aLocalTransform.d(),
                aLocalTransform.e() + fAAOffset, aLocalTransform.f() + fAAOffset));

            // use unit rectangle, transformation is already set to include ObjectToWorld
            const D2D1_RECT_F rect = { FLOAT(0.0), FLOAT(0.0), FLOAT(1.0), FLOAT(1.0) };

            // draw as unit rectangle as brush filled rectangle
            getRenderTarget()->FillRectangle(&rect, pBitmapBrush);
            bDone = true;
        }
    }

    if (!bDone)
        increaseError();
}

void D2DPixelProcessor2D::processBasePrimitive2D(const primitive2d::BasePrimitive2D& rCandidate)
{
    if (0 == mnRecursionCounter)
        getRenderTarget()->BeginDraw();
    mnRecursionCounter++;

    switch (rCandidate.getPrimitive2DID())
    {
        // Geometry that *has* to be processed
        //
        // These Primitives have *no* decompose implementation, so these are the basic ones
        // Just four to go to make a processor work completely (but not optimized)
        // NOTE: This *could* theoretically be reduced to one and all could implement
        //       a decompose to pixel data, but that seemed not to make sense to me when
        //       I designed this. Thus these four are the lowest-level best representation
        //       from my POV
        case PRIMITIVE2D_ID_BITMAPPRIMITIVE2D:
        {
            processBitmapPrimitive2D(
                static_cast<const primitive2d::BitmapPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_POINTARRAYPRIMITIVE2D:
        {
            processPointArrayPrimitive2D(
                static_cast<const primitive2d::PointArrayPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_POLYGONHAIRLINEPRIMITIVE2D:
        {
            processPolygonHairlinePrimitive2D(
                static_cast<const primitive2d::PolygonHairlinePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_POLYPOLYGONCOLORPRIMITIVE2D:
        {
            processPolyPolygonColorPrimitive2D(
                static_cast<const primitive2d::PolyPolygonColorPrimitive2D&>(rCandidate));
            break;
        }

        // Embedding/groups that *have* to be processed
        //
        // These represent qualifiers for freely defined content, e.g. making
        // any combination of primitives freely transformed or transparent
        // NOTE: PRIMITIVE2D_ID_MODIFIEDCOLORPRIMITIVE2D and
        //       PRIMITIVE2D_ID_TRANSFORMPRIMITIVE2D are pretty much default-
        //       implementations that can and are re-used in all processors.
        // So - with these and PRIMITIVE2D_ID_INVERTPRIMITIVE2D marked to
        // be removed in the future - just three really to be implemented
        // locally specifically
        case PRIMITIVE2D_ID_TRANSPARENCEPRIMITIVE2D:
        {
            processTransparencePrimitive2D(
                static_cast<const primitive2d::TransparencePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_INVERTPRIMITIVE2D:
        {
            // TODO: fallback is at VclPixelProcessor2D::processInvertPrimitive2D, so
            // not in reach. Ignore for now.
            // NOTE: We *urgently* need to get rid of the last parts in LO that use
            //       XOR paint. Modern graphic systems allow no read access to the
            //       pixel targets, but that's naturally a precondition for XOR
            break;
        }
        case PRIMITIVE2D_ID_MASKPRIMITIVE2D:
        {
            processMaskPrimitive2DPixel(
                static_cast<const primitive2d::MaskPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_MODIFIEDCOLORPRIMITIVE2D:
        {
            processModifiedColorPrimitive2D(
                static_cast<const primitive2d::ModifiedColorPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_TRANSFORMPRIMITIVE2D:
        {
            processTransformPrimitive2D(
                static_cast<const primitive2d::TransformPrimitive2D&>(rCandidate));
            break;
        }

        // Geometry that *may* be processed due to being able to do it better
        // then using the decomposition.
        // NOTE: In these implementations you could always call what the default
        //       case below does - call process(rCandidate) to use the decomposition.
        //       So these impls should only do something if they can do it better/
        //       faster that the decomposition. So some of them check if they could
        //       - and if not - use exactly that.
        case PRIMITIVE2D_ID_UNIFIEDTRANSPARENCEPRIMITIVE2D:
        {
            // transparence with a fixed alpha for all content, can be done
            // significally faster
            processUnifiedTransparencePrimitive2D(
                static_cast<const primitive2d::UnifiedTransparencePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_MARKERARRAYPRIMITIVE2D:
        {
            // can be done simpler and without AA better locally
            processMarkerArrayPrimitive2D(
                static_cast<const primitive2d::MarkerArrayPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_BACKGROUNDCOLORPRIMITIVE2D:
        {
            // reset to a color, can be done more effectively locally, would
            // else decompose to a polygon fill
            processBackgroundColorPrimitive2D(
                static_cast<const primitive2d::BackgroundColorPrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_POLYGONSTROKEPRIMITIVE2D:
        {
            // fat and stroked lines - much better doable locally, would decompose
            // to the full line geometry creation (tessellation)
            processPolygonStrokePrimitive2D(
                static_cast<const primitive2d::PolygonStrokePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_LINERECTANGLEPRIMITIVE2D:
        {
            // simple primitive to support future fast callbacks from OutputDevice
            // (see 'Example POC' in Gerrit), decomposes to polygon primitive
            processLineRectanglePrimitive2D(
                static_cast<const primitive2d::LineRectanglePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_FILLEDRECTANGLEPRIMITIVE2D:
        {
            // simple primitive to support future fast callbacks from OutputDevice
            // (see 'Example POC' in Gerrit), decomposes to filled polygon primitive
            processFilledRectanglePrimitive2D(
                static_cast<const primitive2d::FilledRectanglePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_SINGLELINEPRIMITIVE2D:
        {
            // simple primitive to support future fast callbacks from OutputDevice
            // (see 'Example POC' in Gerrit), decomposes to polygon primitive
            processSingleLinePrimitive2D(
                static_cast<const primitive2d::SingleLinePrimitive2D&>(rCandidate));
            break;
        }
        case PRIMITIVE2D_ID_FILLGRAPHICPRIMITIVE2D:
        {
            processFillGraphicPrimitive2D(
                static_cast<const primitive2d::FillGraphicPrimitive2D&>(rCandidate));
            break;
        }

        // continue with decompose as fallback
        default:
        {
            SAL_INFO("drawinglayer", "default case for " << drawinglayer::primitive2d::idToString(
                                         rCandidate.getPrimitive2DID()));
            // process recursively
            process(rCandidate);
            break;
        }
    }

    mnRecursionCounter--;
    if (0 == mnRecursionCounter)
        getRenderTarget()->EndDraw();
}
} // end of namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */