summaryrefslogtreecommitdiffstats
path: root/canvas/source/opengl/ogl_canvashelper.cxx
blob: 6dcf933f07239f788b7d977700f501b0b5170946 (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
/* -*- 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/.
 */

#include <sal/config.h>

#include <memory>
#include <functional>
#include <epoxy/gl.h>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/utils/canvastools.hxx>
#include <com/sun/star/rendering/CompositeOperation.hpp>
#include <rtl/crc.h>
#include <rtl/math.hxx>
#include <tools/diagnose_ex.h>
#include <vcl/font.hxx>
#include <vcl/metric.hxx>
#include <vcl/virdev.hxx>

#include "ogl_canvasbitmap.hxx"
#include "ogl_canvasfont.hxx"
#include "ogl_canvastools.hxx"
#include "ogl_texturecache.hxx"
#include "ogl_tools.hxx"

#include "ogl_canvashelper.hxx"

using namespace ::com::sun::star;
using namespace std::placeholders;

namespace oglcanvas
{
    /* Concepts:
       =========

       This OpenGL canvas implementation tries to keep all render
       output as high-level as possible, i.e. geometry data and
       externally-provided bitmaps. Therefore, calls at the
       XCanvas-interfaces are not immediately transformed into colored
       pixel inside some GL buffer, but are retained simply with their
       call parameters. Only after XSpriteCanvas::updateScreen() has
       been called, this all gets transferred to the OpenGL subsystem
       and converted to a visible scene. The big advantage is, this
       makes sprite modifications practically zero-overhead, and saves
       a lot on texture memory (compared to the directx canvas, which
       immediately dumps every render call into a texture).

       The drawback, of course, is that complex images churn a lot of
       GPU cycles on every re-rendering.

       For the while, I'll be using immediate mode, i.e. transfer data
       over and over again to the OpenGL subsystem. Alternatively,
       there are display lists, which at least keep the data on the
       server, or even better, vertex buffers, which copy geometry
       data over en bloc.

       Next todo: put polygon geometry into vertex buffer (LRU cache
       necessary?) - or, rather, buffer objects! prune entries older
       than one updateScreen() call)

       Text: http://www.opengl.org/resources/features/fontsurvey/
     */

    struct CanvasHelper::Action
    {
        ::basegfx::B2DHomMatrix         maTransform;
        GLenum                          meSrcBlendMode;
        GLenum                          meDstBlendMode;
        rendering::ARGBColor            maARGBColor;
        ::basegfx::B2DPolyPolygonVector maPolyPolys;

        std::function< bool (
                            const CanvasHelper&,
                            const ::basegfx::B2DHomMatrix&,
                            GLenum,
                            GLenum,
                            const rendering::ARGBColor&,
                            const ::basegfx::B2DPolyPolygonVector&)> maFunction;
    };

    namespace
    {
        bool lcl_drawLine( const CanvasHelper&              /*rHelper*/,
                           const ::basegfx::B2DHomMatrix&   rTransform,
                           GLenum                           eSrcBlend,
                           GLenum                           eDstBlend,
                           const rendering::ARGBColor&      rColor,
                           const geometry::RealPoint2D&     rStartPoint,
                           const geometry::RealPoint2D&     rEndPoint )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rColor);

            glBegin(GL_LINES);
            glVertex2d(rStartPoint.X, rStartPoint.Y);
            glVertex2d(rEndPoint.X, rEndPoint.Y);
            glEnd();

            return true;
        }

        bool lcl_drawPolyPolygon( const CanvasHelper&                    /*rHelper*/,
                                  const ::basegfx::B2DHomMatrix&         rTransform,
                                  GLenum                                 eSrcBlend,
                                  GLenum                                 eDstBlend,
                                  const rendering::ARGBColor&            rColor,
                                  const ::basegfx::B2DPolyPolygonVector& rPolyPolygons )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rColor);

            for( const auto& rPoly : rPolyPolygons )
                renderPolyPolygon( rPoly );

            return true;
        }

        bool lcl_fillPolyPolygon( const CanvasHelper&                    /*rHelper*/,
                                  const ::basegfx::B2DHomMatrix&         rTransform,
                                  GLenum                                 eSrcBlend,
                                  GLenum                                 eDstBlend,
                                  const rendering::ARGBColor&            rColor,
                                  const ::basegfx::B2DPolyPolygonVector& rPolyPolygons )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rColor);

            for( const auto& rPoly : rPolyPolygons )
            {
                glBegin( GL_TRIANGLES );
                renderComplexPolyPolygon( rPoly );
                glEnd();
            }

            return true;
        }

        bool lcl_fillGradientPolyPolygon( const CanvasHelper&                            rHelper,
                                          const ::basegfx::B2DHomMatrix&                 rTransform,
                                          GLenum                                         eSrcBlend,
                                          GLenum                                         eDstBlend,
                                          const ::canvas::ParametricPolyPolygon::Values& rValues,
                                          const rendering::Texture&                      rTexture,
                                          const ::basegfx::B2DPolyPolygonVector&         rPolyPolygons )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rendering::ARGBColor());

            // convert to weird canvas textur coordinate system (not
            // [0,1]^2, but path coordinate system)
            ::basegfx::B2DHomMatrix aTextureTransform;
            ::basegfx::unotools::homMatrixFromAffineMatrix( aTextureTransform,
                                                            rTexture.AffineTransform );
            ::basegfx::B2DRange aBounds;
            for( const auto& rPoly : rPolyPolygons )
                aBounds.expand( ::basegfx::utils::getRange( rPoly ) );
            aTextureTransform.translate(-aBounds.getMinX(), -aBounds.getMinY());
            aTextureTransform.scale(1/aBounds.getWidth(), 1/aBounds.getHeight());

            const sal_Int32 nNumCols=rValues.maColors.getLength();
            uno::Sequence< rendering::ARGBColor > aColors(nNumCols);
            rendering::ARGBColor* const pColors=aColors.getArray();
            rendering::ARGBColor* pCurrCol=pColors;
            for( sal_Int32 i=0; i<nNumCols; ++i )
                *pCurrCol++ = rHelper.getDevice()->getDeviceColorSpace()->convertToARGB(rValues.maColors[i])[0];

            OSL_ASSERT(nNumCols == rValues.maStops.getLength());

            switch( rValues.meType )
            {
                case ::canvas::ParametricPolyPolygon::GradientType::Linear:
                    rHelper.getDeviceHelper()->useLinearGradientShader(pColors,
                                                                       rValues.maStops,
                                                                       aTextureTransform);
                    break;

                case ::canvas::ParametricPolyPolygon::GradientType::Elliptical:
                    rHelper.getDeviceHelper()->useRadialGradientShader(pColors,
                                                                       rValues.maStops,
                                                                       aTextureTransform);
                    break;

                case ::canvas::ParametricPolyPolygon::GradientType::Rectangular:
                    rHelper.getDeviceHelper()->useRectangularGradientShader(pColors,
                                                                            rValues.maStops,
                                                                            aTextureTransform);
                    break;

                default:
                    ENSURE_OR_THROW( false,
                                      "CanvasHelper lcl_fillGradientPolyPolygon(): Unexpected case" );
            }


            for( const auto& rPoly : rPolyPolygons )
            {
                glBegin(GL_TRIANGLES);
                renderComplexPolyPolygon( rPoly );
                glEnd();
            }

            glUseProgram(0);
            glLoadIdentity();
            glMatrixMode(GL_MODELVIEW);

            return true;
        }

        bool lcl_drawOwnBitmap( const CanvasHelper&              /*rHelper*/,
                                const ::basegfx::B2DHomMatrix&   rTransform,
                                GLenum                           eSrcBlend,
                                GLenum                           eDstBlend,
                                const rendering::ARGBColor&      rColor,
                                const CanvasBitmap&              rBitmap )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rColor);

            return rBitmap.renderRecordedActions();
        }

        bool lcl_drawGenericBitmap( const CanvasHelper&              rHelper,
                                    const ::basegfx::B2DHomMatrix&   rTransform,
                                    GLenum                           eSrcBlend,
                                    GLenum                           eDstBlend,
                                    const rendering::ARGBColor&      rColor,
                                    const geometry::IntegerSize2D&   rPixelSize,
                                    const uno::Sequence<sal_Int8>&   rPixelData,
                                    sal_uInt32                       nPixelCrc32 )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rColor);

            const unsigned int nTexId=rHelper.getDeviceHelper()->getTextureCache().getTexture(
                rPixelSize, rPixelData.getConstArray(), nPixelCrc32);

            glBindTexture(GL_TEXTURE_2D, nTexId);
            glEnable(GL_TEXTURE_2D);
            glTexParameteri(GL_TEXTURE_2D,
                            GL_TEXTURE_MIN_FILTER,
                            GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D,
                            GL_TEXTURE_MAG_FILTER,
                            GL_NEAREST);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA,
                        GL_ONE_MINUS_SRC_ALPHA);

            // blend against fixed vertex color; texture alpha is multiplied in
            glColor4f(1,1,1,1);

            glBegin(GL_TRIANGLE_STRIP);
            glTexCoord2f(0,0); glVertex2d(0,0);
            glTexCoord2f(0,1); glVertex2d(0, rPixelSize.Height);
            glTexCoord2f(1,0); glVertex2d(rPixelSize.Width,0);
            glTexCoord2f(1,1); glVertex2d(rPixelSize.Width,rPixelSize.Height);
            glEnd();

            glBindTexture(GL_TEXTURE_2D, 0);
            glDisable(GL_TEXTURE_2D);

            return true;
        }

        bool lcl_fillTexturedPolyPolygon( const CanvasHelper&                    rHelper,
                                          const ::basegfx::B2DHomMatrix&         rTransform,
                                          GLenum                                 eSrcBlend,
                                          GLenum                                 eDstBlend,
                                          const rendering::Texture&              rTexture,
                                          const geometry::IntegerSize2D&         rPixelSize,
                                          const uno::Sequence<sal_Int8>&         rPixelData,
                                          sal_uInt32                             nPixelCrc32,
                                          const ::basegfx::B2DPolyPolygonVector& rPolyPolygons )
        {
            TransformationPreserver aPreserver;
            setupState(rTransform, eSrcBlend, eDstBlend, rendering::ARGBColor());

            const unsigned int nTexId=rHelper.getDeviceHelper()->getTextureCache().getTexture(
                rPixelSize, rPixelData.getConstArray(), nPixelCrc32);

            glBindTexture(GL_TEXTURE_2D, nTexId);
            glEnable(GL_TEXTURE_2D);
            glTexParameteri(GL_TEXTURE_2D,
                            GL_TEXTURE_MIN_FILTER,
                            GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D,
                            GL_TEXTURE_MAG_FILTER,
                            GL_NEAREST);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA,
                        GL_ONE_MINUS_SRC_ALPHA);

            // convert to weird canvas textur coordinate system (not
            // [0,1]^2, but path coordinate system)
            ::basegfx::B2DHomMatrix aTextureTransform;
            ::basegfx::unotools::homMatrixFromAffineMatrix( aTextureTransform,
                                                            rTexture.AffineTransform );
            ::basegfx::B2DRange aBounds;
            for( const auto& rPolyPolygon : rPolyPolygons )
                aBounds.expand( ::basegfx::utils::getRange( rPolyPolygon ) );
            aTextureTransform.translate(-aBounds.getMinX(), -aBounds.getMinY());
            aTextureTransform.scale(1/aBounds.getWidth(), 1/aBounds.getHeight());
            aTextureTransform.invert();

            glMatrixMode(GL_TEXTURE);
            double aTexTransform[] =
                {
                    aTextureTransform.get(0,0), aTextureTransform.get(1,0), 0, 0,
                    aTextureTransform.get(0,1), aTextureTransform.get(1,1), 0, 0,
                    0,                          0,                          1, 0,
                    aTextureTransform.get(0,2), aTextureTransform.get(1,2), 0, 1
                };
            glLoadMatrixd(aTexTransform);

            // blend against fixed vertex color; texture alpha is multiplied in
            glColor4f(1,1,1,rTexture.Alpha);

            for( const auto& rPolyPolygon : rPolyPolygons )
            {
                glBegin(GL_TRIANGLES);
                renderComplexPolyPolygon( rPolyPolygon );
                glEnd();
            }

            glLoadIdentity();
            glMatrixMode(GL_MODELVIEW);

            glBindTexture(GL_TEXTURE_2D, 0);
            glDisable(GL_TEXTURE_2D);

            return true;
        }
    }

    CanvasHelper::CanvasHelper() :
        mpDevice( nullptr ),
        mpDeviceHelper( nullptr ),
        mpRecordedActions()
    {}

    CanvasHelper::~CanvasHelper()
    {}

    CanvasHelper& CanvasHelper::operator=( const CanvasHelper& rSrc )
    {
        mpDevice = rSrc.mpDevice;
        mpDeviceHelper = rSrc.mpDeviceHelper;
        mpRecordedActions = rSrc.mpRecordedActions;
        return *this;
    }

    void CanvasHelper::disposing()
    {
        RecordVectorT aThrowaway;
        mpRecordedActions.swap( aThrowaway );
        mpDevice = nullptr;
        mpDeviceHelper = nullptr;
    }

    void CanvasHelper::init( rendering::XGraphicDevice& rDevice,
                             SpriteDeviceHelper& rDeviceHelper )
    {
        mpDevice = &rDevice;
        mpDeviceHelper = &rDeviceHelper;
    }

    void CanvasHelper::clear()
    {
        mpRecordedActions->clear();
    }

    void CanvasHelper::drawLine( const rendering::XCanvas*      /*pCanvas*/,
                                 const geometry::RealPoint2D&   aStartPoint,
                                 const geometry::RealPoint2D&   aEndPoint,
                                 const rendering::ViewState&    viewState,
                                 const rendering::RenderState&  renderState )
    {
        if( mpDevice )
        {
            mpRecordedActions->push_back( Action() );
            Action& rAct=mpRecordedActions->back();

            setupGraphicsState( rAct, viewState, renderState );
            rAct.maFunction = std::bind(&lcl_drawLine,
                                          std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5,
                                          aStartPoint, aEndPoint);
        }
    }

    void CanvasHelper::drawBezier( const rendering::XCanvas*            /*pCanvas*/,
                                   const geometry::RealBezierSegment2D& aBezierSegment,
                                   const geometry::RealPoint2D&         aEndPoint,
                                   const rendering::ViewState&          viewState,
                                   const rendering::RenderState&        renderState )
    {
        if( !mpDevice )
            return;

        mpRecordedActions->push_back( Action() );
        Action& rAct=mpRecordedActions->back();

        setupGraphicsState( rAct, viewState, renderState );

        // TODO(F2): subdivide&render whole curve
        rAct.maFunction = std::bind(&lcl_drawLine,
                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5,
                                        geometry::RealPoint2D(
                                            aBezierSegment.Px,
                                            aBezierSegment.Py),
                                        aEndPoint);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::drawPolyPolygon( const rendering::XCanvas*                          /*pCanvas*/,
                                                                                 const uno::Reference< rendering::XPolyPolygon2D >& xPolyPolygon,
                                                                                 const rendering::ViewState&                        viewState,
                                                                                 const rendering::RenderState&                      renderState )
    {
        ENSURE_OR_THROW( xPolyPolygon.is(),
                          "CanvasHelper::drawPolyPolygon: polygon is NULL");

        if( mpDevice )
        {
            mpRecordedActions->push_back( Action() );
            Action& rAct=mpRecordedActions->back();

            setupGraphicsState( rAct, viewState, renderState );
            rAct.maPolyPolys.push_back(
                ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D(xPolyPolygon));
            rAct.maPolyPolys.back().makeUnique(); // own copy, for thread safety

            rAct.maFunction = &lcl_drawPolyPolygon;
        }

        // TODO(P1): Provide caching here.
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::strokePolyPolygon( const rendering::XCanvas*                            /*pCanvas*/,
                                                                                   const uno::Reference< rendering::XPolyPolygon2D >&   xPolyPolygon,
                                                                                   const rendering::ViewState&                          viewState,
                                                                                   const rendering::RenderState&                        renderState,
                                                                                   const rendering::StrokeAttributes&                   /*strokeAttributes*/ )
    {
        ENSURE_OR_THROW( xPolyPolygon.is(),
                          "CanvasHelper::strokePolyPolygon: polygon is NULL");

        if( mpDevice )
        {
            mpRecordedActions->push_back( Action() );
            Action& rAct=mpRecordedActions->back();

            setupGraphicsState( rAct, viewState, renderState );
            rAct.maPolyPolys.push_back(
                ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D(xPolyPolygon));
            rAct.maPolyPolys.back().makeUnique(); // own copy, for thread safety

            // TODO(F3): fallback to drawPolyPolygon currently
            rAct.maFunction = &lcl_drawPolyPolygon;
        }

        // TODO(P1): Provide caching here.
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::strokeTexturedPolyPolygon( const rendering::XCanvas*                            /*pCanvas*/,
                                                                                           const uno::Reference< rendering::XPolyPolygon2D >&   /*xPolyPolygon*/,
                                                                                           const rendering::ViewState&                          /*viewState*/,
                                                                                           const rendering::RenderState&                        /*renderState*/,
                                                                                           const uno::Sequence< rendering::Texture >&           /*textures*/,
                                                                                           const rendering::StrokeAttributes&                   /*strokeAttributes*/ )
    {
        // TODO
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::strokeTextureMappedPolyPolygon( const rendering::XCanvas*                           /*pCanvas*/,
                                                                                                const uno::Reference< rendering::XPolyPolygon2D >&  /*xPolyPolygon*/,
                                                                                                const rendering::ViewState&                         /*viewState*/,
                                                                                                const rendering::RenderState&                       /*renderState*/,
                                                                                                const uno::Sequence< rendering::Texture >&          /*textures*/,
                                                                                                const uno::Reference< geometry::XMapping2D >&       /*xMapping*/,
                                                                                                const rendering::StrokeAttributes&                  /*strokeAttributes*/ )
    {
        // TODO
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XPolyPolygon2D >   CanvasHelper::queryStrokeShapes( const rendering::XCanvas*                            /*pCanvas*/,
                                                                                   const uno::Reference< rendering::XPolyPolygon2D >&   /*xPolyPolygon*/,
                                                                                   const rendering::ViewState&                          /*viewState*/,
                                                                                   const rendering::RenderState&                        /*renderState*/,
                                                                                   const rendering::StrokeAttributes&                   /*strokeAttributes*/ )
    {
        // TODO
        return uno::Reference< rendering::XPolyPolygon2D >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::fillPolyPolygon( const rendering::XCanvas*                          /*pCanvas*/,
                                                                                 const uno::Reference< rendering::XPolyPolygon2D >& xPolyPolygon,
                                                                                 const rendering::ViewState&                        viewState,
                                                                                 const rendering::RenderState&                      renderState )
    {
        ENSURE_OR_THROW( xPolyPolygon.is(),
                          "CanvasHelper::fillPolyPolygon: polygon is NULL");

        if( mpDevice )
        {
            mpRecordedActions->push_back( Action() );
            Action& rAct=mpRecordedActions->back();

            setupGraphicsState( rAct, viewState, renderState );
            rAct.maPolyPolys.push_back(
                ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D(xPolyPolygon));
            rAct.maPolyPolys.back().makeUnique(); // own copy, for thread safety

            rAct.maFunction = &lcl_fillPolyPolygon;
        }

        // TODO(P1): Provide caching here.
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::fillTexturedPolyPolygon( const rendering::XCanvas*                          /*pCanvas*/,
                                                                                         const uno::Reference< rendering::XPolyPolygon2D >& xPolyPolygon,
                                                                                         const rendering::ViewState&                        viewState,
                                                                                         const rendering::RenderState&                      renderState,
                                                                                         const uno::Sequence< rendering::Texture >&         textures )
    {
        ENSURE_OR_THROW( xPolyPolygon.is(),
                          "CanvasHelper::fillPolyPolygon: polygon is NULL");

        if( mpDevice )
        {
            mpRecordedActions->push_back( Action() );
            Action& rAct=mpRecordedActions->back();

            setupGraphicsState( rAct, viewState, renderState );
            rAct.maPolyPolys.push_back(
                ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D(xPolyPolygon));
            rAct.maPolyPolys.back().makeUnique(); // own copy, for thread safety

            // TODO(F1): Multi-texturing
            if( textures[0].Gradient.is() )
            {
                // try to cast XParametricPolyPolygon2D reference to
                // our implementation class.
                ::canvas::ParametricPolyPolygon* pGradient =
                      dynamic_cast< ::canvas::ParametricPolyPolygon* >( textures[0].Gradient.get() );

                if( pGradient )
                {
                    // copy state from Gradient polypoly locally
                    // (given object might change!)
                    const ::canvas::ParametricPolyPolygon::Values& rValues(
                        pGradient->getValues() );

                    rAct.maFunction = std::bind(&lcl_fillGradientPolyPolygon,
                                                    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,
                                                    rValues,
                                                    textures[0],
                                                    std::placeholders::_6);
                }
                else
                {
                    // TODO(F1): The generic case is missing here
                    ENSURE_OR_THROW( false,
                                      "CanvasHelper::fillTexturedPolyPolygon(): unknown parametric polygon encountered" );
                }
            }
            else if( textures[0].Bitmap.is() )
            {
                // own bitmap?
                CanvasBitmap* pOwnBitmap=dynamic_cast<CanvasBitmap*>(textures[0].Bitmap.get());
                if( pOwnBitmap )
                {
                    // TODO(F2): own texture bitmap
                }
                else
                {
                    // TODO(P3): Highly inefficient - simply copies pixel data

                    uno::Reference< rendering::XIntegerReadOnlyBitmap > xIntegerBitmap(
                        textures[0].Bitmap,
                        uno::UNO_QUERY);
                    if( xIntegerBitmap.is() )
                    {
                        const geometry::IntegerSize2D aSize=xIntegerBitmap->getSize();
                        rendering::IntegerBitmapLayout aLayout;
                        uno::Sequence<sal_Int8> aPixelData=
                            xIntegerBitmap->getData(
                                aLayout,
                                geometry::IntegerRectangle2D(0,0,aSize.Width,aSize.Height));

                        // force-convert color to ARGB8888 int color space
                        uno::Sequence<sal_Int8> aARGBBytes(
                            aLayout.ColorSpace->convertToIntegerColorSpace(
                                aPixelData,
                                canvas::tools::getStdColorSpace()));

                        rAct.maFunction = std::bind(&lcl_fillTexturedPolyPolygon,
                                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4,
                                                        textures[0],
                                                        aSize,
                                                        aARGBBytes,
                                                        rtl_crc32(0,
                                                                  aARGBBytes.getConstArray(),
                                                                  aARGBBytes.getLength()),
                                                        std::placeholders::_6);
                    }
                    // TODO(F1): handle non-integer case
                }
            }
        }

        // TODO(P1): Provide caching here.
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::fillTextureMappedPolyPolygon( const rendering::XCanvas*                             /*pCanvas*/,
                                                                                              const uno::Reference< rendering::XPolyPolygon2D >&    /*xPolyPolygon*/,
                                                                                              const rendering::ViewState&                           /*viewState*/,
                                                                                              const rendering::RenderState&                         /*renderState*/,
                                                                                              const uno::Sequence< rendering::Texture >&            /*textures*/,
                                                                                              const uno::Reference< geometry::XMapping2D >&         /*xMapping*/ )
    {
        // TODO
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCanvasFont > CanvasHelper::createFont( const rendering::XCanvas*                    /*pCanvas*/,
                                                                       const rendering::FontRequest&                fontRequest,
                                                                       const uno::Sequence< beans::PropertyValue >& extraFontProperties,
                                                                       const geometry::Matrix2D&                    fontMatrix )
    {
        if( mpDevice )
            return uno::Reference< rendering::XCanvasFont >(
                    new CanvasFont(fontRequest, extraFontProperties, fontMatrix ) );

        return uno::Reference< rendering::XCanvasFont >();
    }

    uno::Sequence< rendering::FontInfo > CanvasHelper::queryAvailableFonts( const rendering::XCanvas*                       /*pCanvas*/,
                                                                            const rendering::FontInfo&                      /*aFilter*/,
                                                                            const uno::Sequence< beans::PropertyValue >&    /*aFontProperties*/ )
    {
        // TODO
        return uno::Sequence< rendering::FontInfo >();
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::drawText( const rendering::XCanvas*                         /*pCanvas*/,
                                                                          const rendering::StringContext&                   /*text*/,
                                                                          const uno::Reference< rendering::XCanvasFont >&   /*xFont*/,
                                                                          const rendering::ViewState&                       /*viewState*/,
                                                                          const rendering::RenderState&                     /*renderState*/,
                                                                          sal_Int8                                          /*textDirection*/ )
    {
        // TODO - but not used from slideshow
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::drawTextLayout( const rendering::XCanvas*                       /*pCanvas*/,
                                                                                const uno::Reference< rendering::XTextLayout >& xLayoutetText,
                                                                                const rendering::ViewState&                     viewState,
                                                                                const rendering::RenderState&                   renderState )
    {
        ENSURE_OR_THROW( xLayoutetText.is(),
                          "CanvasHelper::drawTextLayout: text is NULL");

        if( mpDevice )
        {
            ScopedVclPtrInstance< VirtualDevice > pVDev;
            pVDev->EnableOutput(false);

            CanvasFont* pFont=dynamic_cast<CanvasFont*>(xLayoutetText->getFont().get());
            const rendering::StringContext& rTxt=xLayoutetText->getText();
            if( pFont && rTxt.Length )
            {
                // create the font
                const rendering::FontRequest& rFontRequest = pFont->getFontRequest();
                const geometry::Matrix2D&     rFontMatrix = pFont->getFontMatrix();
                vcl::Font aFont(
                    rFontRequest.FontDescription.FamilyName,
                    rFontRequest.FontDescription.StyleName,
                    Size( 0, ::basegfx::fround(rFontRequest.CellSize)));

                aFont.SetAlignment( ALIGN_BASELINE );
                aFont.SetCharSet( (rFontRequest.FontDescription.IsSymbolFont==util::TriState_YES) ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE );
                aFont.SetVertical( rFontRequest.FontDescription.IsVertical==util::TriState_YES );
                aFont.SetWeight( static_cast<FontWeight>(rFontRequest.FontDescription.FontDescription.Weight) );
                aFont.SetItalic( (rFontRequest.FontDescription.FontDescription.Letterform<=8) ? ITALIC_NONE : ITALIC_NORMAL );

                if (pFont->getEmphasisMark())
                    aFont.SetEmphasisMark(FontEmphasisMark(pFont->getEmphasisMark()));

                // adjust to stretched font
                if(!::rtl::math::approxEqual(rFontMatrix.m00, rFontMatrix.m11))
                {
                    const Size aSize = pVDev->GetFontMetric( aFont ).GetFontSize();
                    const double fDividend( rFontMatrix.m10 + rFontMatrix.m11 );
                    double fStretch = rFontMatrix.m00 + rFontMatrix.m01;

                    if( !::basegfx::fTools::equalZero( fDividend) )
                        fStretch /= fDividend;

                    const sal_Int32 nNewWidth = ::basegfx::fround( aSize.Width() * fStretch );

                    aFont.SetAverageFontWidth( nNewWidth );
                }

                // set font
                pVDev->SetFont(aFont);

                mpRecordedActions->push_back( Action() );
                Action& rAct=mpRecordedActions->back();

                setupGraphicsState( rAct, viewState, renderState );

                // handle custom spacing, if there
                uno::Sequence<double> aLogicalAdvancements=xLayoutetText->queryLogicalAdvancements();
                if( aLogicalAdvancements.hasElements() )
                {
                    // create the DXArray
                    const sal_Int32 nLen( aLogicalAdvancements.getLength() );
                    std::unique_ptr<long[]> pDXArray( new long[nLen] );
                    for( sal_Int32 i=0; i<nLen; ++i )
                        pDXArray[i] = basegfx::fround( aLogicalAdvancements[i] );

                    // get the glyphs
                    pVDev->GetTextOutlines(rAct.maPolyPolys,
                                          rTxt.Text,
                                          0,
                                          rTxt.StartPosition,
                                          rTxt.Length,
                                          0,
                                          pDXArray.get() );
                }
                else
                {
                    // get the glyphs
                    pVDev->GetTextOutlines(rAct.maPolyPolys,
                                          rTxt.Text,
                                          0,
                                          rTxt.StartPosition,
                                          rTxt.Length );
                }

                // own copy, for thread safety
                for( auto& rPoly : rAct.maPolyPolys )
                    rPoly.makeUnique();

                rAct.maFunction = &lcl_fillPolyPolygon;
            }
        }

        // TODO
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::drawBitmap( const rendering::XCanvas*                   /*pCanvas*/,
                                                                            const uno::Reference< rendering::XBitmap >& xBitmap,
                                                                            const rendering::ViewState&                 viewState,
                                                                            const rendering::RenderState&               renderState )
    {
        ENSURE_OR_THROW( xBitmap.is(),
                          "CanvasHelper::drawBitmap: bitmap is NULL");

        if( mpDevice )
        {
            // own bitmap?
            CanvasBitmap* pOwnBitmap=dynamic_cast<CanvasBitmap*>(xBitmap.get());
            if( pOwnBitmap )
            {
                // insert as transformed copy of bitmap action vector -
                // during rendering, this gets rendered into a temporary
                // buffer, and then composited to the front
                mpRecordedActions->push_back( Action() );
                Action& rAct=mpRecordedActions->back();

                setupGraphicsState( rAct, viewState, renderState );
                rAct.maFunction = std::bind(&lcl_drawOwnBitmap,
                                                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5,
                                                *pOwnBitmap);
            }
            else
            {
                // TODO(P3): Highly inefficient - simply copies pixel data

                uno::Reference< rendering::XIntegerReadOnlyBitmap > xIntegerBitmap(
                    xBitmap, uno::UNO_QUERY);
                if( xIntegerBitmap.is() )
                {
                    const geometry::IntegerSize2D aSize=xBitmap->getSize();
                    rendering::IntegerBitmapLayout aLayout;
                    uno::Sequence<sal_Int8> aPixelData=
                        xIntegerBitmap->getData(
                            aLayout,
                            geometry::IntegerRectangle2D(0,0,aSize.Width,aSize.Height));

                    // force-convert color to ARGB8888 int color space
                    uno::Sequence<sal_Int8> aARGBBytes(
                        aLayout.ColorSpace->convertToIntegerColorSpace(
                            aPixelData,
                            canvas::tools::getStdColorSpace()));

                    mpRecordedActions->push_back( Action() );
                    Action& rAct=mpRecordedActions->back();

                    setupGraphicsState( rAct, viewState, renderState );
                    rAct.maFunction = std::bind(&lcl_drawGenericBitmap,
                                                    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5,
                                                    aSize, aARGBBytes,
                                                    rtl_crc32(0,
                                                              aARGBBytes.getConstArray(),
                                                              aARGBBytes.getLength()));
                }
                // TODO(F1): handle non-integer case
            }
        }

        // TODO(P1): Provide caching here.
        return uno::Reference< rendering::XCachedPrimitive >(nullptr);
    }

    uno::Reference< rendering::XCachedPrimitive > CanvasHelper::drawBitmapModulated( const rendering::XCanvas*                      pCanvas,
                                                                                     const uno::Reference< rendering::XBitmap >&    xBitmap,
                                                                                     const rendering::ViewState&                    viewState,
                                                                                     const rendering::RenderState&                  renderState )
    {
        // TODO(F3): remove this wart altogether
        return drawBitmap(pCanvas, xBitmap, viewState, renderState);
    }


    void CanvasHelper::setupGraphicsState( Action&                       o_action,
                                           const rendering::ViewState&   viewState,
                                           const rendering::RenderState& renderState )
    {
        ENSURE_OR_THROW( mpDevice,
                          "CanvasHelper::setupGraphicsState: reference device invalid" );

        // TODO(F3): clipping
        // TODO(P2): think about caching transformations between canvas calls

        // setup overall transform only now. View clip above was
        // relative to view transform
        ::canvas::tools::mergeViewAndRenderTransform(o_action.maTransform,
                                                     viewState,
                                                     renderState);
        // setup compositing - mapping courtesy David Reveman
        // (glitz_operator.c)
        switch( renderState.CompositeOperation )
        {
            case rendering::CompositeOperation::OVER:
                o_action.meSrcBlendMode=GL_ONE;
                o_action.meDstBlendMode=GL_ONE_MINUS_SRC_ALPHA;
                break;
            case rendering::CompositeOperation::CLEAR:
                o_action.meSrcBlendMode=GL_ZERO;
                o_action.meDstBlendMode=GL_ZERO;
                break;
            case rendering::CompositeOperation::SOURCE:
                o_action.meSrcBlendMode=GL_ONE;
                o_action.meDstBlendMode=GL_ZERO;
                break;
            case rendering::CompositeOperation::UNDER:
            case rendering::CompositeOperation::DESTINATION:
                o_action.meSrcBlendMode=GL_ZERO;
                o_action.meDstBlendMode=GL_ONE;
                break;
            case rendering::CompositeOperation::INSIDE:
                o_action.meSrcBlendMode=GL_DST_ALPHA;
                o_action.meDstBlendMode=GL_ZERO;
                break;
            case rendering::CompositeOperation::INSIDE_REVERSE:
                o_action.meSrcBlendMode=GL_ONE_MINUS_DST_ALPHA;
                o_action.meDstBlendMode=GL_ZERO;
                break;
            case rendering::CompositeOperation::OUTSIDE:
                o_action.meSrcBlendMode=GL_ONE_MINUS_DST_ALPHA;
                o_action.meDstBlendMode=GL_ONE;
                break;
            case rendering::CompositeOperation::OUTSIDE_REVERSE:
                o_action.meSrcBlendMode=GL_ZERO;
                o_action.meDstBlendMode=GL_ONE_MINUS_SRC_ALPHA;
                break;
            case rendering::CompositeOperation::ATOP:
                o_action.meSrcBlendMode=GL_DST_ALPHA;
                o_action.meDstBlendMode=GL_ONE_MINUS_SRC_ALPHA;
                break;
            case rendering::CompositeOperation::ATOP_REVERSE:
                o_action.meSrcBlendMode=GL_ONE_MINUS_DST_ALPHA;
                o_action.meDstBlendMode=GL_SRC_ALPHA;
                break;
            case rendering::CompositeOperation::XOR:
                o_action.meSrcBlendMode=GL_ONE_MINUS_DST_ALPHA;
                o_action.meDstBlendMode=GL_ONE_MINUS_SRC_ALPHA;
                break;
            case rendering::CompositeOperation::ADD:
                o_action.meSrcBlendMode=GL_ONE;
                o_action.meDstBlendMode=GL_ONE;
                break;
            case rendering::CompositeOperation::SATURATE:
                o_action.meSrcBlendMode=GL_SRC_ALPHA_SATURATE;
                o_action.meDstBlendMode=GL_SRC_ALPHA_SATURATE;
                break;

            default:
                ENSURE_OR_THROW( false, "CanvasHelper::setupGraphicsState: unexpected mode" );
                break;
        }

        if (renderState.DeviceColor.hasElements())
            o_action.maARGBColor =
                mpDevice->getDeviceColorSpace()->convertToARGB(renderState.DeviceColor)[0];
    }

    bool CanvasHelper::renderRecordedActions() const
    {
        for( const auto& rRecordedAction : *mpRecordedActions )
        {
            if( !rRecordedAction.maFunction( *this,
                                             rRecordedAction.maTransform,
                                             rRecordedAction.meSrcBlendMode,
                                             rRecordedAction.meDstBlendMode,
                                             rRecordedAction.maARGBColor,
                                             rRecordedAction.maPolyPolys ) )
                return false;
        }

        return true;
    }

    size_t CanvasHelper::getRecordedActionCount() const
    {
        return mpRecordedActions->size();
    }
}

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