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