summaryrefslogtreecommitdiff
path: root/canvas/source/opengl/ogl_spritedevicehelper.cxx
blob: c6accde3e94d42485c85ed08d2b3906f779caf4b (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
/* -*- 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 "ogl_spritedevicehelper.hxx"
#include "ogl_spritecanvas.hxx"
#include "ogl_canvasbitmap.hxx"
#include "ogl_canvastools.hxx"
#include "ogl_canvascustomsprite.hxx"
#include "ogl_texturecache.hxx"

#include <canvas/verbosetrace.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/tools/unopolypolygon.hxx>

#include <osl/mutex.hxx>
#include <rtl/instance.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/NoSupportException.hpp>
#include <com/sun/star/rendering/XColorSpace.hpp>
#include <com/sun/star/rendering/XIntegerBitmapColorSpace.hpp>

#include <vcl/sysdata.hxx>
#include <vcl/syschild.hxx>
#include <vcl/canvastools.hxx>
#include <toolkit/helper/vclunohelper.hxx>

#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>

namespace unx
{
 #include <X11/keysym.h>
 #include <X11/X.h>
 #include <GL/glx.h>
 #include <GL/glxext.h>
}


using namespace ::com::sun::star;

static bool lcl_bErrorTriggered=false;
static int lcl_XErrorHandler( unx::Display*, unx::XErrorEvent* )
{
    lcl_bErrorTriggered = true;
    return 0;
}

/** Dummy vertex processing. Simply uses default pipeline for vertex
   transformation, and forwards texture coodinates to fragment shader
 */
static const char dummyVertexShader[] =
{
    "varying vec2 v_textureCoords2d;                                            "
    "void main(void)                                                            "
    "{                                                                          "
    "    gl_Position = ftransform();                                            "
    "    v_textureCoords2d = gl_MultiTexCoord0.st;                              "
    "}                                                                          "
};

/** Two-color linear gradient
 */
static const char linearTwoColorGradientFragmentShader[] =
{
    "#version 120                                                            \n"
    "uniform vec4   v_startColor4d;                                            "
    "uniform vec4   v_endColor4d;                                              "
    "uniform mat3x2 m_transform;                                               "
    "varying vec2   v_textureCoords2d;                                         "
    "void main(void)                                                           "
    "{                                                                         "
    "    gl_FragColor = mix(v_startColor4d,                                    "
    "                       v_endColor4d,                                      "
    "                       clamp(                                             "
    "                          (m_transform * vec3(v_textureCoords2d,1)).s,    "
    "                          0.0, 1.0));                                     "
    "}                                                                         "
};

/** N-color linear gradient
 */
static const char linearMultiColorGradientFragmentShader[] =
{
    "#version 120                                                            \n"
    "uniform int       i_nColors;                                              "
    "uniform sampler1D t_colorArray4d;                                         "
    "uniform sampler1D t_stopArray1d;                                          "
    "uniform mat3x2    m_transform;                                            "
    "varying vec2      v_textureCoords2d;                                      "
    "                                                                          "
    "int findBucket(float t)                                                   "
    "{                                                                         "
    "    int nMinBucket=0;                                                     "
    "    while( nMinBucket < i_nColors &&                                      "
    "           texture1D(t_stopArray1d, nMinBucket).s < t )                   "
    "        ++nMinBucket;                                                     "
    "    return max(nMinBucket-1,0);                                           "
    "}                                                                         "
    "                                                                          "
    "void main(void)                                                           "
    "{                                                                         "
    "    const float fAlpha =                                                  "
    "        clamp( (m_transform * vec3(v_textureCoords2d,1)).s,               "
    "               0.0, 1.0 );                                                "
    "                                                                          "
    "    const int nMinBucket=findBucket( fAlpha );                            "
    "                                                                          "
    "    const float fLerp =                                                   "
    "        (fAlpha-texture1D(t_stopArray1d, nMinBucket).s) /                 "
    "        (texture1D(t_stopArray1d, nMinBucket+1).s -                       "
    "         texture1D(t_stopArray1d, nMinBucket).s);                         "
    "                                                                          "
    "    gl_FragColor = mix(texture1D(t_colorArray4d, nMinBucket),             "
    "                       texture1D(t_colorArray4d, nMinBucket+1),           "
    "                       fLerp);                                            "
    "}                                                                         "
};

/** Two-color radial gradient
 */
static const char radialTwoColorGradientFragmentShader[] =
{
    "#version 120                                                             \n"
    "uniform vec4   v_startColor4d;                                             "
    "uniform vec4   v_endColor4d;                                               "
    "uniform mat3x2 m_transform;                                                "
    "varying vec2   v_textureCoords2d;                                          "
    "const vec2     v_center2d = vec2(0,0);                                     "
    "void main(void)                                                            "
    "{                                                                          "
    "    gl_FragColor = mix(v_startColor4d,                                     "
    "                       v_endColor4d,                                       "
    "                       1.0 - distance(                                     "
    "                          vec2(                                            "
    "                             m_transform * vec3(v_textureCoords2d,1)),     "
    "                          v_center2d));                                    "
    "}                                                                          "
};

/** Multi-color radial gradient
 */
static const char radialMultiColorGradientFragmentShader[] =
{
    "#version 120                                                             \n"
    "uniform int       i_nColors;                                              "
    "uniform sampler1D t_colorArray4d;                                         "
    "uniform sampler1D t_stopArray1d;                                          "
    "uniform mat3x2    m_transform;                                            "
    "varying vec2      v_textureCoords2d;                                      "
    "const vec2        v_center2d = vec2(0,0);                                 "
    "                                                                          "
    "int findBucket(float t)                                                   "
    "{                                                                         "
    "    int nMinBucket=0;                                                     "
    "    while( nMinBucket < i_nColors &&                                      "
    "           texture1D(t_stopArray1d, nMinBucket).s < t )                   "
    "        ++nMinBucket;                                                     "
    "    return max(nMinBucket-1,0);                                           "
    "}                                                                         "
    "                                                                          "
    "void main(void)                                                           "
    "{                                                                         "
    "    const float fAlpha =                                                  "
    "        clamp( 1.0 - distance(                                            "
    "               vec2( m_transform * vec3(v_textureCoords2d,1)),            "
    "                     v_center2d),                                         "
    "               0.0, 1.0 );                                                "
    "                                                                          "
    "    const int nMinBucket=findBucket( fAlpha );                            "
    "                                                                          "
    "    const float fLerp =                                                   "
    "        (fAlpha-texture1D(t_stopArray1d, nMinBucket).s) /                 "
    "        (texture1D(t_stopArray1d, nMinBucket+1).s -                       "
    "         texture1D(t_stopArray1d, nMinBucket).s);                         "
    "                                                                          "
    "    gl_FragColor = mix(texture1D(t_colorArray4d, nMinBucket),             "
    "                       texture1D(t_colorArray4d, nMinBucket+1),           "
    "                       fLerp);                                            "
    "}                                                                         "
};

/** Two-color rectangular gradient
 */
static const char rectangularTwoColorGradientFragmentShader[] =
{
    "#version 120                                                             \n"
    "uniform vec4   v_startColor4d;                                             "
    "uniform vec4   v_endColor4d;                                               "
    "uniform mat3x2 m_transform;                                                "
    "varying vec2   v_textureCoords2d;                                          "
    "void main(void)                                                            "
    "{                                                                          "
    "    const vec2 v = abs( vec2(m_transform * vec3(v_textureCoords2d,1)) );   "
    "    const float t = max(v.x, v.y);                                         "
    "    gl_FragColor = mix(v_startColor4d,                                     "
    "                       v_endColor4d,                                       "
    "                       1.0-t);                                             "
    "}                                                                          "
};

/** Multi-color rectangular gradient
 */
static const char rectangularMultiColorGradientFragmentShader[] =
{
    "#version 120                                                             \n"
    "uniform int       i_nColors;                                              "
    "uniform sampler1D t_colorArray4d;                                         "
    "uniform sampler1D t_stopArray1d;                                          "
    "uniform mat3x2    m_transform;                                            "
    "varying vec2      v_textureCoords2d;                                      "
    "                                                                          "
    "int findBucket(float t)                                                   "
    "{                                                                         "
    "    int nMinBucket=0;                                                     "
    "    while( nMinBucket < i_nColors &&                                      "
    "           texture1D(t_stopArray1d, nMinBucket).s < t )                   "
    "        ++nMinBucket;                                                     "
    "    return max(nMinBucket-1,0);                                           "
    "}                                                                         "
    "                                                                          "
    "void main(void)                                                           "
    "{                                                                         "
    "    const vec2  v = abs( vec2(m_transform * vec3(v_textureCoords2d,1)) ); "
    "    const float fAlpha = 1 - max(v.x, v.y);                               "
    "                                                                          "
    "    const int nMinBucket=findBucket( fAlpha );                            "
    "                                                                          "
    "    const float fLerp =                                                   "
    "        (fAlpha-texture1D(t_stopArray1d, nMinBucket).s) /                 "
    "        (texture1D(t_stopArray1d, nMinBucket+1).s -                       "
    "         texture1D(t_stopArray1d, nMinBucket).s);                         "
    "                                                                          "
    "    gl_FragColor = mix(texture1D(t_colorArray4d, nMinBucket),             "
    "                       texture1D(t_colorArray4d, nMinBucket+1),           "
    "                       fLerp);                                            "
    "}                                                                         "
};

static void initContext()
{
    // need the backside for mirror effects
    glDisable(GL_CULL_FACE);

    // no perspective, we're 2D
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    // misc preferences
    glEnable(GL_POINT_SMOOTH);
    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_POLYGON_SMOOTH);
    glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
    glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
    glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST);
    glShadeModel(GL_FLAT);
}

static void initTransformation(const ::Size& rSize, bool bMirror=false)
{
    // use whole window
    glViewport( 0,0,
                (GLsizei)rSize.Width(),
                (GLsizei)rSize.Height() );

    // model coordinate system is already in device pixel
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslated(-1.0, (bMirror ? -1.0 : 1.0), 0.0);
    glScaled( 2.0  / rSize.Width(),
              (bMirror ? 2.0 : -2.0) / rSize.Height(),
              1.0 );

    // clear to black
    glClearColor(0,0,0,0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

static boost::shared_ptr<SystemChildWindow> createChildWindow( unx::XVisualInfo*& viWin,
                                                               unx::XVisualInfo*& viPB,
                                                               void*&             fbConfig,
                                                               Window&            rWindow,
                                                               unx::Display*      pDisplay,
                                                               int                nScreen )
{
    // select appropriate visual
    static int winAttrList3[] =
        {
            GLX_RGBA,//only TrueColor or DirectColor
            //single buffered
            GLX_RED_SIZE,4,//use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,//use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,//use the maximum blue bits, with a minimum of 4 bits
            GLX_DEPTH_SIZE,0,//no depth buffer
            None
        };
    static int pBufAttrList3[] =
        {
            GLX_DOUBLEBUFFER,False,// never doublebuffer pbuffer
            GLX_RED_SIZE,4,//use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,//use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,//use the maximum blue bits, with a minimum of 4 bits
            GLX_ALPHA_SIZE,4,
            GLX_DEPTH_SIZE,0,//no depth buffer
            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
            None
        };
    static int winAttrList2[] =
        {
            GLX_RGBA,//only TrueColor or DirectColor
            /// single buffered
            GLX_RED_SIZE,4,/// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,/// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,/// use the maximum blue bits, with a minimum of 4 bits
            GLX_DEPTH_SIZE,1,/// use the maximum depth bits, making sure there is a depth buffer
            None
        };
    static int pBufAttrList2[] =
        {
            GLX_DOUBLEBUFFER,False,// never doublebuffer pbuffer
            GLX_RED_SIZE,4,/// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,/// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,/// use the maximum blue bits, with a minimum of 4 bits
            GLX_ALPHA_SIZE,4,
            GLX_DEPTH_SIZE,1,/// use the maximum depth bits, making sure there is a depth buffer
            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
            None
        };
    static int winAttrList1[] =
        {
            GLX_RGBA,//only TrueColor or DirectColor
            GLX_DOUBLEBUFFER,/// only double buffer
            GLX_RED_SIZE,4,/// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,/// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,/// use the maximum blue bits, with a minimum of 4 bits
            GLX_DEPTH_SIZE,0,/// no depth buffer
            None
        };
    static int pBufAttrList1[] =
        {
            GLX_DOUBLEBUFFER,False,// never doublebuffer pbuffer
            GLX_RED_SIZE,4,/// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,/// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,/// use the maximum blue bits, with a minimum of 4 bits
            GLX_ALPHA_SIZE,4,
            GLX_DEPTH_SIZE,0,/// no depth buffer
            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
            None
        };
    static int winAttrList0[] =
        {
            GLX_RGBA,//only TrueColor or DirectColor
            GLX_DOUBLEBUFFER,// only double buffer
            GLX_RED_SIZE,4,// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,// use the maximum blue bits, with a minimum of 4 bits
            GLX_DEPTH_SIZE,1,// use the maximum depth bits, making sure there is a depth buffer
            None
        };
    static int pBufAttrList0[] =
        {
            GLX_DOUBLEBUFFER,False,// never doublebuffer pbuffer
            GLX_RED_SIZE,4,// use the maximum red bits, with a minimum of 4 bits
            GLX_GREEN_SIZE,4,// use the maximum green bits, with a minimum of 4 bits
            GLX_BLUE_SIZE,4,// use the maximum blue bits, with a minimum of 4 bits
            GLX_ALPHA_SIZE,4,
            GLX_DEPTH_SIZE,1,// use the maximum depth bits, making sure there is a depth buffer
            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
            None
        };
    static int* winAttrTable[] =
        {
            winAttrList0,
            winAttrList1,
            winAttrList2,
            winAttrList3,
            NULL
        };
    static int* pBufAttrTable[] =
        {
            pBufAttrList0,
            pBufAttrList1,
            pBufAttrList2,
            pBufAttrList3,
            NULL
        };
    int** pWinAttributeTable = winAttrTable;
    int** pBufAttributeTable = pBufAttrTable;

    boost::shared_ptr<SystemChildWindow> pResult;
    unx::GLXFBConfig* fbConfigs=NULL;
    int nConfigs, nVal;
    while( *pWinAttributeTable && *pBufAttributeTable )
    {
        // try to find a window visual for the current set of
        // attributes
        viWin = unx::glXChooseVisual( pDisplay,
                                      nScreen,
                                      *pWinAttributeTable );
        if( viWin )
        {
            // try to find a framebuffer config for the current set of
            // attributes
            fbConfigs = glXChooseFBConfig( pDisplay,
                                           nScreen,
                                           *pBufAttributeTable,
                                           &nConfigs );
            // don't use glXGetFBConfigs, that does not list alpha-configs
            // fbConfigs = unx::glXGetFBConfigs(pDisplay, nScreen, &nConfigs);
            for(int i=0; i<nConfigs; i++)
            {
                viPB = glXGetVisualFromFBConfig(pDisplay, fbConfigs[i]);
                if( viPB && viPB->visualid != viWin->visualid )
                {
                    glXGetFBConfigAttrib(pDisplay,
                                         fbConfigs[i],
                                         GLX_DRAWABLE_TYPE,
                                         &nVal);

                    if( (GLX_PBUFFER_BIT|GLX_WINDOW_BIT|GLX_PIXMAP_BIT)
                        == (nVal & (GLX_PBUFFER_BIT|GLX_WINDOW_BIT|GLX_PIXMAP_BIT)) )
                    {
                        SystemWindowData winData;
                        winData.nSize = sizeof(winData);
                        SAL_INFO("canvas.ogl", "using VisualID " << viWin->visualid << " for OpenGL canvas");
                        winData.pVisual = (void*)(viWin->visual);
                        pResult.reset( new SystemChildWindow(&rWindow, 0, &winData, false) );

                        if( pResult->GetSystemData() )
                        {
                            fbConfig = &fbConfigs[i];
                            return pResult;
                        }

                        pResult.reset();
                    }

                    XFree(viPB);
                }
            }

            XFree(viWin);
        }

        ++pWinAttributeTable;
        ++pBufAttributeTable;
    }

    return pResult;
}


namespace oglcanvas
{
    /** Compile shader program

        Code courtesy rodo
     */
    void SpriteDeviceHelper::compileShader(unsigned int& o_rShaderHandle,
                                           unsigned int  eShaderType,
                                           const char*   pShaderSourceCode)
    {
        GLint nCompileStatus;
        char log[1024];

        o_rShaderHandle = glCreateShader( eShaderType );
        glShaderSource( o_rShaderHandle, 1, &pShaderSourceCode, NULL );
        glCompileShader( o_rShaderHandle );
        glGetShaderInfoLog( o_rShaderHandle, sizeof(log), NULL, log );
        SAL_INFO("canvas.ogl", "shader compile log: " << log);

        glGetShaderiv( o_rShaderHandle, GL_COMPILE_STATUS, &nCompileStatus );
        if( !nCompileStatus )
        {
            glDeleteShader(o_rShaderHandle);
            o_rShaderHandle=0;
        }
    }

    /** Link vertex & fragment shaders

        Code courtesy rodo
     */
    void SpriteDeviceHelper::linkShaders(unsigned int& o_rProgramHandle,
                                         unsigned int  nVertexProgramId,
                                         unsigned int  nFragmentProgramId)
    {
        if( !nVertexProgramId || !nFragmentProgramId )
            return;

        o_rProgramHandle = glCreateProgram();
        glAttachShader( o_rProgramHandle, nVertexProgramId );
        glAttachShader( o_rProgramHandle, nFragmentProgramId );

        char log[1024];
        GLint nProgramLinked;

        glLinkProgram( o_rProgramHandle );
        glGetProgramInfoLog( o_rProgramHandle, sizeof(log), NULL, log );
        SAL_INFO("canvas.ogl", "shader program link log: " << log);
        glGetProgramiv( o_rProgramHandle, GL_LINK_STATUS, &nProgramLinked );

        if( !nProgramLinked )
        {
            glDeleteProgram(o_rProgramHandle);
            o_rProgramHandle=0;
        }
    }

    SpriteDeviceHelper::SpriteDeviceHelper() :
        mpDevice(NULL),
        mpSpriteCanvas(NULL),
        maActiveSprites(),
        maLastUpdate(),
        mpChildWindow(),
        mpDisplay(NULL),
        mpGLContext(NULL),
        mpGLPBufContext(NULL),
        mpFBConfig(NULL),
        mpTextureCache(new TextureCache()),
        mnDummyVertexProgram(0),
        mnLinearTwoColorGradientFragmentProgram(0),
        mnLinearMultiColorGradientFragmentProgram(0),
        mnRadialTwoColorGradientFragmentProgram(0),
        mnRadialMultiColorGradientFragmentProgram(0),
        mnRectangularTwoColorGradientFragmentProgram(0),
        mnRectangularMultiColorGradientFragmentProgram(0),
        mnLinearTwoColorGradientProgram(0),
        mnLinearMultiColorGradientProgram(0),
        mnRadialTwoColorGradientProgram(0),
        mnRadialMultiColorGradientProgram(0),
        mnRectangularTwoColorGradientProgram(0),
        mnRectangularMultiColorGradientProgram(0)
    {}

    void SpriteDeviceHelper::init( Window&               rWindow,
                                   SpriteCanvas&         rSpriteCanvas,
                                   const awt::Rectangle& rViewArea )
    {
        mpSpriteCanvas = &rSpriteCanvas;

        rSpriteCanvas.setWindow(
            uno::Reference<awt::XWindow2>(
                VCLUnoHelper::GetInterface(&rWindow),
                uno::UNO_QUERY_THROW) );

        // init OpenGL
        const SystemEnvData* sysData(rWindow.GetSystemData());
        unx::Display* pDisplay=reinterpret_cast<unx::Display*>(sysData->pDisplay);
        mpDisplay=pDisplay;
        if( !unx::glXQueryExtension(pDisplay, NULL, NULL) )
            return;

        unx::Window xWindow = sysData->aWindow;
        unx::XWindowAttributes xAttr;
        unx::XGetWindowAttributes( pDisplay, xWindow, &xAttr );
        int nScreen = XScreenNumberOfScreen( xAttr.screen );

        unx::Window childXWindow=0;
        unx::XVisualInfo* viWin=NULL;
        unx::XVisualInfo* viPB=NULL;
        mpChildWindow=createChildWindow(viWin,viPB,mpFBConfig,
                                        rWindow,pDisplay,nScreen);

        // tweak SysChild window to act as an input-transparent
        // overlay
        if( mpChildWindow )
        {
            childXWindow=mpChildWindow->GetSystemData()->aWindow;
            mpChildWindow->SetMouseTransparent(true);
            mpChildWindow->SetParentClipMode( PARENTCLIPMODE_NOCLIP );
            mpChildWindow->EnableEraseBackground(false);
            mpChildWindow->SetControlForeground();
            mpChildWindow->SetControlBackground();
            mpChildWindow->EnablePaint(false);

            unx::GLXContext pContext1 =
                glXCreateContext(pDisplay,
                                 viWin,
                                 0,
                                 GL_TRUE);
            mpGLContext = pContext1;

            unx::GLXContext pContext2 =
                glXCreateContext( pDisplay,
                                  viPB,
                                  pContext1,
                                  GL_TRUE );
            mpGLPBufContext = pContext2;

            XFree(viWin);
            XFree(viPB);

            if( !glXMakeCurrent( pDisplay,
                                 childXWindow,
                                 pContext1) )
            {
                glXDestroyContext(pDisplay, pContext1);
                glXDestroyContext(pDisplay, pContext2);
                throw lang::NoSupportException("Could not select OpenGL context!", NULL);
            }

            const GLubyte* extensions=glGetString( GL_EXTENSIONS );
            if( gluCheckExtension((const GLubyte*)"GLX_SGI_swap_control", extensions) )
            {
                // try to enable vsync
                typedef GLint (*glXSwapIntervalProc)(GLint);
                glXSwapIntervalProc glXSwapInterval =
                    (glXSwapIntervalProc) unx::glXGetProcAddress((const GLubyte*)"glXSwapIntervalSGI");
                if( glXSwapInterval )
                {
                    int (*oldHandler)(unx::Display*, unx::XErrorEvent*);

                    // synchronize on global mutex - no other ogl
                    // canvas instance permitted to enter here
                    {
                        ::osl::MutexGuard aGuard( *::osl::Mutex::getGlobalMutex() );

                        // replace error handler temporarily
                        oldHandler = unx::XSetErrorHandler( lcl_XErrorHandler );

                        lcl_bErrorTriggered = false;

                        // Note: if this fails, so be it. Buggy
                        // drivers will then not have vsync.
                        glXSwapInterval(1);

                        // sync so that we possibly get an XError
                        unx::glXWaitGL();
                        XSync(pDisplay, false);

                        unx::XSetErrorHandler( oldHandler );
                    }
                }
            }

            // init window context
            initContext();

            // compile & link shaders - code courtesy rodo
            compileShader(mnDummyVertexProgram,
                          GL_VERTEX_SHADER,
                          dummyVertexShader);
            compileShader(mnLinearTwoColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          linearTwoColorGradientFragmentShader);
            compileShader(mnLinearMultiColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          linearMultiColorGradientFragmentShader);
            compileShader(mnRadialTwoColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          radialTwoColorGradientFragmentShader);
            compileShader(mnRadialMultiColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          radialMultiColorGradientFragmentShader);
            compileShader(mnRectangularTwoColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          rectangularTwoColorGradientFragmentShader);
            compileShader(mnRectangularMultiColorGradientFragmentProgram,
                          GL_FRAGMENT_SHADER,
                          rectangularMultiColorGradientFragmentShader);
            linkShaders(mnLinearTwoColorGradientProgram,
                        mnDummyVertexProgram,
                        mnLinearTwoColorGradientFragmentProgram);
            linkShaders(mnLinearMultiColorGradientProgram,
                        mnDummyVertexProgram,
                        mnLinearMultiColorGradientFragmentProgram);
            linkShaders(mnRadialTwoColorGradientProgram,
                        mnDummyVertexProgram,
                        mnRadialTwoColorGradientFragmentProgram);
            linkShaders(mnRadialMultiColorGradientProgram,
                        mnDummyVertexProgram,
                        mnRadialMultiColorGradientFragmentProgram);
            linkShaders(mnRectangularTwoColorGradientProgram,
                        mnDummyVertexProgram,
                        mnRectangularTwoColorGradientFragmentProgram);
            linkShaders(mnRectangularMultiColorGradientProgram,
                        mnDummyVertexProgram,
                        mnRectangularMultiColorGradientFragmentProgram);

            glXMakeCurrent(pDisplay, None, NULL);
        }

        if( !mpGLContext || glGetError() != GL_NO_ERROR )
            throw lang::NoSupportException(
                "Could not create OpenGL context, or an error occurred doing so!", NULL);

        notifySizeUpdate(rViewArea);
        mpChildWindow->Show();
        // TODO(E3): check for GL_ARB_imaging extension
    }

    void SpriteDeviceHelper::disposing()
    {
        // release all references
        mpSpriteCanvas = NULL;
        mpDevice = NULL;
        mpTextureCache.reset();

        if( mpGLContext )
        {
            glDeleteProgram( mnRectangularTwoColorGradientProgram );
            glDeleteProgram( mnRectangularMultiColorGradientProgram );
            glDeleteProgram( mnRadialTwoColorGradientProgram );
            glDeleteProgram( mnRadialMultiColorGradientProgram );
            glDeleteProgram( mnLinearTwoColorGradientProgram );
            glDeleteProgram( mnLinearMultiColorGradientProgram );
            glDeleteShader( mnRectangularTwoColorGradientFragmentProgram );
            glDeleteShader( mnRectangularMultiColorGradientFragmentProgram );
            glDeleteShader( mnRadialTwoColorGradientFragmentProgram );
            glDeleteShader( mnRadialMultiColorGradientFragmentProgram );
            glDeleteShader( mnLinearTwoColorGradientFragmentProgram );
            glDeleteShader( mnLinearMultiColorGradientFragmentProgram );
            glDeleteShader( mnDummyVertexProgram );

            glXDestroyContext(reinterpret_cast<unx::Display*>(mpDisplay),
                              reinterpret_cast<unx::GLXContext>(mpGLContext));
        }

        mpDisplay = NULL;
        mpGLContext = NULL;
        mpChildWindow.reset();
    }

    geometry::RealSize2D SpriteDeviceHelper::getPhysicalResolution()
    {
        if( !mpChildWindow )
            return ::canvas::tools::createInfiniteSize2D(); // we're disposed

        // Map a one-by-one millimeter box to pixel
        const MapMode aOldMapMode( mpChildWindow->GetMapMode() );
        mpChildWindow->SetMapMode( MapMode(MAP_MM) );
        const Size aPixelSize( mpChildWindow->LogicToPixel(Size(1,1)) );
        mpChildWindow->SetMapMode( aOldMapMode );

        return ::vcl::unotools::size2DFromSize( aPixelSize );
    }

    geometry::RealSize2D SpriteDeviceHelper::getPhysicalSize()
    {
        if( !mpChildWindow )
            return ::canvas::tools::createInfiniteSize2D(); // we're disposed

        // Map the pixel dimensions of the output window to millimeter
        const MapMode aOldMapMode( mpChildWindow->GetMapMode() );
        mpChildWindow->SetMapMode( MapMode(MAP_MM) );
        const Size aLogSize( mpChildWindow->PixelToLogic(mpChildWindow->GetOutputSizePixel()) );
        mpChildWindow->SetMapMode( aOldMapMode );

        return ::vcl::unotools::size2DFromSize( aLogSize );
    }

    uno::Reference< rendering::XLinePolyPolygon2D > SpriteDeviceHelper::createCompatibleLinePolyPolygon(
        const uno::Reference< rendering::XGraphicDevice >&              /*rDevice*/,
        const uno::Sequence< uno::Sequence< geometry::RealPoint2D > >&  points )
    {
        // disposed?
        if( !mpSpriteCanvas )
            return uno::Reference< rendering::XLinePolyPolygon2D >(); // we're disposed

        return uno::Reference< rendering::XLinePolyPolygon2D >(
            new ::basegfx::unotools::UnoPolyPolygon(
                ::basegfx::unotools::polyPolygonFromPoint2DSequenceSequence( points )));
    }

    uno::Reference< rendering::XBezierPolyPolygon2D > SpriteDeviceHelper::createCompatibleBezierPolyPolygon(
        const uno::Reference< rendering::XGraphicDevice >&                      /*rDevice*/,
        const uno::Sequence< uno::Sequence< geometry::RealBezierSegment2D > >&  points )
    {
        // disposed?
        if( !mpSpriteCanvas )
            return uno::Reference< rendering::XBezierPolyPolygon2D >(); // we're disposed

        return uno::Reference< rendering::XBezierPolyPolygon2D >(
            new ::basegfx::unotools::UnoPolyPolygon(
                ::basegfx::unotools::polyPolygonFromBezier2DSequenceSequence( points ) ) );
    }

    uno::Reference< rendering::XBitmap > SpriteDeviceHelper::createCompatibleBitmap(
        const uno::Reference< rendering::XGraphicDevice >&  /*rDevice*/,
        const geometry::IntegerSize2D&                      size )
    {
        // disposed?
        if( !mpSpriteCanvas )
            return uno::Reference< rendering::XBitmap >(); // we're disposed

        return uno::Reference< rendering::XBitmap >(
            new CanvasBitmap( size,
                              mpSpriteCanvas,
                              *this,
                              false ) );
    }

    uno::Reference< rendering::XVolatileBitmap > SpriteDeviceHelper::createVolatileBitmap(
        const uno::Reference< rendering::XGraphicDevice >&  /*rDevice*/,
        const geometry::IntegerSize2D&                      /*size*/ )
    {
        return uno::Reference< rendering::XVolatileBitmap >();
    }

    uno::Reference< rendering::XBitmap > SpriteDeviceHelper::createCompatibleAlphaBitmap(
        const uno::Reference< rendering::XGraphicDevice >&  /*rDevice*/,
        const geometry::IntegerSize2D&                      size )
    {
        // disposed?
        if( !mpSpriteCanvas )
            return uno::Reference< rendering::XBitmap >(); // we're disposed

        return uno::Reference< rendering::XBitmap >(
            new CanvasBitmap( size,
                              mpSpriteCanvas,
                              *this,
                              true ) );
    }

    uno::Reference< rendering::XVolatileBitmap > SpriteDeviceHelper::createVolatileAlphaBitmap(
        const uno::Reference< rendering::XGraphicDevice >&  /*rDevice*/,
        const geometry::IntegerSize2D&                      /*size*/ )
    {
        return uno::Reference< rendering::XVolatileBitmap >();
    }

    sal_Bool SpriteDeviceHelper::hasFullScreenMode()
    {
        // TODO(F3): offer fullscreen mode the XCanvas way
        return false;
    }

    sal_Bool SpriteDeviceHelper::enterFullScreenMode( sal_Bool /*bEnter*/ )
    {
        // TODO(F3): offer fullscreen mode the XCanvas way
        return false;
    }

    ::sal_Int32 SpriteDeviceHelper::createBuffers( ::sal_Int32 /*nBuffers*/ )
    {
        // TODO(F3): implement XBufferStrategy interface. For now, we
        // _always_ will have exactly one backbuffer
        return 1;
    }

    void SpriteDeviceHelper::destroyBuffers()
    {
        // TODO(F3): implement XBufferStrategy interface. For now, we
        // _always_ will have exactly one backbuffer
    }

    namespace
    {
        /** Functor providing a StrictWeakOrdering for XSprites (over
            priority)
         */
        struct SpriteComparator
        {
            bool operator()( const ::rtl::Reference<CanvasCustomSprite>& rLHS,
                             const ::rtl::Reference<CanvasCustomSprite>& rRHS ) const
            {
                const double nPrioL( rLHS->getPriority() );
                const double nPrioR( rRHS->getPriority() );

                // if prios are equal, tie-break on ptr value
                return nPrioL == nPrioR ? rLHS.get() < rRHS.get() : nPrioL < nPrioR;
            }
        };
    }

    ::sal_Bool SpriteDeviceHelper::showBuffer( bool bIsVisible, ::sal_Bool /*bUpdateAll*/ )
    {
        // hidden or disposed?
        if( !bIsVisible || !mpChildWindow || !mpSpriteCanvas )
            return false;

        if( !activateWindowContext() )
            return false;

        const ::Size& rOutputSize=mpChildWindow->GetSizePixel();
        initTransformation(rOutputSize);

        // render the actual spritecanvas content
        mpSpriteCanvas->renderRecordedActions();

        // render all sprites (in order of priority) on top of that
        std::vector< ::rtl::Reference<CanvasCustomSprite> > aSprites;
        std::copy(maActiveSprites.begin(),
                  maActiveSprites.end(),
                  std::back_insert_iterator<
                       std::vector< ::rtl::Reference< CanvasCustomSprite > > >(aSprites));
        std::sort(aSprites.begin(),
                  aSprites.end(),
                  SpriteComparator());
        std::for_each(aSprites.begin(),
                      aSprites.end(),
                      boost::mem_fn(&CanvasCustomSprite::renderSprite));


        // frame counter, other info
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslated(-1.0, 1.0, 0.0);
        glScaled( 2.0  / rOutputSize.Width(),
                  -2.0 / rOutputSize.Height(),
                  1.0 );

        const double denominator( maLastUpdate.getElapsedTime() );
        maLastUpdate.reset();

        const double fps(denominator == 0.0 ? 100.0 : 1.0/denominator);
        std::vector<double> aVec; aVec.push_back(fps);
        aVec.push_back(maActiveSprites.size());
        aVec.push_back(mpTextureCache->getCacheSize());
        aVec.push_back(mpTextureCache->getCacheMissCount());
        aVec.push_back(mpTextureCache->getCacheHitCount());
        renderOSD( aVec, 20 );

        // switch buffer, sync etc.
        const unx::Window aXWindow=mpChildWindow->GetSystemData()->aWindow;
        unx::glXSwapBuffers(reinterpret_cast<unx::Display*>(mpDisplay),
                            aXWindow);
        mpChildWindow->Show();
        unx::glXWaitGL();
        XSync( reinterpret_cast<unx::Display*>(mpDisplay), false );

        // flush texture cache, such that it does not build up
        // indefinitely.
        // TODO: have max cache size/LRU time in config, prune only on
        // demand
        mpTextureCache->prune();

        return true;
    }

    ::sal_Bool SpriteDeviceHelper::switchBuffer( bool bIsVisible, ::sal_Bool bUpdateAll )
    {
        // no difference for VCL canvas
        return showBuffer( bIsVisible, bUpdateAll );
    }

    uno::Any SpriteDeviceHelper::isAccelerated() const
    {
        return ::com::sun::star::uno::makeAny(false);
    }

    uno::Any SpriteDeviceHelper::getDeviceHandle() const
    {
        return uno::makeAny( reinterpret_cast< sal_Int64 >(mpChildWindow.get()) );
    }

    uno::Any SpriteDeviceHelper::getSurfaceHandle() const
    {
        return uno::Any();
    }

    uno::Reference<rendering::XColorSpace> SpriteDeviceHelper::getColorSpace() const
    {
        // always the same
        return uno::Reference<rendering::XColorSpace>(
            ::canvas::tools::getStdColorSpace(),
            uno::UNO_QUERY);
    }

    void SpriteDeviceHelper::notifySizeUpdate( const awt::Rectangle& rBounds )
    {
        if( mpChildWindow )
            mpChildWindow->setPosSizePixel(
                0,0,rBounds.Width,rBounds.Height);
    }

    void SpriteDeviceHelper::dumpScreenContent() const
    {
        SAL_INFO("canvas.ogl", BOOST_CURRENT_FUNCTION );
    }

    void SpriteDeviceHelper::show( const ::rtl::Reference< CanvasCustomSprite >& xSprite )
    {
        maActiveSprites.insert(xSprite);
    }

    void SpriteDeviceHelper::hide( const ::rtl::Reference< CanvasCustomSprite >& xSprite )
    {
        maActiveSprites.erase(xSprite);
    }

    static void setupUniforms( unsigned int                                 nProgramId,
                               const ::basegfx::B2DHomMatrix&               rTexTransform )
    {
        const GLint nTransformLocation = glGetUniformLocation(nProgramId,
                                                             "m_transform" );
        // OGL is column-major
        float aTexTransform[] =
            {
                float(rTexTransform.get(0,0)), float(rTexTransform.get(1,0)),
                float(rTexTransform.get(0,1)), float(rTexTransform.get(1,1)),
                float(rTexTransform.get(0,2)), float(rTexTransform.get(1,2))
            };
        glUniformMatrix3x2fv(nTransformLocation,1,false,aTexTransform);
    }

    static void setupUniforms( unsigned int                   nProgramId,
                               const rendering::ARGBColor*    pColors,
                               const uno::Sequence< double >& rStops,
                               const ::basegfx::B2DHomMatrix& rTexTransform )
    {
        glUseProgram(nProgramId);

        GLuint nColorsTexture;
        glActiveTexture(GL_TEXTURE0);
        glGenTextures(1, &nColorsTexture);
        glBindTexture(GL_TEXTURE_1D, nColorsTexture);

        const sal_Int32 nColors=rStops.getLength();
        glTexImage1D( GL_TEXTURE_1D, 0, GL_RGBA, nColors, 0, GL_RGBA, GL_DOUBLE, pColors );
        glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
        glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

        GLuint nStopsTexture;
        glActiveTexture(GL_TEXTURE1);
        glGenTextures(1, &nStopsTexture);
        glBindTexture(GL_TEXTURE_1D, nStopsTexture);

        glTexImage1D( GL_TEXTURE_1D, 0, GL_ALPHA, nColors, 0, GL_ALPHA, GL_DOUBLE, rStops.getConstArray() );
        glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
        glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

        const GLint nColorArrayLocation = glGetUniformLocation(nProgramId,
                                                               "t_colorArray4d" );
        glUniform1i( nColorArrayLocation, 0 ); // unit 0

        const GLint nStopArrayLocation = glGetUniformLocation(nProgramId,
                                                              "t_stopArray1d" );
        glUniform1i( nStopArrayLocation, 1 ); // unit 1

        const GLint nNumColorLocation = glGetUniformLocation(nProgramId,
                                                             "i_nColors" );
        glUniform1i( nNumColorLocation, nColors-1 );

        setupUniforms(nProgramId,rTexTransform);
    }

    static void setupUniforms( unsigned int                   nProgramId,
                               const rendering::ARGBColor&    rStartColor,
                               const rendering::ARGBColor&    rEndColor,
                               const ::basegfx::B2DHomMatrix& rTexTransform )
    {
        glUseProgram(nProgramId);

        const GLint nStartColorLocation = glGetUniformLocation(nProgramId,
                                                               "v_startColor4d" );
        glUniform4f(nStartColorLocation,
                    rStartColor.Red,
                    rStartColor.Green,
                    rStartColor.Blue,
                    rStartColor.Alpha);

        const GLint nEndColorLocation = glGetUniformLocation(nProgramId,
                                                             "v_endColor4d" );
        glUniform4f(nEndColorLocation,
                    rEndColor.Red,
                    rEndColor.Green,
                    rEndColor.Blue,
                    rEndColor.Alpha);

        setupUniforms(nProgramId,rTexTransform);
    }

    void SpriteDeviceHelper::useLinearGradientShader( const rendering::ARGBColor*    pColors,
                                                      const uno::Sequence< double >& rStops,
                                                      const ::basegfx::B2DHomMatrix& rTexTransform )
    {
        if( rStops.getLength() > 2 )
            setupUniforms(mnLinearMultiColorGradientProgram, pColors, rStops, rTexTransform);
        else
            setupUniforms(mnLinearTwoColorGradientProgram, pColors[0], pColors[1], rTexTransform);
    }

    void SpriteDeviceHelper::useRadialGradientShader( const rendering::ARGBColor*    pColors,
                                                      const uno::Sequence< double >& rStops,
                                                      const ::basegfx::B2DHomMatrix& rTexTransform )
    {
        if( rStops.getLength() > 2 )
            setupUniforms(mnRadialMultiColorGradientProgram, pColors, rStops, rTexTransform);
        else
            setupUniforms(mnRadialTwoColorGradientProgram, pColors[0], pColors[1], rTexTransform);
    }

    void SpriteDeviceHelper::useRectangularGradientShader( const rendering::ARGBColor*    pColors,
                                                           const uno::Sequence< double >& rStops,
                                                           const ::basegfx::B2DHomMatrix& rTexTransform )
    {
        if( rStops.getLength() > 2 )
            setupUniforms(mnRectangularMultiColorGradientProgram, pColors, rStops, rTexTransform);
        else
            setupUniforms(mnRectangularTwoColorGradientProgram, pColors[0], pColors[1], rTexTransform);
    }

    bool SpriteDeviceHelper::activatePBufferContext(const ::basegfx::B2IVector& rSize,
                                                    unsigned int                PBuffer) const
    {
        if( !glXMakeCurrent( reinterpret_cast<unx::Display*>(mpDisplay),
                             PBuffer,
                             reinterpret_cast<unx::GLXContext>(mpGLPBufContext)) )
        {
            SAL_INFO("canvas.ogl", "SpriteDeviceHelper::activatePBufferContext(): cannot activate GL context");
            return false;
        }

        initContext();
        initTransformation(
            ::Size(
                rSize.getX(),
                rSize.getY()),
            true);

        return true;
    }

    bool SpriteDeviceHelper::activateWindowContext() const
    {
        const unx::Window aXWindow=mpChildWindow->GetSystemData()->aWindow;
        if( !glXMakeCurrent( reinterpret_cast<unx::Display*>(mpDisplay),
                             aXWindow,
                             reinterpret_cast<unx::GLXContext>(mpGLContext)) )
        {
            SAL_INFO("canvas.ogl", "SpriteDeviceHelper::activateWindowContext(): cannot activate GL context");
            return false;
        }

        return true;
    }

    bool SpriteDeviceHelper::updatePBufferTexture( const ::basegfx::B2IVector& rSize,
                                                   unsigned int                nTextId ) const
    {
        glBindTexture( GL_TEXTURE_2D, nTextId );
        glEnable(GL_TEXTURE_2D);
        glCopyTexSubImage2D( GL_TEXTURE_2D,
                             0, 0, 0, 0, 0,
                             rSize.getX(),
                             rSize.getY() );
        glBindTexture(GL_TEXTURE_2D, 0);

        return true;
    }

    namespace
    {
        class BufferContextImpl : public IBufferContext
        {
            ::basegfx::B2IVector       maSize;
            const SpriteDeviceHelper&  mrDeviceHelper;
            unx::GLXPbuffer            mpPBuffer;
#if 0
            unx::Display*              mpDisplay;
#endif
            unsigned int               mnTexture;

            virtual bool startBufferRendering() SAL_OVERRIDE
            {
                return mrDeviceHelper.activatePBufferContext(maSize,mpPBuffer);
            }

            virtual bool endBufferRendering() SAL_OVERRIDE
            {
                mrDeviceHelper.updatePBufferTexture(maSize,mnTexture);
                if( !mrDeviceHelper.activateWindowContext() )
                    return false;

                glBindTexture( GL_TEXTURE_2D, mnTexture );

                return true;
            }

        public:
            BufferContextImpl(const SpriteDeviceHelper&   rDeviceHelper,
                              unx::GLXPbuffer             pBuffer,
                              unx::Display*
#if 0
                                                          pDisplay
#endif
                              ,
                              const ::basegfx::B2IVector& rSize) :
                maSize(rSize),
                mrDeviceHelper(rDeviceHelper),
                mpPBuffer(pBuffer),
#if 0
                mpDisplay(pDisplay),
#endif
                mnTexture(0)
            {
                glGenTextures( 1, &mnTexture );
#if 1
                glBindTexture( GL_TEXTURE_2D, mnTexture );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
                glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA,
                              maSize.getX(), maSize.getY(),
                              0, GL_RGBA, GL_UNSIGNED_BYTE, new int[maSize.getX()*maSize.getY()] );
#endif
            }

            ~BufferContextImpl()
            {
#if 0
                glBindTexture(GL_TEXTURE_2D, 0);
                glDeleteTextures( 1, &mnTexture );
                glXDestroyPbuffer( mpDisplay, mpPBuffer );
#endif
            }
        };
    }

    IBufferContextSharedPtr SpriteDeviceHelper::createBufferContext(const ::basegfx::B2IVector& rSize) const
    {
        int pBufAttribs[] =
            {
                GLX_PBUFFER_WIDTH,   rSize.getX(),
                GLX_PBUFFER_HEIGHT,  rSize.getY(),
                GLX_LARGEST_PBUFFER, False,
                None
            };

        unx::GLXPbuffer pBuffer;
        pBuffer = unx::glXCreatePbuffer( reinterpret_cast<unx::Display*>(mpDisplay),
                                         *reinterpret_cast<unx::GLXFBConfig*>(mpFBConfig),
                                         pBufAttribs );

        IBufferContextSharedPtr pRet;
        if( pBuffer )
            pRet.reset(new BufferContextImpl(
                           *this,
                           pBuffer,
                           reinterpret_cast<unx::Display*>(mpDisplay),
                           rSize));

        return pRet;
    }

    TextureCache& SpriteDeviceHelper::getTextureCache() const
    {
        return *mpTextureCache;
    }
}

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