- Implement CCM_{GET|SET}COLORSCHEME.
[wine] / objects / region.c
1 /*
2  * GDI region objects. Shamelessly ripped out from the X11 distribution
3  * Thanks for the nice licence.
4  *
5  * Copyright 1993, 1994, 1995 Alexandre Julliard
6  * Modifications and additions: Copyright 1998 Huw Davies
7  *                                        1999 Alex Korobka
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 /************************************************************************
25
26 Copyright (c) 1987, 1988  X Consortium
27
28 Permission is hereby granted, free of charge, to any person obtaining a copy
29 of this software and associated documentation files (the "Software"), to deal
30 in the Software without restriction, including without limitation the rights
31 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32 copies of the Software, and to permit persons to whom the Software is
33 furnished to do so, subject to the following conditions:
34
35 The above copyright notice and this permission notice shall be included in
36 all copies or substantial portions of the Software.
37
38 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
41 X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
42 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
43 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
44
45 Except as contained in this notice, the name of the X Consortium shall not be
46 used in advertising or otherwise to promote the sale, use or other dealings
47 in this Software without prior written authorization from the X Consortium.
48
49
50 Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
51
52                         All Rights Reserved
53
54 Permission to use, copy, modify, and distribute this software and its 
55 documentation for any purpose and without fee is hereby granted, 
56 provided that the above copyright notice appear in all copies and that
57 both that copyright notice and this permission notice appear in 
58 supporting documentation, and that the name of Digital not be
59 used in advertising or publicity pertaining to distribution of the
60 software without specific, written prior permission.  
61
62 DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
63 ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
64 DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
65 ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
66 WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
67 ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
68 SOFTWARE.
69
70 ************************************************************************/
71 /*
72  * The functions in this file implement the Region abstraction, similar to one
73  * used in the X11 sample server. A Region is simply an area, as the name
74  * implies, and is implemented as a "y-x-banded" array of rectangles. To
75  * explain: Each Region is made up of a certain number of rectangles sorted
76  * by y coordinate first, and then by x coordinate.
77  *
78  * Furthermore, the rectangles are banded such that every rectangle with a
79  * given upper-left y coordinate (y1) will have the same lower-right y
80  * coordinate (y2) and vice versa. If a rectangle has scanlines in a band, it
81  * will span the entire vertical distance of the band. This means that some
82  * areas that could be merged into a taller rectangle will be represented as
83  * several shorter rectangles to account for shorter rectangles to its left
84  * or right but within its "vertical scope".
85  *
86  * An added constraint on the rectangles is that they must cover as much
87  * horizontal area as possible. E.g. no two rectangles in a band are allowed
88  * to touch.
89  *
90  * Whenever possible, bands will be merged together to cover a greater vertical
91  * distance (and thus reduce the number of rectangles). Two bands can be merged
92  * only if the bottom of one touches the top of the other and they have
93  * rectangles in the same places (of the same width, of course). This maintains
94  * the y-x-banding that's so nice to have...
95  */
96
97 #include <stdlib.h>
98 #include <string.h>
99 #include "windef.h"
100 #include "wingdi.h"
101 #include "wine/debug.h"
102 #include "region.h"
103 #include "gdi.h"
104
105 WINE_DEFAULT_DEBUG_CHANNEL(region);
106
107 /*  1 if two RECTs overlap.
108  *  0 if two RECTs do not overlap.
109  */
110 #define EXTENTCHECK(r1, r2) \
111         ((r1)->right > (r2)->left && \
112          (r1)->left < (r2)->right && \
113          (r1)->bottom > (r2)->top && \
114          (r1)->top < (r2)->bottom)
115
116 /*
117  *   Check to see if there is enough memory in the present region.
118  */
119
120 static inline int xmemcheck(WINEREGION *reg, LPRECT *rect, LPRECT *firstrect ) {
121     if (reg->numRects >= (reg->size - 1)) {
122         *firstrect = HeapReAlloc( GetProcessHeap(), 0, *firstrect, (2 * (sizeof(RECT)) * (reg->size)));
123         if (*firstrect == 0)
124             return 0;
125         reg->size *= 2;
126         *rect = (*firstrect)+reg->numRects;
127     }
128     return 1;
129 }
130
131 #define MEMCHECK(reg, rect, firstrect) xmemcheck(reg,&(rect),&(firstrect))
132
133 #define EMPTY_REGION(pReg) { \
134     (pReg)->numRects = 0; \
135     (pReg)->extents.left = (pReg)->extents.top = 0; \
136     (pReg)->extents.right = (pReg)->extents.bottom = 0; \
137     (pReg)->type = NULLREGION; \
138  }
139
140 #define REGION_NOT_EMPTY(pReg) pReg->numRects
141
142 #define INRECT(r, x, y) \
143       ( ( ((r).right >  x)) && \
144         ( ((r).left <= x)) && \
145         ( ((r).bottom >  y)) && \
146         ( ((r).top <= y)) )
147
148
149 /*
150  * number of points to buffer before sending them off
151  * to scanlines() :  Must be an even number
152  */
153 #define NUMPTSTOBUFFER 200
154
155 /*
156  * used to allocate buffers for points and link
157  * the buffers together
158  */
159
160 typedef struct _POINTBLOCK {
161     POINT pts[NUMPTSTOBUFFER];
162     struct _POINTBLOCK *next;
163 } POINTBLOCK;
164
165
166
167 /*
168  *     This file contains a few macros to help track
169  *     the edge of a filled object.  The object is assumed
170  *     to be filled in scanline order, and thus the
171  *     algorithm used is an extension of Bresenham's line
172  *     drawing algorithm which assumes that y is always the
173  *     major axis.
174  *     Since these pieces of code are the same for any filled shape,
175  *     it is more convenient to gather the library in one
176  *     place, but since these pieces of code are also in
177  *     the inner loops of output primitives, procedure call
178  *     overhead is out of the question.
179  *     See the author for a derivation if needed.
180  */
181
182
183 /*
184  *  In scan converting polygons, we want to choose those pixels
185  *  which are inside the polygon.  Thus, we add .5 to the starting
186  *  x coordinate for both left and right edges.  Now we choose the
187  *  first pixel which is inside the pgon for the left edge and the
188  *  first pixel which is outside the pgon for the right edge.
189  *  Draw the left pixel, but not the right.
190  *
191  *  How to add .5 to the starting x coordinate:
192  *      If the edge is moving to the right, then subtract dy from the
193  *  error term from the general form of the algorithm.
194  *      If the edge is moving to the left, then add dy to the error term.
195  *
196  *  The reason for the difference between edges moving to the left
197  *  and edges moving to the right is simple:  If an edge is moving
198  *  to the right, then we want the algorithm to flip immediately.
199  *  If it is moving to the left, then we don't want it to flip until
200  *  we traverse an entire pixel.
201  */
202 #define BRESINITPGON(dy, x1, x2, xStart, d, m, m1, incr1, incr2) { \
203     int dx;      /* local storage */ \
204 \
205     /* \
206      *  if the edge is horizontal, then it is ignored \
207      *  and assumed not to be processed.  Otherwise, do this stuff. \
208      */ \
209     if ((dy) != 0) { \
210         xStart = (x1); \
211         dx = (x2) - xStart; \
212         if (dx < 0) { \
213             m = dx / (dy); \
214             m1 = m - 1; \
215             incr1 = -2 * dx + 2 * (dy) * m1; \
216             incr2 = -2 * dx + 2 * (dy) * m; \
217             d = 2 * m * (dy) - 2 * dx - 2 * (dy); \
218         } else { \
219             m = dx / (dy); \
220             m1 = m + 1; \
221             incr1 = 2 * dx - 2 * (dy) * m1; \
222             incr2 = 2 * dx - 2 * (dy) * m; \
223             d = -2 * m * (dy) + 2 * dx; \
224         } \
225     } \
226 }
227
228 #define BRESINCRPGON(d, minval, m, m1, incr1, incr2) { \
229     if (m1 > 0) { \
230         if (d > 0) { \
231             minval += m1; \
232             d += incr1; \
233         } \
234         else { \
235             minval += m; \
236             d += incr2; \
237         } \
238     } else {\
239         if (d >= 0) { \
240             minval += m1; \
241             d += incr1; \
242         } \
243         else { \
244             minval += m; \
245             d += incr2; \
246         } \
247     } \
248 }
249
250 /*
251  *     This structure contains all of the information needed
252  *     to run the bresenham algorithm.
253  *     The variables may be hardcoded into the declarations
254  *     instead of using this structure to make use of
255  *     register declarations.
256  */
257 typedef struct {
258     INT minor_axis;     /* minor axis        */
259     INT d;              /* decision variable */
260     INT m, m1;          /* slope and slope+1 */
261     INT incr1, incr2;   /* error increments */
262 } BRESINFO;
263
264
265 #define BRESINITPGONSTRUCT(dmaj, min1, min2, bres) \
266         BRESINITPGON(dmaj, min1, min2, bres.minor_axis, bres.d, \
267                      bres.m, bres.m1, bres.incr1, bres.incr2)
268
269 #define BRESINCRPGONSTRUCT(bres) \
270         BRESINCRPGON(bres.d, bres.minor_axis, bres.m, bres.m1, bres.incr1, bres.incr2)
271
272
273
274 /*
275  *     These are the data structures needed to scan
276  *     convert regions.  Two different scan conversion
277  *     methods are available -- the even-odd method, and
278  *     the winding number method.
279  *     The even-odd rule states that a point is inside
280  *     the polygon if a ray drawn from that point in any
281  *     direction will pass through an odd number of
282  *     path segments.
283  *     By the winding number rule, a point is decided
284  *     to be inside the polygon if a ray drawn from that
285  *     point in any direction passes through a different
286  *     number of clockwise and counter-clockwise path
287  *     segments.
288  *
289  *     These data structures are adapted somewhat from
290  *     the algorithm in (Foley/Van Dam) for scan converting
291  *     polygons.
292  *     The basic algorithm is to start at the top (smallest y)
293  *     of the polygon, stepping down to the bottom of
294  *     the polygon by incrementing the y coordinate.  We
295  *     keep a list of edges which the current scanline crosses,
296  *     sorted by x.  This list is called the Active Edge Table (AET)
297  *     As we change the y-coordinate, we update each entry in 
298  *     in the active edge table to reflect the edges new xcoord.
299  *     This list must be sorted at each scanline in case
300  *     two edges intersect.
301  *     We also keep a data structure known as the Edge Table (ET),
302  *     which keeps track of all the edges which the current
303  *     scanline has not yet reached.  The ET is basically a
304  *     list of ScanLineList structures containing a list of
305  *     edges which are entered at a given scanline.  There is one
306  *     ScanLineList per scanline at which an edge is entered.
307  *     When we enter a new edge, we move it from the ET to the AET.
308  *
309  *     From the AET, we can implement the even-odd rule as in
310  *     (Foley/Van Dam).
311  *     The winding number rule is a little trickier.  We also
312  *     keep the EdgeTableEntries in the AET linked by the
313  *     nextWETE (winding EdgeTableEntry) link.  This allows
314  *     the edges to be linked just as before for updating
315  *     purposes, but only uses the edges linked by the nextWETE
316  *     link as edges representing spans of the polygon to
317  *     drawn (as with the even-odd rule).
318  */
319
320 /*
321  * for the winding number rule
322  */
323 #define CLOCKWISE          1
324 #define COUNTERCLOCKWISE  -1 
325
326 typedef struct _EdgeTableEntry {
327      INT ymax;           /* ycoord at which we exit this edge. */
328      BRESINFO bres;        /* Bresenham info to run the edge     */
329      struct _EdgeTableEntry *next;       /* next in the list     */
330      struct _EdgeTableEntry *back;       /* for insertion sort   */
331      struct _EdgeTableEntry *nextWETE;   /* for winding num rule */
332      int ClockWise;        /* flag for winding number rule       */
333 } EdgeTableEntry;
334
335
336 typedef struct _ScanLineList{
337      INT scanline;            /* the scanline represented */
338      EdgeTableEntry *edgelist;  /* header node              */
339      struct _ScanLineList *next;  /* next in the list       */
340 } ScanLineList;
341
342
343 typedef struct {
344      INT ymax;               /* ymax for the polygon     */
345      INT ymin;               /* ymin for the polygon     */
346      ScanLineList scanlines;   /* header node              */
347 } EdgeTable;
348
349
350 /*
351  * Here is a struct to help with storage allocation
352  * so we can allocate a big chunk at a time, and then take
353  * pieces from this heap when we need to.
354  */
355 #define SLLSPERBLOCK 25
356
357 typedef struct _ScanLineListBlock {
358      ScanLineList SLLs[SLLSPERBLOCK];
359      struct _ScanLineListBlock *next;
360 } ScanLineListBlock;
361
362
363 /*
364  *
365  *     a few macros for the inner loops of the fill code where
366  *     performance considerations don't allow a procedure call.
367  *
368  *     Evaluate the given edge at the given scanline.
369  *     If the edge has expired, then we leave it and fix up
370  *     the active edge table; otherwise, we increment the
371  *     x value to be ready for the next scanline.
372  *     The winding number rule is in effect, so we must notify
373  *     the caller when the edge has been removed so he
374  *     can reorder the Winding Active Edge Table.
375  */
376 #define EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET) { \
377    if (pAET->ymax == y) {          /* leaving this edge */ \
378       pPrevAET->next = pAET->next; \
379       pAET = pPrevAET->next; \
380       fixWAET = 1; \
381       if (pAET) \
382          pAET->back = pPrevAET; \
383    } \
384    else { \
385       BRESINCRPGONSTRUCT(pAET->bres); \
386       pPrevAET = pAET; \
387       pAET = pAET->next; \
388    } \
389 }
390
391
392 /*
393  *     Evaluate the given edge at the given scanline.
394  *     If the edge has expired, then we leave it and fix up
395  *     the active edge table; otherwise, we increment the
396  *     x value to be ready for the next scanline.
397  *     The even-odd rule is in effect.
398  */
399 #define EVALUATEEDGEEVENODD(pAET, pPrevAET, y) { \
400    if (pAET->ymax == y) {          /* leaving this edge */ \
401       pPrevAET->next = pAET->next; \
402       pAET = pPrevAET->next; \
403       if (pAET) \
404          pAET->back = pPrevAET; \
405    } \
406    else { \
407       BRESINCRPGONSTRUCT(pAET->bres); \
408       pPrevAET = pAET; \
409       pAET = pAET->next; \
410    } \
411 }
412
413 typedef void (*voidProcp)();
414
415 /* Note the parameter order is different from the X11 equivalents */
416
417 static void REGION_CopyRegion(WINEREGION *d, WINEREGION *s);
418 static void REGION_IntersectRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
419 static void REGION_UnionRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
420 static void REGION_SubtractRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
421 static void REGION_XorRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
422 static void REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn);
423
424 #define RGN_DEFAULT_RECTS       2
425
426 /***********************************************************************
427  *            REGION_DumpRegion
428  *            Outputs the contents of a WINEREGION
429  */
430 static void REGION_DumpRegion(WINEREGION *pReg)
431 {
432     RECT *pRect, *pRectEnd = pReg->rects + pReg->numRects;
433
434     TRACE("Region %p: %d,%d - %d,%d %d rects\n", pReg,
435             pReg->extents.left, pReg->extents.top,
436             pReg->extents.right, pReg->extents.bottom, pReg->numRects);
437     for(pRect = pReg->rects; pRect < pRectEnd; pRect++)
438         TRACE("\t%d,%d - %d,%d\n", pRect->left, pRect->top,
439                        pRect->right, pRect->bottom);
440     return;
441 }
442
443
444 /***********************************************************************
445  *            REGION_AllocWineRegion
446  *            Create a new empty WINEREGION.
447  */
448 static WINEREGION *REGION_AllocWineRegion( INT n )
449 {
450     WINEREGION *pReg;
451
452     if ((pReg = HeapAlloc(GetProcessHeap(), 0, sizeof( WINEREGION ))))
453     {
454         if ((pReg->rects = HeapAlloc(GetProcessHeap(), 0, n * sizeof( RECT ))))
455         {
456             pReg->size = n;
457             EMPTY_REGION(pReg);
458             return pReg;
459         }
460         HeapFree(GetProcessHeap(), 0, pReg);
461     }
462     return NULL;
463 }
464
465
466 /***********************************************************************
467  *          REGION_CreateRegion
468  *          Create a new empty region.
469  */
470 static HRGN REGION_CreateRegion( INT n )
471 {
472     HRGN hrgn;
473     RGNOBJ *obj;
474
475     if(!(obj = GDI_AllocObject( sizeof(RGNOBJ), REGION_MAGIC, &hrgn ))) return 0;
476     if(!(obj->rgn = REGION_AllocWineRegion(n))) {
477         GDI_FreeObject( hrgn, obj );
478         return 0;
479     }
480     GDI_ReleaseObj( hrgn );
481     return hrgn;
482 }
483
484
485 /***********************************************************************
486  *           REGION_DestroyWineRegion
487  */
488 static void REGION_DestroyWineRegion( WINEREGION* pReg )
489 {
490     HeapFree( GetProcessHeap(), 0, pReg->rects );
491     HeapFree( GetProcessHeap(), 0, pReg );
492     return;
493 }
494
495 /***********************************************************************
496  *           REGION_DeleteObject
497  */
498 BOOL REGION_DeleteObject( HRGN hrgn, RGNOBJ * obj )
499 {
500     TRACE(" %04x\n", hrgn );
501
502     REGION_DestroyWineRegion( obj->rgn );
503     return GDI_FreeObject( hrgn, obj );
504 }
505
506 /***********************************************************************
507  *           OffsetRgn    (GDI.101)
508  */
509 INT16 WINAPI OffsetRgn16( HRGN16 hrgn, INT16 x, INT16 y )
510 {
511     return OffsetRgn( hrgn, x, y );
512 }
513
514 /***********************************************************************
515  *           OffsetRgn   (GDI32.@)
516  */
517 INT WINAPI OffsetRgn( HRGN hrgn, INT x, INT y )
518 {
519     RGNOBJ * obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
520     INT ret;
521
522     TRACE("%04x %d,%d\n", hrgn, x, y);
523
524     if (!obj)
525         return ERROR;
526
527     if(x || y) {
528         int nbox = obj->rgn->numRects;
529         RECT *pbox = obj->rgn->rects;
530         
531         if(nbox) {
532             while(nbox--) {
533                 pbox->left += x;
534                 pbox->right += x;
535                 pbox->top += y;
536                 pbox->bottom += y;
537                 pbox++;
538             }
539             obj->rgn->extents.left += x;
540             obj->rgn->extents.right += x;
541             obj->rgn->extents.top += y;
542             obj->rgn->extents.bottom += y;
543         }
544     }
545     ret = obj->rgn->type;
546     GDI_ReleaseObj( hrgn );
547     return ret;
548 }
549
550
551 /***********************************************************************
552  *           GetRgnBox    (GDI.134)
553  */
554 INT16 WINAPI GetRgnBox16( HRGN16 hrgn, LPRECT16 rect )
555 {
556     RECT r;
557     INT16 ret = (INT16)GetRgnBox( hrgn, &r );
558     CONV_RECT32TO16( &r, rect );
559     return ret;
560 }
561
562 /***********************************************************************
563  *           GetRgnBox    (GDI32.@)
564  */
565 INT WINAPI GetRgnBox( HRGN hrgn, LPRECT rect )
566 {
567     RGNOBJ * obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
568     if (obj)
569     {
570         INT ret;
571         TRACE(" %04x\n", hrgn );
572         rect->left = obj->rgn->extents.left;
573         rect->top = obj->rgn->extents.top;
574         rect->right = obj->rgn->extents.right;
575         rect->bottom = obj->rgn->extents.bottom;
576         ret = obj->rgn->type;
577         GDI_ReleaseObj(hrgn);
578         return ret;
579     }
580     return ERROR;
581 }
582
583
584 /***********************************************************************
585  *           CreateRectRgn    (GDI.64)
586  *
587  * NOTE: Doesn't call CreateRectRgn because of differences in SetRectRgn16/32
588  */
589 HRGN16 WINAPI CreateRectRgn16(INT16 left, INT16 top, INT16 right, INT16 bottom)
590 {
591     HRGN16 hrgn;
592
593     if (!(hrgn = (HRGN16)REGION_CreateRegion(RGN_DEFAULT_RECTS)))
594         return 0;
595     TRACE("\n");
596     SetRectRgn16(hrgn, left, top, right, bottom);
597     return hrgn;
598 }
599
600
601 /***********************************************************************
602  *           CreateRectRgn   (GDI32.@)
603  */
604 HRGN WINAPI CreateRectRgn(INT left, INT top, INT right, INT bottom)
605 {
606     HRGN hrgn;
607
608     /* Allocate 2 rects by default to reduce the number of reallocs */
609
610     if (!(hrgn = REGION_CreateRegion(RGN_DEFAULT_RECTS)))
611         return 0;
612     TRACE("\n");
613     SetRectRgn(hrgn, left, top, right, bottom);
614     return hrgn;
615 }
616
617 /***********************************************************************
618  *           CreateRectRgnIndirect    (GDI.65)
619  */
620 HRGN16 WINAPI CreateRectRgnIndirect16( const RECT16* rect )
621 {
622     return CreateRectRgn16( rect->left, rect->top, rect->right, rect->bottom );
623 }
624
625
626 /***********************************************************************
627  *           CreateRectRgnIndirect    (GDI32.@)
628  */
629 HRGN WINAPI CreateRectRgnIndirect( const RECT* rect )
630 {
631     return CreateRectRgn( rect->left, rect->top, rect->right, rect->bottom );
632 }
633
634
635 /***********************************************************************
636  *           SetRectRgn    (GDI.172)
637  *
638  * NOTE: Win 3.1 sets region to empty if left > right
639  */
640 VOID WINAPI SetRectRgn16( HRGN16 hrgn, INT16 left, INT16 top,
641                           INT16 right, INT16 bottom )
642 {
643     if(left < right)
644         SetRectRgn( hrgn, left, top, right, bottom );
645     else
646         SetRectRgn( hrgn, 0, 0, 0, 0 );
647 }
648
649
650 /***********************************************************************
651  *           SetRectRgn    (GDI32.@)
652  *
653  * Allows either or both left and top to be greater than right or bottom.
654  */
655 BOOL WINAPI SetRectRgn( HRGN hrgn, INT left, INT top,
656                           INT right, INT bottom )
657 {
658     RGNOBJ * obj;
659
660     TRACE(" %04x %d,%d-%d,%d\n", 
661           hrgn, left, top, right, bottom );
662     
663     if (!(obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC ))) return FALSE;
664
665     if (left > right) { INT tmp = left; left = right; right = tmp; }
666     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
667
668     if((left != right) && (top != bottom))
669     {
670         obj->rgn->rects->left = obj->rgn->extents.left = left;
671         obj->rgn->rects->top = obj->rgn->extents.top = top;
672         obj->rgn->rects->right = obj->rgn->extents.right = right;
673         obj->rgn->rects->bottom = obj->rgn->extents.bottom = bottom;
674         obj->rgn->numRects = 1;
675         obj->rgn->type = SIMPLEREGION;
676     }
677     else
678         EMPTY_REGION(obj->rgn);
679
680     GDI_ReleaseObj( hrgn );
681     return TRUE;
682 }
683
684
685 /***********************************************************************
686  *           CreateRoundRectRgn    (GDI.444)
687  *
688  * If either ellipse dimension is zero we call CreateRectRgn16 for its
689  * `special' behaviour. -ve ellipse dimensions can result in GPFs under win3.1
690  * we just let CreateRoundRectRgn convert them to +ve values. 
691  */
692
693 HRGN16 WINAPI CreateRoundRectRgn16( INT16 left, INT16 top,
694                                     INT16 right, INT16 bottom,
695                                     INT16 ellipse_width, INT16 ellipse_height )
696 {
697     if( ellipse_width == 0 || ellipse_height == 0 )
698         return CreateRectRgn16( left, top, right, bottom );
699     else
700         return (HRGN16)CreateRoundRectRgn( left, top, right, bottom,
701                                          ellipse_width, ellipse_height );
702 }
703
704 /***********************************************************************
705  *           CreateRoundRectRgn    (GDI32.@)
706  */
707 HRGN WINAPI CreateRoundRectRgn( INT left, INT top,
708                                     INT right, INT bottom,
709                                     INT ellipse_width, INT ellipse_height )
710 {
711     RGNOBJ * obj;
712     HRGN hrgn;
713     int asq, bsq, d, xd, yd;
714     RECT rect;
715
716       /* Make the dimensions sensible */
717
718     if (left > right) { INT tmp = left; left = right; right = tmp; }
719     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
720
721     ellipse_width = abs(ellipse_width);
722     ellipse_height = abs(ellipse_height);
723
724       /* Check parameters */
725
726     if (ellipse_width > right-left) ellipse_width = right-left;
727     if (ellipse_height > bottom-top) ellipse_height = bottom-top;
728
729       /* Check if we can do a normal rectangle instead */
730
731     if ((ellipse_width < 2) || (ellipse_height < 2))
732         return CreateRectRgn( left, top, right, bottom );
733
734       /* Create region */
735
736     d = (ellipse_height < 128) ? ((3 * ellipse_height) >> 2) : 64;
737     if (!(hrgn = REGION_CreateRegion(d))) return 0;
738     if (!(obj = GDI_GetObjPtr( hrgn, REGION_MAGIC ))) return 0;
739     TRACE("(%d,%d-%d,%d %dx%d): ret=%04x\n",
740           left, top, right, bottom, ellipse_width, ellipse_height, hrgn );
741
742       /* Ellipse algorithm, based on an article by K. Porter */
743       /* in DDJ Graphics Programming Column, 8/89 */
744
745     asq = ellipse_width * ellipse_width / 4;        /* a^2 */
746     bsq = ellipse_height * ellipse_height / 4;      /* b^2 */
747     d = bsq - asq * ellipse_height / 2 + asq / 4;   /* b^2 - a^2b + a^2/4 */
748     xd = 0;
749     yd = asq * ellipse_height;                      /* 2a^2b */
750
751     rect.left   = left + ellipse_width / 2;
752     rect.right  = right - ellipse_width / 2;
753
754       /* Loop to draw first half of quadrant */
755
756     while (xd < yd)
757     {
758         if (d > 0)  /* if nearest pixel is toward the center */
759         {
760               /* move toward center */
761             rect.top = top++;
762             rect.bottom = rect.top + 1;
763             REGION_UnionRectWithRegion( &rect, obj->rgn );
764             rect.top = --bottom;
765             rect.bottom = rect.top + 1;
766             REGION_UnionRectWithRegion( &rect, obj->rgn );
767             yd -= 2*asq;
768             d  -= yd;
769         }
770         rect.left--;        /* next horiz point */
771         rect.right++;
772         xd += 2*bsq;
773         d  += bsq + xd;
774     }
775
776       /* Loop to draw second half of quadrant */
777
778     d += (3 * (asq-bsq) / 2 - (xd+yd)) / 2;
779     while (yd >= 0)
780     {
781           /* next vertical point */
782         rect.top = top++;
783         rect.bottom = rect.top + 1;
784         REGION_UnionRectWithRegion( &rect, obj->rgn );
785         rect.top = --bottom;
786         rect.bottom = rect.top + 1;
787         REGION_UnionRectWithRegion( &rect, obj->rgn );
788         if (d < 0)   /* if nearest pixel is outside ellipse */
789         {
790             rect.left--;     /* move away from center */
791             rect.right++;
792             xd += 2*bsq;
793             d  += xd;
794         }
795         yd -= 2*asq;
796         d  += asq - yd;
797     }
798
799       /* Add the inside rectangle */
800
801     if (top <= bottom)
802     {
803         rect.top = top;
804         rect.bottom = bottom;
805         REGION_UnionRectWithRegion( &rect, obj->rgn );
806     }
807     obj->rgn->type = SIMPLEREGION; /* FIXME? */
808     GDI_ReleaseObj( hrgn );
809     return hrgn;
810 }
811
812
813 /***********************************************************************
814  *           CreateEllipticRgn    (GDI.54)
815  */
816 HRGN16 WINAPI CreateEllipticRgn16( INT16 left, INT16 top,
817                                    INT16 right, INT16 bottom )
818 {
819     return (HRGN16)CreateRoundRectRgn( left, top, right, bottom,
820                                          right-left, bottom-top );
821 }
822
823
824 /***********************************************************************
825  *           CreateEllipticRgn    (GDI32.@)
826  */
827 HRGN WINAPI CreateEllipticRgn( INT left, INT top,
828                                    INT right, INT bottom )
829 {
830     return CreateRoundRectRgn( left, top, right, bottom,
831                                  right-left, bottom-top );
832 }
833
834
835 /***********************************************************************
836  *           CreateEllipticRgnIndirect    (GDI.55)
837  */
838 HRGN16 WINAPI CreateEllipticRgnIndirect16( const RECT16 *rect )
839 {
840     return CreateRoundRectRgn( rect->left, rect->top, rect->right,
841                                  rect->bottom, rect->right - rect->left,
842                                  rect->bottom - rect->top );
843 }
844
845
846 /***********************************************************************
847  *           CreateEllipticRgnIndirect    (GDI32.@)
848  */
849 HRGN WINAPI CreateEllipticRgnIndirect( const RECT *rect )
850 {
851     return CreateRoundRectRgn( rect->left, rect->top, rect->right,
852                                  rect->bottom, rect->right - rect->left,
853                                  rect->bottom - rect->top );
854 }
855
856 /***********************************************************************
857  *           GetRegionData   (GDI32.@)
858  * 
859  * MSDN: GetRegionData, Return Values:
860  *
861  * "If the function succeeds and dwCount specifies an adequate number of bytes,
862  * the return value is always dwCount. If dwCount is too small or the function
863  * fails, the return value is 0. If lpRgnData is NULL, the return value is the
864  * required number of bytes.
865  *
866  * If the function fails, the return value is zero."
867  */
868 DWORD WINAPI GetRegionData(HRGN hrgn, DWORD count, LPRGNDATA rgndata)
869 {
870     DWORD size;
871     RGNOBJ *obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
872     
873     TRACE(" %04x count = %ld, rgndata = %p\n",
874                    hrgn, count, rgndata);
875
876     if(!obj) return 0;
877
878     size = obj->rgn->numRects * sizeof(RECT);
879     if(count < (size + sizeof(RGNDATAHEADER)) || rgndata == NULL)
880     {
881         GDI_ReleaseObj( hrgn );
882         if (rgndata) /* buffer is too small, signal it by return 0 */
883             return 0;
884         else            /* user requested buffer size with rgndata NULL */
885             return size + sizeof(RGNDATAHEADER);
886     }
887
888     rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
889     rgndata->rdh.iType = RDH_RECTANGLES;
890     rgndata->rdh.nCount = obj->rgn->numRects;
891     rgndata->rdh.nRgnSize = size;
892     rgndata->rdh.rcBound.left = obj->rgn->extents.left;
893     rgndata->rdh.rcBound.top = obj->rgn->extents.top;
894     rgndata->rdh.rcBound.right = obj->rgn->extents.right;
895     rgndata->rdh.rcBound.bottom = obj->rgn->extents.bottom;
896
897     memcpy( rgndata->Buffer, obj->rgn->rects, size );
898
899     GDI_ReleaseObj( hrgn );
900     return size + sizeof(RGNDATAHEADER);
901 }
902
903 /***********************************************************************
904  *           GetRegionData   (GDI.607)
905  * FIXME: is LPRGNDATA the same in Win16 and Win32 ?
906  */
907 DWORD WINAPI GetRegionData16(HRGN16 hrgn, DWORD count, LPRGNDATA rgndata)
908 {
909     return GetRegionData((HRGN)hrgn, count, rgndata);
910 }
911
912 /***********************************************************************
913  *           ExtCreateRegion   (GDI32.@)
914  * 
915  */
916 HRGN WINAPI ExtCreateRegion( const XFORM* lpXform, DWORD dwCount, const RGNDATA* rgndata)
917 {
918     HRGN hrgn;
919
920     TRACE(" %p %ld %p = ", lpXform, dwCount, rgndata );
921
922     if( lpXform )
923         WARN("(Xform not implemented - ignored) ");
924     
925     if( rgndata->rdh.iType != RDH_RECTANGLES )
926     {
927         /* FIXME: We can use CreatePolyPolygonRgn() here
928          *        for trapezoidal data */
929
930         WARN("(Unsupported region data) ");
931         goto fail;
932     }
933
934     if( (hrgn = REGION_CreateRegion( rgndata->rdh.nCount )) )
935     {
936         RECT *pCurRect, *pEndRect;
937         RGNOBJ *obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
938
939         if (obj) {
940             pEndRect = (RECT *)rgndata->Buffer + rgndata->rdh.nCount;
941             for(pCurRect = (RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
942                 REGION_UnionRectWithRegion( pCurRect, obj->rgn );
943             GDI_ReleaseObj( hrgn );
944
945             TRACE("%04x\n", hrgn );
946             return hrgn;
947         }
948         else ERR("Could not get pointer to newborn Region!");
949     }
950 fail:
951     WARN("Failed\n");
952     return 0;
953 }
954
955 /***********************************************************************
956  *           PtInRegion    (GDI.161)
957  */
958 BOOL16 WINAPI PtInRegion16( HRGN16 hrgn, INT16 x, INT16 y )
959 {
960     return PtInRegion( hrgn, x, y );
961 }
962
963
964 /***********************************************************************
965  *           PtInRegion    (GDI32.@)
966  */
967 BOOL WINAPI PtInRegion( HRGN hrgn, INT x, INT y )
968 {
969     RGNOBJ * obj;
970     BOOL ret = FALSE;
971     
972     if ((obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC )))
973     {
974         int i;
975
976         if (obj->rgn->numRects > 0 && INRECT(obj->rgn->extents, x, y))
977             for (i = 0; i < obj->rgn->numRects; i++)
978                 if (INRECT (obj->rgn->rects[i], x, y))
979                 {
980                     ret = TRUE;
981                     break;
982                 }
983         GDI_ReleaseObj( hrgn );
984     }
985     return ret;
986 }
987
988
989 /***********************************************************************
990  *           RectInRegion    (GDI.466)
991  *           RectInRegionOld (GDI.181)
992  */
993 BOOL16 WINAPI RectInRegion16( HRGN16 hrgn, const RECT16 *rect )
994 {
995     RECT r32;
996
997     CONV_RECT16TO32(rect, &r32);
998     return (BOOL16)RectInRegion(hrgn, &r32);
999 }
1000
1001
1002 /***********************************************************************
1003  *           RectInRegion    (GDI32.@)
1004  *
1005  * Returns TRUE if rect is at least partly inside hrgn
1006  */
1007 BOOL WINAPI RectInRegion( HRGN hrgn, const RECT *rect )
1008 {
1009     RGNOBJ * obj;
1010     BOOL ret = FALSE;
1011     
1012     if ((obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC )))
1013     {
1014         RECT *pCurRect, *pRectEnd;
1015     
1016     /* this is (just) a useful optimization */
1017         if ((obj->rgn->numRects > 0) && EXTENTCHECK(&obj->rgn->extents,
1018                                                       rect))
1019         {
1020             for (pCurRect = obj->rgn->rects, pRectEnd = pCurRect +
1021              obj->rgn->numRects; pCurRect < pRectEnd; pCurRect++)
1022             {
1023                 if (pCurRect->bottom <= rect->top)
1024                     continue;             /* not far enough down yet */
1025
1026                 if (pCurRect->top >= rect->bottom)
1027                     break;                /* too far down */
1028
1029                 if (pCurRect->right <= rect->left)
1030                     continue;              /* not far enough over yet */
1031
1032                 if (pCurRect->left >= rect->right) {
1033                     continue;
1034                 }
1035
1036                 ret = TRUE;
1037                 break;
1038             }
1039         }
1040         GDI_ReleaseObj(hrgn);
1041     }
1042     return ret;
1043 }
1044
1045 /***********************************************************************
1046  *           EqualRgn    (GDI.72)
1047  */
1048 BOOL16 WINAPI EqualRgn16( HRGN16 rgn1, HRGN16 rgn2 )
1049 {
1050     return EqualRgn( rgn1, rgn2 );
1051 }
1052
1053
1054 /***********************************************************************
1055  *           EqualRgn    (GDI32.@)
1056  */
1057 BOOL WINAPI EqualRgn( HRGN hrgn1, HRGN hrgn2 )
1058 {
1059     RGNOBJ *obj1, *obj2;
1060     BOOL ret = FALSE;
1061
1062     if ((obj1 = (RGNOBJ *) GDI_GetObjPtr( hrgn1, REGION_MAGIC ))) 
1063     {
1064         if ((obj2 = (RGNOBJ *) GDI_GetObjPtr( hrgn2, REGION_MAGIC ))) 
1065         {
1066             int i;
1067
1068             if ( obj1->rgn->numRects != obj2->rgn->numRects ) goto done;
1069             if ( obj1->rgn->numRects == 0 )
1070             {
1071                 ret = TRUE;
1072                 goto done;
1073             
1074             }
1075             if (obj1->rgn->extents.left   != obj2->rgn->extents.left) goto done;
1076             if (obj1->rgn->extents.right  != obj2->rgn->extents.right) goto done;
1077             if (obj1->rgn->extents.top    != obj2->rgn->extents.top) goto done;
1078             if (obj1->rgn->extents.bottom != obj2->rgn->extents.bottom) goto done;
1079             for( i = 0; i < obj1->rgn->numRects; i++ )
1080             {
1081                 if (obj1->rgn->rects[i].left   != obj2->rgn->rects[i].left) goto done;
1082                 if (obj1->rgn->rects[i].right  != obj2->rgn->rects[i].right) goto done;
1083                 if (obj1->rgn->rects[i].top    != obj2->rgn->rects[i].top) goto done;
1084                 if (obj1->rgn->rects[i].bottom != obj2->rgn->rects[i].bottom) goto done;
1085             }
1086             ret = TRUE;
1087         done:
1088             GDI_ReleaseObj(hrgn2);
1089         }
1090         GDI_ReleaseObj(hrgn1);
1091     }
1092     return ret;
1093 }
1094 /***********************************************************************
1095  *           REGION_UnionRectWithRegion
1096  *           Adds a rectangle to a WINEREGION
1097  *           See below for REGION_UnionRectWithRgn
1098  */
1099 static void REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn)
1100 {
1101     WINEREGION region;
1102
1103     region.rects = &region.extents;
1104     region.numRects = 1;
1105     region.size = 1;
1106     region.type = SIMPLEREGION;
1107     region.extents = *rect;
1108     REGION_UnionRegion(rgn, rgn, &region);
1109     return;
1110 }
1111
1112 /***********************************************************************
1113  *           REGION_UnionRectWithRgn
1114  *           Adds a rectangle to a HRGN
1115  *           A helper used by scroll.c
1116  */
1117 BOOL REGION_UnionRectWithRgn( HRGN hrgn, const RECT *lpRect )
1118 {
1119     RGNOBJ *obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
1120
1121     if(!obj) return FALSE;
1122     REGION_UnionRectWithRegion( lpRect, obj->rgn );
1123     GDI_ReleaseObj(hrgn);
1124     return TRUE;
1125 }
1126
1127 /***********************************************************************
1128  *           REGION_CreateFrameRgn
1129  *
1130  * Create a region that is a frame around another region.
1131  * Expand all rectangles by +/- x and y, then subtract original region.
1132  */
1133 BOOL REGION_FrameRgn( HRGN hDest, HRGN hSrc, INT x, INT y )
1134 {
1135     BOOL bRet;
1136     RGNOBJ *srcObj = (RGNOBJ*) GDI_GetObjPtr( hSrc, REGION_MAGIC );
1137
1138     if (!srcObj) return FALSE;
1139     if (srcObj->rgn->numRects != 0) 
1140     {
1141         RGNOBJ* destObj = (RGNOBJ*) GDI_GetObjPtr( hDest, REGION_MAGIC );
1142         RECT *pRect, *pEndRect;
1143         RECT tempRect;
1144
1145         EMPTY_REGION( destObj->rgn );
1146         
1147         pEndRect = srcObj->rgn->rects + srcObj->rgn->numRects;
1148         for(pRect = srcObj->rgn->rects; pRect < pEndRect; pRect++)
1149         {
1150             tempRect.left = pRect->left - x;        
1151             tempRect.top = pRect->top - y;
1152             tempRect.right = pRect->right + x;
1153             tempRect.bottom = pRect->bottom + y;
1154             REGION_UnionRectWithRegion( &tempRect, destObj->rgn );
1155         }
1156         REGION_SubtractRegion( destObj->rgn, destObj->rgn, srcObj->rgn );
1157         GDI_ReleaseObj ( hDest );
1158         bRet = TRUE;
1159     }
1160     else
1161         bRet = FALSE;
1162     GDI_ReleaseObj( hSrc );
1163     return bRet;
1164 }
1165
1166 /***********************************************************************
1167  *           REGION_LPTODP
1168  *
1169  * Convert region to device co-ords for the supplied dc. 
1170  */
1171 BOOL REGION_LPTODP( HDC hdc, HRGN hDest, HRGN hSrc )
1172 {
1173     RECT *pCurRect, *pEndRect;
1174     RGNOBJ *srcObj, *destObj;
1175     DC * dc = DC_GetDCPtr( hdc );
1176     RECT tmpRect;
1177     BOOL ret = FALSE;
1178
1179     TRACE(" hdc=%04x dest=%04x src=%04x\n",
1180           hdc, hDest, hSrc) ;
1181     if (!dc) return ret;
1182     
1183     if (dc->MapMode == MM_TEXT) /* Requires only a translation */
1184     {
1185         if( CombineRgn( hDest, hSrc, 0, RGN_COPY ) == ERROR ) goto done;
1186         OffsetRgn( hDest, dc->vportOrgX - dc->wndOrgX, 
1187                      dc->vportOrgY - dc->wndOrgY );
1188         ret = TRUE;
1189         goto done;
1190     }
1191
1192     if(!( srcObj = (RGNOBJ *) GDI_GetObjPtr( hSrc, REGION_MAGIC) ))
1193         goto done;
1194     if(!( destObj = (RGNOBJ *) GDI_GetObjPtr( hDest, REGION_MAGIC) ))
1195     {
1196         GDI_ReleaseObj( hSrc );
1197         goto done;
1198     }
1199     EMPTY_REGION( destObj->rgn );
1200
1201     pEndRect = srcObj->rgn->rects + srcObj->rgn->numRects;
1202     for(pCurRect = srcObj->rgn->rects; pCurRect < pEndRect; pCurRect++)
1203     {
1204         tmpRect = *pCurRect;
1205         tmpRect.left = XLPTODP( dc, tmpRect.left );
1206         tmpRect.top = YLPTODP( dc, tmpRect.top );
1207         tmpRect.right = XLPTODP( dc, tmpRect.right );
1208         tmpRect.bottom = YLPTODP( dc, tmpRect.bottom );
1209
1210         if (tmpRect.left > tmpRect.right) 
1211         { INT tmp = tmpRect.left; tmpRect.left = tmpRect.right; tmpRect.right = tmp; }
1212         if (tmpRect.top > tmpRect.bottom) 
1213         { INT tmp = tmpRect.top; tmpRect.top = tmpRect.bottom; tmpRect.bottom = tmp; }
1214
1215         REGION_UnionRectWithRegion( &tmpRect, destObj->rgn );
1216     }
1217     ret = TRUE;
1218     
1219     GDI_ReleaseObj( hDest );
1220     GDI_ReleaseObj( hSrc );
1221  done:
1222     GDI_ReleaseObj( hdc );
1223     return ret;
1224 }
1225     
1226 /***********************************************************************
1227  *           CombineRgn    (GDI.47)
1228  */
1229 INT16 WINAPI CombineRgn16(HRGN16 hDest, HRGN16 hSrc1, HRGN16 hSrc2, INT16 mode)
1230 {
1231     return (INT16)CombineRgn( hDest, hSrc1, hSrc2, mode );
1232 }
1233
1234
1235 /***********************************************************************
1236  *           CombineRgn   (GDI32.@)
1237  *
1238  * Note: The behavior is correct even if src and dest regions are the same.
1239  */
1240 INT WINAPI CombineRgn(HRGN hDest, HRGN hSrc1, HRGN hSrc2, INT mode)
1241 {
1242     RGNOBJ *destObj = (RGNOBJ *) GDI_GetObjPtr( hDest, REGION_MAGIC);
1243     INT result = ERROR;
1244
1245     TRACE(" %04x,%04x -> %04x mode=%x\n", 
1246           hSrc1, hSrc2, hDest, mode );
1247     if (destObj)
1248     {
1249         RGNOBJ *src1Obj = (RGNOBJ *) GDI_GetObjPtr( hSrc1, REGION_MAGIC);
1250
1251         if (src1Obj)
1252         {
1253             TRACE("dump src1Obj:\n");
1254             if(TRACE_ON(region)) 
1255               REGION_DumpRegion(src1Obj->rgn);
1256             if (mode == RGN_COPY)
1257             {
1258                 REGION_CopyRegion( destObj->rgn, src1Obj->rgn );
1259                 result = destObj->rgn->type;
1260             }
1261             else
1262             {
1263                 RGNOBJ *src2Obj = (RGNOBJ *) GDI_GetObjPtr( hSrc2, REGION_MAGIC);
1264
1265                 if (src2Obj)
1266                 {
1267                     TRACE("dump src2Obj:\n");
1268                     if(TRACE_ON(region)) 
1269                         REGION_DumpRegion(src2Obj->rgn);
1270                     switch (mode)
1271                     {
1272                     case RGN_AND:
1273                         REGION_IntersectRegion( destObj->rgn, src1Obj->rgn, src2Obj->rgn);
1274                         break;
1275                     case RGN_OR:
1276                         REGION_UnionRegion( destObj->rgn, src1Obj->rgn, src2Obj->rgn );
1277                         break;
1278                     case RGN_XOR:
1279                         REGION_XorRegion( destObj->rgn, src1Obj->rgn, src2Obj->rgn );
1280                         break;
1281                     case RGN_DIFF:
1282                         REGION_SubtractRegion( destObj->rgn, src1Obj->rgn, src2Obj->rgn );
1283                         break;
1284                     }
1285                     result = destObj->rgn->type;
1286                     GDI_ReleaseObj( hSrc2 );
1287                 }
1288             }
1289             GDI_ReleaseObj( hSrc1 );
1290         }
1291         TRACE("dump destObj:\n");
1292         if(TRACE_ON(region)) 
1293           REGION_DumpRegion(destObj->rgn);
1294
1295         GDI_ReleaseObj( hDest );
1296     } else {
1297        ERR("Invalid rgn=%04x\n", hDest);
1298     }
1299     return result;
1300 }
1301
1302 /***********************************************************************
1303  *           REGION_SetExtents
1304  *           Re-calculate the extents of a region
1305  */
1306 static void REGION_SetExtents (WINEREGION *pReg)
1307 {
1308     RECT *pRect, *pRectEnd, *pExtents;
1309
1310     if (pReg->numRects == 0)
1311     {
1312         pReg->extents.left = 0;
1313         pReg->extents.top = 0;
1314         pReg->extents.right = 0;
1315         pReg->extents.bottom = 0;
1316         return;
1317     }
1318
1319     pExtents = &pReg->extents;
1320     pRect = pReg->rects;
1321     pRectEnd = &pRect[pReg->numRects - 1];
1322
1323     /*
1324      * Since pRect is the first rectangle in the region, it must have the
1325      * smallest top and since pRectEnd is the last rectangle in the region,
1326      * it must have the largest bottom, because of banding. Initialize left and
1327      * right from pRect and pRectEnd, resp., as good things to initialize them
1328      * to...
1329      */
1330     pExtents->left = pRect->left;
1331     pExtents->top = pRect->top;
1332     pExtents->right = pRectEnd->right;
1333     pExtents->bottom = pRectEnd->bottom;
1334
1335     while (pRect <= pRectEnd)
1336     {
1337         if (pRect->left < pExtents->left)
1338             pExtents->left = pRect->left;
1339         if (pRect->right > pExtents->right)
1340             pExtents->right = pRect->right;
1341         pRect++;
1342     }
1343 }
1344
1345 /***********************************************************************
1346  *           REGION_CopyRegion
1347  */
1348 static void REGION_CopyRegion(WINEREGION *dst, WINEREGION *src)
1349 {
1350     if (dst != src) /*  don't want to copy to itself */
1351     {  
1352         if (dst->size < src->numRects)
1353         {
1354             if (! (dst->rects = HeapReAlloc( GetProcessHeap(), 0, dst->rects,
1355                                 src->numRects * sizeof(RECT) )))
1356                 return;
1357             dst->size = src->numRects;
1358         }
1359         dst->numRects = src->numRects;
1360         dst->extents.left = src->extents.left;
1361         dst->extents.top = src->extents.top;
1362         dst->extents.right = src->extents.right;
1363         dst->extents.bottom = src->extents.bottom;
1364         dst->type = src->type;
1365
1366         memcpy((char *) dst->rects, (char *) src->rects,
1367                (int) (src->numRects * sizeof(RECT)));
1368     }
1369     return;
1370 }
1371
1372 /***********************************************************************
1373  *           REGION_Coalesce
1374  *
1375  *      Attempt to merge the rects in the current band with those in the
1376  *      previous one. Used only by REGION_RegionOp.
1377  *
1378  * Results:
1379  *      The new index for the previous band.
1380  *
1381  * Side Effects:
1382  *      If coalescing takes place:
1383  *          - rectangles in the previous band will have their bottom fields
1384  *            altered.
1385  *          - pReg->numRects will be decreased.
1386  *
1387  */
1388 static INT REGION_Coalesce (
1389              WINEREGION *pReg, /* Region to coalesce */
1390              INT prevStart,  /* Index of start of previous band */
1391              INT curStart    /* Index of start of current band */
1392 ) {
1393     RECT *pPrevRect;          /* Current rect in previous band */
1394     RECT *pCurRect;           /* Current rect in current band */
1395     RECT *pRegEnd;            /* End of region */
1396     INT curNumRects;          /* Number of rectangles in current band */
1397     INT prevNumRects;         /* Number of rectangles in previous band */
1398     INT bandtop;               /* top coordinate for current band */
1399
1400     pRegEnd = &pReg->rects[pReg->numRects];
1401
1402     pPrevRect = &pReg->rects[prevStart];
1403     prevNumRects = curStart - prevStart;
1404
1405     /*
1406      * Figure out how many rectangles are in the current band. Have to do
1407      * this because multiple bands could have been added in REGION_RegionOp
1408      * at the end when one region has been exhausted.
1409      */
1410     pCurRect = &pReg->rects[curStart];
1411     bandtop = pCurRect->top;
1412     for (curNumRects = 0;
1413          (pCurRect != pRegEnd) && (pCurRect->top == bandtop);
1414          curNumRects++)
1415     {
1416         pCurRect++;
1417     }
1418     
1419     if (pCurRect != pRegEnd)
1420     {
1421         /*
1422          * If more than one band was added, we have to find the start
1423          * of the last band added so the next coalescing job can start
1424          * at the right place... (given when multiple bands are added,
1425          * this may be pointless -- see above).
1426          */
1427         pRegEnd--;
1428         while (pRegEnd[-1].top == pRegEnd->top)
1429         {
1430             pRegEnd--;
1431         }
1432         curStart = pRegEnd - pReg->rects;
1433         pRegEnd = pReg->rects + pReg->numRects;
1434     }
1435         
1436     if ((curNumRects == prevNumRects) && (curNumRects != 0)) {
1437         pCurRect -= curNumRects;
1438         /*
1439          * The bands may only be coalesced if the bottom of the previous
1440          * matches the top scanline of the current.
1441          */
1442         if (pPrevRect->bottom == pCurRect->top)
1443         {
1444             /*
1445              * Make sure the bands have rects in the same places. This
1446              * assumes that rects have been added in such a way that they
1447              * cover the most area possible. I.e. two rects in a band must
1448              * have some horizontal space between them.
1449              */
1450             do
1451             {
1452                 if ((pPrevRect->left != pCurRect->left) ||
1453                     (pPrevRect->right != pCurRect->right))
1454                 {
1455                     /*
1456                      * The bands don't line up so they can't be coalesced.
1457                      */
1458                     return (curStart);
1459                 }
1460                 pPrevRect++;
1461                 pCurRect++;
1462                 prevNumRects -= 1;
1463             } while (prevNumRects != 0);
1464
1465             pReg->numRects -= curNumRects;
1466             pCurRect -= curNumRects;
1467             pPrevRect -= curNumRects;
1468
1469             /*
1470              * The bands may be merged, so set the bottom of each rect
1471              * in the previous band to that of the corresponding rect in
1472              * the current band.
1473              */
1474             do
1475             {
1476                 pPrevRect->bottom = pCurRect->bottom;
1477                 pPrevRect++;
1478                 pCurRect++;
1479                 curNumRects -= 1;
1480             } while (curNumRects != 0);
1481
1482             /*
1483              * If only one band was added to the region, we have to backup
1484              * curStart to the start of the previous band.
1485              *
1486              * If more than one band was added to the region, copy the
1487              * other bands down. The assumption here is that the other bands
1488              * came from the same region as the current one and no further
1489              * coalescing can be done on them since it's all been done
1490              * already... curStart is already in the right place.
1491              */
1492             if (pCurRect == pRegEnd)
1493             {
1494                 curStart = prevStart;
1495             }
1496             else
1497             {
1498                 do
1499                 {
1500                     *pPrevRect++ = *pCurRect++;
1501                 } while (pCurRect != pRegEnd);
1502             }
1503             
1504         }
1505     }
1506     return (curStart);
1507 }
1508
1509 /***********************************************************************
1510  *           REGION_RegionOp
1511  *
1512  *      Apply an operation to two regions. Called by REGION_Union,
1513  *      REGION_Inverse, REGION_Subtract, REGION_Intersect...
1514  *
1515  * Results:
1516  *      None.
1517  *
1518  * Side Effects:
1519  *      The new region is overwritten.
1520  *
1521  * Notes:
1522  *      The idea behind this function is to view the two regions as sets.
1523  *      Together they cover a rectangle of area that this function divides
1524  *      into horizontal bands where points are covered only by one region
1525  *      or by both. For the first case, the nonOverlapFunc is called with
1526  *      each the band and the band's upper and lower extents. For the
1527  *      second, the overlapFunc is called to process the entire band. It
1528  *      is responsible for clipping the rectangles in the band, though
1529  *      this function provides the boundaries.
1530  *      At the end of each band, the new region is coalesced, if possible,
1531  *      to reduce the number of rectangles in the region.
1532  *
1533  */
1534 static void REGION_RegionOp(
1535             WINEREGION *newReg, /* Place to store result */
1536             WINEREGION *reg1,   /* First region in operation */
1537             WINEREGION *reg2,   /* 2nd region in operation */
1538             void (*overlapFunc)(),     /* Function to call for over-lapping bands */
1539             void (*nonOverlap1Func)(), /* Function to call for non-overlapping bands in region 1 */
1540             void (*nonOverlap2Func)()  /* Function to call for non-overlapping bands in region 2 */
1541 ) {
1542     RECT *r1;                         /* Pointer into first region */
1543     RECT *r2;                         /* Pointer into 2d region */
1544     RECT *r1End;                      /* End of 1st region */
1545     RECT *r2End;                      /* End of 2d region */
1546     INT ybot;                         /* Bottom of intersection */
1547     INT ytop;                         /* Top of intersection */
1548     RECT *oldRects;                   /* Old rects for newReg */
1549     INT prevBand;                     /* Index of start of
1550                                                  * previous band in newReg */
1551     INT curBand;                      /* Index of start of current
1552                                                  * band in newReg */
1553     RECT *r1BandEnd;                  /* End of current band in r1 */
1554     RECT *r2BandEnd;                  /* End of current band in r2 */
1555     INT top;                          /* Top of non-overlapping band */
1556     INT bot;                          /* Bottom of non-overlapping band */
1557     
1558     /*
1559      * Initialization:
1560      *  set r1, r2, r1End and r2End appropriately, preserve the important
1561      * parts of the destination region until the end in case it's one of
1562      * the two source regions, then mark the "new" region empty, allocating
1563      * another array of rectangles for it to use.
1564      */
1565     r1 = reg1->rects;
1566     r2 = reg2->rects;
1567     r1End = r1 + reg1->numRects;
1568     r2End = r2 + reg2->numRects;
1569     
1570
1571     /*
1572      * newReg may be one of the src regions so we can't empty it. We keep a 
1573      * note of its rects pointer (so that we can free them later), preserve its
1574      * extents and simply set numRects to zero. 
1575      */
1576
1577     oldRects = newReg->rects;
1578     newReg->numRects = 0;
1579
1580     /*
1581      * Allocate a reasonable number of rectangles for the new region. The idea
1582      * is to allocate enough so the individual functions don't need to
1583      * reallocate and copy the array, which is time consuming, yet we don't
1584      * have to worry about using too much memory. I hope to be able to
1585      * nuke the Xrealloc() at the end of this function eventually.
1586      */
1587     newReg->size = max(reg1->numRects,reg2->numRects) * 2;
1588
1589     if (! (newReg->rects = HeapAlloc( GetProcessHeap(), 0, 
1590                                   sizeof(RECT) * newReg->size )))
1591     {
1592         newReg->size = 0;
1593         return;
1594     }
1595     
1596     /*
1597      * Initialize ybot and ytop.
1598      * In the upcoming loop, ybot and ytop serve different functions depending
1599      * on whether the band being handled is an overlapping or non-overlapping
1600      * band.
1601      *  In the case of a non-overlapping band (only one of the regions
1602      * has points in the band), ybot is the bottom of the most recent
1603      * intersection and thus clips the top of the rectangles in that band.
1604      * ytop is the top of the next intersection between the two regions and
1605      * serves to clip the bottom of the rectangles in the current band.
1606      *  For an overlapping band (where the two regions intersect), ytop clips
1607      * the top of the rectangles of both regions and ybot clips the bottoms.
1608      */
1609     if (reg1->extents.top < reg2->extents.top)
1610         ybot = reg1->extents.top;
1611     else
1612         ybot = reg2->extents.top;
1613     
1614     /*
1615      * prevBand serves to mark the start of the previous band so rectangles
1616      * can be coalesced into larger rectangles. qv. miCoalesce, above.
1617      * In the beginning, there is no previous band, so prevBand == curBand
1618      * (curBand is set later on, of course, but the first band will always
1619      * start at index 0). prevBand and curBand must be indices because of
1620      * the possible expansion, and resultant moving, of the new region's
1621      * array of rectangles.
1622      */
1623     prevBand = 0;
1624     
1625     do
1626     {
1627         curBand = newReg->numRects;
1628
1629         /*
1630          * This algorithm proceeds one source-band (as opposed to a
1631          * destination band, which is determined by where the two regions
1632          * intersect) at a time. r1BandEnd and r2BandEnd serve to mark the
1633          * rectangle after the last one in the current band for their
1634          * respective regions.
1635          */
1636         r1BandEnd = r1;
1637         while ((r1BandEnd != r1End) && (r1BandEnd->top == r1->top))
1638         {
1639             r1BandEnd++;
1640         }
1641         
1642         r2BandEnd = r2;
1643         while ((r2BandEnd != r2End) && (r2BandEnd->top == r2->top))
1644         {
1645             r2BandEnd++;
1646         }
1647         
1648         /*
1649          * First handle the band that doesn't intersect, if any.
1650          *
1651          * Note that attention is restricted to one band in the
1652          * non-intersecting region at once, so if a region has n
1653          * bands between the current position and the next place it overlaps
1654          * the other, this entire loop will be passed through n times.
1655          */
1656         if (r1->top < r2->top)
1657         {
1658             top = max(r1->top,ybot);
1659             bot = min(r1->bottom,r2->top);
1660
1661             if ((top != bot) && (nonOverlap1Func != (void (*)())NULL))
1662             {
1663                 (* nonOverlap1Func) (newReg, r1, r1BandEnd, top, bot);
1664             }
1665
1666             ytop = r2->top;
1667         }
1668         else if (r2->top < r1->top)
1669         {
1670             top = max(r2->top,ybot);
1671             bot = min(r2->bottom,r1->top);
1672
1673             if ((top != bot) && (nonOverlap2Func != (void (*)())NULL))
1674             {
1675                 (* nonOverlap2Func) (newReg, r2, r2BandEnd, top, bot);
1676             }
1677
1678             ytop = r1->top;
1679         }
1680         else
1681         {
1682             ytop = r1->top;
1683         }
1684
1685         /*
1686          * If any rectangles got added to the region, try and coalesce them
1687          * with rectangles from the previous band. Note we could just do
1688          * this test in miCoalesce, but some machines incur a not
1689          * inconsiderable cost for function calls, so...
1690          */
1691         if (newReg->numRects != curBand)
1692         {
1693             prevBand = REGION_Coalesce (newReg, prevBand, curBand);
1694         }
1695
1696         /*
1697          * Now see if we've hit an intersecting band. The two bands only
1698          * intersect if ybot > ytop
1699          */
1700         ybot = min(r1->bottom, r2->bottom);
1701         curBand = newReg->numRects;
1702         if (ybot > ytop)
1703         {
1704             (* overlapFunc) (newReg, r1, r1BandEnd, r2, r2BandEnd, ytop, ybot);
1705
1706         }
1707         
1708         if (newReg->numRects != curBand)
1709         {
1710             prevBand = REGION_Coalesce (newReg, prevBand, curBand);
1711         }
1712
1713         /*
1714          * If we've finished with a band (bottom == ybot) we skip forward
1715          * in the region to the next band.
1716          */
1717         if (r1->bottom == ybot)
1718         {
1719             r1 = r1BandEnd;
1720         }
1721         if (r2->bottom == ybot)
1722         {
1723             r2 = r2BandEnd;
1724         }
1725     } while ((r1 != r1End) && (r2 != r2End));
1726
1727     /*
1728      * Deal with whichever region still has rectangles left.
1729      */
1730     curBand = newReg->numRects;
1731     if (r1 != r1End)
1732     {
1733         if (nonOverlap1Func != (void (*)())NULL)
1734         {
1735             do
1736             {
1737                 r1BandEnd = r1;
1738                 while ((r1BandEnd < r1End) && (r1BandEnd->top == r1->top))
1739                 {
1740                     r1BandEnd++;
1741                 }
1742                 (* nonOverlap1Func) (newReg, r1, r1BandEnd,
1743                                      max(r1->top,ybot), r1->bottom);
1744                 r1 = r1BandEnd;
1745             } while (r1 != r1End);
1746         }
1747     }
1748     else if ((r2 != r2End) && (nonOverlap2Func != (void (*)())NULL))
1749     {
1750         do
1751         {
1752             r2BandEnd = r2;
1753             while ((r2BandEnd < r2End) && (r2BandEnd->top == r2->top))
1754             {
1755                  r2BandEnd++;
1756             }
1757             (* nonOverlap2Func) (newReg, r2, r2BandEnd,
1758                                 max(r2->top,ybot), r2->bottom);
1759             r2 = r2BandEnd;
1760         } while (r2 != r2End);
1761     }
1762
1763     if (newReg->numRects != curBand)
1764     {
1765         (void) REGION_Coalesce (newReg, prevBand, curBand);
1766     }
1767
1768     /*
1769      * A bit of cleanup. To keep regions from growing without bound,
1770      * we shrink the array of rectangles to match the new number of
1771      * rectangles in the region. This never goes to 0, however...
1772      *
1773      * Only do this stuff if the number of rectangles allocated is more than
1774      * twice the number of rectangles in the region (a simple optimization...).
1775      */
1776     if ((newReg->numRects < (newReg->size >> 1)) && (newReg->numRects > 2))
1777     {
1778         if (REGION_NOT_EMPTY(newReg))
1779         {
1780             RECT *prev_rects = newReg->rects;
1781             newReg->size = newReg->numRects;
1782             newReg->rects = HeapReAlloc( GetProcessHeap(), 0, newReg->rects,
1783                                    sizeof(RECT) * newReg->size );
1784             if (! newReg->rects)
1785                 newReg->rects = prev_rects;
1786         }
1787         else
1788         {
1789             /*
1790              * No point in doing the extra work involved in an Xrealloc if
1791              * the region is empty
1792              */
1793             newReg->size = 1;
1794             HeapFree( GetProcessHeap(), 0, newReg->rects );
1795             newReg->rects = HeapAlloc( GetProcessHeap(), 0, sizeof(RECT) );
1796         }
1797     }
1798     HeapFree( GetProcessHeap(), 0, oldRects );
1799     return;
1800 }
1801
1802 /***********************************************************************
1803  *          Region Intersection
1804  ***********************************************************************/
1805
1806
1807 /***********************************************************************
1808  *           REGION_IntersectO
1809  *
1810  * Handle an overlapping band for REGION_Intersect.
1811  *
1812  * Results:
1813  *      None.
1814  *
1815  * Side Effects:
1816  *      Rectangles may be added to the region.
1817  *
1818  */
1819 static void REGION_IntersectO(WINEREGION *pReg,  RECT *r1, RECT *r1End,
1820                 RECT *r2, RECT *r2End, INT top, INT bottom)
1821
1822 {
1823     INT       left, right;
1824     RECT      *pNextRect;
1825
1826     pNextRect = &pReg->rects[pReg->numRects];
1827
1828     while ((r1 != r1End) && (r2 != r2End))
1829     {
1830         left = max(r1->left, r2->left);
1831         right = min(r1->right, r2->right);
1832
1833         /*
1834          * If there's any overlap between the two rectangles, add that
1835          * overlap to the new region.
1836          * There's no need to check for subsumption because the only way
1837          * such a need could arise is if some region has two rectangles
1838          * right next to each other. Since that should never happen...
1839          */
1840         if (left < right)
1841         {
1842             MEMCHECK(pReg, pNextRect, pReg->rects);
1843             pNextRect->left = left;
1844             pNextRect->top = top;
1845             pNextRect->right = right;
1846             pNextRect->bottom = bottom;
1847             pReg->numRects += 1;
1848             pNextRect++;
1849         }
1850
1851         /*
1852          * Need to advance the pointers. Shift the one that extends
1853          * to the right the least, since the other still has a chance to
1854          * overlap with that region's next rectangle, if you see what I mean.
1855          */
1856         if (r1->right < r2->right)
1857         {
1858             r1++;
1859         }
1860         else if (r2->right < r1->right)
1861         {
1862             r2++;
1863         }
1864         else
1865         {
1866             r1++;
1867             r2++;
1868         }
1869     }
1870     return;
1871 }
1872
1873 /***********************************************************************
1874  *           REGION_IntersectRegion
1875  */
1876 static void REGION_IntersectRegion(WINEREGION *newReg, WINEREGION *reg1,
1877                                    WINEREGION *reg2)
1878 {
1879    /* check for trivial reject */
1880     if ( (!(reg1->numRects)) || (!(reg2->numRects))  ||
1881         (!EXTENTCHECK(&reg1->extents, &reg2->extents)))
1882         newReg->numRects = 0;
1883     else
1884         REGION_RegionOp (newReg, reg1, reg2, 
1885          (voidProcp) REGION_IntersectO, (voidProcp) NULL, (voidProcp) NULL);
1886     
1887     /*
1888      * Can't alter newReg's extents before we call miRegionOp because
1889      * it might be one of the source regions and miRegionOp depends
1890      * on the extents of those regions being the same. Besides, this
1891      * way there's no checking against rectangles that will be nuked
1892      * due to coalescing, so we have to examine fewer rectangles.
1893      */
1894     REGION_SetExtents(newReg);
1895     newReg->type = (newReg->numRects) ?
1896                        ((newReg->numRects > 1) ? COMPLEXREGION : SIMPLEREGION)
1897                        : NULLREGION ;
1898     return;
1899 }
1900
1901 /***********************************************************************
1902  *           Region Union
1903  ***********************************************************************/
1904
1905 /***********************************************************************
1906  *           REGION_UnionNonO
1907  *
1908  *      Handle a non-overlapping band for the union operation. Just
1909  *      Adds the rectangles into the region. Doesn't have to check for
1910  *      subsumption or anything.
1911  *
1912  * Results:
1913  *      None.
1914  *
1915  * Side Effects:
1916  *      pReg->numRects is incremented and the final rectangles overwritten
1917  *      with the rectangles we're passed.
1918  *
1919  */
1920 static void REGION_UnionNonO (WINEREGION *pReg, RECT *r, RECT *rEnd,
1921                               INT top, INT bottom)
1922 {
1923     RECT *pNextRect;
1924
1925     pNextRect = &pReg->rects[pReg->numRects];
1926
1927     while (r != rEnd)
1928     {
1929         MEMCHECK(pReg, pNextRect, pReg->rects);
1930         pNextRect->left = r->left;
1931         pNextRect->top = top;
1932         pNextRect->right = r->right;
1933         pNextRect->bottom = bottom;
1934         pReg->numRects += 1;
1935         pNextRect++;
1936         r++;
1937     }
1938     return;
1939 }
1940
1941 /***********************************************************************
1942  *           REGION_UnionO
1943  *
1944  *      Handle an overlapping band for the union operation. Picks the
1945  *      left-most rectangle each time and merges it into the region.
1946  *
1947  * Results:
1948  *      None.
1949  *
1950  * Side Effects:
1951  *      Rectangles are overwritten in pReg->rects and pReg->numRects will
1952  *      be changed.
1953  *
1954  */
1955 static void REGION_UnionO (WINEREGION *pReg, RECT *r1, RECT *r1End,
1956                            RECT *r2, RECT *r2End, INT top, INT bottom)
1957 {
1958     RECT *pNextRect;
1959     
1960     pNextRect = &pReg->rects[pReg->numRects];
1961
1962 #define MERGERECT(r) \
1963     if ((pReg->numRects != 0) &&  \
1964         (pNextRect[-1].top == top) &&  \
1965         (pNextRect[-1].bottom == bottom) &&  \
1966         (pNextRect[-1].right >= r->left))  \
1967     {  \
1968         if (pNextRect[-1].right < r->right)  \
1969         {  \
1970             pNextRect[-1].right = r->right;  \
1971         }  \
1972     }  \
1973     else  \
1974     {  \
1975         MEMCHECK(pReg, pNextRect, pReg->rects);  \
1976         pNextRect->top = top;  \
1977         pNextRect->bottom = bottom;  \
1978         pNextRect->left = r->left;  \
1979         pNextRect->right = r->right;  \
1980         pReg->numRects += 1;  \
1981         pNextRect += 1;  \
1982     }  \
1983     r++;
1984     
1985     while ((r1 != r1End) && (r2 != r2End))
1986     {
1987         if (r1->left < r2->left)
1988         {
1989             MERGERECT(r1);
1990         }
1991         else
1992         {
1993             MERGERECT(r2);
1994         }
1995     }
1996     
1997     if (r1 != r1End)
1998     {
1999         do
2000         {
2001             MERGERECT(r1);
2002         } while (r1 != r1End);
2003     }
2004     else while (r2 != r2End)
2005     {
2006         MERGERECT(r2);
2007     }
2008     return;
2009 }
2010
2011 /***********************************************************************
2012  *           REGION_UnionRegion
2013  */
2014 static void REGION_UnionRegion(WINEREGION *newReg, WINEREGION *reg1,
2015                                WINEREGION *reg2)
2016 {
2017     /*  checks all the simple cases */
2018
2019     /*
2020      * Region 1 and 2 are the same or region 1 is empty
2021      */
2022     if ( (reg1 == reg2) || (!(reg1->numRects)) )
2023     {
2024         if (newReg != reg2)
2025             REGION_CopyRegion(newReg, reg2);
2026         return;
2027     }
2028
2029     /*
2030      * if nothing to union (region 2 empty)
2031      */
2032     if (!(reg2->numRects))
2033     {
2034         if (newReg != reg1)
2035             REGION_CopyRegion(newReg, reg1);
2036         return;
2037     }
2038
2039     /*
2040      * Region 1 completely subsumes region 2
2041      */
2042     if ((reg1->numRects == 1) && 
2043         (reg1->extents.left <= reg2->extents.left) &&
2044         (reg1->extents.top <= reg2->extents.top) &&
2045         (reg1->extents.right >= reg2->extents.right) &&
2046         (reg1->extents.bottom >= reg2->extents.bottom))
2047     {
2048         if (newReg != reg1)
2049             REGION_CopyRegion(newReg, reg1);
2050         return;
2051     }
2052
2053     /*
2054      * Region 2 completely subsumes region 1
2055      */
2056     if ((reg2->numRects == 1) && 
2057         (reg2->extents.left <= reg1->extents.left) &&
2058         (reg2->extents.top <= reg1->extents.top) &&
2059         (reg2->extents.right >= reg1->extents.right) &&
2060         (reg2->extents.bottom >= reg1->extents.bottom))
2061     {
2062         if (newReg != reg2)
2063             REGION_CopyRegion(newReg, reg2);
2064         return;
2065     }
2066
2067     REGION_RegionOp (newReg, reg1, reg2, (voidProcp) REGION_UnionO, 
2068                 (voidProcp) REGION_UnionNonO, (voidProcp) REGION_UnionNonO);
2069
2070     newReg->extents.left = min(reg1->extents.left, reg2->extents.left);
2071     newReg->extents.top = min(reg1->extents.top, reg2->extents.top);
2072     newReg->extents.right = max(reg1->extents.right, reg2->extents.right);
2073     newReg->extents.bottom = max(reg1->extents.bottom, reg2->extents.bottom);
2074     newReg->type = (newReg->numRects) ?
2075                         ((newReg->numRects > 1) ? COMPLEXREGION : SIMPLEREGION)
2076                         : NULLREGION ;
2077     return;
2078 }
2079
2080 /***********************************************************************
2081  *           Region Subtraction
2082  ***********************************************************************/
2083
2084 /***********************************************************************
2085  *           REGION_SubtractNonO1
2086  *
2087  *      Deal with non-overlapping band for subtraction. Any parts from
2088  *      region 2 we discard. Anything from region 1 we add to the region.
2089  *
2090  * Results:
2091  *      None.
2092  *
2093  * Side Effects:
2094  *      pReg may be affected.
2095  *
2096  */
2097 static void REGION_SubtractNonO1 (WINEREGION *pReg, RECT *r, RECT *rEnd, 
2098                 INT top, INT bottom)
2099 {
2100     RECT *pNextRect;
2101         
2102     pNextRect = &pReg->rects[pReg->numRects];
2103         
2104     while (r != rEnd)
2105     {
2106         MEMCHECK(pReg, pNextRect, pReg->rects);
2107         pNextRect->left = r->left;
2108         pNextRect->top = top;
2109         pNextRect->right = r->right;
2110         pNextRect->bottom = bottom;
2111         pReg->numRects += 1;
2112         pNextRect++;
2113         r++;
2114     }
2115     return;
2116 }
2117
2118
2119 /***********************************************************************
2120  *           REGION_SubtractO
2121  *
2122  *      Overlapping band subtraction. x1 is the left-most point not yet
2123  *      checked.
2124  *
2125  * Results:
2126  *      None.
2127  *
2128  * Side Effects:
2129  *      pReg may have rectangles added to it.
2130  *
2131  */
2132 static void REGION_SubtractO (WINEREGION *pReg, RECT *r1, RECT *r1End, 
2133                 RECT *r2, RECT *r2End, INT top, INT bottom)
2134 {
2135     RECT *pNextRect;
2136     INT left;
2137     
2138     left = r1->left;
2139     pNextRect = &pReg->rects[pReg->numRects];
2140
2141     while ((r1 != r1End) && (r2 != r2End))
2142     {
2143         if (r2->right <= left)
2144         {
2145             /*
2146              * Subtrahend missed the boat: go to next subtrahend.
2147              */
2148             r2++;
2149         }
2150         else if (r2->left <= left)
2151         {
2152             /*
2153              * Subtrahend preceeds minuend: nuke left edge of minuend.
2154              */
2155             left = r2->right;
2156             if (left >= r1->right)
2157             {
2158                 /*
2159                  * Minuend completely covered: advance to next minuend and
2160                  * reset left fence to edge of new minuend.
2161                  */
2162                 r1++;
2163                 if (r1 != r1End)
2164                     left = r1->left;
2165             }
2166             else
2167             {
2168                 /*
2169                  * Subtrahend now used up since it doesn't extend beyond
2170                  * minuend
2171                  */
2172                 r2++;
2173             }
2174         }
2175         else if (r2->left < r1->right)
2176         {
2177             /*
2178              * Left part of subtrahend covers part of minuend: add uncovered
2179              * part of minuend to region and skip to next subtrahend.
2180              */
2181             MEMCHECK(pReg, pNextRect, pReg->rects);
2182             pNextRect->left = left;
2183             pNextRect->top = top;
2184             pNextRect->right = r2->left;
2185             pNextRect->bottom = bottom;
2186             pReg->numRects += 1;
2187             pNextRect++;
2188             left = r2->right;
2189             if (left >= r1->right)
2190             {
2191                 /*
2192                  * Minuend used up: advance to new...
2193                  */
2194                 r1++;
2195                 if (r1 != r1End)
2196                     left = r1->left;
2197             }
2198             else
2199             {
2200                 /*
2201                  * Subtrahend used up
2202                  */
2203                 r2++;
2204             }
2205         }
2206         else
2207         {
2208             /*
2209              * Minuend used up: add any remaining piece before advancing.
2210              */
2211             if (r1->right > left)
2212             {
2213                 MEMCHECK(pReg, pNextRect, pReg->rects);
2214                 pNextRect->left = left;
2215                 pNextRect->top = top;
2216                 pNextRect->right = r1->right;
2217                 pNextRect->bottom = bottom;
2218                 pReg->numRects += 1;
2219                 pNextRect++;
2220             }
2221             r1++;
2222             left = r1->left;
2223         }
2224     }
2225
2226     /*
2227      * Add remaining minuend rectangles to region.
2228      */
2229     while (r1 != r1End)
2230     {
2231         MEMCHECK(pReg, pNextRect, pReg->rects);
2232         pNextRect->left = left;
2233         pNextRect->top = top;
2234         pNextRect->right = r1->right;
2235         pNextRect->bottom = bottom;
2236         pReg->numRects += 1;
2237         pNextRect++;
2238         r1++;
2239         if (r1 != r1End)
2240         {
2241             left = r1->left;
2242         }
2243     }
2244     return;
2245 }
2246         
2247 /***********************************************************************
2248  *           REGION_SubtractRegion
2249  *
2250  *      Subtract regS from regM and leave the result in regD.
2251  *      S stands for subtrahend, M for minuend and D for difference.
2252  *
2253  * Results:
2254  *      TRUE.
2255  *
2256  * Side Effects:
2257  *      regD is overwritten.
2258  *
2259  */
2260 static void REGION_SubtractRegion(WINEREGION *regD, WINEREGION *regM,
2261                                                        WINEREGION *regS )
2262 {
2263    /* check for trivial reject */
2264     if ( (!(regM->numRects)) || (!(regS->numRects))  ||
2265         (!EXTENTCHECK(&regM->extents, &regS->extents)) )
2266     {
2267         REGION_CopyRegion(regD, regM);
2268         return;
2269     }
2270  
2271     REGION_RegionOp (regD, regM, regS, (voidProcp) REGION_SubtractO, 
2272                 (voidProcp) REGION_SubtractNonO1, (voidProcp) NULL);
2273
2274     /*
2275      * Can't alter newReg's extents before we call miRegionOp because
2276      * it might be one of the source regions and miRegionOp depends
2277      * on the extents of those regions being the unaltered. Besides, this
2278      * way there's no checking against rectangles that will be nuked
2279      * due to coalescing, so we have to examine fewer rectangles.
2280      */
2281     REGION_SetExtents (regD);
2282     regD->type = (regD->numRects) ?
2283                        ((regD->numRects > 1) ? COMPLEXREGION : SIMPLEREGION)
2284                        : NULLREGION ;
2285     return;
2286 }
2287
2288 /***********************************************************************
2289  *           REGION_XorRegion
2290  */
2291 static void REGION_XorRegion(WINEREGION *dr, WINEREGION *sra,
2292                                                         WINEREGION *srb)
2293 {
2294     WINEREGION *tra, *trb;
2295
2296     if ((! (tra = REGION_AllocWineRegion(sra->numRects + 1))) || 
2297         (! (trb = REGION_AllocWineRegion(srb->numRects + 1))))
2298         return;
2299     REGION_SubtractRegion(tra,sra,srb);
2300     REGION_SubtractRegion(trb,srb,sra);
2301     REGION_UnionRegion(dr,tra,trb);
2302     REGION_DestroyWineRegion(tra);
2303     REGION_DestroyWineRegion(trb);
2304     return;
2305 }
2306
2307 /**************************************************************************
2308  *
2309  *    Poly Regions
2310  * 
2311  *************************************************************************/
2312
2313 #define LARGE_COORDINATE  0x7fffffff /* FIXME */
2314 #define SMALL_COORDINATE  0x80000000
2315
2316 /***********************************************************************
2317  *     REGION_InsertEdgeInET
2318  *
2319  *     Insert the given edge into the edge table.
2320  *     First we must find the correct bucket in the
2321  *     Edge table, then find the right slot in the
2322  *     bucket.  Finally, we can insert it.
2323  *
2324  */
2325 static void REGION_InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE,
2326                 INT scanline, ScanLineListBlock **SLLBlock, INT *iSLLBlock)
2327
2328 {
2329     EdgeTableEntry *start, *prev;
2330     ScanLineList *pSLL, *pPrevSLL;
2331     ScanLineListBlock *tmpSLLBlock;
2332
2333     /*
2334      * find the right bucket to put the edge into
2335      */
2336     pPrevSLL = &ET->scanlines;
2337     pSLL = pPrevSLL->next;
2338     while (pSLL && (pSLL->scanline < scanline)) 
2339     {
2340         pPrevSLL = pSLL;
2341         pSLL = pSLL->next;
2342     }
2343
2344     /*
2345      * reassign pSLL (pointer to ScanLineList) if necessary
2346      */
2347     if ((!pSLL) || (pSLL->scanline > scanline)) 
2348     {
2349         if (*iSLLBlock > SLLSPERBLOCK-1) 
2350         {
2351             tmpSLLBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(ScanLineListBlock));
2352             if(!tmpSLLBlock)
2353             {
2354                 WARN("Can't alloc SLLB\n");
2355                 return;
2356             }
2357             (*SLLBlock)->next = tmpSLLBlock;
2358             tmpSLLBlock->next = (ScanLineListBlock *)NULL;
2359             *SLLBlock = tmpSLLBlock;
2360             *iSLLBlock = 0;
2361         }
2362         pSLL = &((*SLLBlock)->SLLs[(*iSLLBlock)++]);
2363
2364         pSLL->next = pPrevSLL->next;
2365         pSLL->edgelist = (EdgeTableEntry *)NULL;
2366         pPrevSLL->next = pSLL;
2367     }
2368     pSLL->scanline = scanline;
2369
2370     /*
2371      * now insert the edge in the right bucket
2372      */
2373     prev = (EdgeTableEntry *)NULL;
2374     start = pSLL->edgelist;
2375     while (start && (start->bres.minor_axis < ETE->bres.minor_axis)) 
2376     {
2377         prev = start;
2378         start = start->next;
2379     }
2380     ETE->next = start;
2381
2382     if (prev)
2383         prev->next = ETE;
2384     else
2385         pSLL->edgelist = ETE;
2386 }
2387
2388 /***********************************************************************
2389  *     REGION_CreateEdgeTable
2390  *
2391  *     This routine creates the edge table for
2392  *     scan converting polygons. 
2393  *     The Edge Table (ET) looks like:
2394  *
2395  *    EdgeTable
2396  *     --------
2397  *    |  ymax  |        ScanLineLists
2398  *    |scanline|-->------------>-------------->...
2399  *     --------   |scanline|   |scanline|
2400  *                |edgelist|   |edgelist|
2401  *                ---------    ---------
2402  *                    |             |
2403  *                    |             |
2404  *                    V             V
2405  *              list of ETEs   list of ETEs
2406  *
2407  *     where ETE is an EdgeTableEntry data structure,
2408  *     and there is one ScanLineList per scanline at
2409  *     which an edge is initially entered.
2410  *
2411  */
2412 static void REGION_CreateETandAET(const INT *Count, INT nbpolygons, 
2413             const POINT *pts, EdgeTable *ET, EdgeTableEntry *AET,
2414             EdgeTableEntry *pETEs, ScanLineListBlock *pSLLBlock)
2415 {
2416     const POINT *top, *bottom;
2417     const POINT *PrevPt, *CurrPt, *EndPt;
2418     INT poly, count;
2419     int iSLLBlock = 0;
2420     int dy;
2421
2422     
2423     /*
2424      *  initialize the Active Edge Table
2425      */
2426     AET->next = (EdgeTableEntry *)NULL;
2427     AET->back = (EdgeTableEntry *)NULL;
2428     AET->nextWETE = (EdgeTableEntry *)NULL;
2429     AET->bres.minor_axis = SMALL_COORDINATE;
2430
2431     /*
2432      *  initialize the Edge Table.
2433      */
2434     ET->scanlines.next = (ScanLineList *)NULL;
2435     ET->ymax = SMALL_COORDINATE;
2436     ET->ymin = LARGE_COORDINATE;
2437     pSLLBlock->next = (ScanLineListBlock *)NULL;
2438
2439     EndPt = pts - 1;
2440     for(poly = 0; poly < nbpolygons; poly++)
2441     {
2442         count = Count[poly];
2443         EndPt += count;
2444         if(count < 2)
2445             continue;
2446         
2447         PrevPt = EndPt;
2448
2449     /*
2450      *  for each vertex in the array of points.
2451      *  In this loop we are dealing with two vertices at
2452      *  a time -- these make up one edge of the polygon.
2453      */
2454         while (count--) 
2455         {
2456             CurrPt = pts++;
2457
2458         /*
2459          *  find out which point is above and which is below.
2460          */
2461             if (PrevPt->y > CurrPt->y) 
2462             {
2463                 bottom = PrevPt, top = CurrPt;
2464                 pETEs->ClockWise = 0;
2465             }
2466             else 
2467             {
2468                 bottom = CurrPt, top = PrevPt;
2469                 pETEs->ClockWise = 1;
2470             }
2471
2472         /*
2473          * don't add horizontal edges to the Edge table.
2474          */
2475             if (bottom->y != top->y) 
2476             {
2477                 pETEs->ymax = bottom->y-1;
2478                                 /* -1 so we don't get last scanline */
2479
2480             /*
2481              *  initialize integer edge algorithm
2482              */
2483                 dy = bottom->y - top->y;
2484                 BRESINITPGONSTRUCT(dy, top->x, bottom->x, pETEs->bres);
2485
2486                 REGION_InsertEdgeInET(ET, pETEs, top->y, &pSLLBlock, 
2487                                                                 &iSLLBlock);
2488
2489                 if (PrevPt->y > ET->ymax)
2490                   ET->ymax = PrevPt->y;
2491                 if (PrevPt->y < ET->ymin)
2492                   ET->ymin = PrevPt->y;
2493                 pETEs++;
2494             }
2495
2496             PrevPt = CurrPt;
2497         }
2498     }
2499 }
2500
2501 /***********************************************************************
2502  *     REGION_loadAET
2503  *
2504  *     This routine moves EdgeTableEntries from the
2505  *     EdgeTable into the Active Edge Table,
2506  *     leaving them sorted by smaller x coordinate.
2507  *
2508  */
2509 static void REGION_loadAET(EdgeTableEntry *AET, EdgeTableEntry *ETEs)
2510 {
2511     EdgeTableEntry *pPrevAET;
2512     EdgeTableEntry *tmp;
2513
2514     pPrevAET = AET;
2515     AET = AET->next;
2516     while (ETEs) 
2517     {
2518         while (AET && (AET->bres.minor_axis < ETEs->bres.minor_axis)) 
2519         {
2520             pPrevAET = AET;
2521             AET = AET->next;
2522         }
2523         tmp = ETEs->next;
2524         ETEs->next = AET;
2525         if (AET)
2526             AET->back = ETEs;
2527         ETEs->back = pPrevAET;
2528         pPrevAET->next = ETEs;
2529         pPrevAET = ETEs;
2530
2531         ETEs = tmp;
2532     }
2533 }
2534
2535 /***********************************************************************
2536  *     REGION_computeWAET
2537  *
2538  *     This routine links the AET by the
2539  *     nextWETE (winding EdgeTableEntry) link for
2540  *     use by the winding number rule.  The final 
2541  *     Active Edge Table (AET) might look something
2542  *     like:
2543  *
2544  *     AET
2545  *     ----------  ---------   ---------
2546  *     |ymax    |  |ymax    |  |ymax    | 
2547  *     | ...    |  |...     |  |...     |
2548  *     |next    |->|next    |->|next    |->...
2549  *     |nextWETE|  |nextWETE|  |nextWETE|
2550  *     ---------   ---------   ^--------
2551  *         |                   |       |
2552  *         V------------------->       V---> ...
2553  *
2554  */
2555 static void REGION_computeWAET(EdgeTableEntry *AET)
2556 {
2557     register EdgeTableEntry *pWETE;
2558     register int inside = 1;
2559     register int isInside = 0;
2560
2561     AET->nextWETE = (EdgeTableEntry *)NULL;
2562     pWETE = AET;
2563     AET = AET->next;
2564     while (AET) 
2565     {
2566         if (AET->ClockWise)
2567             isInside++;
2568         else
2569             isInside--;
2570
2571         if ((!inside && !isInside) ||
2572             ( inside &&  isInside)) 
2573         {
2574             pWETE->nextWETE = AET;
2575             pWETE = AET;
2576             inside = !inside;
2577         }
2578         AET = AET->next;
2579     }
2580     pWETE->nextWETE = (EdgeTableEntry *)NULL;
2581 }
2582
2583 /***********************************************************************
2584  *     REGION_InsertionSort
2585  *
2586  *     Just a simple insertion sort using
2587  *     pointers and back pointers to sort the Active
2588  *     Edge Table.
2589  *
2590  */
2591 static BOOL REGION_InsertionSort(EdgeTableEntry *AET)
2592 {
2593     EdgeTableEntry *pETEchase;
2594     EdgeTableEntry *pETEinsert;
2595     EdgeTableEntry *pETEchaseBackTMP;
2596     BOOL changed = FALSE;
2597
2598     AET = AET->next;
2599     while (AET) 
2600     {
2601         pETEinsert = AET;
2602         pETEchase = AET;
2603         while (pETEchase->back->bres.minor_axis > AET->bres.minor_axis)
2604             pETEchase = pETEchase->back;
2605
2606         AET = AET->next;
2607         if (pETEchase != pETEinsert) 
2608         {
2609             pETEchaseBackTMP = pETEchase->back;
2610             pETEinsert->back->next = AET;
2611             if (AET)
2612                 AET->back = pETEinsert->back;
2613             pETEinsert->next = pETEchase;
2614             pETEchase->back->next = pETEinsert;
2615             pETEchase->back = pETEinsert;
2616             pETEinsert->back = pETEchaseBackTMP;
2617             changed = TRUE;
2618         }
2619     }
2620     return changed;
2621 }
2622
2623 /***********************************************************************
2624  *     REGION_FreeStorage
2625  *
2626  *     Clean up our act.
2627  */
2628 static void REGION_FreeStorage(ScanLineListBlock *pSLLBlock)
2629 {
2630     ScanLineListBlock   *tmpSLLBlock;
2631
2632     while (pSLLBlock) 
2633     {
2634         tmpSLLBlock = pSLLBlock->next;
2635         HeapFree( GetProcessHeap(), 0, pSLLBlock );
2636         pSLLBlock = tmpSLLBlock;
2637     }
2638 }
2639
2640
2641 /***********************************************************************
2642  *     REGION_PtsToRegion
2643  *
2644  *     Create an array of rectangles from a list of points.
2645  */
2646 static int REGION_PtsToRegion(int numFullPtBlocks, int iCurPtBlock, 
2647                        POINTBLOCK *FirstPtBlock, WINEREGION *reg)
2648 {
2649     RECT *rects;
2650     POINT *pts;
2651     POINTBLOCK *CurPtBlock;
2652     int i;
2653     RECT *extents;
2654     INT numRects;
2655  
2656     extents = &reg->extents;
2657  
2658     numRects = ((numFullPtBlocks * NUMPTSTOBUFFER) + iCurPtBlock) >> 1;
2659  
2660     if (!(reg->rects = HeapReAlloc( GetProcessHeap(), 0, reg->rects, 
2661                            sizeof(RECT) * numRects )))
2662         return(0);
2663  
2664     reg->size = numRects;
2665     CurPtBlock = FirstPtBlock;
2666     rects = reg->rects - 1;
2667     numRects = 0;
2668     extents->left = LARGE_COORDINATE,  extents->right = SMALL_COORDINATE;
2669  
2670     for ( ; numFullPtBlocks >= 0; numFullPtBlocks--) {
2671         /* the loop uses 2 points per iteration */
2672         i = NUMPTSTOBUFFER >> 1;
2673         if (!numFullPtBlocks)
2674             i = iCurPtBlock >> 1;
2675         for (pts = CurPtBlock->pts; i--; pts += 2) {
2676             if (pts->x == pts[1].x)
2677                 continue;
2678             if (numRects && pts->x == rects->left && pts->y == rects->bottom &&
2679                 pts[1].x == rects->right &&
2680                 (numRects == 1 || rects[-1].top != rects->top) &&
2681                 (i && pts[2].y > pts[1].y)) {
2682                 rects->bottom = pts[1].y + 1;
2683                 continue;
2684             }
2685             numRects++;
2686             rects++;
2687             rects->left = pts->x;  rects->top = pts->y;
2688             rects->right = pts[1].x;  rects->bottom = pts[1].y + 1;
2689             if (rects->left < extents->left)
2690                 extents->left = rects->left;
2691             if (rects->right > extents->right)
2692                 extents->right = rects->right;
2693         }
2694         CurPtBlock = CurPtBlock->next;
2695     }
2696
2697     if (numRects) {
2698         extents->top = reg->rects->top;
2699         extents->bottom = rects->bottom;
2700     } else {
2701         extents->left = 0;
2702         extents->top = 0;
2703         extents->right = 0;
2704         extents->bottom = 0;
2705     }
2706     reg->numRects = numRects;
2707  
2708     return(TRUE);
2709 }
2710
2711 /***********************************************************************
2712  *           CreatePolyPolygonRgn    (GDI32.@)
2713  */
2714 HRGN WINAPI CreatePolyPolygonRgn(const POINT *Pts, const INT *Count, 
2715                       INT nbpolygons, INT mode)
2716 {
2717     HRGN hrgn;
2718     RGNOBJ *obj;
2719     WINEREGION *region;
2720     register EdgeTableEntry *pAET;   /* Active Edge Table       */
2721     register INT y;                /* current scanline        */
2722     register int iPts = 0;           /* number of pts in buffer */
2723     register EdgeTableEntry *pWETE;  /* Winding Edge Table Entry*/
2724     register ScanLineList *pSLL;     /* current scanLineList    */
2725     register POINT *pts;           /* output buffer           */
2726     EdgeTableEntry *pPrevAET;        /* ptr to previous AET     */
2727     EdgeTable ET;                    /* header node for ET      */
2728     EdgeTableEntry AET;              /* header node for AET     */
2729     EdgeTableEntry *pETEs;           /* EdgeTableEntries pool   */
2730     ScanLineListBlock SLLBlock;      /* header for scanlinelist */
2731     int fixWAET = FALSE;
2732     POINTBLOCK FirstPtBlock, *curPtBlock; /* PtBlock buffers    */
2733     POINTBLOCK *tmpPtBlock;
2734     int numFullPtBlocks = 0;
2735     INT poly, total;
2736
2737     if(!(hrgn = REGION_CreateRegion(nbpolygons)))
2738         return 0;
2739     obj = (RGNOBJ *) GDI_GetObjPtr( hrgn, REGION_MAGIC );
2740     region = obj->rgn;
2741
2742     /* special case a rectangle */
2743
2744     if (((nbpolygons == 1) && ((*Count == 4) ||
2745        ((*Count == 5) && (Pts[4].x == Pts[0].x) && (Pts[4].y == Pts[0].y)))) &&
2746         (((Pts[0].y == Pts[1].y) &&
2747           (Pts[1].x == Pts[2].x) &&
2748           (Pts[2].y == Pts[3].y) &&
2749           (Pts[3].x == Pts[0].x)) ||
2750          ((Pts[0].x == Pts[1].x) &&
2751           (Pts[1].y == Pts[2].y) &&
2752           (Pts[2].x == Pts[3].x) &&
2753           (Pts[3].y == Pts[0].y))))
2754     {
2755         SetRectRgn( hrgn, min(Pts[0].x, Pts[2].x), min(Pts[0].y, Pts[2].y), 
2756                             max(Pts[0].x, Pts[2].x), max(Pts[0].y, Pts[2].y) );
2757         GDI_ReleaseObj( hrgn );
2758         return hrgn;
2759     }
2760     
2761     for(poly = total = 0; poly < nbpolygons; poly++)
2762         total += Count[poly];
2763     if (! (pETEs = HeapAlloc( GetProcessHeap(), 0, sizeof(EdgeTableEntry) * total )))
2764     {
2765         REGION_DeleteObject( hrgn, obj );
2766         return 0;
2767     }
2768     pts = FirstPtBlock.pts;
2769     REGION_CreateETandAET(Count, nbpolygons, Pts, &ET, &AET, pETEs, &SLLBlock);
2770     pSLL = ET.scanlines.next;
2771     curPtBlock = &FirstPtBlock;
2772  
2773     if (mode != WINDING) {
2774         /*
2775          *  for each scanline
2776          */
2777         for (y = ET.ymin; y < ET.ymax; y++) {
2778             /*
2779              *  Add a new edge to the active edge table when we
2780              *  get to the next edge.
2781              */
2782             if (pSLL != NULL && y == pSLL->scanline) {
2783                 REGION_loadAET(&AET, pSLL->edgelist);
2784                 pSLL = pSLL->next;
2785             }
2786             pPrevAET = &AET;
2787             pAET = AET.next;
2788  
2789             /*
2790              *  for each active edge
2791              */
2792             while (pAET) {
2793                 pts->x = pAET->bres.minor_axis,  pts->y = y;
2794                 pts++, iPts++;
2795  
2796                 /*
2797                  *  send out the buffer
2798                  */
2799                 if (iPts == NUMPTSTOBUFFER) {
2800                     tmpPtBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(POINTBLOCK));
2801                     if(!tmpPtBlock) {
2802                         WARN("Can't alloc tPB\n");
2803                         return 0;
2804                     }
2805                     curPtBlock->next = tmpPtBlock;
2806                     curPtBlock = tmpPtBlock;
2807                     pts = curPtBlock->pts;
2808                     numFullPtBlocks++;
2809                     iPts = 0;
2810                 }
2811                 EVALUATEEDGEEVENODD(pAET, pPrevAET, y);
2812             }
2813             REGION_InsertionSort(&AET);
2814         }
2815     }
2816     else {
2817         /*
2818          *  for each scanline
2819          */
2820         for (y = ET.ymin; y < ET.ymax; y++) {
2821             /*
2822              *  Add a new edge to the active edge table when we
2823              *  get to the next edge.
2824              */
2825             if (pSLL != NULL && y == pSLL->scanline) {
2826                 REGION_loadAET(&AET, pSLL->edgelist);
2827                 REGION_computeWAET(&AET);
2828                 pSLL = pSLL->next;
2829             }
2830             pPrevAET = &AET;
2831             pAET = AET.next;
2832             pWETE = pAET;
2833  
2834             /*
2835              *  for each active edge
2836              */
2837             while (pAET) {
2838                 /*
2839                  *  add to the buffer only those edges that
2840                  *  are in the Winding active edge table.
2841                  */
2842                 if (pWETE == pAET) {
2843                     pts->x = pAET->bres.minor_axis,  pts->y = y;
2844                     pts++, iPts++;
2845  
2846                     /*
2847                      *  send out the buffer
2848                      */
2849                     if (iPts == NUMPTSTOBUFFER) {
2850                         tmpPtBlock = HeapAlloc( GetProcessHeap(), 0,
2851                                                sizeof(POINTBLOCK) );
2852                         if(!tmpPtBlock) {
2853                             WARN("Can't alloc tPB\n");
2854                             REGION_DeleteObject( hrgn, obj );
2855                             return 0;
2856                         }
2857                         curPtBlock->next = tmpPtBlock;
2858                         curPtBlock = tmpPtBlock;
2859                         pts = curPtBlock->pts;
2860                         numFullPtBlocks++;    iPts = 0;
2861                     }
2862                     pWETE = pWETE->nextWETE;
2863                 }
2864                 EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET);
2865             }
2866  
2867             /*
2868              *  recompute the winding active edge table if
2869              *  we just resorted or have exited an edge.
2870              */
2871             if (REGION_InsertionSort(&AET) || fixWAET) {
2872                 REGION_computeWAET(&AET);
2873                 fixWAET = FALSE;
2874             }
2875         }
2876     }
2877     REGION_FreeStorage(SLLBlock.next);  
2878     REGION_PtsToRegion(numFullPtBlocks, iPts, &FirstPtBlock, region);
2879     region->type = (region->numRects) ?
2880                         ((region->numRects > 1) ? COMPLEXREGION : SIMPLEREGION)
2881                         : NULLREGION;
2882
2883     for (curPtBlock = FirstPtBlock.next; --numFullPtBlocks >= 0;) {
2884         tmpPtBlock = curPtBlock->next;
2885         HeapFree( GetProcessHeap(), 0, curPtBlock );
2886         curPtBlock = tmpPtBlock;
2887     }
2888     HeapFree( GetProcessHeap(), 0, pETEs );
2889     GDI_ReleaseObj( hrgn );
2890     return hrgn;
2891 }
2892
2893
2894 /***********************************************************************
2895  *           CreatePolygonRgn    (GDI.63)
2896  */
2897 HRGN16 WINAPI CreatePolygonRgn16( const POINT16 * points, INT16 count,
2898                                   INT16 mode )
2899 {
2900     return CreatePolyPolygonRgn16( points, &count, 1, mode );
2901 }
2902
2903 /***********************************************************************
2904  *           CreatePolyPolygonRgn    (GDI.451)
2905  */
2906 HRGN16 WINAPI CreatePolyPolygonRgn16( const POINT16 *points,
2907                 const INT16 *count, INT16 nbpolygons, INT16 mode )
2908 {
2909     HRGN hrgn;
2910     int i, npts = 0;
2911     INT *count32;
2912     POINT *points32;
2913
2914     for (i = 0; i < nbpolygons; i++)
2915         npts += count[i];
2916     points32 = HeapAlloc( GetProcessHeap(), 0, npts * sizeof(POINT) );
2917     for (i = 0; i < npts; i++)
2918         CONV_POINT16TO32( &(points[i]), &(points32[i]) );
2919
2920     count32 = HeapAlloc( GetProcessHeap(), 0, nbpolygons * sizeof(INT) );
2921     for (i = 0; i < nbpolygons; i++)
2922         count32[i] = count[i];
2923     hrgn = CreatePolyPolygonRgn( points32, count32, nbpolygons, mode );
2924     HeapFree( GetProcessHeap(), 0, count32 );
2925     HeapFree( GetProcessHeap(), 0, points32 );
2926     return hrgn;
2927 }
2928
2929 /***********************************************************************
2930  *           CreatePolygonRgn    (GDI32.@)
2931  */
2932 HRGN WINAPI CreatePolygonRgn( const POINT *points, INT count,
2933                                   INT mode )
2934 {
2935     return CreatePolyPolygonRgn( points, &count, 1, mode );
2936 }
2937
2938
2939 /***********************************************************************
2940  * GetRandomRgn [GDI32.@]
2941  *
2942  * NOTES
2943  *     This function is documented in MSDN online
2944  */
2945 INT WINAPI GetRandomRgn(HDC hDC, HRGN hRgn, DWORD dwCode)
2946 {
2947     switch (dwCode)
2948     {
2949         case 4: /* == SYSRGN ? */
2950         {
2951             DC *dc = DC_GetDCPtr (hDC);
2952             OSVERSIONINFOA vi;
2953             POINT org;
2954
2955             if (!dc) return -1;
2956             CombineRgn (hRgn, dc->hVisRgn, 0, RGN_COPY);
2957             /*
2958              *     On Windows NT/2000,
2959              *           the region returned is in screen coordinates.
2960              *     On Windows 95/98, 
2961              *           the region returned is in window coordinates
2962              */
2963             vi.dwOSVersionInfoSize = sizeof(vi);
2964             if (GetVersionExA( &vi ) && vi.dwPlatformId == VER_PLATFORM_WIN32_NT)
2965                 GetDCOrgEx(hDC, &org);
2966             else
2967                 org.x = org.y = 0;
2968             org.x -= dc->DCOrgX;
2969             org.y -= dc->DCOrgY;
2970             OffsetRgn (hRgn, org.x, org.y);
2971             GDI_ReleaseObj( hDC );
2972             return 1;
2973         }
2974 /*      case 1:
2975             return GetClipRgn (hDC, hRgn);
2976 */
2977         default:
2978             WARN("Unknown dwCode %ld\n", dwCode);
2979             return -1;
2980     }
2981
2982     return -1;
2983 }
2984
2985 /***********************************************************************
2986  *           REGION_CropAndOffsetRegion
2987  */
2988 static BOOL REGION_CropAndOffsetRegion(const POINT* off, const RECT *rect, WINEREGION *rgnSrc, WINEREGION* rgnDst)
2989 {
2990
2991     if( !rect ) /* just copy and offset */
2992     {
2993         RECT *xrect;
2994         if( rgnDst == rgnSrc )
2995         {
2996             if( off->x || off->y )
2997                 xrect = rgnDst->rects;
2998             else 
2999                 return TRUE;
3000         }
3001         else
3002             xrect = HeapReAlloc( GetProcessHeap(), 0, rgnDst->rects,
3003                                 rgnSrc->size * sizeof( RECT ));
3004         if( xrect )
3005         {
3006             INT i;
3007
3008             if( rgnDst != rgnSrc )
3009                 memcpy( rgnDst, rgnSrc, sizeof( WINEREGION ));
3010
3011             if( off->x || off->y )
3012             {
3013                 for( i = 0; i < rgnDst->numRects; i++ )
3014                 {
3015                     xrect[i].left = rgnSrc->rects[i].left + off->x;
3016                     xrect[i].right = rgnSrc->rects[i].right + off->x;
3017                     xrect[i].top = rgnSrc->rects[i].top + off->y;
3018                     xrect[i].bottom = rgnSrc->rects[i].bottom + off->y;
3019                 }
3020                 rgnDst->extents.left   += off->x;
3021                 rgnDst->extents.right  += off->x;
3022                 rgnDst->extents.top    += off->y;
3023                 rgnDst->extents.bottom += off->y;
3024             }
3025             else
3026                 memcpy( xrect, rgnSrc->rects, rgnDst->numRects * sizeof(RECT));
3027             rgnDst->rects = xrect;
3028         } else
3029             return FALSE;
3030     }
3031     else if ((rect->left >= rect->right) ||
3032              (rect->top >= rect->bottom) ||
3033              !EXTENTCHECK(rect, &rgnSrc->extents))
3034     {
3035 empty:
3036         if( !rgnDst->rects )
3037         {
3038             rgnDst->rects = HeapAlloc(GetProcessHeap(), 0, RGN_DEFAULT_RECTS * sizeof( RECT ));
3039             if( rgnDst->rects )
3040                 rgnDst->size = RGN_DEFAULT_RECTS;
3041             else
3042                 return FALSE;
3043         }
3044
3045         TRACE("cropped to empty!\n");
3046         EMPTY_REGION(rgnDst);
3047     }
3048     else /* region box and clipping rect appear to intersect */
3049     {
3050         RECT *lpr;
3051         INT i, j, clipa, clipb;
3052         INT left = rgnSrc->extents.right + off->x;
3053         INT right = rgnSrc->extents.left + off->x;
3054
3055         for( clipa = 0; rgnSrc->rects[clipa].bottom <= rect->top; clipa++ )
3056              ; /* skip bands above the clipping rectangle */
3057
3058         for( clipb = clipa; clipb < rgnSrc->numRects; clipb++ )
3059              if( rgnSrc->rects[clipb].top >= rect->bottom )
3060                  break;    /* and below it */
3061
3062         /* clipa - index of the first rect in the first intersecting band
3063          * clipb - index of the last rect in the last intersecting band
3064          */
3065
3066         if((rgnDst != rgnSrc) && (rgnDst->size < (i = (clipb - clipa))))
3067         {
3068             rgnDst->rects = HeapReAlloc( GetProcessHeap(), 0, 
3069                                 rgnDst->rects, i * sizeof(RECT));
3070             if( !rgnDst->rects ) return FALSE;
3071             rgnDst->size = i;
3072         }
3073
3074         if( TRACE_ON(region) )
3075         {
3076             REGION_DumpRegion( rgnSrc );
3077             TRACE("\tclipa = %i, clipb = %i\n", clipa, clipb );
3078         }
3079
3080         for( i = clipa, j = 0; i < clipb ; i++ )
3081         {
3082              /* i - src index, j - dst index, j is always <= i for obvious reasons */
3083
3084              lpr = rgnSrc->rects + i;
3085              if( lpr->left < rect->right && lpr->right > rect->left )
3086              {
3087                  rgnDst->rects[j].top = lpr->top + off->y;
3088                  rgnDst->rects[j].bottom = lpr->bottom + off->y;
3089                  rgnDst->rects[j].left = ((lpr->left > rect->left) ? lpr->left : rect->left) + off->x;
3090                  rgnDst->rects[j].right = ((lpr->right < rect->right) ? lpr->right : rect->right) + off->x;
3091
3092                  if( rgnDst->rects[j].left < left ) left = rgnDst->rects[j].left;
3093                  if( rgnDst->rects[j].right > right ) right = rgnDst->rects[j].right;
3094
3095                  j++;
3096              }
3097         }
3098
3099         if( j == 0 ) goto empty;
3100
3101         rgnDst->extents.left = left;
3102         rgnDst->extents.right = right;
3103
3104         left = rect->top + off->y;
3105         right = rect->bottom + off->y;
3106
3107         rgnDst->numRects = j--;
3108         for( i = 0; i <= j; i++ )       /* fixup top band */
3109              if( rgnDst->rects[i].top < left )
3110                  rgnDst->rects[i].top = left;
3111              else
3112                  break;
3113
3114         for( i = j; i >= 0; i-- )       /* fixup bottom band */
3115              if( rgnDst->rects[i].bottom > right )
3116                  rgnDst->rects[i].bottom = right;
3117              else
3118                  break;
3119
3120         rgnDst->extents.top = rgnDst->rects[0].top;
3121         rgnDst->extents.bottom = rgnDst->rects[j].bottom;
3122
3123         rgnDst->type = (j >= 1) ? COMPLEXREGION : SIMPLEREGION;
3124
3125         if( TRACE_ON(region) )
3126         {
3127             TRACE("result:\n");
3128             REGION_DumpRegion( rgnDst );
3129         }
3130     }
3131
3132     return TRUE;
3133 }
3134
3135 /***********************************************************************
3136  *           REGION_CropRgn
3137  *
3138  *
3139  * hSrc:        Region to crop and offset.
3140  * lpRect:      Clipping rectangle. Can be NULL (no clipping).
3141  * lpPt:        Points to offset the cropped region. Can be NULL (no offset).
3142  *
3143  * hDst: Region to hold the result (a new region is created if it's 0).
3144  *       Allowed to be the same region as hSrc in which case everything
3145  *       will be done in place, with no memory reallocations.
3146  *
3147  * Returns: hDst if success, 0 otherwise.
3148  */
3149 HRGN REGION_CropRgn( HRGN hDst, HRGN hSrc, const RECT *lpRect, const POINT *lpPt )
3150 {
3151 /*  Optimization of the following generic code:
3152
3153     HRGN h; 
3154
3155     if( lpRect ) 
3156         h = CreateRectRgn( lpRect->left, lpRect->top, lpRect->right, lpRect->bottom );
3157     else
3158         h = CreateRectRgn( 0, 0, 0, 0 );
3159     if( hDst == 0 ) hDst = h;
3160     if( lpRect )
3161         CombineRgn( hDst, hSrc, h, RGN_AND );
3162     else
3163         CombineRgn( hDst, hSrc, 0, RGN_COPY );
3164     if( lpPt )
3165         OffsetRgn( hDst, lpPt->x, lpPt->y );
3166     if( hDst != h )
3167         DeleteObject( h );
3168     return hDst;
3169
3170 */
3171
3172     RGNOBJ *objSrc = (RGNOBJ *) GDI_GetObjPtr( hSrc, REGION_MAGIC );
3173
3174     if(objSrc)
3175     {
3176         RGNOBJ *objDst;
3177         WINEREGION *rgnDst;
3178
3179         if( hDst )
3180         {
3181             if (!(objDst = (RGNOBJ *) GDI_GetObjPtr( hDst, REGION_MAGIC )))
3182             {
3183                hDst = 0;
3184                goto done;
3185             }
3186             rgnDst = objDst->rgn;
3187         }
3188         else
3189         {
3190             if ((rgnDst = HeapAlloc(GetProcessHeap(), 0, sizeof( WINEREGION ))))
3191             {
3192                 rgnDst->size = rgnDst->numRects = 0;
3193                 rgnDst->rects = NULL;   /* back end will allocate exact number */
3194             }
3195         }
3196
3197         if( rgnDst )
3198         {
3199             POINT pt = { 0, 0 };
3200
3201             if( !lpPt ) lpPt = &pt;
3202
3203             if( lpRect )
3204                 TRACE("src %p -> dst %p (%i,%i)-(%i,%i) by (%li,%li)\n", objSrc->rgn, rgnDst,
3205                       lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, lpPt->x, lpPt->y );
3206             else
3207                 TRACE("src %p -> dst %p by (%li,%li)\n", objSrc->rgn, rgnDst, lpPt->x, lpPt->y ); 
3208
3209             if( REGION_CropAndOffsetRegion( lpPt, lpRect, objSrc->rgn, rgnDst ) == FALSE )
3210             {
3211                 if( hDst ) /* existing rgn */
3212                 {
3213                     GDI_ReleaseObj(hDst);
3214                     hDst = 0;
3215                     goto done;
3216                 }
3217                 goto fail;
3218             }
3219             else if( hDst == 0 )
3220             {
3221                 if (!(objDst = GDI_AllocObject( sizeof(RGNOBJ), REGION_MAGIC, &hDst )))
3222                 {
3223 fail:
3224                     if( rgnDst->rects )
3225                         HeapFree( GetProcessHeap(), 0, rgnDst->rects );
3226                     HeapFree( GetProcessHeap(), 0, rgnDst );
3227                     goto done;
3228                 }
3229                 objDst->rgn = rgnDst;
3230             }
3231
3232             GDI_ReleaseObj(hDst);
3233         }
3234         else hDst = 0;
3235 done:
3236         GDI_ReleaseObj(hSrc);
3237         return hDst;
3238     }
3239     return 0;
3240 }
3241
3242 /***********************************************************************
3243  *           GetMetaRgn    (GDI32.@)
3244  */
3245 INT WINAPI GetMetaRgn( HDC hdc, HRGN hRgn )
3246 {
3247   FIXME( "stub\n" );
3248
3249   return 0;
3250 }
3251
3252
3253 /***********************************************************************
3254  *           SetMetaRgn    (GDI32.@)
3255  */
3256 INT WINAPI SetMetaRgn( HDC hdc )
3257 {
3258   FIXME( "stub\n" );
3259
3260   return ERROR;
3261 }