summaryrefslogtreecommitdiff
path: root/canvas/source/directx/dx_9rm.cxx
blob: 8d3ffd8b275511d8465c533bceb459dda5c655b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/


#if DIRECTX_VERSION == 0x0900

#define MAX_TEXTURE_SIZE (2048)
#define MIN_TEXTURE_SIZE (32)
//#define FAKE_MAX_NUMBER_TEXTURES (2)
//#define FAKE_MAX_TEXTURE_SIZE (4096)

#define VERTEX_BUFFER_SIZE (341*3) // 1023, the size of the internal
                                   // vertex buffer (must be divisable
                                   // by 3, as each triangle primitive
                                   // has 3 vertices)

#include <vcl/syschild.hxx>
#include <vcl/window.hxx>

#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <tools/diagnose_ex.h>

#include <canvas/elapsedtime.hxx>
#include <canvas/canvastools.hxx>
#include <canvas/rendering/icolorbuffer.hxx>
#include <canvas/rendering/isurface.hxx>
#include <canvas/rendering/irendermodule.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/vector/b2dsize.hxx>
#include <basegfx/vector/b2isize.hxx>
#include <basegfx/point/b2ipoint.hxx>
#include <basegfx/range/b2irectangle.hxx>
#include <boost/scoped_ptr.hpp>
#include <com/sun/star/lang/NoSupportException.hpp>

#include "dx_rendermodule.hxx"
#include "dx_config.hxx"

#undef WB_LEFT
#undef WB_RIGHT

#include "dx_impltools.hxx"
#include <vcl/sysdata.hxx>

#if defined(DX_DEBUG_IMAGES)
# if OSL_DEBUG_LEVEL > 0
#  include <imdebug.h>
#  undef min
#  undef max
# endif
#endif

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

//////////////////////////////////////////////////////////////////////////////////
// 'dxcanvas' namespace
//////////////////////////////////////////////////////////////////////////////////

namespace dxcanvas
{
    namespace
    {
        //////////////////////////////////////////////////////////////////////////////////
        // monitorSupport
        //////////////////////////////////////////////////////////////////////////////////

        class monitorSupport
        {
        public:

            monitorSupport() :
                mhLibrary(LoadLibrary("user32.dll")),
                mpMonitorFromWindow(NULL)
            {
                if(mhLibrary)
                    mpMonitorFromWindow = reinterpret_cast<fMonitorFromWindow>(
                        GetProcAddress(
                            mhLibrary,"MonitorFromWindow"));
            }

            ~monitorSupport()
            {
                if(mhLibrary)
                    FreeLibrary(mhLibrary);
                mhLibrary=0;
            }

            HMONITOR MonitorFromWindow( HWND hwnd )
            {
                // return adapter_default in case something went wrong...
                if(!(mpMonitorFromWindow))
                    return HMONITOR(0);
                // MONITOR_DEFAULTTONEAREST
                const DWORD dwFlags(0x00000002);
                return mpMonitorFromWindow(hwnd,dwFlags);
            }
        private:

            HINSTANCE mhLibrary;
            typedef HMONITOR (WINAPI *fMonitorFromWindow )( HWND hwnd, DWORD dwFlags );
            fMonitorFromWindow mpMonitorFromWindow;
        };

        monitorSupport aMonitorSupport;


        class DXRenderModule;

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface
        //////////////////////////////////////////////////////////////////////////////////

        /** ISurface implemenation.

            @attention holds the DXRenderModule via non-refcounted
            reference! This is safe with current state of affairs, since
            the canvas::PageManager holds surface and render module via
            shared_ptr (and makes sure all surfaces are deleted before its
            render module member goes out of scope).
        */
        class DXSurface : public canvas::ISurface
        {
        public:
            DXSurface( DXRenderModule&           rRenderModule,
                       const ::basegfx::B2ISize& rSize );
            ~DXSurface();

            virtual bool selectTexture();
            virtual bool isValid();
            virtual bool update( const ::basegfx::B2IPoint& rDestPos,
                                const ::basegfx::B2IRange& rSourceRect,
                                ::canvas::IColorBuffer&    rSource );
            virtual ::basegfx::B2IVector getSize();
            COMReference<IDirect3DTexture9> getTexture() const;

        private:
            /// Guard local methods against concurrent acces to RenderModule
            class ImplRenderModuleGuard : private ::boost::noncopyable
            {
            public:
                explicit inline ImplRenderModuleGuard( DXRenderModule& rRenderModule );
                inline ~ImplRenderModuleGuard();

            private:
                DXRenderModule& mrRenderModule;
            };

            DXRenderModule&                  mrRenderModule;
            COMReference<IDirect3DTexture9>  mpTexture;

            ::basegfx::B2IVector             maSize;
        };


        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule
        //////////////////////////////////////////////////////////////////////////////////

        /// Default implementation of IDXRenderModule
        class DXRenderModule : public IDXRenderModule
        {
        public:
            explicit DXRenderModule( const ::Window& rWindow );
            ~DXRenderModule();

            virtual void lock() const { maMutex.acquire(); }
            virtual void unlock() const { maMutex.release(); }

            virtual COMReference<IDirect3DSurface9>
                createSystemMemorySurface( const ::basegfx::B2IVector& rSize );
            virtual void disposing();
            virtual HWND getHWND() const { return mhWnd; }
            virtual void screenShot();

            virtual bool flip( const ::basegfx::B2IRectangle& rUpdateArea,
                               const ::basegfx::B2IRectangle& rCurrWindowArea );

            virtual void resize( const ::basegfx::B2IRange& rect );
            virtual ::basegfx::B2IVector getPageSize();
            virtual ::canvas::ISurfaceSharedPtr createSurface( const ::basegfx::B2IVector& surfaceSize );
            virtual void beginPrimitive( PrimitiveType eType );
            virtual void endPrimitive();
            virtual void pushVertex( const ::canvas::Vertex& vertex );
            virtual bool isError();

            COMReference<IDirect3DDevice9> getDevice() { return mpDevice; }

            void flushVertexCache();
            void commitVertexCache();

        private:

            bool create( const ::Window& rWindow );
            bool createDevice();
            bool verifyDevice( const UINT nAdapter );
            UINT getAdapterFromWindow();

            /** This object represents the DirectX state machine.  In order
                to serialize access to DirectX's global state, a global
                mutex is required.
            */
            static ::osl::Mutex                         maMutex;

            HWND                                        mhWnd;
            COMReference<IDirect3DDevice9>              mpDevice;
            COMReference<IDirect3D9>                    mpDirect3D9;
            COMReference<IDirect3DSwapChain9>           mpSwapChain;
            COMReference<IDirect3DVertexBuffer9>        mpVertexBuffer;
            ::canvas::ISurfaceSharedPtr                 mpTexture;
            ::boost::scoped_ptr<SystemChildWindow>      mpWindow;
            ::basegfx::B2IVector                        maSize;
            typedef std::vector<canvas::Vertex>         vertexCache_t;
            vertexCache_t                               maVertexCache;
            std::size_t                                 mnCount;
            int                                         mnBeginSceneCount;
            bool                                        mbCanUseDynamicTextures;
            bool                                        mbError;
            PrimitiveType                               meType;
            ::basegfx::B2IVector                        maPageSize;
            D3DPRESENT_PARAMETERS                       mad3dpp;

            inline bool isDisposed() const { return (mhWnd==NULL); }

            struct dxvertex
            {
                float x,y,z,rhw;
                DWORD diffuse;
                float u,v;
            };

            std::size_t                                 maNumVertices;
            std::size_t                                 maWriteIndex;
            std::size_t                                 maReadIndex;
        };

        ::osl::Mutex DXRenderModule::maMutex;

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::ImplRenderModuleGuard
        //////////////////////////////////////////////////////////////////////////////////

        inline DXSurface::ImplRenderModuleGuard::ImplRenderModuleGuard(
            DXRenderModule& rRenderModule ) :
            mrRenderModule( rRenderModule )
        {
            mrRenderModule.lock();
        }

        inline DXSurface::ImplRenderModuleGuard::~ImplRenderModuleGuard()
        {
            mrRenderModule.unlock();
        }

#ifdef FAKE_MAX_NUMBER_TEXTURES
        static sal_uInt32 gNumSurfaces = 0;
#endif

        void fillRect( sal_uInt32 *pDest,
                       sal_uInt32 dwWidth,
                       sal_uInt32 dwHeight,
                       sal_uInt32 dwPitch,
                       sal_uInt32 dwColor )
        {
            for(sal_uInt32 i=0; i<dwWidth; ++i)
            {
                pDest[i]=dwColor;
                pDest[((dwHeight-1)*dwPitch)+i]=dwColor;
            }

            for(sal_uInt32 j=0; j<dwHeight; ++j)
            {
                pDest[0]=dwColor;
                pDest[dwWidth-1]=dwColor;
                pDest += dwPitch;
            }
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::DXSurface
        //////////////////////////////////////////////////////////////////////////////////

        DXSurface::DXSurface( DXRenderModule&           rRenderModule,
                              const ::basegfx::B2ISize& rSize ) :
            mrRenderModule(rRenderModule),
            mpTexture(NULL),
            maSize()
        {
            ImplRenderModuleGuard aGuard( mrRenderModule );

#ifdef FAKE_MAX_NUMBER_TEXTURES
            ++gNumSurfaces;
            if(gNumSurfaces >= FAKE_MAX_NUMBER_TEXTURES)
                return;
#endif

#ifdef FAKE_MAX_TEXTURE_SIZE
            if(rSize.getX() > FAKE_MAX_TEXTURE_SIZE)
                return;
            if(rSize.getY() > FAKE_MAX_TEXTURE_SIZE)
                return;
#endif

            ENSURE_ARG_OR_THROW(rSize.getX() > 0 && rSize.getY() > 0,
                            "DXSurface::DXSurface(): request for zero-sized surface");

            COMReference<IDirect3DDevice9> pDevice(rRenderModule.getDevice());

            IDirect3DTexture9 *pTexture(NULL);
            if(FAILED(pDevice->CreateTexture(
                rSize.getX(),
                rSize.getY(),
                1,0,D3DFMT_A8R8G8B8,
                D3DPOOL_MANAGED,
                &pTexture,NULL)))
                return;

            mpTexture=COMReference<IDirect3DTexture9>(pTexture);
            maSize = rSize;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::~DXSurface
        //////////////////////////////////////////////////////////////////////////////////

        DXSurface::~DXSurface()
        {
            ImplRenderModuleGuard aGuard( mrRenderModule );

#ifdef FAKE_MAX_NUMBER_TEXTURES
            gNumSurfaces--;
#endif
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::selectTexture
        //////////////////////////////////////////////////////////////////////////////////

        bool DXSurface::selectTexture()
        {
            ImplRenderModuleGuard aGuard( mrRenderModule );
            mrRenderModule.flushVertexCache();
            COMReference<IDirect3DDevice9> pDevice(mrRenderModule.getDevice());

            if( FAILED(pDevice->SetTexture(0,mpTexture.get())) )
                return false;

            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::isValid
        //////////////////////////////////////////////////////////////////////////////////

        bool DXSurface::isValid()
        {
            ImplRenderModuleGuard aGuard( mrRenderModule );

            if(!(mpTexture.is()))
                return false;
            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::update
        //////////////////////////////////////////////////////////////////////////////////

        bool DXSurface::update( const ::basegfx::B2IPoint& rDestPos,
                                const ::basegfx::B2IRange& rSourceRect,
                                ::canvas::IColorBuffer&    rSource )
        {
            ImplRenderModuleGuard aGuard( mrRenderModule );

            // can't update if surface is not valid, that means
            // either not existent nor restored...
            if(!(isValid()))
                return false;

            D3DLOCKED_RECT aLockedRect;
            RECT rect;
            rect.left = std::max(sal_Int32(0),rDestPos.getX());
            rect.top =  std::max(sal_Int32(0),rDestPos.getY());
            // to avoid interpolation artifacts from other textures,
            // the surface manager allocates one pixel gap between
            // them. Clear that to transparent.
            rect.right = std::min(maSize.getX(),
                                  rect.left + sal_Int32(rSourceRect.getWidth()+1));
            rect.bottom = std::min(maSize.getY(),
                                   rect.top + sal_Int32(rSourceRect.getHeight()+1));
            const bool bClearRightColumn( rect.right < maSize.getX() );
            const bool bClearBottomRow( rect.bottom < maSize.getY() );

            if(SUCCEEDED(mpTexture->LockRect(0,&aLockedRect,&rect,D3DLOCK_NOSYSLOCK)))
            {
                if(sal_uInt8* pImage = rSource.lock())
                {
                    switch( rSource.getFormat() )
                    {
                        case ::canvas::IColorBuffer::FMT_A8R8G8B8:
                        {
                            const std::size_t nSourceBytesPerPixel(4);
                            const std::size_t nSourcePitchInBytes(rSource.getStride());
                            pImage += rSourceRect.getMinY()*nSourcePitchInBytes;
                            pImage += rSourceRect.getMinX()*nSourceBytesPerPixel;

                            // calculate the destination memory address
                            sal_uInt8 *pDst = (sal_uInt8*)aLockedRect.pBits;

                            const sal_uInt32 nNumBytesToCopy(
                                static_cast<sal_uInt32>(
                                    rSourceRect.getWidth())*
                                nSourceBytesPerPixel);
                            const sal_uInt64 nNumLines(rSourceRect.getHeight());

                            for(sal_uInt32 i=0; i<nNumLines; ++i)
                            {
                                rtl_copyMemory(pDst,pImage,nNumBytesToCopy);

                                if( bClearRightColumn )
                                {
                                    // to avoid interpolation artifacts
                                    // from other textures, the surface
                                    // manager allocates one pixel gap
                                    // between them. Clear that to
                                    // transparent.
                                    pDst[nNumBytesToCopy] =
                                        pDst[nNumBytesToCopy+1] =
                                        pDst[nNumBytesToCopy+2] =
                                        pDst[nNumBytesToCopy+3] = 0x00;
                                }
                                pDst += aLockedRect.Pitch;
                                pImage += nSourcePitchInBytes;
                            }

                            if( bClearBottomRow )
                                rtl_zeroMemory(pDst,nNumBytesToCopy+4);
                        }
                        break;

                        case ::canvas::IColorBuffer::FMT_R8G8B8:
                        {
                            const std::size_t nSourceBytesPerPixel(3);
                            const std::size_t nSourcePitchInBytes(rSource.getStride());
                            pImage += rSourceRect.getMinY()*nSourcePitchInBytes;
                            pImage += rSourceRect.getMinX()*nSourceBytesPerPixel;

                            // calculate the destination memory address
                            sal_uInt8 *pDst = (sal_uInt8*)aLockedRect.pBits;

                            const sal_Int32 nNumColumns(
                                sal::static_int_cast<sal_Int32>(rSourceRect.getWidth()));
                            const sal_Int32 nNumLines(
                                sal::static_int_cast<sal_Int32>(rSourceRect.getHeight()));
                            for(sal_Int32 i=0; i<nNumLines; ++i)
                            {
                                sal_uInt32 *pDstScanline = reinterpret_cast<sal_uInt32 *>(pDst);
                                sal_uInt8 *pSrcScanline = reinterpret_cast<sal_uInt8 *>(pImage);

                                for(sal_Int32 x=0; x<nNumColumns; ++x)
                                {
                                    sal_uInt32 color(0xFF000000);
                                    color |= pSrcScanline[2]<<16;
                                    color |= pSrcScanline[1]<<8;
                                    color |= pSrcScanline[0];
                                    pSrcScanline += 3;
                                    *pDstScanline++ = color;
                                }
                                if( bClearRightColumn )
                                    *pDstScanline++ = 0xFF000000;

                                pDst += aLockedRect.Pitch;
                                pImage += nSourcePitchInBytes;
                            }

                            if( bClearBottomRow )
                                rtl_zeroMemory(pDst,4*(nNumColumns+1));
                        }
                        break;

                        case ::canvas::IColorBuffer::FMT_X8R8G8B8:
                        {
                            const std::size_t nSourceBytesPerPixel(4);
                            const std::size_t nSourcePitchInBytes(rSource.getStride());
                            pImage += rSourceRect.getMinY()*nSourcePitchInBytes;
                            pImage += rSourceRect.getMinX()*nSourceBytesPerPixel;

                            // calculate the destination memory address
                            sal_uInt8 *pDst = (sal_uInt8*)aLockedRect.pBits;

                            const sal_Int32 nNumLines(
                                sal::static_int_cast<sal_Int32>(rSourceRect.getHeight()));
                            const sal_Int32 nNumColumns(
                                sal::static_int_cast<sal_Int32>(rSourceRect.getWidth()));
                            for(sal_Int32 i=0; i<nNumLines; ++i)
                            {
                                sal_uInt32 *pSrc32 = reinterpret_cast<sal_uInt32 *>(pImage);
                                sal_uInt32 *pDst32 = reinterpret_cast<sal_uInt32 *>(pDst);
                                for(sal_Int32 j=0; j<nNumColumns; ++j)
                                    pDst32[j] = 0xFF000000 | pSrc32[j];

                                if( bClearRightColumn )
                                    pDst32[nNumColumns] = 0xFF000000;

                                pDst += aLockedRect.Pitch;
                                pImage += nSourcePitchInBytes;
                            }

                            if( bClearBottomRow )
                                rtl_zeroMemory(pDst,4*(nNumColumns+1));
                        }
                        break;

                        default:
                            ENSURE_OR_RETURN_FALSE(false,
                                            "DXSurface::update(): Unknown/unimplemented buffer format" );
                            break;
                    }

                    rSource.unlock();
                }

                return SUCCEEDED(mpTexture->UnlockRect(0));
            }

            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXSurface::getSize
        //////////////////////////////////////////////////////////////////////////////////

        ::basegfx::B2IVector DXSurface::getSize()
        {
            return maSize;
        }

        COMReference<IDirect3DTexture9> DXSurface::getTexture() const
        {
            return mpTexture;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::DXRenderModule
        //////////////////////////////////////////////////////////////////////////////////

        DXRenderModule::DXRenderModule( const ::Window& rWindow ) :
            mhWnd(0),
            mpDevice(),
            mpDirect3D9(),
            mpSwapChain(),
            mpVertexBuffer(),
            mpTexture(),
            maSize(),
            maVertexCache(),
            mnCount(0),
            mnBeginSceneCount(0),
            mbCanUseDynamicTextures(false),
            mbError( false ),
            meType( PRIMITIVE_TYPE_UNKNOWN ),
            maPageSize(),
            mad3dpp(),
            maNumVertices( VERTEX_BUFFER_SIZE ),
            maWriteIndex(0),
            maReadIndex(0)
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(!(create(rWindow)))
            {
                throw lang::NoSupportException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                         "Could not create DirectX device!") ),NULL);
            }

            // allocate a single texture surface which can be used later.
            // we also use this to calibrate the page size.
            ::basegfx::B2IVector aPageSize(maPageSize);
            while(true)
            {
                mpTexture = ::canvas::ISurfaceSharedPtr(
                    new DXSurface(*this,aPageSize));
                if(mpTexture->isValid())
                    break;

                aPageSize.setX(aPageSize.getX()>>1);
                aPageSize.setY(aPageSize.getY()>>1);
                if((aPageSize.getX() < MIN_TEXTURE_SIZE) ||
                   (aPageSize.getY() < MIN_TEXTURE_SIZE))
                {
                    throw lang::NoSupportException(
                        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                            "Could not create DirectX device - "
                                            "insufficient texture space!") ),NULL);
                }
            }
            maPageSize=aPageSize;

            IDirect3DVertexBuffer9 *pVB(NULL);
            DWORD aFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1);
            if( FAILED(mpDevice->CreateVertexBuffer(sizeof(dxvertex)*maNumVertices,
                                                    D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
                                                    aFVF,
                                                    D3DPOOL_DEFAULT,
                                                    &pVB,
                                                    NULL)) )
            {
                throw lang::NoSupportException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                         "Could not create DirectX device - out of memory!")),NULL);
            }

            mpVertexBuffer=COMReference<IDirect3DVertexBuffer9>(pVB);
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::~DXRenderModule
        //////////////////////////////////////////////////////////////////////////////////

        DXRenderModule::~DXRenderModule()
        {
            disposing();
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::disposing
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::disposing()
        {
            if(!(mhWnd))
                return;

            mpTexture.reset();
            mpWindow.reset();
            mhWnd=NULL;

            // refrain from releasing the DX9 objects. We're the only
            // ones holding references to them, and it might be
            // dangerous to destroy the DX9 device, before all other
            // objects are dead.
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::create
        //////////////////////////////////////////////////////////////////////////////////

        bool DXRenderModule::create( const ::Window& rWindow )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            maVertexCache.reserve(1024);

            mpWindow.reset(
                new SystemChildWindow(
                const_cast<Window *>(&rWindow), 0) );

            // system child window must not receive mouse events
            mpWindow->SetMouseTransparent( TRUE );

            // parent should receive paint messages as well
            // [PARENTCLIPMODE_NOCLIP], the argument is here
            // passed as plain numeric value since the stupid
            // define utilizes a USHORT cast.
            mpWindow->SetParentClipMode(0x0002);

            // the system child window must not clear its background
            mpWindow->EnableEraseBackground( sal_False );

            mpWindow->SetControlForeground();
            mpWindow->SetControlBackground();
            mpWindow->EnablePaint(sal_False);

            const SystemEnvData *pData = mpWindow->GetSystemData();
            const HWND hwnd(reinterpret_cast<HWND>(pData->hWnd));
            mhWnd = const_cast<HWND>(hwnd);

            ENSURE_OR_THROW( IsWindow( reinterpret_cast<HWND>(mhWnd) ),
                            "DXRenderModule::create() No valid HWND given." );

            // retrieve position and size of the parent window
            const ::Size &rSizePixel(rWindow.GetSizePixel());

            // remember the size of the parent window, since we
            // need to use this for our child window.
            maSize.setX(static_cast<sal_Int32>(rSizePixel.Width()));
            maSize.setY(static_cast<sal_Int32>(rSizePixel.Height()));

            // let the child window cover the same size as the parent window.
            mpWindow->setPosSizePixel(0,0,maSize.getX(),maSize.getY());

            // TODO(F2): since we would like to share precious hardware
            // resources, the direct3d9 object should be global. each new
            // request for a canvas should only create a new swapchain.
            mpDirect3D9 = COMReference<IDirect3D9>(
                Direct3DCreate9(D3D_SDK_VERSION));
            if(!mpDirect3D9.is())
                return false;

            // create a device from the direct3d9 object.
            if(!(createDevice()))
                return false;

            mpWindow->Show();

            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::verifyDevice
        //////////////////////////////////////////////////////////////////////////////////

        bool DXRenderModule::verifyDevice( const UINT nAdapter )
        {
            ENSURE_OR_THROW( mpDirect3D9.is(),
                              "DXRenderModule::verifyDevice() No valid device." );

            // ask direct3d9 about the capabilities of hardware devices on a specific adapter.
            // here we decide if the underlying hardware of the machine 'is good enough'.
            // since we only need a tiny little fraction of what could be used, this
            // is basically a no-op.
            D3DCAPS9 aCaps;
            if(FAILED(mpDirect3D9->GetDeviceCaps(nAdapter,D3DDEVTYPE_HAL,&aCaps)))
                return false;
            if(!(aCaps.MaxTextureWidth))
                return false;
            if(!(aCaps.MaxTextureHeight))
                return false;
            maPageSize = ::basegfx::B2IVector(aCaps.MaxTextureWidth,aCaps.MaxTextureHeight);

            // check device against white & blacklist entries
            D3DADAPTER_IDENTIFIER9 aIdent;
            if(FAILED(mpDirect3D9->GetAdapterIdentifier(nAdapter,0,&aIdent)))
                return false;

            DXCanvasItem aConfigItem;
            DXCanvasItem::DeviceInfo aInfo;
            aInfo.nVendorId = aIdent.VendorId;
            aInfo.nDeviceId = aIdent.DeviceId;
            aInfo.nDeviceSubSysId = aIdent.SubSysId;
            aInfo.nDeviceRevision = aIdent.Revision;

            aInfo.nDriverId = HIWORD(aIdent.DriverVersion.HighPart);
            aInfo.nDriverVersion = LOWORD(aIdent.DriverVersion.HighPart);
            aInfo.nDriverSubVersion = HIWORD(aIdent.DriverVersion.LowPart);
            aInfo.nDriverBuildId = LOWORD(aIdent.DriverVersion.LowPart);

            if( !aConfigItem.isDeviceUsable(aInfo) )
                return false;

            if( aConfigItem.isBlacklistCurrentDevice() )
            {
                aConfigItem.blacklistDevice(aInfo);
                return false;
            }

            aConfigItem.adaptMaxTextureSize(maPageSize);

            mbCanUseDynamicTextures = (aCaps.Caps2 & D3DCAPS2_DYNAMICTEXTURES) != 0;

            return true;
        }


        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::createDevice
        //////////////////////////////////////////////////////////////////////////////////

        bool DXRenderModule::createDevice()
        {
            // we expect that the caller provides us with a valid HWND
            ENSURE_OR_THROW( IsWindow(mhWnd),
                              "DXRenderModule::createDevice() No valid HWND given." );

            // we expect that the caller already created the direct3d9 object.
            ENSURE_OR_THROW( mpDirect3D9.is(),
                              "DXRenderModule::createDevice() no direct3d?." );

            // find the adapter identifier from the window.
            const UINT aAdapter(getAdapterFromWindow());
            if(aAdapter == static_cast<UINT>(-1))
                return false;

            // verify that device possibly works
            if( !verifyDevice(aAdapter) )
                return false;

            // query the display mode from the selected adapter.
            // we'll later request the backbuffer format to be same
            // same as the display format.
            D3DDISPLAYMODE d3ddm;
            mpDirect3D9->GetAdapterDisplayMode(aAdapter,&d3ddm);

            // we need to use D3DSWAPEFFECT_COPY here since the canvas-api has
            // basically nothing to do with efficient resource handling. it tries
            // to avoid drawing whenevery possible, which is simply not the most
            // efficient way we could leverage the hardware in this case. it would
            // be far better to redraw the backbuffer each time we would like to
            // display the content of the backbuffer, but we need to face reality
            // here and follow how the canvas was designed.

            // Strictly speaking, we don't need a full screen worth of
            // backbuffer here. We could also scale dynamically with
            // the current window size, but this will make it
            // necessary to temporarily have two buffers while copying
            // from the old to the new one. What's more, at the time
            // we need a larger buffer, DX might not have sufficient
            // resources available, and we're then left with too small
            // a back buffer, and no way of falling back to a
            // different canvas implementation.
            ZeroMemory( &mad3dpp, sizeof(mad3dpp) );
            mad3dpp.BackBufferWidth = std::max(sal_Int32(maSize.getX()),
                                               sal_Int32(d3ddm.Width));
            mad3dpp.BackBufferHeight = std::max(sal_Int32(maSize.getY()),
                                                sal_Int32(d3ddm.Height));
            mad3dpp.BackBufferCount = 1;
            mad3dpp.Windowed = TRUE;
            mad3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
            mad3dpp.BackBufferFormat = d3ddm.Format;
            mad3dpp.EnableAutoDepthStencil = FALSE;
            mad3dpp.hDeviceWindow = mhWnd;
            mad3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

            // now create the device, first try hardware vertex processing,
            // then software vertex processing. if both queries fail, we give up
            // and indicate failure.
            IDirect3DDevice9 *pDevice(NULL);
            if(FAILED(mpDirect3D9->CreateDevice(aAdapter,
                                                D3DDEVTYPE_HAL,
                                                mhWnd,
                                                D3DCREATE_HARDWARE_VERTEXPROCESSING|
                                                D3DCREATE_MULTITHREADED|D3DCREATE_FPU_PRESERVE,
                                                &mad3dpp,
                                                &pDevice)))
                if(FAILED(mpDirect3D9->CreateDevice(aAdapter,
                                                    D3DDEVTYPE_HAL,
                                                    mhWnd,
                                                    D3DCREATE_SOFTWARE_VERTEXPROCESSING|
                                                    D3DCREATE_MULTITHREADED|D3DCREATE_FPU_PRESERVE,
                                                    &mad3dpp,
                                                    &pDevice)))
                    return false;

            // got it, store it in a safe place...
            mpDevice=COMReference<IDirect3DDevice9>(pDevice);

            // After CreateDevice, the first swap chain already exists, so just get it...
            IDirect3DSwapChain9 *pSwapChain(NULL);
            pDevice->GetSwapChain(0,&pSwapChain);
            mpSwapChain=COMReference<IDirect3DSwapChain9>(pSwapChain);
            if( !mpSwapChain.is() )
                return false;

            // clear the render target [which is the backbuffer in this case].
            // we are forced to do this once, and furthermore right now.
            // please note that this is only possible since we created the
            // backbuffer with copy semantics [the content is preserved after
            // calls to Present()], which is an unnecessarily expensive operation.
            LPDIRECT3DSURFACE9 pBackBuffer = NULL;
            mpSwapChain->GetBackBuffer(0,D3DBACKBUFFER_TYPE_MONO,&pBackBuffer);
            mpDevice->SetRenderTarget( 0, pBackBuffer );
            mpDevice->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0L);
            pBackBuffer->Release();

            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::createSystemMemorySurface
        //////////////////////////////////////////////////////////////////////////////////

        COMReference<IDirect3DSurface9> DXRenderModule::createSystemMemorySurface( const ::basegfx::B2IVector& rSize )
        {
            if(isDisposed())
                return COMReference<IDirect3DSurface9>(NULL);

            // please note that D3DFMT_X8R8G8B8 is the only format we're
            // able to choose here, since GetDC() doesn't support any
            // other 32bit-format.
            IDirect3DSurface9 *pSurface(NULL);
            if( FAILED(mpDevice->CreateOffscreenPlainSurface(
                           rSize.getX(),
                           rSize.getY(),
                           D3DFMT_X8R8G8B8,
                           D3DPOOL_SYSTEMMEM,
                           &pSurface,
                           NULL)) )
            {
                throw lang::NoSupportException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                         "Could not create offscreen surface - out of mem!") ),NULL);
            }

            return COMReference<IDirect3DSurface9>(pSurface);
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::flip
        //////////////////////////////////////////////////////////////////////////////////

        bool DXRenderModule::flip( const ::basegfx::B2IRectangle& rUpdateArea,
                                   const ::basegfx::B2IRectangle& /*rCurrWindowArea*/ )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed() || !mpSwapChain.is())
                return false;

            flushVertexCache();

            // TODO(P2): Might be faster to actually pass update area here
            RECT aRect =
                {
                    rUpdateArea.getMinX(),
                    rUpdateArea.getMinY(),
                    rUpdateArea.getMaxX(),
                    rUpdateArea.getMaxY()
                };
            HRESULT hr(mpSwapChain->Present(&aRect,&aRect,NULL,NULL,0));
            if(FAILED(hr))
            {
                if(hr != D3DERR_DEVICELOST)
                    return false;

                // interestingly enough, sometimes the Reset() below
                // *still* causes DeviceLost errors. So, cycle until
                // DX was kind enough to really reset the device...
                do
                {
                    mpVertexBuffer.reset();
                    hr = mpDevice->Reset(&mad3dpp);
                    if(SUCCEEDED(hr))
                    {
                        IDirect3DVertexBuffer9 *pVB(NULL);
                        DWORD aFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1);
                        if( FAILED(mpDevice->CreateVertexBuffer(sizeof(dxvertex)*maNumVertices,
                                                                D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,
                                                                aFVF,
                                                                D3DPOOL_DEFAULT,
                                                                &pVB,
                                                                NULL)) )
                        {
                            throw lang::NoSupportException(
                                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                                     "Could not create DirectX device - out of memory!")),NULL);
                        }
                        mpVertexBuffer=COMReference<IDirect3DVertexBuffer9>(pVB);

                        // retry after the restore
                        if(SUCCEEDED(mpSwapChain->Present(&aRect,&aRect,NULL,NULL,0)))
                            return true;
                    }

                    TimeValue aTimeout;
                    aTimeout.Seconds=1;
                    aTimeout.Nanosec=0;
                    osl_waitThread(&aTimeout);
                }
                while(hr == D3DERR_DEVICELOST);

                return false;
            }

            return true;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::screenShot
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::screenShot()
        {
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::resize
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::resize( const ::basegfx::B2IRange& rect )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed())
                return;

            // don't do anything if the size didn't change.
            if(maSize.getX() == static_cast<sal_Int32>(rect.getWidth()) &&
               maSize.getY() == static_cast<sal_Int32>(rect.getHeight()))
               return;

            // TODO(Q2): use numeric cast to prevent overflow
            maSize.setX(static_cast<sal_Int32>(rect.getWidth()));
            maSize.setY(static_cast<sal_Int32>(rect.getHeight()));

            mpWindow->setPosSizePixel(0,0,maSize.getX(),maSize.getY());

            // resize back buffer, if necessary
            // -------------------------------------------------------------

            // don't attempt to create anything if the
            // requested size is NULL.
            if(!(maSize.getX()))
                return;
            if(!(maSize.getY()))
                return;

            // backbuffer too small (might happen, if window is
            // maximized across multiple monitors)
            if( sal_Int32(mad3dpp.BackBufferWidth) < maSize.getX() ||
                sal_Int32(mad3dpp.BackBufferHeight) < maSize.getY() )
            {
                mad3dpp.BackBufferWidth = maSize.getX();
                mad3dpp.BackBufferHeight = maSize.getY();

                // clear before, save resources
                mpSwapChain.reset();

                IDirect3DSwapChain9 *pSwapChain(NULL);
                if(FAILED(mpDevice->CreateAdditionalSwapChain(&mad3dpp,&pSwapChain)))
                    return;
                mpSwapChain=COMReference<IDirect3DSwapChain9>(pSwapChain);

                // clear the render target [which is the backbuffer in this case].
                // we are forced to do this once, and furthermore right now.
                // please note that this is only possible since we created the
                // backbuffer with copy semantics [the content is preserved after
                // calls to Present()], which is an unnecessarily expensive operation.
                LPDIRECT3DSURFACE9 pBackBuffer = NULL;
                mpSwapChain->GetBackBuffer(0,D3DBACKBUFFER_TYPE_MONO,&pBackBuffer);
                mpDevice->SetRenderTarget( 0, pBackBuffer );
                mpDevice->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0L);
                pBackBuffer->Release();
            }
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::getPageSize
        //////////////////////////////////////////////////////////////////////////////////

        ::basegfx::B2IVector DXRenderModule::getPageSize()
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );
            return maPageSize;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::createSurface
        //////////////////////////////////////////////////////////////////////////////////

        ::canvas::ISurfaceSharedPtr DXRenderModule::createSurface( const ::basegfx::B2IVector& surfaceSize )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed())
                return ::canvas::ISurfaceSharedPtr();

            const ::basegfx::B2IVector& rPageSize( getPageSize() );
            ::basegfx::B2ISize aSize(surfaceSize);
            if(!(aSize.getX()))
                aSize.setX(rPageSize.getX());
            if(!(aSize.getY()))
                aSize.setY(rPageSize.getY());

            if(mpTexture.use_count() == 1)
                return mpTexture;

            return ::canvas::ISurfaceSharedPtr( new DXSurface(*this,aSize) );
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::beginPrimitive
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::beginPrimitive( PrimitiveType eType )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed())
                return;

            ENSURE_OR_THROW( !mnBeginSceneCount,
                              "DXRenderModule::beginPrimitive(): nested call" );

            ++mnBeginSceneCount;
            meType=eType;
            mnCount=0;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::endPrimitive
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::endPrimitive()
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed())
                return;

            --mnBeginSceneCount;
            meType=PRIMITIVE_TYPE_UNKNOWN;
            mnCount=0;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::pushVertex
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::pushVertex( const ::canvas::Vertex& vertex )
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            if(isDisposed())
                return;

            switch(meType)
            {
                case PRIMITIVE_TYPE_TRIANGLE:
                {
                    maVertexCache.push_back(vertex);
                    ++mnCount;
                    mnCount &= 3;
                    break;
                }

                case PRIMITIVE_TYPE_QUAD:
                {
                    if(mnCount == 3)
                    {
                        const std::size_t size(maVertexCache.size());
                        ::canvas::Vertex v0(maVertexCache[size-1]);
                        ::canvas::Vertex v2(maVertexCache[size-3]);
                        maVertexCache.push_back(v0);
                        maVertexCache.push_back(vertex);
                        maVertexCache.push_back(v2);
                        mnCount=0;
                    }
                    else
                    {
                        maVertexCache.push_back(vertex);
                        ++mnCount;
                    }
                    break;
                }

                default:
                    OSL_FAIL("DXRenderModule::pushVertex(): unexpected primitive type");
                    break;
            }
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::isError
        //////////////////////////////////////////////////////////////////////////////////

        bool DXRenderModule::isError()
        {
            // TODO(P2): get rid of those fine-grained locking
            ::osl::MutexGuard aGuard( maMutex );

            return mbError;
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::getAdapterFromWindow
        //////////////////////////////////////////////////////////////////////////////////

        UINT DXRenderModule::getAdapterFromWindow()
        {
            HMONITOR hMonitor(aMonitorSupport.MonitorFromWindow(mhWnd));
            UINT aAdapterCount(mpDirect3D9->GetAdapterCount());
            for(UINT i=0; i<aAdapterCount; ++i)
                if(hMonitor == mpDirect3D9->GetAdapterMonitor(i))
                    return i;
            return static_cast<UINT>(-1);
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::commitVertexCache
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::commitVertexCache()
        {
            if(maReadIndex != maWriteIndex)
            {
                const std::size_t nVertexStride = sizeof(dxvertex);
                const unsigned int nNumVertices = maWriteIndex-maReadIndex;
                const unsigned int nNumPrimitives = nNumVertices / 3;

                if(FAILED(mpDevice->SetStreamSource(0,mpVertexBuffer.get(),0,nVertexStride)))
                    return;

                if(FAILED(mpDevice->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)))
                    return;

                if(FAILED(mpDevice->BeginScene()))
                    return;

                mbError |= FAILED(mpDevice->DrawPrimitive(D3DPT_TRIANGLELIST,maReadIndex,nNumPrimitives));
                mbError |= FAILED(mpDevice->EndScene());

                maReadIndex += nNumVertices;
            }
        }

        //////////////////////////////////////////////////////////////////////////////////
        // DXRenderModule::flushVertexCache
        //////////////////////////////////////////////////////////////////////////////////

        void DXRenderModule::flushVertexCache()
        {
            if(!(maVertexCache.size()))
                return;

            mbError=true;

            if( FAILED(mpDevice->SetRenderState(D3DRS_LIGHTING,FALSE)))
                return;

            // enable texture alpha blending
            if( FAILED(mpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE)))
                return;

            mpDevice->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_LINEAR);
            mpDevice->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_LINEAR);
            mpDevice->SetSamplerState(0,D3DSAMP_ADDRESSU ,D3DTADDRESS_CLAMP );
            mpDevice->SetSamplerState(0,D3DSAMP_ADDRESSV ,D3DTADDRESS_CLAMP );

            // configure the fixed-function pipeline.
            // the only 'feature' we need here is to modulate the alpha-channels
            // from the texture and the interpolated diffuse color. the result
            // will then be blended with the backbuffer.
            // fragment color = texture color * diffuse.alpha.
            mpDevice->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_MODULATE);
            mpDevice->SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE);
            mpDevice->SetTextureStageState(0,D3DTSS_ALPHAARG2,D3DTA_DIFFUSE);

            // normal combination of object...
            if( FAILED(mpDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA)) )
                return;

            // ..and background color
            if( FAILED(mpDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA)) )
                return;

            // disable backface culling; this enables us to mirror sprites
            // by simply reverting the triangles, which, with enabled
            // culling, would be invisible otherwise
            if( FAILED(mpDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE)) )
                return;

            mbError=false;

            std::size_t nSize(maVertexCache.size());
            const std::size_t nVertexStride = sizeof(dxvertex);

            const ::basegfx::B2IVector aPageSize(getPageSize());
            const float nHalfPixelSizeX(0.5f/aPageSize.getX());
            const float nHalfPixelSizeY(0.5f/aPageSize.getY());
            vertexCache_t::const_iterator it(maVertexCache.begin());

            while( nSize )
            {
                DWORD dwLockFlags(D3DLOCK_NOOVERWRITE);

                // Check to see if there's space for the current set of
                // vertices in the buffer.
                if( maNumVertices - maWriteIndex < nSize )
                {
                    commitVertexCache();
                    dwLockFlags = D3DLOCK_DISCARD;
                    maWriteIndex = 0;
                    maReadIndex = 0;
                }

                dxvertex *vertices(NULL);
                const std::size_t nNumVertices(
                    std::min(maNumVertices - maWriteIndex,
                             nSize));
                if(FAILED(mpVertexBuffer->Lock(maWriteIndex*nVertexStride,
                                               nNumVertices*nVertexStride,
                                               (void **)&vertices,
                                               dwLockFlags)))
                    return;

                std::size_t nIndex(0);
                while( nIndex < nNumVertices )
                {
                    dxvertex &dest = vertices[nIndex++];
                    dest.x=it->x;
                    dest.y=it->y;
                    dest.z=it->z;
                    dest.rhw=1;
                    const sal_uInt32 alpha(static_cast<sal_uInt32>(it->a*255.0f));
                    dest.diffuse=D3DCOLOR_ARGB(alpha,255,255,255);
                    dest.u=static_cast<float>(it->u + nHalfPixelSizeX);
                    dest.v=static_cast<float>(it->v + nHalfPixelSizeY);
                    ++it;
                }

                mpVertexBuffer->Unlock();

                // Advance to the next position in the vertex buffer.
                maWriteIndex += nNumVertices;
                nSize -= nNumVertices;

                commitVertexCache();
            }

            maVertexCache.clear();
        }
    }

    //////////////////////////////////////////////////////////////////////////////////
    // createRenderModule
    //////////////////////////////////////////////////////////////////////////////////

    IDXRenderModuleSharedPtr createRenderModule( const ::Window& rParent )
    {
        return IDXRenderModuleSharedPtr( new DXRenderModule(rParent) );
    }
}

#endif

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