include: Assorted spelling fixes.
[wine] / dlls / gdi32 / region.c
1 /*
2  * GDI region objects. Shamelessly ripped out from the X11 distribution
3  * Thanks for the nice license.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 <stdarg.h>
98 #include <stdlib.h>
99 #include <string.h>
100 #include "windef.h"
101 #include "winbase.h"
102 #include "wingdi.h"
103 #include "gdi_private.h"
104 #include "wine/debug.h"
105
106 WINE_DEFAULT_DEBUG_CHANNEL(region);
107
108
109 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc );
110 static BOOL REGION_DeleteObject( HGDIOBJ handle );
111
112 static const struct gdi_obj_funcs region_funcs =
113 {
114     REGION_SelectObject,  /* pSelectObject */
115     NULL,                 /* pGetObjectA */
116     NULL,                 /* pGetObjectW */
117     NULL,                 /* pUnrealizeObject */
118     REGION_DeleteObject   /* pDeleteObject */
119 };
120
121 /*  1 if two RECTs overlap.
122  *  0 if two RECTs do not overlap.
123  */
124 #define EXTENTCHECK(r1, r2) \
125         ((r1)->right > (r2)->left && \
126          (r1)->left < (r2)->right && \
127          (r1)->bottom > (r2)->top && \
128          (r1)->top < (r2)->bottom)
129
130
131 static BOOL add_rect( WINEREGION *reg, INT left, INT top, INT right, INT bottom )
132 {
133     RECT *rect;
134     if (reg->numRects >= reg->size)
135     {
136         RECT *newrects = HeapReAlloc( GetProcessHeap(), 0, reg->rects, 2 * sizeof(RECT) * reg->size );
137         if (!newrects) return FALSE;
138         reg->rects = newrects;
139         reg->size *= 2;
140     }
141     rect = reg->rects + reg->numRects++;
142     rect->left = left;
143     rect->top = top;
144     rect->right = right;
145     rect->bottom = bottom;
146     return TRUE;
147 }
148
149 #define EMPTY_REGION(pReg) do { \
150     (pReg)->numRects = 0; \
151     (pReg)->extents.left = (pReg)->extents.top = 0; \
152     (pReg)->extents.right = (pReg)->extents.bottom = 0; \
153  } while(0)
154
155 #define INRECT(r, x, y) \
156       ( ( ((r).right >  x)) && \
157         ( ((r).left <= x)) && \
158         ( ((r).bottom >  y)) && \
159         ( ((r).top <= y)) )
160
161
162 /*
163  * number of points to buffer before sending them off
164  * to scanlines() :  Must be an even number
165  */
166 #define NUMPTSTOBUFFER 200
167
168 /*
169  * used to allocate buffers for points and link
170  * the buffers together
171  */
172
173 typedef struct _POINTBLOCK {
174     POINT pts[NUMPTSTOBUFFER];
175     struct _POINTBLOCK *next;
176 } POINTBLOCK;
177
178
179
180 /*
181  *     This file contains a few macros to help track
182  *     the edge of a filled object.  The object is assumed
183  *     to be filled in scanline order, and thus the
184  *     algorithm used is an extension of Bresenham's line
185  *     drawing algorithm which assumes that y is always the
186  *     major axis.
187  *     Since these pieces of code are the same for any filled shape,
188  *     it is more convenient to gather the library in one
189  *     place, but since these pieces of code are also in
190  *     the inner loops of output primitives, procedure call
191  *     overhead is out of the question.
192  *     See the author for a derivation if needed.
193  */
194
195
196 /*
197  *  In scan converting polygons, we want to choose those pixels
198  *  which are inside the polygon.  Thus, we add .5 to the starting
199  *  x coordinate for both left and right edges.  Now we choose the
200  *  first pixel which is inside the pgon for the left edge and the
201  *  first pixel which is outside the pgon for the right edge.
202  *  Draw the left pixel, but not the right.
203  *
204  *  How to add .5 to the starting x coordinate:
205  *      If the edge is moving to the right, then subtract dy from the
206  *  error term from the general form of the algorithm.
207  *      If the edge is moving to the left, then add dy to the error term.
208  *
209  *  The reason for the difference between edges moving to the left
210  *  and edges moving to the right is simple:  If an edge is moving
211  *  to the right, then we want the algorithm to flip immediately.
212  *  If it is moving to the left, then we don't want it to flip until
213  *  we traverse an entire pixel.
214  */
215 #define BRESINITPGON(dy, x1, x2, xStart, d, m, m1, incr1, incr2) { \
216     int dx;      /* local storage */ \
217 \
218     /* \
219      *  if the edge is horizontal, then it is ignored \
220      *  and assumed not to be processed.  Otherwise, do this stuff. \
221      */ \
222     if ((dy) != 0) { \
223         xStart = (x1); \
224         dx = (x2) - xStart; \
225         if (dx < 0) { \
226             m = dx / (dy); \
227             m1 = m - 1; \
228             incr1 = -2 * dx + 2 * (dy) * m1; \
229             incr2 = -2 * dx + 2 * (dy) * m; \
230             d = 2 * m * (dy) - 2 * dx - 2 * (dy); \
231         } else { \
232             m = dx / (dy); \
233             m1 = m + 1; \
234             incr1 = 2 * dx - 2 * (dy) * m1; \
235             incr2 = 2 * dx - 2 * (dy) * m; \
236             d = -2 * m * (dy) + 2 * dx; \
237         } \
238     } \
239 }
240
241 #define BRESINCRPGON(d, minval, m, m1, incr1, incr2) { \
242     if (m1 > 0) { \
243         if (d > 0) { \
244             minval += m1; \
245             d += incr1; \
246         } \
247         else { \
248             minval += m; \
249             d += incr2; \
250         } \
251     } else {\
252         if (d >= 0) { \
253             minval += m1; \
254             d += incr1; \
255         } \
256         else { \
257             minval += m; \
258             d += incr2; \
259         } \
260     } \
261 }
262
263 /*
264  *     This structure contains all of the information needed
265  *     to run the bresenham algorithm.
266  *     The variables may be hardcoded into the declarations
267  *     instead of using this structure to make use of
268  *     register declarations.
269  */
270 typedef struct {
271     INT minor_axis;     /* minor axis        */
272     INT d;              /* decision variable */
273     INT m, m1;          /* slope and slope+1 */
274     INT incr1, incr2;   /* error increments */
275 } BRESINFO;
276
277
278 #define BRESINITPGONSTRUCT(dmaj, min1, min2, bres) \
279         BRESINITPGON(dmaj, min1, min2, bres.minor_axis, bres.d, \
280                      bres.m, bres.m1, bres.incr1, bres.incr2)
281
282 #define BRESINCRPGONSTRUCT(bres) \
283         BRESINCRPGON(bres.d, bres.minor_axis, bres.m, bres.m1, bres.incr1, bres.incr2)
284
285
286
287 /*
288  *     These are the data structures needed to scan
289  *     convert regions.  Two different scan conversion
290  *     methods are available -- the even-odd method, and
291  *     the winding number method.
292  *     The even-odd rule states that a point is inside
293  *     the polygon if a ray drawn from that point in any
294  *     direction will pass through an odd number of
295  *     path segments.
296  *     By the winding number rule, a point is decided
297  *     to be inside the polygon if a ray drawn from that
298  *     point in any direction passes through a different
299  *     number of clockwise and counter-clockwise path
300  *     segments.
301  *
302  *     These data structures are adapted somewhat from
303  *     the algorithm in (Foley/Van Dam) for scan converting
304  *     polygons.
305  *     The basic algorithm is to start at the top (smallest y)
306  *     of the polygon, stepping down to the bottom of
307  *     the polygon by incrementing the y coordinate.  We
308  *     keep a list of edges which the current scanline crosses,
309  *     sorted by x.  This list is called the Active Edge Table (AET)
310  *     As we change the y-coordinate, we update each entry in
311  *     in the active edge table to reflect the edges new xcoord.
312  *     This list must be sorted at each scanline in case
313  *     two edges intersect.
314  *     We also keep a data structure known as the Edge Table (ET),
315  *     which keeps track of all the edges which the current
316  *     scanline has not yet reached.  The ET is basically a
317  *     list of ScanLineList structures containing a list of
318  *     edges which are entered at a given scanline.  There is one
319  *     ScanLineList per scanline at which an edge is entered.
320  *     When we enter a new edge, we move it from the ET to the AET.
321  *
322  *     From the AET, we can implement the even-odd rule as in
323  *     (Foley/Van Dam).
324  *     The winding number rule is a little trickier.  We also
325  *     keep the EdgeTableEntries in the AET linked by the
326  *     nextWETE (winding EdgeTableEntry) link.  This allows
327  *     the edges to be linked just as before for updating
328  *     purposes, but only uses the edges linked by the nextWETE
329  *     link as edges representing spans of the polygon to
330  *     drawn (as with the even-odd rule).
331  */
332
333 /*
334  * for the winding number rule
335  */
336 #define CLOCKWISE          1
337 #define COUNTERCLOCKWISE  -1
338
339 typedef struct _EdgeTableEntry {
340      INT ymax;           /* ycoord at which we exit this edge. */
341      BRESINFO bres;        /* Bresenham info to run the edge     */
342      struct _EdgeTableEntry *next;       /* next in the list     */
343      struct _EdgeTableEntry *back;       /* for insertion sort   */
344      struct _EdgeTableEntry *nextWETE;   /* for winding num rule */
345      int ClockWise;        /* flag for winding number rule       */
346 } EdgeTableEntry;
347
348
349 typedef struct _ScanLineList{
350      INT scanline;            /* the scanline represented */
351      EdgeTableEntry *edgelist;  /* header node              */
352      struct _ScanLineList *next;  /* next in the list       */
353 } ScanLineList;
354
355
356 typedef struct {
357      INT ymax;               /* ymax for the polygon     */
358      INT ymin;               /* ymin for the polygon     */
359      ScanLineList scanlines;   /* header node              */
360 } EdgeTable;
361
362
363 /*
364  * Here is a struct to help with storage allocation
365  * so we can allocate a big chunk at a time, and then take
366  * pieces from this heap when we need to.
367  */
368 #define SLLSPERBLOCK 25
369
370 typedef struct _ScanLineListBlock {
371      ScanLineList SLLs[SLLSPERBLOCK];
372      struct _ScanLineListBlock *next;
373 } ScanLineListBlock;
374
375
376 /*
377  *
378  *     a few macros for the inner loops of the fill code where
379  *     performance considerations don't allow a procedure call.
380  *
381  *     Evaluate the given edge at the given scanline.
382  *     If the edge has expired, then we leave it and fix up
383  *     the active edge table; otherwise, we increment the
384  *     x value to be ready for the next scanline.
385  *     The winding number rule is in effect, so we must notify
386  *     the caller when the edge has been removed so he
387  *     can reorder the Winding Active Edge Table.
388  */
389 #define EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET) { \
390    if (pAET->ymax == y) {          /* leaving this edge */ \
391       pPrevAET->next = pAET->next; \
392       pAET = pPrevAET->next; \
393       fixWAET = 1; \
394       if (pAET) \
395          pAET->back = pPrevAET; \
396    } \
397    else { \
398       BRESINCRPGONSTRUCT(pAET->bres); \
399       pPrevAET = pAET; \
400       pAET = pAET->next; \
401    } \
402 }
403
404
405 /*
406  *     Evaluate the given edge at the given scanline.
407  *     If the edge has expired, then we leave it and fix up
408  *     the active edge table; otherwise, we increment the
409  *     x value to be ready for the next scanline.
410  *     The even-odd rule is in effect.
411  */
412 #define EVALUATEEDGEEVENODD(pAET, pPrevAET, y) { \
413    if (pAET->ymax == y) {          /* leaving this edge */ \
414       pPrevAET->next = pAET->next; \
415       pAET = pPrevAET->next; \
416       if (pAET) \
417          pAET->back = pPrevAET; \
418    } \
419    else { \
420       BRESINCRPGONSTRUCT(pAET->bres); \
421       pPrevAET = pAET; \
422       pAET = pAET->next; \
423    } \
424 }
425
426 /* Note the parameter order is different from the X11 equivalents */
427
428 static BOOL REGION_CopyRegion(WINEREGION *d, WINEREGION *s);
429 static BOOL REGION_OffsetRegion(WINEREGION *d, WINEREGION *s, INT x, INT y);
430 static BOOL REGION_IntersectRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
431 static BOOL REGION_UnionRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
432 static BOOL REGION_SubtractRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
433 static BOOL REGION_XorRegion(WINEREGION *d, WINEREGION *s1, WINEREGION *s2);
434 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn);
435
436 #define RGN_DEFAULT_RECTS       2
437
438
439 /***********************************************************************
440  *            get_region_type
441  */
442 static inline INT get_region_type( const WINEREGION *obj )
443 {
444     switch(obj->numRects)
445     {
446     case 0:  return NULLREGION;
447     case 1:  return SIMPLEREGION;
448     default: return COMPLEXREGION;
449     }
450 }
451
452
453 /***********************************************************************
454  *            REGION_DumpRegion
455  *            Outputs the contents of a WINEREGION
456  */
457 static void REGION_DumpRegion(WINEREGION *pReg)
458 {
459     RECT *pRect, *pRectEnd = pReg->rects + pReg->numRects;
460
461     TRACE("Region %p: %d,%d - %d,%d %d rects\n", pReg,
462             pReg->extents.left, pReg->extents.top,
463             pReg->extents.right, pReg->extents.bottom, pReg->numRects);
464     for(pRect = pReg->rects; pRect < pRectEnd; pRect++)
465         TRACE("\t%d,%d - %d,%d\n", pRect->left, pRect->top,
466                        pRect->right, pRect->bottom);
467     return;
468 }
469
470
471 /***********************************************************************
472  *            init_region
473  *
474  * Initialize a new empty region.
475  */
476 static BOOL init_region( WINEREGION *pReg, INT n )
477 {
478     if (!(pReg->rects = HeapAlloc(GetProcessHeap(), 0, n * sizeof( RECT )))) return FALSE;
479     pReg->size = n;
480     EMPTY_REGION(pReg);
481     return TRUE;
482 }
483
484 /***********************************************************************
485  *           destroy_region
486  */
487 static void destroy_region( WINEREGION *pReg )
488 {
489     HeapFree( GetProcessHeap(), 0, pReg->rects );
490 }
491
492 /***********************************************************************
493  *           REGION_DeleteObject
494  */
495 static BOOL REGION_DeleteObject( HGDIOBJ handle )
496 {
497     WINEREGION *rgn = free_gdi_handle( handle );
498
499     if (!rgn) return FALSE;
500     HeapFree( GetProcessHeap(), 0, rgn->rects );
501     HeapFree( GetProcessHeap(), 0, rgn );
502     return TRUE;
503 }
504
505 /***********************************************************************
506  *           REGION_SelectObject
507  */
508 static HGDIOBJ REGION_SelectObject( HGDIOBJ handle, HDC hdc )
509 {
510     return ULongToHandle(SelectClipRgn( hdc, handle ));
511 }
512
513
514 /***********************************************************************
515  *           REGION_OffsetRegion
516  *           Offset a WINEREGION by x,y
517  */
518 static BOOL REGION_OffsetRegion( WINEREGION *rgn, WINEREGION *srcrgn, INT x, INT y )
519 {
520     if( rgn != srcrgn)
521     {
522         if (!REGION_CopyRegion( rgn, srcrgn)) return FALSE;
523     }
524     if(x || y) {
525         int nbox = rgn->numRects;
526         RECT *pbox = rgn->rects;
527
528         if(nbox) {
529             while(nbox--) {
530                 pbox->left += x;
531                 pbox->right += x;
532                 pbox->top += y;
533                 pbox->bottom += y;
534                 pbox++;
535             }
536             rgn->extents.left += x;
537             rgn->extents.right += x;
538             rgn->extents.top += y;
539             rgn->extents.bottom += y;
540         }
541     }
542     return TRUE;
543 }
544
545 /***********************************************************************
546  *           OffsetRgn   (GDI32.@)
547  *
548  * Moves a region by the specified X- and Y-axis offsets.
549  *
550  * PARAMS
551  *   hrgn [I] Region to offset.
552  *   x    [I] Offset right if positive or left if negative.
553  *   y    [I] Offset down if positive or up if negative.
554  *
555  * RETURNS
556  *   Success:
557  *     NULLREGION - The new region is empty.
558  *     SIMPLEREGION - The new region can be represented by one rectangle.
559  *     COMPLEXREGION - The new region can only be represented by more than
560  *                     one rectangle.
561  *   Failure: ERROR
562  */
563 INT WINAPI OffsetRgn( HRGN hrgn, INT x, INT y )
564 {
565     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
566     INT ret;
567
568     TRACE("%p %d,%d\n", hrgn, x, y);
569
570     if (!obj)
571         return ERROR;
572
573     REGION_OffsetRegion( obj, obj, x, y);
574
575     ret = get_region_type( obj );
576     GDI_ReleaseObj( hrgn );
577     return ret;
578 }
579
580
581 /***********************************************************************
582  *           GetRgnBox    (GDI32.@)
583  *
584  * Retrieves the bounding rectangle of the region. The bounding rectangle
585  * is the smallest rectangle that contains the entire region.
586  *
587  * PARAMS
588  *   hrgn [I] Region to retrieve bounding rectangle from.
589  *   rect [O] Rectangle that will receive the coordinates of the bounding
590  *            rectangle.
591  *
592  * RETURNS
593  *     NULLREGION - The new region is empty.
594  *     SIMPLEREGION - The new region can be represented by one rectangle.
595  *     COMPLEXREGION - The new region can only be represented by more than
596  *                     one rectangle.
597  */
598 INT WINAPI GetRgnBox( HRGN hrgn, LPRECT rect )
599 {
600     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
601     if (obj)
602     {
603         INT ret;
604         rect->left = obj->extents.left;
605         rect->top = obj->extents.top;
606         rect->right = obj->extents.right;
607         rect->bottom = obj->extents.bottom;
608         TRACE("%p (%d,%d-%d,%d)\n", hrgn,
609                rect->left, rect->top, rect->right, rect->bottom);
610         ret = get_region_type( obj );
611         GDI_ReleaseObj(hrgn);
612         return ret;
613     }
614     return ERROR;
615 }
616
617
618 /***********************************************************************
619  *           CreateRectRgn   (GDI32.@)
620  *
621  * Creates a simple rectangular region.
622  *
623  * PARAMS
624  *   left   [I] Left coordinate of rectangle.
625  *   top    [I] Top coordinate of rectangle.
626  *   right  [I] Right coordinate of rectangle.
627  *   bottom [I] Bottom coordinate of rectangle.
628  *
629  * RETURNS
630  *   Success: Handle to region.
631  *   Failure: NULL.
632  */
633 HRGN WINAPI CreateRectRgn(INT left, INT top, INT right, INT bottom)
634 {
635     HRGN hrgn;
636     WINEREGION *obj;
637
638     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
639
640     /* Allocate 2 rects by default to reduce the number of reallocs */
641     if (!init_region( obj, RGN_DEFAULT_RECTS ))
642     {
643         HeapFree( GetProcessHeap(), 0, obj );
644         return 0;
645     }
646     if (!(hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs )))
647     {
648         HeapFree( GetProcessHeap(), 0, obj->rects );
649         HeapFree( GetProcessHeap(), 0, obj );
650         return 0;
651     }
652     TRACE( "%d,%d-%d,%d returning %p\n", left, top, right, bottom, hrgn );
653     SetRectRgn(hrgn, left, top, right, bottom);
654     return hrgn;
655 }
656
657
658 /***********************************************************************
659  *           CreateRectRgnIndirect    (GDI32.@)
660  *
661  * Creates a simple rectangular region.
662  *
663  * PARAMS
664  *   rect [I] Coordinates of rectangular region.
665  *
666  * RETURNS
667  *   Success: Handle to region.
668  *   Failure: NULL.
669  */
670 HRGN WINAPI CreateRectRgnIndirect( const RECT* rect )
671 {
672     return CreateRectRgn( rect->left, rect->top, rect->right, rect->bottom );
673 }
674
675
676 /***********************************************************************
677  *           SetRectRgn    (GDI32.@)
678  *
679  * Sets a region to a simple rectangular region.
680  *
681  * PARAMS
682  *   hrgn   [I] Region to convert.
683  *   left   [I] Left coordinate of rectangle.
684  *   top    [I] Top coordinate of rectangle.
685  *   right  [I] Right coordinate of rectangle.
686  *   bottom [I] Bottom coordinate of rectangle.
687  *
688  * RETURNS
689  *   Success: Non-zero.
690  *   Failure: Zero.
691  *
692  * NOTES
693  *   Allows either or both left and top to be greater than right or bottom.
694  */
695 BOOL WINAPI SetRectRgn( HRGN hrgn, INT left, INT top,
696                           INT right, INT bottom )
697 {
698     WINEREGION *obj;
699
700     TRACE("%p %d,%d-%d,%d\n", hrgn, left, top, right, bottom );
701
702     if (!(obj = GDI_GetObjPtr( hrgn, OBJ_REGION ))) return FALSE;
703
704     if (left > right) { INT tmp = left; left = right; right = tmp; }
705     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
706
707     if((left != right) && (top != bottom))
708     {
709         obj->rects->left = obj->extents.left = left;
710         obj->rects->top = obj->extents.top = top;
711         obj->rects->right = obj->extents.right = right;
712         obj->rects->bottom = obj->extents.bottom = bottom;
713         obj->numRects = 1;
714     }
715     else
716         EMPTY_REGION(obj);
717
718     GDI_ReleaseObj( hrgn );
719     return TRUE;
720 }
721
722
723 /***********************************************************************
724  *           CreateRoundRectRgn    (GDI32.@)
725  *
726  * Creates a rectangular region with rounded corners.
727  *
728  * PARAMS
729  *   left           [I] Left coordinate of rectangle.
730  *   top            [I] Top coordinate of rectangle.
731  *   right          [I] Right coordinate of rectangle.
732  *   bottom         [I] Bottom coordinate of rectangle.
733  *   ellipse_width  [I] Width of the ellipse at each corner.
734  *   ellipse_height [I] Height of the ellipse at each corner.
735  *
736  * RETURNS
737  *   Success: Handle to region.
738  *   Failure: NULL.
739  *
740  * NOTES
741  *   If ellipse_width or ellipse_height is less than 2 logical units then
742  *   it is treated as though CreateRectRgn() was called instead.
743  */
744 HRGN WINAPI CreateRoundRectRgn( INT left, INT top,
745                                     INT right, INT bottom,
746                                     INT ellipse_width, INT ellipse_height )
747 {
748     WINEREGION *obj;
749     HRGN hrgn = 0;
750     int a, b, i, x, y;
751     INT64 asq, bsq, dx, dy, err;
752     RECT *rects;
753
754       /* Make the dimensions sensible */
755
756     if (left > right) { INT tmp = left; left = right; right = tmp; }
757     if (top > bottom) { INT tmp = top; top = bottom; bottom = tmp; }
758     /* the region is for the rectangle interior, but only at right and bottom for some reason */
759     right--;
760     bottom--;
761
762     ellipse_width = min( right - left, abs( ellipse_width ));
763     ellipse_height = min( bottom - top, abs( ellipse_height ));
764
765       /* Check if we can do a normal rectangle instead */
766
767     if ((ellipse_width < 2) || (ellipse_height < 2))
768         return CreateRectRgn( left, top, right, bottom );
769
770     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
771     obj->size = ellipse_height;
772     obj->numRects = ellipse_height;
773     obj->extents.left   = left;
774     obj->extents.top    = top;
775     obj->extents.right  = right;
776     obj->extents.bottom = bottom;
777
778     obj->rects = rects = HeapAlloc( GetProcessHeap(), 0, obj->size * sizeof(RECT) );
779     if (!rects) goto done;
780
781     /* based on an algorithm by Alois Zingl */
782
783     a = ellipse_width - 1;
784     b = ellipse_height - 1;
785     asq = (INT64)8 * a * a;
786     bsq = (INT64)8 * b * b;
787     dx  = (INT64)4 * b * b * (1 - a);
788     dy  = (INT64)4 * a * a * (1 + (b % 2));
789     err = dx + dy + a * a * (b % 2);
790
791     x = 0;
792     y = ellipse_height / 2;
793
794     rects[y].left = left;
795     rects[y].right = right;
796
797     while (x <= ellipse_width / 2)
798     {
799         INT64 e2 = 2 * err;
800         if (e2 >= dx)
801         {
802             x++;
803             err += dx += bsq;
804         }
805         if (e2 <= dy)
806         {
807             y++;
808             err += dy += asq;
809             rects[y].left = left + x;
810             rects[y].right = right - x;
811         }
812     }
813     for (i = 0; i < ellipse_height / 2; i++)
814     {
815         rects[i].left = rects[b - i].left;
816         rects[i].right = rects[b - i].right;
817         rects[i].top = top + i;
818         rects[i].bottom = rects[i].top + 1;
819     }
820     for (; i < ellipse_height; i++)
821     {
822         rects[i].top = bottom - ellipse_height + i;
823         rects[i].bottom = rects[i].top + 1;
824     }
825     rects[ellipse_height / 2].top = top + ellipse_height / 2;  /* extend to top of rectangle */
826
827     hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs );
828
829     TRACE("(%d,%d-%d,%d %dx%d): ret=%p\n",
830           left, top, right, bottom, ellipse_width, ellipse_height, hrgn );
831 done:
832     if (!hrgn)
833     {
834         HeapFree( GetProcessHeap(), 0, obj->rects );
835         HeapFree( GetProcessHeap(), 0, obj );
836     }
837     return hrgn;
838 }
839
840
841 /***********************************************************************
842  *           CreateEllipticRgn    (GDI32.@)
843  *
844  * Creates an elliptical region.
845  *
846  * PARAMS
847  *   left   [I] Left coordinate of bounding rectangle.
848  *   top    [I] Top coordinate of bounding rectangle.
849  *   right  [I] Right coordinate of bounding rectangle.
850  *   bottom [I] Bottom coordinate of bounding rectangle.
851  *
852  * RETURNS
853  *   Success: Handle to region.
854  *   Failure: NULL.
855  *
856  * NOTES
857  *   This is a special case of CreateRoundRectRgn() where the width of the
858  *   ellipse at each corner is equal to the width the rectangle and
859  *   the same for the height.
860  */
861 HRGN WINAPI CreateEllipticRgn( INT left, INT top,
862                                    INT right, INT bottom )
863 {
864     return CreateRoundRectRgn( left, top, right, bottom,
865                                  right-left, bottom-top );
866 }
867
868
869 /***********************************************************************
870  *           CreateEllipticRgnIndirect    (GDI32.@)
871  *
872  * Creates an elliptical region.
873  *
874  * PARAMS
875  *   rect [I] Pointer to bounding rectangle of the ellipse.
876  *
877  * RETURNS
878  *   Success: Handle to region.
879  *   Failure: NULL.
880  *
881  * NOTES
882  *   This is a special case of CreateRoundRectRgn() where the width of the
883  *   ellipse at each corner is equal to the width the rectangle and
884  *   the same for the height.
885  */
886 HRGN WINAPI CreateEllipticRgnIndirect( const RECT *rect )
887 {
888     return CreateRoundRectRgn( rect->left, rect->top, rect->right,
889                                  rect->bottom, rect->right - rect->left,
890                                  rect->bottom - rect->top );
891 }
892
893 /***********************************************************************
894  *           GetRegionData   (GDI32.@)
895  *
896  * Retrieves the data that specifies the region.
897  *
898  * PARAMS
899  *   hrgn    [I] Region to retrieve the region data from.
900  *   count   [I] The size of the buffer pointed to by rgndata in bytes.
901  *   rgndata [I] The buffer to receive data about the region.
902  *
903  * RETURNS
904  *   Success: If rgndata is NULL then the required number of bytes. Otherwise,
905  *            the number of bytes copied to the output buffer.
906  *   Failure: 0.
907  *
908  * NOTES
909  *   The format of the Buffer member of RGNDATA is determined by the iType
910  *   member of the region data header.
911  *   Currently this is always RDH_RECTANGLES, which specifies that the format
912  *   is the array of RECT's that specify the region. The length of the array
913  *   is specified by the nCount member of the region data header.
914  */
915 DWORD WINAPI GetRegionData(HRGN hrgn, DWORD count, LPRGNDATA rgndata)
916 {
917     DWORD size;
918     WINEREGION *obj = GDI_GetObjPtr( hrgn, OBJ_REGION );
919
920     TRACE(" %p count = %d, rgndata = %p\n", hrgn, count, rgndata);
921
922     if(!obj) return 0;
923
924     size = obj->numRects * sizeof(RECT);
925     if(count < (size + sizeof(RGNDATAHEADER)) || rgndata == NULL)
926     {
927         GDI_ReleaseObj( hrgn );
928         if (rgndata) /* buffer is too small, signal it by return 0 */
929             return 0;
930         else            /* user requested buffer size with rgndata NULL */
931             return size + sizeof(RGNDATAHEADER);
932     }
933
934     rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
935     rgndata->rdh.iType = RDH_RECTANGLES;
936     rgndata->rdh.nCount = obj->numRects;
937     rgndata->rdh.nRgnSize = size;
938     rgndata->rdh.rcBound.left = obj->extents.left;
939     rgndata->rdh.rcBound.top = obj->extents.top;
940     rgndata->rdh.rcBound.right = obj->extents.right;
941     rgndata->rdh.rcBound.bottom = obj->extents.bottom;
942
943     memcpy( rgndata->Buffer, obj->rects, size );
944
945     GDI_ReleaseObj( hrgn );
946     return size + sizeof(RGNDATAHEADER);
947 }
948
949
950 static void translate( POINT *pt, UINT count, const XFORM *xform )
951 {
952     while (count--)
953     {
954         double x = pt->x;
955         double y = pt->y;
956         pt->x = floor( x * xform->eM11 + y * xform->eM21 + xform->eDx + 0.5 );
957         pt->y = floor( x * xform->eM12 + y * xform->eM22 + xform->eDy + 0.5 );
958         pt++;
959     }
960 }
961
962
963 /***********************************************************************
964  *           ExtCreateRegion   (GDI32.@)
965  *
966  * Creates a region as specified by the transformation data and region data.
967  *
968  * PARAMS
969  *   lpXform [I] World-space to logical-space transformation data.
970  *   dwCount [I] Size of the data pointed to by rgndata, in bytes.
971  *   rgndata [I] Data that specifies the region.
972  *
973  * RETURNS
974  *   Success: Handle to region.
975  *   Failure: NULL.
976  *
977  * NOTES
978  *   See GetRegionData().
979  */
980 HRGN WINAPI ExtCreateRegion( const XFORM* lpXform, DWORD dwCount, const RGNDATA* rgndata)
981 {
982     HRGN hrgn = 0;
983     WINEREGION *obj;
984
985     if (!rgndata)
986     {
987         SetLastError( ERROR_INVALID_PARAMETER );
988         return 0;
989     }
990
991     if (rgndata->rdh.dwSize < sizeof(RGNDATAHEADER))
992         return 0;
993
994     /* XP doesn't care about the type */
995     if( rgndata->rdh.iType != RDH_RECTANGLES )
996         WARN("(Unsupported region data type: %u)\n", rgndata->rdh.iType);
997
998     if (lpXform)
999     {
1000         const RECT *pCurRect, *pEndRect;
1001
1002         hrgn = CreateRectRgn( 0, 0, 0, 0 );
1003
1004         pEndRect = (const RECT *)rgndata->Buffer + rgndata->rdh.nCount;
1005         for (pCurRect = (const RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
1006         {
1007             static const INT count = 4;
1008             HRGN poly_hrgn;
1009             POINT pt[4];
1010
1011             pt[0].x = pCurRect->left;
1012             pt[0].y = pCurRect->top;
1013             pt[1].x = pCurRect->right;
1014             pt[1].y = pCurRect->top;
1015             pt[2].x = pCurRect->right;
1016             pt[2].y = pCurRect->bottom;
1017             pt[3].x = pCurRect->left;
1018             pt[3].y = pCurRect->bottom;
1019
1020             translate( pt, 4, lpXform );
1021             poly_hrgn = CreatePolyPolygonRgn( pt, &count, 1, WINDING );
1022             CombineRgn( hrgn, hrgn, poly_hrgn, RGN_OR );
1023             DeleteObject( poly_hrgn );
1024         }
1025         return hrgn;
1026     }
1027
1028     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) return 0;
1029
1030     if (init_region( obj, rgndata->rdh.nCount ))
1031     {
1032         const RECT *pCurRect, *pEndRect;
1033
1034         pEndRect = (const RECT *)rgndata->Buffer + rgndata->rdh.nCount;
1035         for(pCurRect = (const RECT *)rgndata->Buffer; pCurRect < pEndRect; pCurRect++)
1036         {
1037             if (pCurRect->left < pCurRect->right && pCurRect->top < pCurRect->bottom)
1038             {
1039                 if (!REGION_UnionRectWithRegion( pCurRect, obj )) goto done;
1040             }
1041         }
1042         hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs );
1043     }
1044     else
1045     {
1046         HeapFree( GetProcessHeap(), 0, obj );
1047         return 0;
1048     }
1049
1050 done:
1051     if (!hrgn)
1052     {
1053         HeapFree( GetProcessHeap(), 0, obj->rects );
1054         HeapFree( GetProcessHeap(), 0, obj );
1055     }
1056     TRACE("%p %d %p returning %p\n", lpXform, dwCount, rgndata, hrgn );
1057     return hrgn;
1058 }
1059
1060
1061 /***********************************************************************
1062  *           PtInRegion    (GDI32.@)
1063  *
1064  * Tests whether the specified point is inside a region.
1065  *
1066  * PARAMS
1067  *   hrgn [I] Region to test.
1068  *   x    [I] X-coordinate of point to test.
1069  *   y    [I] Y-coordinate of point to test.
1070  *
1071  * RETURNS
1072  *   Non-zero if the point is inside the region or zero otherwise.
1073  */
1074 BOOL WINAPI PtInRegion( HRGN hrgn, INT x, INT y )
1075 {
1076     WINEREGION *obj;
1077     BOOL ret = FALSE;
1078
1079     if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1080     {
1081         int i;
1082
1083         if (obj->numRects > 0 && INRECT(obj->extents, x, y))
1084             for (i = 0; i < obj->numRects; i++)
1085                 if (INRECT (obj->rects[i], x, y))
1086                 {
1087                     ret = TRUE;
1088                     break;
1089                 }
1090         GDI_ReleaseObj( hrgn );
1091     }
1092     return ret;
1093 }
1094
1095
1096 /***********************************************************************
1097  *           RectInRegion    (GDI32.@)
1098  *
1099  * Tests if a rectangle is at least partly inside the specified region.
1100  *
1101  * PARAMS
1102  *   hrgn [I] Region to test.
1103  *   rect [I] Rectangle to test.
1104  *
1105  * RETURNS
1106  *   Non-zero if the rectangle is partially inside the region or
1107  *   zero otherwise.
1108  */
1109 BOOL WINAPI RectInRegion( HRGN hrgn, const RECT *rect )
1110 {
1111     WINEREGION *obj;
1112     BOOL ret = FALSE;
1113     RECT rc;
1114
1115     /* swap the coordinates to make right >= left and bottom >= top */
1116     /* (region building rectangles are normalized the same way) */
1117     if( rect->top > rect->bottom) {
1118         rc.top = rect->bottom;
1119         rc.bottom = rect->top;
1120     } else {
1121         rc.top = rect->top;
1122         rc.bottom = rect->bottom;
1123     }
1124     if( rect->right < rect->left) {
1125         rc.right = rect->left;
1126         rc.left = rect->right;
1127     } else {
1128         rc.right = rect->right;
1129         rc.left = rect->left;
1130     }
1131
1132     if ((obj = GDI_GetObjPtr( hrgn, OBJ_REGION )))
1133     {
1134         RECT *pCurRect, *pRectEnd;
1135
1136     /* this is (just) a useful optimization */
1137         if ((obj->numRects > 0) && EXTENTCHECK(&obj->extents, &rc))
1138         {
1139             for (pCurRect = obj->rects, pRectEnd = pCurRect +
1140              obj->numRects; pCurRect < pRectEnd; pCurRect++)
1141             {
1142                 if (pCurRect->bottom <= rc.top)
1143                     continue;             /* not far enough down yet */
1144
1145                 if (pCurRect->top >= rc.bottom)
1146                     break;                /* too far down */
1147
1148                 if (pCurRect->right <= rc.left)
1149                     continue;              /* not far enough over yet */
1150
1151                 if (pCurRect->left >= rc.right) {
1152                     continue;
1153                 }
1154
1155                 ret = TRUE;
1156                 break;
1157             }
1158         }
1159         GDI_ReleaseObj(hrgn);
1160     }
1161     return ret;
1162 }
1163
1164 /***********************************************************************
1165  *           EqualRgn    (GDI32.@)
1166  *
1167  * Tests whether one region is identical to another.
1168  *
1169  * PARAMS
1170  *   hrgn1 [I] The first region to compare.
1171  *   hrgn2 [I] The second region to compare.
1172  *
1173  * RETURNS
1174  *   Non-zero if both regions are identical or zero otherwise.
1175  */
1176 BOOL WINAPI EqualRgn( HRGN hrgn1, HRGN hrgn2 )
1177 {
1178     WINEREGION *obj1, *obj2;
1179     BOOL ret = FALSE;
1180
1181     if ((obj1 = GDI_GetObjPtr( hrgn1, OBJ_REGION )))
1182     {
1183         if ((obj2 = GDI_GetObjPtr( hrgn2, OBJ_REGION )))
1184         {
1185             int i;
1186
1187             if ( obj1->numRects != obj2->numRects ) goto done;
1188             if ( obj1->numRects == 0 )
1189             {
1190                 ret = TRUE;
1191                 goto done;
1192
1193             }
1194             if (obj1->extents.left   != obj2->extents.left) goto done;
1195             if (obj1->extents.right  != obj2->extents.right) goto done;
1196             if (obj1->extents.top    != obj2->extents.top) goto done;
1197             if (obj1->extents.bottom != obj2->extents.bottom) goto done;
1198             for( i = 0; i < obj1->numRects; i++ )
1199             {
1200                 if (obj1->rects[i].left   != obj2->rects[i].left) goto done;
1201                 if (obj1->rects[i].right  != obj2->rects[i].right) goto done;
1202                 if (obj1->rects[i].top    != obj2->rects[i].top) goto done;
1203                 if (obj1->rects[i].bottom != obj2->rects[i].bottom) goto done;
1204             }
1205             ret = TRUE;
1206         done:
1207             GDI_ReleaseObj(hrgn2);
1208         }
1209         GDI_ReleaseObj(hrgn1);
1210     }
1211     return ret;
1212 }
1213
1214 /***********************************************************************
1215  *           REGION_UnionRectWithRegion
1216  *           Adds a rectangle to a WINEREGION
1217  */
1218 static BOOL REGION_UnionRectWithRegion(const RECT *rect, WINEREGION *rgn)
1219 {
1220     WINEREGION region;
1221
1222     region.rects = &region.extents;
1223     region.numRects = 1;
1224     region.size = 1;
1225     region.extents = *rect;
1226     return REGION_UnionRegion(rgn, rgn, &region);
1227 }
1228
1229
1230 BOOL add_rect_to_region( HRGN rgn, const RECT *rect )
1231 {
1232     WINEREGION *obj = GDI_GetObjPtr( rgn, OBJ_REGION );
1233     BOOL ret;
1234
1235     if (!obj) return FALSE;
1236     ret = REGION_UnionRectWithRegion( rect, obj );
1237     GDI_ReleaseObj( rgn );
1238     return ret;
1239 }
1240
1241 /***********************************************************************
1242  *           REGION_CreateFrameRgn
1243  *
1244  * Create a region that is a frame around another region.
1245  * Compute the intersection of the region moved in all 4 directions
1246  * ( +x, -x, +y, -y) and subtract from the original.
1247  * The result looks slightly better than in Windows :)
1248  */
1249 BOOL REGION_FrameRgn( HRGN hDest, HRGN hSrc, INT x, INT y )
1250 {
1251     WINEREGION tmprgn;
1252     BOOL bRet = FALSE;
1253     WINEREGION* destObj = NULL;
1254     WINEREGION *srcObj = GDI_GetObjPtr( hSrc, OBJ_REGION );
1255
1256     tmprgn.rects = NULL;
1257     if (!srcObj) return FALSE;
1258     if (srcObj->numRects != 0)
1259     {
1260         if (!(destObj = GDI_GetObjPtr( hDest, OBJ_REGION ))) goto done;
1261         if (!init_region( &tmprgn, srcObj->numRects )) goto done;
1262
1263         if (!REGION_OffsetRegion( destObj, srcObj, -x, 0)) goto done;
1264         if (!REGION_OffsetRegion( &tmprgn, srcObj, x, 0)) goto done;
1265         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1266         if (!REGION_OffsetRegion( &tmprgn, srcObj, 0, -y)) goto done;
1267         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1268         if (!REGION_OffsetRegion( &tmprgn, srcObj, 0, y)) goto done;
1269         if (!REGION_IntersectRegion( destObj, destObj, &tmprgn )) goto done;
1270         if (!REGION_SubtractRegion( destObj, srcObj, destObj )) goto done;
1271         bRet = TRUE;
1272     }
1273 done:
1274     HeapFree( GetProcessHeap(), 0, tmprgn.rects );
1275     if (destObj) GDI_ReleaseObj ( hDest );
1276     GDI_ReleaseObj( hSrc );
1277     return bRet;
1278 }
1279
1280
1281 /***********************************************************************
1282  *           CombineRgn   (GDI32.@)
1283  *
1284  * Combines two regions with the specified operation and stores the result
1285  * in the specified destination region.
1286  *
1287  * PARAMS
1288  *   hDest [I] The region that receives the combined result.
1289  *   hSrc1 [I] The first source region.
1290  *   hSrc2 [I] The second source region.
1291  *   mode  [I] The way in which the source regions will be combined. See notes.
1292  *
1293  * RETURNS
1294  *   Success:
1295  *     NULLREGION - The new region is empty.
1296  *     SIMPLEREGION - The new region can be represented by one rectangle.
1297  *     COMPLEXREGION - The new region can only be represented by more than
1298  *                     one rectangle.
1299  *   Failure: ERROR
1300  *
1301  * NOTES
1302  *   The two source regions can be the same region.
1303  *   The mode can be one of the following:
1304  *|  RGN_AND - Intersection of the regions
1305  *|  RGN_OR - Union of the regions
1306  *|  RGN_XOR - Unions of the regions minus any intersection.
1307  *|  RGN_DIFF - Difference (subtraction) of the regions.
1308  */
1309 INT WINAPI CombineRgn(HRGN hDest, HRGN hSrc1, HRGN hSrc2, INT mode)
1310 {
1311     WINEREGION *destObj = GDI_GetObjPtr( hDest, OBJ_REGION );
1312     INT result = ERROR;
1313
1314     TRACE(" %p,%p -> %p mode=%x\n", hSrc1, hSrc2, hDest, mode );
1315     if (destObj)
1316     {
1317         WINEREGION *src1Obj = GDI_GetObjPtr( hSrc1, OBJ_REGION );
1318
1319         if (src1Obj)
1320         {
1321             TRACE("dump src1Obj:\n");
1322             if(TRACE_ON(region))
1323               REGION_DumpRegion(src1Obj);
1324             if (mode == RGN_COPY)
1325             {
1326                 if (REGION_CopyRegion( destObj, src1Obj ))
1327                     result = get_region_type( destObj );
1328             }
1329             else
1330             {
1331                 WINEREGION *src2Obj = GDI_GetObjPtr( hSrc2, OBJ_REGION );
1332
1333                 if (src2Obj)
1334                 {
1335                     TRACE("dump src2Obj:\n");
1336                     if(TRACE_ON(region))
1337                         REGION_DumpRegion(src2Obj);
1338                     switch (mode)
1339                     {
1340                     case RGN_AND:
1341                         if (REGION_IntersectRegion( destObj, src1Obj, src2Obj ))
1342                             result = get_region_type( destObj );
1343                         break;
1344                     case RGN_OR:
1345                         if (REGION_UnionRegion( destObj, src1Obj, src2Obj ))
1346                             result = get_region_type( destObj );
1347                         break;
1348                     case RGN_XOR:
1349                         if (REGION_XorRegion( destObj, src1Obj, src2Obj ))
1350                             result = get_region_type( destObj );
1351                         break;
1352                     case RGN_DIFF:
1353                         if (REGION_SubtractRegion( destObj, src1Obj, src2Obj ))
1354                             result = get_region_type( destObj );
1355                         break;
1356                     }
1357                     GDI_ReleaseObj( hSrc2 );
1358                 }
1359             }
1360             GDI_ReleaseObj( hSrc1 );
1361         }
1362         TRACE("dump destObj:\n");
1363         if(TRACE_ON(region))
1364           REGION_DumpRegion(destObj);
1365
1366         GDI_ReleaseObj( hDest );
1367     }
1368     return result;
1369 }
1370
1371 /***********************************************************************
1372  *           REGION_SetExtents
1373  *           Re-calculate the extents of a region
1374  */
1375 static void REGION_SetExtents (WINEREGION *pReg)
1376 {
1377     RECT *pRect, *pRectEnd, *pExtents;
1378
1379     if (pReg->numRects == 0)
1380     {
1381         pReg->extents.left = 0;
1382         pReg->extents.top = 0;
1383         pReg->extents.right = 0;
1384         pReg->extents.bottom = 0;
1385         return;
1386     }
1387
1388     pExtents = &pReg->extents;
1389     pRect = pReg->rects;
1390     pRectEnd = &pRect[pReg->numRects - 1];
1391
1392     /*
1393      * Since pRect is the first rectangle in the region, it must have the
1394      * smallest top and since pRectEnd is the last rectangle in the region,
1395      * it must have the largest bottom, because of banding. Initialize left and
1396      * right from pRect and pRectEnd, resp., as good things to initialize them
1397      * to...
1398      */
1399     pExtents->left = pRect->left;
1400     pExtents->top = pRect->top;
1401     pExtents->right = pRectEnd->right;
1402     pExtents->bottom = pRectEnd->bottom;
1403
1404     while (pRect <= pRectEnd)
1405     {
1406         if (pRect->left < pExtents->left)
1407             pExtents->left = pRect->left;
1408         if (pRect->right > pExtents->right)
1409             pExtents->right = pRect->right;
1410         pRect++;
1411     }
1412 }
1413
1414 /***********************************************************************
1415  *           REGION_CopyRegion
1416  */
1417 static BOOL REGION_CopyRegion(WINEREGION *dst, WINEREGION *src)
1418 {
1419     if (dst != src) /*  don't want to copy to itself */
1420     {
1421         if (dst->size < src->numRects)
1422         {
1423             RECT *rects = HeapReAlloc( GetProcessHeap(), 0, dst->rects, src->numRects * sizeof(RECT) );
1424             if (!rects) return FALSE;
1425             dst->rects = rects;
1426             dst->size = src->numRects;
1427         }
1428         dst->numRects = src->numRects;
1429         dst->extents.left = src->extents.left;
1430         dst->extents.top = src->extents.top;
1431         dst->extents.right = src->extents.right;
1432         dst->extents.bottom = src->extents.bottom;
1433         memcpy(dst->rects, src->rects, src->numRects * sizeof(RECT));
1434     }
1435     return TRUE;
1436 }
1437
1438 /***********************************************************************
1439  *           REGION_MirrorRegion
1440  */
1441 static BOOL REGION_MirrorRegion( WINEREGION *dst, WINEREGION *src, int width )
1442 {
1443     int i, start, end;
1444     RECT extents;
1445     RECT *rects = HeapAlloc( GetProcessHeap(), 0, src->numRects * sizeof(RECT) );
1446
1447     if (!rects) return FALSE;
1448
1449     extents.left   = width - src->extents.right;
1450     extents.right  = width - src->extents.left;
1451     extents.top    = src->extents.top;
1452     extents.bottom = src->extents.bottom;
1453
1454     for (start = 0; start < src->numRects; start = end)
1455     {
1456         /* find the end of the current band */
1457         for (end = start + 1; end < src->numRects; end++)
1458             if (src->rects[end].top != src->rects[end - 1].top) break;
1459
1460         for (i = 0; i < end - start; i++)
1461         {
1462             rects[start + i].left   = width - src->rects[end - i - 1].right;
1463             rects[start + i].right  = width - src->rects[end - i - 1].left;
1464             rects[start + i].top    = src->rects[end - i - 1].top;
1465             rects[start + i].bottom = src->rects[end - i - 1].bottom;
1466         }
1467     }
1468
1469     HeapFree( GetProcessHeap(), 0, dst->rects );
1470     dst->rects    = rects;
1471     dst->size     = src->numRects;
1472     dst->numRects = src->numRects;
1473     dst->extents  = extents;
1474     return TRUE;
1475 }
1476
1477 /***********************************************************************
1478  *           mirror_region
1479  */
1480 INT mirror_region( HRGN dst, HRGN src, INT width )
1481 {
1482     WINEREGION *src_rgn, *dst_rgn;
1483     INT ret = ERROR;
1484
1485     if (!(src_rgn = GDI_GetObjPtr( src, OBJ_REGION ))) return ERROR;
1486     if ((dst_rgn = GDI_GetObjPtr( dst, OBJ_REGION )))
1487     {
1488         if (REGION_MirrorRegion( dst_rgn, src_rgn, width )) ret = get_region_type( dst_rgn );
1489         GDI_ReleaseObj( dst_rgn );
1490     }
1491     GDI_ReleaseObj( src_rgn );
1492     return ret;
1493 }
1494
1495 /***********************************************************************
1496  *           MirrorRgn    (GDI32.@)
1497  */
1498 BOOL WINAPI MirrorRgn( HWND hwnd, HRGN hrgn )
1499 {
1500     static const WCHAR user32W[] = {'u','s','e','r','3','2','.','d','l','l',0};
1501     static BOOL (WINAPI *pGetWindowRect)( HWND hwnd, LPRECT rect );
1502     RECT rect;
1503
1504     /* yes, a HWND in gdi32, don't ask */
1505     if (!pGetWindowRect)
1506     {
1507         HMODULE user32 = GetModuleHandleW(user32W);
1508         if (!user32) return FALSE;
1509         if (!(pGetWindowRect = (void *)GetProcAddress( user32, "GetWindowRect" ))) return FALSE;
1510     }
1511     pGetWindowRect( hwnd, &rect );
1512     return mirror_region( hrgn, hrgn, rect.right - rect.left ) != ERROR;
1513 }
1514
1515
1516 /***********************************************************************
1517  *           REGION_Coalesce
1518  *
1519  *      Attempt to merge the rects in the current band with those in the
1520  *      previous one. Used only by REGION_RegionOp.
1521  *
1522  * Results:
1523  *      The new index for the previous band.
1524  *
1525  * Side Effects:
1526  *      If coalescing takes place:
1527  *          - rectangles in the previous band will have their bottom fields
1528  *            altered.
1529  *          - pReg->numRects will be decreased.
1530  *
1531  */
1532 static INT REGION_Coalesce (
1533              WINEREGION *pReg, /* Region to coalesce */
1534              INT prevStart,  /* Index of start of previous band */
1535              INT curStart    /* Index of start of current band */
1536 ) {
1537     RECT *pPrevRect;          /* Current rect in previous band */
1538     RECT *pCurRect;           /* Current rect in current band */
1539     RECT *pRegEnd;            /* End of region */
1540     INT curNumRects;          /* Number of rectangles in current band */
1541     INT prevNumRects;         /* Number of rectangles in previous band */
1542     INT bandtop;               /* top coordinate for current band */
1543
1544     pRegEnd = &pReg->rects[pReg->numRects];
1545
1546     pPrevRect = &pReg->rects[prevStart];
1547     prevNumRects = curStart - prevStart;
1548
1549     /*
1550      * Figure out how many rectangles are in the current band. Have to do
1551      * this because multiple bands could have been added in REGION_RegionOp
1552      * at the end when one region has been exhausted.
1553      */
1554     pCurRect = &pReg->rects[curStart];
1555     bandtop = pCurRect->top;
1556     for (curNumRects = 0;
1557          (pCurRect != pRegEnd) && (pCurRect->top == bandtop);
1558          curNumRects++)
1559     {
1560         pCurRect++;
1561     }
1562
1563     if (pCurRect != pRegEnd)
1564     {
1565         /*
1566          * If more than one band was added, we have to find the start
1567          * of the last band added so the next coalescing job can start
1568          * at the right place... (given when multiple bands are added,
1569          * this may be pointless -- see above).
1570          */
1571         pRegEnd--;
1572         while (pRegEnd[-1].top == pRegEnd->top)
1573         {
1574             pRegEnd--;
1575         }
1576         curStart = pRegEnd - pReg->rects;
1577         pRegEnd = pReg->rects + pReg->numRects;
1578     }
1579
1580     if ((curNumRects == prevNumRects) && (curNumRects != 0)) {
1581         pCurRect -= curNumRects;
1582         /*
1583          * The bands may only be coalesced if the bottom of the previous
1584          * matches the top scanline of the current.
1585          */
1586         if (pPrevRect->bottom == pCurRect->top)
1587         {
1588             /*
1589              * Make sure the bands have rects in the same places. This
1590              * assumes that rects have been added in such a way that they
1591              * cover the most area possible. I.e. two rects in a band must
1592              * have some horizontal space between them.
1593              */
1594             do
1595             {
1596                 if ((pPrevRect->left != pCurRect->left) ||
1597                     (pPrevRect->right != pCurRect->right))
1598                 {
1599                     /*
1600                      * The bands don't line up so they can't be coalesced.
1601                      */
1602                     return (curStart);
1603                 }
1604                 pPrevRect++;
1605                 pCurRect++;
1606                 prevNumRects -= 1;
1607             } while (prevNumRects != 0);
1608
1609             pReg->numRects -= curNumRects;
1610             pCurRect -= curNumRects;
1611             pPrevRect -= curNumRects;
1612
1613             /*
1614              * The bands may be merged, so set the bottom of each rect
1615              * in the previous band to that of the corresponding rect in
1616              * the current band.
1617              */
1618             do
1619             {
1620                 pPrevRect->bottom = pCurRect->bottom;
1621                 pPrevRect++;
1622                 pCurRect++;
1623                 curNumRects -= 1;
1624             } while (curNumRects != 0);
1625
1626             /*
1627              * If only one band was added to the region, we have to backup
1628              * curStart to the start of the previous band.
1629              *
1630              * If more than one band was added to the region, copy the
1631              * other bands down. The assumption here is that the other bands
1632              * came from the same region as the current one and no further
1633              * coalescing can be done on them since it's all been done
1634              * already... curStart is already in the right place.
1635              */
1636             if (pCurRect == pRegEnd)
1637             {
1638                 curStart = prevStart;
1639             }
1640             else
1641             {
1642                 do
1643                 {
1644                     *pPrevRect++ = *pCurRect++;
1645                 } while (pCurRect != pRegEnd);
1646             }
1647
1648         }
1649     }
1650     return (curStart);
1651 }
1652
1653 /***********************************************************************
1654  *           REGION_RegionOp
1655  *
1656  *      Apply an operation to two regions. Called by REGION_Union,
1657  *      REGION_Inverse, REGION_Subtract, REGION_Intersect...
1658  *
1659  * Results:
1660  *      None.
1661  *
1662  * Side Effects:
1663  *      The new region is overwritten.
1664  *
1665  * Notes:
1666  *      The idea behind this function is to view the two regions as sets.
1667  *      Together they cover a rectangle of area that this function divides
1668  *      into horizontal bands where points are covered only by one region
1669  *      or by both. For the first case, the nonOverlapFunc is called with
1670  *      each the band and the band's upper and lower extents. For the
1671  *      second, the overlapFunc is called to process the entire band. It
1672  *      is responsible for clipping the rectangles in the band, though
1673  *      this function provides the boundaries.
1674  *      At the end of each band, the new region is coalesced, if possible,
1675  *      to reduce the number of rectangles in the region.
1676  *
1677  */
1678 static BOOL REGION_RegionOp(
1679             WINEREGION *destReg, /* Place to store result */
1680             WINEREGION *reg1,   /* First region in operation */
1681             WINEREGION *reg2,   /* 2nd region in operation */
1682             BOOL (*overlapFunc)(WINEREGION*, RECT*, RECT*, RECT*, RECT*, INT, INT),     /* Function to call for over-lapping bands */
1683             BOOL (*nonOverlap1Func)(WINEREGION*, RECT*, RECT*, INT, INT), /* Function to call for non-overlapping bands in region 1 */
1684             BOOL (*nonOverlap2Func)(WINEREGION*, RECT*, RECT*, INT, INT)  /* Function to call for non-overlapping bands in region 2 */
1685 ) {
1686     WINEREGION newReg;
1687     RECT *r1;                         /* Pointer into first region */
1688     RECT *r2;                         /* Pointer into 2d region */
1689     RECT *r1End;                      /* End of 1st region */
1690     RECT *r2End;                      /* End of 2d region */
1691     INT ybot;                         /* Bottom of intersection */
1692     INT ytop;                         /* Top of intersection */
1693     INT prevBand;                     /* Index of start of
1694                                                  * previous band in newReg */
1695     INT curBand;                      /* Index of start of current
1696                                                  * band in newReg */
1697     RECT *r1BandEnd;                  /* End of current band in r1 */
1698     RECT *r2BandEnd;                  /* End of current band in r2 */
1699     INT top;                          /* Top of non-overlapping band */
1700     INT bot;                          /* Bottom of non-overlapping band */
1701
1702     /*
1703      * Initialization:
1704      *  set r1, r2, r1End and r2End appropriately, preserve the important
1705      * parts of the destination region until the end in case it's one of
1706      * the two source regions, then mark the "new" region empty, allocating
1707      * another array of rectangles for it to use.
1708      */
1709     r1 = reg1->rects;
1710     r2 = reg2->rects;
1711     r1End = r1 + reg1->numRects;
1712     r2End = r2 + reg2->numRects;
1713
1714     /*
1715      * Allocate a reasonable number of rectangles for the new region. The idea
1716      * is to allocate enough so the individual functions don't need to
1717      * reallocate and copy the array, which is time consuming, yet we don't
1718      * have to worry about using too much memory. I hope to be able to
1719      * nuke the Xrealloc() at the end of this function eventually.
1720      */
1721     if (!init_region( &newReg, max(reg1->numRects,reg2->numRects) * 2 )) return FALSE;
1722
1723     /*
1724      * Initialize ybot and ytop.
1725      * In the upcoming loop, ybot and ytop serve different functions depending
1726      * on whether the band being handled is an overlapping or non-overlapping
1727      * band.
1728      *  In the case of a non-overlapping band (only one of the regions
1729      * has points in the band), ybot is the bottom of the most recent
1730      * intersection and thus clips the top of the rectangles in that band.
1731      * ytop is the top of the next intersection between the two regions and
1732      * serves to clip the bottom of the rectangles in the current band.
1733      *  For an overlapping band (where the two regions intersect), ytop clips
1734      * the top of the rectangles of both regions and ybot clips the bottoms.
1735      */
1736     if (reg1->extents.top < reg2->extents.top)
1737         ybot = reg1->extents.top;
1738     else
1739         ybot = reg2->extents.top;
1740
1741     /*
1742      * prevBand serves to mark the start of the previous band so rectangles
1743      * can be coalesced into larger rectangles. qv. miCoalesce, above.
1744      * In the beginning, there is no previous band, so prevBand == curBand
1745      * (curBand is set later on, of course, but the first band will always
1746      * start at index 0). prevBand and curBand must be indices because of
1747      * the possible expansion, and resultant moving, of the new region's
1748      * array of rectangles.
1749      */
1750     prevBand = 0;
1751
1752     do
1753     {
1754         curBand = newReg.numRects;
1755
1756         /*
1757          * This algorithm proceeds one source-band (as opposed to a
1758          * destination band, which is determined by where the two regions
1759          * intersect) at a time. r1BandEnd and r2BandEnd serve to mark the
1760          * rectangle after the last one in the current band for their
1761          * respective regions.
1762          */
1763         r1BandEnd = r1;
1764         while ((r1BandEnd != r1End) && (r1BandEnd->top == r1->top))
1765         {
1766             r1BandEnd++;
1767         }
1768
1769         r2BandEnd = r2;
1770         while ((r2BandEnd != r2End) && (r2BandEnd->top == r2->top))
1771         {
1772             r2BandEnd++;
1773         }
1774
1775         /*
1776          * First handle the band that doesn't intersect, if any.
1777          *
1778          * Note that attention is restricted to one band in the
1779          * non-intersecting region at once, so if a region has n
1780          * bands between the current position and the next place it overlaps
1781          * the other, this entire loop will be passed through n times.
1782          */
1783         if (r1->top < r2->top)
1784         {
1785             top = max(r1->top,ybot);
1786             bot = min(r1->bottom,r2->top);
1787
1788             if ((top != bot) && (nonOverlap1Func != NULL))
1789             {
1790                 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, top, bot)) return FALSE;
1791             }
1792
1793             ytop = r2->top;
1794         }
1795         else if (r2->top < r1->top)
1796         {
1797             top = max(r2->top,ybot);
1798             bot = min(r2->bottom,r1->top);
1799
1800             if ((top != bot) && (nonOverlap2Func != NULL))
1801             {
1802                 if (!nonOverlap2Func(&newReg, r2, r2BandEnd, top, bot)) return FALSE;
1803             }
1804
1805             ytop = r1->top;
1806         }
1807         else
1808         {
1809             ytop = r1->top;
1810         }
1811
1812         /*
1813          * If any rectangles got added to the region, try and coalesce them
1814          * with rectangles from the previous band. Note we could just do
1815          * this test in miCoalesce, but some machines incur a not
1816          * inconsiderable cost for function calls, so...
1817          */
1818         if (newReg.numRects != curBand)
1819         {
1820             prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1821         }
1822
1823         /*
1824          * Now see if we've hit an intersecting band. The two bands only
1825          * intersect if ybot > ytop
1826          */
1827         ybot = min(r1->bottom, r2->bottom);
1828         curBand = newReg.numRects;
1829         if (ybot > ytop)
1830         {
1831             if (!overlapFunc(&newReg, r1, r1BandEnd, r2, r2BandEnd, ytop, ybot)) return FALSE;
1832         }
1833
1834         if (newReg.numRects != curBand)
1835         {
1836             prevBand = REGION_Coalesce (&newReg, prevBand, curBand);
1837         }
1838
1839         /*
1840          * If we've finished with a band (bottom == ybot) we skip forward
1841          * in the region to the next band.
1842          */
1843         if (r1->bottom == ybot)
1844         {
1845             r1 = r1BandEnd;
1846         }
1847         if (r2->bottom == ybot)
1848         {
1849             r2 = r2BandEnd;
1850         }
1851     } while ((r1 != r1End) && (r2 != r2End));
1852
1853     /*
1854      * Deal with whichever region still has rectangles left.
1855      */
1856     curBand = newReg.numRects;
1857     if (r1 != r1End)
1858     {
1859         if (nonOverlap1Func != NULL)
1860         {
1861             do
1862             {
1863                 r1BandEnd = r1;
1864                 while ((r1BandEnd < r1End) && (r1BandEnd->top == r1->top))
1865                 {
1866                     r1BandEnd++;
1867                 }
1868                 if (!nonOverlap1Func(&newReg, r1, r1BandEnd, max(r1->top,ybot), r1->bottom))
1869                     return FALSE;
1870                 r1 = r1BandEnd;
1871             } while (r1 != r1End);
1872         }
1873     }
1874     else if ((r2 != r2End) && (nonOverlap2Func != NULL))
1875     {
1876         do
1877         {
1878             r2BandEnd = r2;
1879             while ((r2BandEnd < r2End) && (r2BandEnd->top == r2->top))
1880             {
1881                  r2BandEnd++;
1882             }
1883             if (!nonOverlap2Func(&newReg, r2, r2BandEnd, max(r2->top,ybot), r2->bottom))
1884                 return FALSE;
1885             r2 = r2BandEnd;
1886         } while (r2 != r2End);
1887     }
1888
1889     if (newReg.numRects != curBand)
1890     {
1891         REGION_Coalesce (&newReg, prevBand, curBand);
1892     }
1893
1894     /*
1895      * A bit of cleanup. To keep regions from growing without bound,
1896      * we shrink the array of rectangles to match the new number of
1897      * rectangles in the region. This never goes to 0, however...
1898      *
1899      * Only do this stuff if the number of rectangles allocated is more than
1900      * twice the number of rectangles in the region (a simple optimization...).
1901      */
1902     if ((newReg.numRects < (newReg.size >> 1)) && (newReg.numRects > 2))
1903     {
1904         RECT *new_rects = HeapReAlloc( GetProcessHeap(), 0, newReg.rects, newReg.numRects * sizeof(RECT) );
1905         if (new_rects)
1906         {
1907             newReg.rects = new_rects;
1908             newReg.size = newReg.numRects;
1909         }
1910     }
1911     HeapFree( GetProcessHeap(), 0, destReg->rects );
1912     destReg->rects    = newReg.rects;
1913     destReg->size     = newReg.size;
1914     destReg->numRects = newReg.numRects;
1915     return TRUE;
1916 }
1917
1918 /***********************************************************************
1919  *          Region Intersection
1920  ***********************************************************************/
1921
1922
1923 /***********************************************************************
1924  *           REGION_IntersectO
1925  *
1926  * Handle an overlapping band for REGION_Intersect.
1927  *
1928  * Results:
1929  *      None.
1930  *
1931  * Side Effects:
1932  *      Rectangles may be added to the region.
1933  *
1934  */
1935 static BOOL REGION_IntersectO(WINEREGION *pReg,  RECT *r1, RECT *r1End,
1936                               RECT *r2, RECT *r2End, INT top, INT bottom)
1937
1938 {
1939     INT       left, right;
1940
1941     while ((r1 != r1End) && (r2 != r2End))
1942     {
1943         left = max(r1->left, r2->left);
1944         right = min(r1->right, r2->right);
1945
1946         /*
1947          * If there's any overlap between the two rectangles, add that
1948          * overlap to the new region.
1949          * There's no need to check for subsumption because the only way
1950          * such a need could arise is if some region has two rectangles
1951          * right next to each other. Since that should never happen...
1952          */
1953         if (left < right)
1954         {
1955             if (!add_rect( pReg, left, top, right, bottom )) return FALSE;
1956         }
1957
1958         /*
1959          * Need to advance the pointers. Shift the one that extends
1960          * to the right the least, since the other still has a chance to
1961          * overlap with that region's next rectangle, if you see what I mean.
1962          */
1963         if (r1->right < r2->right)
1964         {
1965             r1++;
1966         }
1967         else if (r2->right < r1->right)
1968         {
1969             r2++;
1970         }
1971         else
1972         {
1973             r1++;
1974             r2++;
1975         }
1976     }
1977     return TRUE;
1978 }
1979
1980 /***********************************************************************
1981  *           REGION_IntersectRegion
1982  */
1983 static BOOL REGION_IntersectRegion(WINEREGION *newReg, WINEREGION *reg1,
1984                                    WINEREGION *reg2)
1985 {
1986    /* check for trivial reject */
1987     if ( (!(reg1->numRects)) || (!(reg2->numRects))  ||
1988         (!EXTENTCHECK(&reg1->extents, &reg2->extents)))
1989         newReg->numRects = 0;
1990     else
1991         if (!REGION_RegionOp (newReg, reg1, reg2, REGION_IntersectO, NULL, NULL)) return FALSE;
1992
1993     /*
1994      * Can't alter newReg's extents before we call miRegionOp because
1995      * it might be one of the source regions and miRegionOp depends
1996      * on the extents of those regions being the same. Besides, this
1997      * way there's no checking against rectangles that will be nuked
1998      * due to coalescing, so we have to examine fewer rectangles.
1999      */
2000     REGION_SetExtents(newReg);
2001     return TRUE;
2002 }
2003
2004 /***********************************************************************
2005  *           Region Union
2006  ***********************************************************************/
2007
2008 /***********************************************************************
2009  *           REGION_UnionNonO
2010  *
2011  *      Handle a non-overlapping band for the union operation. Just
2012  *      Adds the rectangles into the region. Doesn't have to check for
2013  *      subsumption or anything.
2014  *
2015  * Results:
2016  *      None.
2017  *
2018  * Side Effects:
2019  *      pReg->numRects is incremented and the final rectangles overwritten
2020  *      with the rectangles we're passed.
2021  *
2022  */
2023 static BOOL REGION_UnionNonO(WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
2024 {
2025     while (r != rEnd)
2026     {
2027         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
2028         r++;
2029     }
2030     return TRUE;
2031 }
2032
2033 /***********************************************************************
2034  *           REGION_UnionO
2035  *
2036  *      Handle an overlapping band for the union operation. Picks the
2037  *      left-most rectangle each time and merges it into the region.
2038  *
2039  * Results:
2040  *      None.
2041  *
2042  * Side Effects:
2043  *      Rectangles are overwritten in pReg->rects and pReg->numRects will
2044  *      be changed.
2045  *
2046  */
2047 static BOOL REGION_UnionO (WINEREGION *pReg, RECT *r1, RECT *r1End,
2048                            RECT *r2, RECT *r2End, INT top, INT bottom)
2049 {
2050 #define MERGERECT(r) \
2051     if ((pReg->numRects != 0) &&  \
2052         (pReg->rects[pReg->numRects-1].top == top) &&  \
2053         (pReg->rects[pReg->numRects-1].bottom == bottom) &&  \
2054         (pReg->rects[pReg->numRects-1].right >= r->left))  \
2055     {  \
2056         if (pReg->rects[pReg->numRects-1].right < r->right)  \
2057             pReg->rects[pReg->numRects-1].right = r->right;  \
2058     }  \
2059     else  \
2060     { \
2061         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE; \
2062     } \
2063     r++;
2064
2065     while ((r1 != r1End) && (r2 != r2End))
2066     {
2067         if (r1->left < r2->left)
2068         {
2069             MERGERECT(r1);
2070         }
2071         else
2072         {
2073             MERGERECT(r2);
2074         }
2075     }
2076
2077     if (r1 != r1End)
2078     {
2079         do
2080         {
2081             MERGERECT(r1);
2082         } while (r1 != r1End);
2083     }
2084     else while (r2 != r2End)
2085     {
2086         MERGERECT(r2);
2087     }
2088     return TRUE;
2089 #undef MERGERECT
2090 }
2091
2092 /***********************************************************************
2093  *           REGION_UnionRegion
2094  */
2095 static BOOL REGION_UnionRegion(WINEREGION *newReg, WINEREGION *reg1, WINEREGION *reg2)
2096 {
2097     BOOL ret = TRUE;
2098
2099     /*  checks all the simple cases */
2100
2101     /*
2102      * Region 1 and 2 are the same or region 1 is empty
2103      */
2104     if ( (reg1 == reg2) || (!(reg1->numRects)) )
2105     {
2106         if (newReg != reg2)
2107             ret = REGION_CopyRegion(newReg, reg2);
2108         return ret;
2109     }
2110
2111     /*
2112      * if nothing to union (region 2 empty)
2113      */
2114     if (!(reg2->numRects))
2115     {
2116         if (newReg != reg1)
2117             ret = REGION_CopyRegion(newReg, reg1);
2118         return ret;
2119     }
2120
2121     /*
2122      * Region 1 completely subsumes region 2
2123      */
2124     if ((reg1->numRects == 1) &&
2125         (reg1->extents.left <= reg2->extents.left) &&
2126         (reg1->extents.top <= reg2->extents.top) &&
2127         (reg1->extents.right >= reg2->extents.right) &&
2128         (reg1->extents.bottom >= reg2->extents.bottom))
2129     {
2130         if (newReg != reg1)
2131             ret = REGION_CopyRegion(newReg, reg1);
2132         return ret;
2133     }
2134
2135     /*
2136      * Region 2 completely subsumes region 1
2137      */
2138     if ((reg2->numRects == 1) &&
2139         (reg2->extents.left <= reg1->extents.left) &&
2140         (reg2->extents.top <= reg1->extents.top) &&
2141         (reg2->extents.right >= reg1->extents.right) &&
2142         (reg2->extents.bottom >= reg1->extents.bottom))
2143     {
2144         if (newReg != reg2)
2145             ret = REGION_CopyRegion(newReg, reg2);
2146         return ret;
2147     }
2148
2149     if ((ret = REGION_RegionOp (newReg, reg1, reg2, REGION_UnionO, REGION_UnionNonO, REGION_UnionNonO)))
2150     {
2151         newReg->extents.left = min(reg1->extents.left, reg2->extents.left);
2152         newReg->extents.top = min(reg1->extents.top, reg2->extents.top);
2153         newReg->extents.right = max(reg1->extents.right, reg2->extents.right);
2154         newReg->extents.bottom = max(reg1->extents.bottom, reg2->extents.bottom);
2155     }
2156     return ret;
2157 }
2158
2159 /***********************************************************************
2160  *           Region Subtraction
2161  ***********************************************************************/
2162
2163 /***********************************************************************
2164  *           REGION_SubtractNonO1
2165  *
2166  *      Deal with non-overlapping band for subtraction. Any parts from
2167  *      region 2 we discard. Anything from region 1 we add to the region.
2168  *
2169  * Results:
2170  *      None.
2171  *
2172  * Side Effects:
2173  *      pReg may be affected.
2174  *
2175  */
2176 static BOOL REGION_SubtractNonO1 (WINEREGION *pReg, RECT *r, RECT *rEnd, INT top, INT bottom)
2177 {
2178     while (r != rEnd)
2179     {
2180         if (!add_rect( pReg, r->left, top, r->right, bottom )) return FALSE;
2181         r++;
2182     }
2183     return TRUE;
2184 }
2185
2186
2187 /***********************************************************************
2188  *           REGION_SubtractO
2189  *
2190  *      Overlapping band subtraction. x1 is the left-most point not yet
2191  *      checked.
2192  *
2193  * Results:
2194  *      None.
2195  *
2196  * Side Effects:
2197  *      pReg may have rectangles added to it.
2198  *
2199  */
2200 static BOOL REGION_SubtractO (WINEREGION *pReg, RECT *r1, RECT *r1End,
2201                               RECT *r2, RECT *r2End, INT top, INT bottom)
2202 {
2203     INT left = r1->left;
2204
2205     while ((r1 != r1End) && (r2 != r2End))
2206     {
2207         if (r2->right <= left)
2208         {
2209             /*
2210              * Subtrahend missed the boat: go to next subtrahend.
2211              */
2212             r2++;
2213         }
2214         else if (r2->left <= left)
2215         {
2216             /*
2217              * Subtrahend precedes minuend: nuke left edge of minuend.
2218              */
2219             left = r2->right;
2220             if (left >= r1->right)
2221             {
2222                 /*
2223                  * Minuend completely covered: advance to next minuend and
2224                  * reset left fence to edge of new minuend.
2225                  */
2226                 r1++;
2227                 if (r1 != r1End)
2228                     left = r1->left;
2229             }
2230             else
2231             {
2232                 /*
2233                  * Subtrahend now used up since it doesn't extend beyond
2234                  * minuend
2235                  */
2236                 r2++;
2237             }
2238         }
2239         else if (r2->left < r1->right)
2240         {
2241             /*
2242              * Left part of subtrahend covers part of minuend: add uncovered
2243              * part of minuend to region and skip to next subtrahend.
2244              */
2245             if (!add_rect( pReg, left, top, r2->left, bottom )) return FALSE;
2246             left = r2->right;
2247             if (left >= r1->right)
2248             {
2249                 /*
2250                  * Minuend used up: advance to new...
2251                  */
2252                 r1++;
2253                 if (r1 != r1End)
2254                     left = r1->left;
2255             }
2256             else
2257             {
2258                 /*
2259                  * Subtrahend used up
2260                  */
2261                 r2++;
2262             }
2263         }
2264         else
2265         {
2266             /*
2267              * Minuend used up: add any remaining piece before advancing.
2268              */
2269             if (r1->right > left)
2270             {
2271                 if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2272             }
2273             r1++;
2274             if (r1 != r1End)
2275                 left = r1->left;
2276         }
2277     }
2278
2279     /*
2280      * Add remaining minuend rectangles to region.
2281      */
2282     while (r1 != r1End)
2283     {
2284         if (!add_rect( pReg, left, top, r1->right, bottom )) return FALSE;
2285         r1++;
2286         if (r1 != r1End)
2287         {
2288             left = r1->left;
2289         }
2290     }
2291     return TRUE;
2292 }
2293
2294 /***********************************************************************
2295  *           REGION_SubtractRegion
2296  *
2297  *      Subtract regS from regM and leave the result in regD.
2298  *      S stands for subtrahend, M for minuend and D for difference.
2299  *
2300  * Results:
2301  *      TRUE.
2302  *
2303  * Side Effects:
2304  *      regD is overwritten.
2305  *
2306  */
2307 static BOOL REGION_SubtractRegion(WINEREGION *regD, WINEREGION *regM, WINEREGION *regS )
2308 {
2309    /* check for trivial reject */
2310     if ( (!(regM->numRects)) || (!(regS->numRects))  ||
2311         (!EXTENTCHECK(&regM->extents, &regS->extents)) )
2312         return REGION_CopyRegion(regD, regM);
2313
2314     if (!REGION_RegionOp (regD, regM, regS, REGION_SubtractO, REGION_SubtractNonO1, NULL))
2315         return FALSE;
2316
2317     /*
2318      * Can't alter newReg's extents before we call miRegionOp because
2319      * it might be one of the source regions and miRegionOp depends
2320      * on the extents of those regions being the unaltered. Besides, this
2321      * way there's no checking against rectangles that will be nuked
2322      * due to coalescing, so we have to examine fewer rectangles.
2323      */
2324     REGION_SetExtents (regD);
2325     return TRUE;
2326 }
2327
2328 /***********************************************************************
2329  *           REGION_XorRegion
2330  */
2331 static BOOL REGION_XorRegion(WINEREGION *dr, WINEREGION *sra, WINEREGION *srb)
2332 {
2333     WINEREGION tra, trb;
2334     BOOL ret;
2335
2336     if (!init_region( &tra, sra->numRects + 1 )) return FALSE;
2337     if ((ret = init_region( &trb, srb->numRects + 1 )))
2338     {
2339         ret = REGION_SubtractRegion(&tra,sra,srb) &&
2340               REGION_SubtractRegion(&trb,srb,sra) &&
2341               REGION_UnionRegion(dr,&tra,&trb);
2342         destroy_region(&trb);
2343     }
2344     destroy_region(&tra);
2345     return ret;
2346 }
2347
2348 /**************************************************************************
2349  *
2350  *    Poly Regions
2351  *
2352  *************************************************************************/
2353
2354 #define LARGE_COORDINATE  0x7fffffff /* FIXME */
2355 #define SMALL_COORDINATE  0x80000000
2356
2357 /***********************************************************************
2358  *     REGION_InsertEdgeInET
2359  *
2360  *     Insert the given edge into the edge table.
2361  *     First we must find the correct bucket in the
2362  *     Edge table, then find the right slot in the
2363  *     bucket.  Finally, we can insert it.
2364  *
2365  */
2366 static void REGION_InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE,
2367                 INT scanline, ScanLineListBlock **SLLBlock, INT *iSLLBlock)
2368
2369 {
2370     EdgeTableEntry *start, *prev;
2371     ScanLineList *pSLL, *pPrevSLL;
2372     ScanLineListBlock *tmpSLLBlock;
2373
2374     /*
2375      * find the right bucket to put the edge into
2376      */
2377     pPrevSLL = &ET->scanlines;
2378     pSLL = pPrevSLL->next;
2379     while (pSLL && (pSLL->scanline < scanline))
2380     {
2381         pPrevSLL = pSLL;
2382         pSLL = pSLL->next;
2383     }
2384
2385     /*
2386      * reassign pSLL (pointer to ScanLineList) if necessary
2387      */
2388     if ((!pSLL) || (pSLL->scanline > scanline))
2389     {
2390         if (*iSLLBlock > SLLSPERBLOCK-1)
2391         {
2392             tmpSLLBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(ScanLineListBlock));
2393             if(!tmpSLLBlock)
2394             {
2395                 WARN("Can't alloc SLLB\n");
2396                 return;
2397             }
2398             (*SLLBlock)->next = tmpSLLBlock;
2399             tmpSLLBlock->next = NULL;
2400             *SLLBlock = tmpSLLBlock;
2401             *iSLLBlock = 0;
2402         }
2403         pSLL = &((*SLLBlock)->SLLs[(*iSLLBlock)++]);
2404
2405         pSLL->next = pPrevSLL->next;
2406         pSLL->edgelist = NULL;
2407         pPrevSLL->next = pSLL;
2408     }
2409     pSLL->scanline = scanline;
2410
2411     /*
2412      * now insert the edge in the right bucket
2413      */
2414     prev = NULL;
2415     start = pSLL->edgelist;
2416     while (start && (start->bres.minor_axis < ETE->bres.minor_axis))
2417     {
2418         prev = start;
2419         start = start->next;
2420     }
2421     ETE->next = start;
2422
2423     if (prev)
2424         prev->next = ETE;
2425     else
2426         pSLL->edgelist = ETE;
2427 }
2428
2429 /***********************************************************************
2430  *     REGION_CreateEdgeTable
2431  *
2432  *     This routine creates the edge table for
2433  *     scan converting polygons.
2434  *     The Edge Table (ET) looks like:
2435  *
2436  *    EdgeTable
2437  *     --------
2438  *    |  ymax  |        ScanLineLists
2439  *    |scanline|-->------------>-------------->...
2440  *     --------   |scanline|   |scanline|
2441  *                |edgelist|   |edgelist|
2442  *                ---------    ---------
2443  *                    |             |
2444  *                    |             |
2445  *                    V             V
2446  *              list of ETEs   list of ETEs
2447  *
2448  *     where ETE is an EdgeTableEntry data structure,
2449  *     and there is one ScanLineList per scanline at
2450  *     which an edge is initially entered.
2451  *
2452  */
2453 static void REGION_CreateETandAET(const INT *Count, INT nbpolygons,
2454             const POINT *pts, EdgeTable *ET, EdgeTableEntry *AET,
2455             EdgeTableEntry *pETEs, ScanLineListBlock *pSLLBlock)
2456 {
2457     const POINT *top, *bottom;
2458     const POINT *PrevPt, *CurrPt, *EndPt;
2459     INT poly, count;
2460     int iSLLBlock = 0;
2461     int dy;
2462
2463
2464     /*
2465      *  initialize the Active Edge Table
2466      */
2467     AET->next = NULL;
2468     AET->back = NULL;
2469     AET->nextWETE = NULL;
2470     AET->bres.minor_axis = SMALL_COORDINATE;
2471
2472     /*
2473      *  initialize the Edge Table.
2474      */
2475     ET->scanlines.next = NULL;
2476     ET->ymax = SMALL_COORDINATE;
2477     ET->ymin = LARGE_COORDINATE;
2478     pSLLBlock->next = NULL;
2479
2480     EndPt = pts - 1;
2481     for(poly = 0; poly < nbpolygons; poly++)
2482     {
2483         count = Count[poly];
2484         EndPt += count;
2485         if(count < 2)
2486             continue;
2487
2488         PrevPt = EndPt;
2489
2490     /*
2491      *  for each vertex in the array of points.
2492      *  In this loop we are dealing with two vertices at
2493      *  a time -- these make up one edge of the polygon.
2494      */
2495         while (count--)
2496         {
2497             CurrPt = pts++;
2498
2499         /*
2500          *  find out which point is above and which is below.
2501          */
2502             if (PrevPt->y > CurrPt->y)
2503             {
2504                 bottom = PrevPt, top = CurrPt;
2505                 pETEs->ClockWise = 0;
2506             }
2507             else
2508             {
2509                 bottom = CurrPt, top = PrevPt;
2510                 pETEs->ClockWise = 1;
2511             }
2512
2513         /*
2514          * don't add horizontal edges to the Edge table.
2515          */
2516             if (bottom->y != top->y)
2517             {
2518                 pETEs->ymax = bottom->y-1;
2519                                 /* -1 so we don't get last scanline */
2520
2521             /*
2522              *  initialize integer edge algorithm
2523              */
2524                 dy = bottom->y - top->y;
2525                 BRESINITPGONSTRUCT(dy, top->x, bottom->x, pETEs->bres);
2526
2527                 REGION_InsertEdgeInET(ET, pETEs, top->y, &pSLLBlock,
2528                                                                 &iSLLBlock);
2529
2530                 if (PrevPt->y > ET->ymax)
2531                   ET->ymax = PrevPt->y;
2532                 if (PrevPt->y < ET->ymin)
2533                   ET->ymin = PrevPt->y;
2534                 pETEs++;
2535             }
2536
2537             PrevPt = CurrPt;
2538         }
2539     }
2540 }
2541
2542 /***********************************************************************
2543  *     REGION_loadAET
2544  *
2545  *     This routine moves EdgeTableEntries from the
2546  *     EdgeTable into the Active Edge Table,
2547  *     leaving them sorted by smaller x coordinate.
2548  *
2549  */
2550 static void REGION_loadAET(EdgeTableEntry *AET, EdgeTableEntry *ETEs)
2551 {
2552     EdgeTableEntry *pPrevAET;
2553     EdgeTableEntry *tmp;
2554
2555     pPrevAET = AET;
2556     AET = AET->next;
2557     while (ETEs)
2558     {
2559         while (AET && (AET->bres.minor_axis < ETEs->bres.minor_axis))
2560         {
2561             pPrevAET = AET;
2562             AET = AET->next;
2563         }
2564         tmp = ETEs->next;
2565         ETEs->next = AET;
2566         if (AET)
2567             AET->back = ETEs;
2568         ETEs->back = pPrevAET;
2569         pPrevAET->next = ETEs;
2570         pPrevAET = ETEs;
2571
2572         ETEs = tmp;
2573     }
2574 }
2575
2576 /***********************************************************************
2577  *     REGION_computeWAET
2578  *
2579  *     This routine links the AET by the
2580  *     nextWETE (winding EdgeTableEntry) link for
2581  *     use by the winding number rule.  The final
2582  *     Active Edge Table (AET) might look something
2583  *     like:
2584  *
2585  *     AET
2586  *     ----------  ---------   ---------
2587  *     |ymax    |  |ymax    |  |ymax    |
2588  *     | ...    |  |...     |  |...     |
2589  *     |next    |->|next    |->|next    |->...
2590  *     |nextWETE|  |nextWETE|  |nextWETE|
2591  *     ---------   ---------   ^--------
2592  *         |                   |       |
2593  *         V------------------->       V---> ...
2594  *
2595  */
2596 static void REGION_computeWAET(EdgeTableEntry *AET)
2597 {
2598     EdgeTableEntry *pWETE;
2599     int inside = 1;
2600     int isInside = 0;
2601
2602     AET->nextWETE = NULL;
2603     pWETE = AET;
2604     AET = AET->next;
2605     while (AET)
2606     {
2607         if (AET->ClockWise)
2608             isInside++;
2609         else
2610             isInside--;
2611
2612         if ((!inside && !isInside) ||
2613             ( inside &&  isInside))
2614         {
2615             pWETE->nextWETE = AET;
2616             pWETE = AET;
2617             inside = !inside;
2618         }
2619         AET = AET->next;
2620     }
2621     pWETE->nextWETE = NULL;
2622 }
2623
2624 /***********************************************************************
2625  *     REGION_InsertionSort
2626  *
2627  *     Just a simple insertion sort using
2628  *     pointers and back pointers to sort the Active
2629  *     Edge Table.
2630  *
2631  */
2632 static BOOL REGION_InsertionSort(EdgeTableEntry *AET)
2633 {
2634     EdgeTableEntry *pETEchase;
2635     EdgeTableEntry *pETEinsert;
2636     EdgeTableEntry *pETEchaseBackTMP;
2637     BOOL changed = FALSE;
2638
2639     AET = AET->next;
2640     while (AET)
2641     {
2642         pETEinsert = AET;
2643         pETEchase = AET;
2644         while (pETEchase->back->bres.minor_axis > AET->bres.minor_axis)
2645             pETEchase = pETEchase->back;
2646
2647         AET = AET->next;
2648         if (pETEchase != pETEinsert)
2649         {
2650             pETEchaseBackTMP = pETEchase->back;
2651             pETEinsert->back->next = AET;
2652             if (AET)
2653                 AET->back = pETEinsert->back;
2654             pETEinsert->next = pETEchase;
2655             pETEchase->back->next = pETEinsert;
2656             pETEchase->back = pETEinsert;
2657             pETEinsert->back = pETEchaseBackTMP;
2658             changed = TRUE;
2659         }
2660     }
2661     return changed;
2662 }
2663
2664 /***********************************************************************
2665  *     REGION_FreeStorage
2666  *
2667  *     Clean up our act.
2668  */
2669 static void REGION_FreeStorage(ScanLineListBlock *pSLLBlock)
2670 {
2671     ScanLineListBlock   *tmpSLLBlock;
2672
2673     while (pSLLBlock)
2674     {
2675         tmpSLLBlock = pSLLBlock->next;
2676         HeapFree( GetProcessHeap(), 0, pSLLBlock );
2677         pSLLBlock = tmpSLLBlock;
2678     }
2679 }
2680
2681
2682 /***********************************************************************
2683  *     REGION_PtsToRegion
2684  *
2685  *     Create an array of rectangles from a list of points.
2686  */
2687 static BOOL REGION_PtsToRegion(int numFullPtBlocks, int iCurPtBlock,
2688                                POINTBLOCK *FirstPtBlock, WINEREGION *reg)
2689 {
2690     RECT *rects;
2691     POINT *pts;
2692     POINTBLOCK *CurPtBlock;
2693     int i;
2694     RECT *extents;
2695     INT numRects;
2696
2697     extents = &reg->extents;
2698
2699     numRects = ((numFullPtBlocks * NUMPTSTOBUFFER) + iCurPtBlock) >> 1;
2700     if (!init_region( reg, numRects )) return FALSE;
2701
2702     reg->size = numRects;
2703     CurPtBlock = FirstPtBlock;
2704     rects = reg->rects - 1;
2705     numRects = 0;
2706     extents->left = LARGE_COORDINATE,  extents->right = SMALL_COORDINATE;
2707
2708     for ( ; numFullPtBlocks >= 0; numFullPtBlocks--) {
2709         /* the loop uses 2 points per iteration */
2710         i = NUMPTSTOBUFFER >> 1;
2711         if (!numFullPtBlocks)
2712             i = iCurPtBlock >> 1;
2713         for (pts = CurPtBlock->pts; i--; pts += 2) {
2714             if (pts->x == pts[1].x)
2715                 continue;
2716             if (numRects && pts->x == rects->left && pts->y == rects->bottom &&
2717                 pts[1].x == rects->right &&
2718                 (numRects == 1 || rects[-1].top != rects->top) &&
2719                 (i && pts[2].y > pts[1].y)) {
2720                 rects->bottom = pts[1].y + 1;
2721                 continue;
2722             }
2723             numRects++;
2724             rects++;
2725             rects->left = pts->x;  rects->top = pts->y;
2726             rects->right = pts[1].x;  rects->bottom = pts[1].y + 1;
2727             if (rects->left < extents->left)
2728                 extents->left = rects->left;
2729             if (rects->right > extents->right)
2730                 extents->right = rects->right;
2731         }
2732         CurPtBlock = CurPtBlock->next;
2733     }
2734
2735     if (numRects) {
2736         extents->top = reg->rects->top;
2737         extents->bottom = rects->bottom;
2738     } else {
2739         extents->left = 0;
2740         extents->top = 0;
2741         extents->right = 0;
2742         extents->bottom = 0;
2743     }
2744     reg->numRects = numRects;
2745
2746     return(TRUE);
2747 }
2748
2749 /***********************************************************************
2750  *           CreatePolyPolygonRgn    (GDI32.@)
2751  */
2752 HRGN WINAPI CreatePolyPolygonRgn(const POINT *Pts, const INT *Count,
2753                       INT nbpolygons, INT mode)
2754 {
2755     HRGN hrgn = 0;
2756     WINEREGION *obj;
2757     EdgeTableEntry *pAET;            /* Active Edge Table       */
2758     INT y;                           /* current scanline        */
2759     int iPts = 0;                    /* number of pts in buffer */
2760     EdgeTableEntry *pWETE;           /* Winding Edge Table Entry*/
2761     ScanLineList *pSLL;              /* current scanLineList    */
2762     POINT *pts;                      /* output buffer           */
2763     EdgeTableEntry *pPrevAET;        /* ptr to previous AET     */
2764     EdgeTable ET;                    /* header node for ET      */
2765     EdgeTableEntry AET;              /* header node for AET     */
2766     EdgeTableEntry *pETEs;           /* EdgeTableEntries pool   */
2767     ScanLineListBlock SLLBlock;      /* header for scanlinelist */
2768     int fixWAET = FALSE;
2769     POINTBLOCK FirstPtBlock, *curPtBlock; /* PtBlock buffers    */
2770     POINTBLOCK *tmpPtBlock;
2771     int numFullPtBlocks = 0;
2772     INT poly, total;
2773
2774     TRACE("%p, count %d, polygons %d, mode %d\n", Pts, *Count, nbpolygons, mode);
2775
2776     /* special case a rectangle */
2777
2778     if (((nbpolygons == 1) && ((*Count == 4) ||
2779        ((*Count == 5) && (Pts[4].x == Pts[0].x) && (Pts[4].y == Pts[0].y)))) &&
2780         (((Pts[0].y == Pts[1].y) &&
2781           (Pts[1].x == Pts[2].x) &&
2782           (Pts[2].y == Pts[3].y) &&
2783           (Pts[3].x == Pts[0].x)) ||
2784          ((Pts[0].x == Pts[1].x) &&
2785           (Pts[1].y == Pts[2].y) &&
2786           (Pts[2].x == Pts[3].x) &&
2787           (Pts[3].y == Pts[0].y))))
2788         return CreateRectRgn( min(Pts[0].x, Pts[2].x), min(Pts[0].y, Pts[2].y),
2789                               max(Pts[0].x, Pts[2].x), max(Pts[0].y, Pts[2].y) );
2790
2791     for(poly = total = 0; poly < nbpolygons; poly++)
2792         total += Count[poly];
2793     if (! (pETEs = HeapAlloc( GetProcessHeap(), 0, sizeof(EdgeTableEntry) * total )))
2794         return 0;
2795
2796     pts = FirstPtBlock.pts;
2797     REGION_CreateETandAET(Count, nbpolygons, Pts, &ET, &AET, pETEs, &SLLBlock);
2798     pSLL = ET.scanlines.next;
2799     curPtBlock = &FirstPtBlock;
2800
2801     if (mode != WINDING) {
2802         /*
2803          *  for each scanline
2804          */
2805         for (y = ET.ymin; y < ET.ymax; y++) {
2806             /*
2807              *  Add a new edge to the active edge table when we
2808              *  get to the next edge.
2809              */
2810             if (pSLL != NULL && y == pSLL->scanline) {
2811                 REGION_loadAET(&AET, pSLL->edgelist);
2812                 pSLL = pSLL->next;
2813             }
2814             pPrevAET = &AET;
2815             pAET = AET.next;
2816
2817             /*
2818              *  for each active edge
2819              */
2820             while (pAET) {
2821                 pts->x = pAET->bres.minor_axis,  pts->y = y;
2822                 pts++, iPts++;
2823
2824                 /*
2825                  *  send out the buffer
2826                  */
2827                 if (iPts == NUMPTSTOBUFFER) {
2828                     tmpPtBlock = HeapAlloc( GetProcessHeap(), 0, sizeof(POINTBLOCK));
2829                     if(!tmpPtBlock) goto done;
2830                     curPtBlock->next = tmpPtBlock;
2831                     curPtBlock = tmpPtBlock;
2832                     pts = curPtBlock->pts;
2833                     numFullPtBlocks++;
2834                     iPts = 0;
2835                 }
2836                 EVALUATEEDGEEVENODD(pAET, pPrevAET, y);
2837             }
2838             REGION_InsertionSort(&AET);
2839         }
2840     }
2841     else {
2842         /*
2843          *  for each scanline
2844          */
2845         for (y = ET.ymin; y < ET.ymax; y++) {
2846             /*
2847              *  Add a new edge to the active edge table when we
2848              *  get to the next edge.
2849              */
2850             if (pSLL != NULL && y == pSLL->scanline) {
2851                 REGION_loadAET(&AET, pSLL->edgelist);
2852                 REGION_computeWAET(&AET);
2853                 pSLL = pSLL->next;
2854             }
2855             pPrevAET = &AET;
2856             pAET = AET.next;
2857             pWETE = pAET;
2858
2859             /*
2860              *  for each active edge
2861              */
2862             while (pAET) {
2863                 /*
2864                  *  add to the buffer only those edges that
2865                  *  are in the Winding active edge table.
2866                  */
2867                 if (pWETE == pAET) {
2868                     pts->x = pAET->bres.minor_axis,  pts->y = y;
2869                     pts++, iPts++;
2870
2871                     /*
2872                      *  send out the buffer
2873                      */
2874                     if (iPts == NUMPTSTOBUFFER) {
2875                         tmpPtBlock = HeapAlloc( GetProcessHeap(), 0,
2876                                                sizeof(POINTBLOCK) );
2877                         if(!tmpPtBlock) goto done;
2878                         curPtBlock->next = tmpPtBlock;
2879                         curPtBlock = tmpPtBlock;
2880                         pts = curPtBlock->pts;
2881                         numFullPtBlocks++;
2882                         iPts = 0;
2883                     }
2884                     pWETE = pWETE->nextWETE;
2885                 }
2886                 EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET);
2887             }
2888
2889             /*
2890              *  recompute the winding active edge table if
2891              *  we just resorted or have exited an edge.
2892              */
2893             if (REGION_InsertionSort(&AET) || fixWAET) {
2894                 REGION_computeWAET(&AET);
2895                 fixWAET = FALSE;
2896             }
2897         }
2898     }
2899
2900     if (!(obj = HeapAlloc( GetProcessHeap(), 0, sizeof(*obj) ))) goto done;
2901
2902     if (!REGION_PtsToRegion(numFullPtBlocks, iPts, &FirstPtBlock, obj))
2903     {
2904         HeapFree( GetProcessHeap(), 0, obj );
2905         goto done;
2906     }
2907     if (!(hrgn = alloc_gdi_handle( obj, OBJ_REGION, &region_funcs )))
2908     {
2909         HeapFree( GetProcessHeap(), 0, obj->rects );
2910         HeapFree( GetProcessHeap(), 0, obj );
2911     }
2912
2913 done:
2914     REGION_FreeStorage(SLLBlock.next);
2915     for (curPtBlock = FirstPtBlock.next; --numFullPtBlocks >= 0;) {
2916         tmpPtBlock = curPtBlock->next;
2917         HeapFree( GetProcessHeap(), 0, curPtBlock );
2918         curPtBlock = tmpPtBlock;
2919     }
2920     HeapFree( GetProcessHeap(), 0, pETEs );
2921     return hrgn;
2922 }
2923
2924
2925 /***********************************************************************
2926  *           CreatePolygonRgn    (GDI32.@)
2927  */
2928 HRGN WINAPI CreatePolygonRgn( const POINT *points, INT count,
2929                                   INT mode )
2930 {
2931     return CreatePolyPolygonRgn( points, &count, 1, mode );
2932 }