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