svn merge -r 23207:23528 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / blenlib / intern / boxpack2d.c
1 /*
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * Contributor(s): Campbell Barton
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 #include <stdlib.h> /* for qsort */
25
26 #include "MEM_guardedalloc.h"
27 #include "BLI_boxpack2d.h"
28  
29 /* BoxPacker for backing 2D rectangles into a square
30  * 
31  * The defined Below are for internal use only */
32
33 /* free vert flags */
34 #define eul 0.0000001f
35 #define BLF 1
36 #define TRF 2
37 #define TLF 4
38 #define BRF 8
39 #define CORNERFLAGS (BLF|TRF|TLF|BRF)
40
41 #define BL 0
42 #define TR 1
43 #define TL 2
44 #define BR 3
45
46 #define BOXLEFT(b)              b->v[BL]->x
47 #define BOXRIGHT(b)             b->v[TR]->x
48 #define BOXBOTTOM(b)    b->v[BL]->y
49 #define BOXTOP(b)               b->v[TR]->y
50 #define BOXAREA(b)              (b->w * b->h)
51
52 #define UPDATE_V34X(b)  b->v[TL]->x = b->v[BL]->x;\
53                                                 b->v[BR]->x = b->v[TR]->x
54 #define UPDATE_V34Y(b)  b->v[TL]->y = b->v[TR]->y;\
55                                                 b->v[BR]->y = b->v[BL]->y
56 #define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)  
57
58 #define SET_BOXLEFT(b, f)       b->v[TR]->x = f + b->w;\
59                                                         b->v[BL]->x = f;\
60                                                         UPDATE_V34X(b)
61 #define SET_BOXRIGHT(b, f)      b->v[BL]->x = f - b->w;\
62                                                         b->v[TR]->x = f;\
63                                                         UPDATE_V34X(b)
64 #define SET_BOXBOTTOM(b, f)     b->v[TR]->y = f + b->h;\
65                                                         b->v[BL]->y = f;\
66                                                         UPDATE_V34Y(b)
67 #define SET_BOXTOP(b, f)        b->v[BL]->y = f - b->h;\
68                                                         b->v[TR]->y = f;\
69                                                         UPDATE_V34Y(b)
70 #define BOXINTERSECT(b1, b2)\
71         (!( BOXLEFT(b1)+eul>=BOXRIGHT(b2) ||\
72                 BOXBOTTOM(b1)+eul>=BOXTOP(b2) ||\
73                 BOXRIGHT(b1)-eul<=BOXLEFT(b2) ||\
74                 BOXTOP(b1)-eul<=BOXBOTTOM(b2) ))
75
76 #define MIN2(x,y)               ( (x)<(y) ? (x) : (y) )
77 #define MAX2(x,y)               ( (x)>(y) ? (x) : (y) )
78
79 /* #define BOXDEBUG(b)\
80  *              printf("\tBox Debug i %i, w:%.3f h:%.3f x:%.3f y:%.3f\n",\
81  *              b->index, b->w, b->h, b->x, b->y) */
82
83 /* qsort function - sort largest to smallest */
84 static int box_areasort(const void *p1, const void *p2)
85 {
86         const boxPack *b1=p1, *b2=p2;
87         float a1, a2;
88
89         a1 = BOXAREA(b1);
90         a2 = BOXAREA(b2);
91         
92         if              ( a1 < a2 ) return  1;
93         else if ( a1 > a2 ) return -1;
94         return 0;
95 }
96
97 /* qsort vertex sorting function
98  * sorts from lower left to top right It uses the current box's width and height 
99  * as offsets when sorting, this has the result of not placing boxes outside
100  * the bounds of the existing backed area where possible
101  * */
102 static float box_width;
103 static float box_height;
104 static boxVert *vertarray;
105
106 static int vertex_sort(const void *p1, const void *p2)
107 {
108         boxVert *v1, *v2;
109         float a1, a2;
110         
111         v1 = vertarray + ((int *) p1)[0];
112         v2 = vertarray + ((int *) p2)[0];
113         
114         a1 = MAX2(v1->x+box_width, v1->y+box_height);
115         a2 = MAX2(v2->x+box_width, v2->y+box_height);
116         
117         /* sort largest to smallest */
118         if              ( a1 > a2 ) return  1;
119         else if ( a1 < a2 ) return -1;
120         return 0;
121 }
122 /* Main boxpacking function accessed from other functions
123  * This sets boxes x,y to positive values, sorting from 0,0 outwards.
124  * There is no limit to the space boxes may take, only that they will be packed
125  * tightly into the lower left hand corner (0,0)
126  * 
127  * boxarray - a pre allocated array of boxes.
128  *              only the 'box->x' and 'box->y' are set, 'box->w' and 'box->h' are used,
129  *              'box->index' is not used at all, the only reason its there
130  *                      is that the box array is sorted by area and programs need to be able
131  *                      to have some way of writing the boxes back to the original data.
132  *      len - the number of boxes in the array.
133  *      tot_width and tot_height are set so you can normalize the data.
134  *  */
135 void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
136 {
137         boxVert *vert; /* the current vert */
138         int box_index, verts_pack_len, i, j, k, isect;
139         int quad_flags[4]= {BLF,TRF,TLF,BRF}; /* use for looping */
140         boxPack *box, *box_test; /*current box and another for intersection tests*/
141         int *vertex_pack_indicies; /*an array of indices used for sorting verts*/
142         
143         if (!len) {
144                 *tot_width =  0.0f;
145                 *tot_height = 0.0f;
146                 return;
147         }
148         
149         /* Sort boxes, biggest first */
150         qsort(boxarray, len, sizeof(boxPack), box_areasort);
151         
152         /* add verts to the boxes, these are only used internally  */
153         vert = vertarray = MEM_mallocN( len*4*sizeof(boxVert), "boxPack Verts");
154         vertex_pack_indicies = MEM_mallocN( len*3*sizeof(int), "boxPack Indices");
155         
156         for (box=boxarray, box_index=0, i=0; box_index < len; box_index++, box++) {
157                                 
158                 vert->blb = vert->brb = vert->tlb =\
159                         vert->isect_cache[0] = vert->isect_cache[1] =\
160                         vert->isect_cache[2] = vert->isect_cache[3] = NULL;
161                 vert->free = CORNERFLAGS &~ TRF;
162                 vert->trb = box;
163                 vert->index = i; i++;
164                 box->v[BL] = vert; vert++;
165                 
166                 vert->trb= vert->brb = vert->tlb =\
167                         vert->isect_cache[0] = vert->isect_cache[1] =\
168                         vert->isect_cache[2] = vert->isect_cache[3] = NULL;
169                 vert->free = CORNERFLAGS &~ BLF;
170                 vert->blb = box;
171                 vert->index = i; i++;
172                 box->v[TR] = vert; vert++;
173                 
174                 vert->trb = vert->blb = vert->tlb =\
175                         vert->isect_cache[0] = vert->isect_cache[1] =\
176                         vert->isect_cache[2] = vert->isect_cache[3] = NULL;
177                 vert->free = CORNERFLAGS &~ BRF;
178                 vert->brb = box;
179                 vert->index = i; i++;
180                 box->v[TL] = vert; vert++;
181                 
182                 vert->trb = vert->blb = vert->brb =\
183                         vert->isect_cache[0] = vert->isect_cache[1] =\
184                         vert->isect_cache[2] = vert->isect_cache[3] = NULL;
185                 vert->free = CORNERFLAGS &~ TLF;
186                 vert->tlb = box; 
187                 vert->index = i; i++;
188                 box->v[BR] = vert; vert++;
189         }
190         vert = NULL;
191         
192         
193         /* Pack the First box!
194          * then enter the main box-packing loop */
195         
196         box = boxarray; /* get the first box  */
197         /* First time, no boxes packed */
198         box->v[BL]->free = 0; /* Can't use any if these */
199         box->v[BR]->free &= ~(BLF|BRF);
200         box->v[TL]->free &= ~(BLF|TLF);
201         
202         *tot_width = box->w;
203         *tot_height = box->h; 
204         
205         /* This sets all the vertex locations */
206         SET_BOXLEFT(box, 0.0f);
207         SET_BOXBOTTOM(box, 0.0f);
208         box->x = box->y = 0.0f;
209         
210         for (i=0; i<3; i++)
211                 vertex_pack_indicies[i] = box->v[i+1]->index; 
212         verts_pack_len = 3;
213         box++; /* next box, needed for the loop below */
214         /* ...done packing the first box */
215
216         /* Main boxpacking loop */
217         for (box_index=1; box_index < len; box_index++, box++) {
218                 
219                 /* These static floatds are used for sorting */
220                 box_width = box->w;
221                 box_height = box->h;
222                 
223                 qsort(vertex_pack_indicies, verts_pack_len, sizeof(int), vertex_sort);
224                 
225                 /* Pack the box in with the others */
226                 /* sort the verts */
227                 isect = 1;
228                 
229                 for (i=0; i<verts_pack_len && isect; i++) {
230                         vert = vertarray + vertex_pack_indicies[i];
231                         /* printf("\ttesting vert %i %i %i %f %f\n", i,
232                          *              vert->free, verts_pack_len, vert->x, vert->y); */
233                         
234                         /* This vert has a free quadrant
235                          * Test if we can place the box here
236                          * vert->free & quad_flags[j] - Checks 
237                          * */
238                                                 
239                         for (j=0; (j<4) && isect; j++) {
240                                 if (vert->free & quad_flags[j]) {
241                                         switch (j) {
242                                         case BL:
243                                                 SET_BOXRIGHT(box, vert->x);
244                                                 SET_BOXTOP(box, vert->y);
245                                                 break;
246                                         case TR:
247                                                 SET_BOXLEFT(box, vert->x);
248                                                 SET_BOXBOTTOM(box, vert->y);
249                                                 break;
250                                         case TL:
251                                                 SET_BOXRIGHT(box, vert->x);
252                                                 SET_BOXBOTTOM(box, vert->y);
253                                                 break;
254                                         case BR:
255                                                 SET_BOXLEFT(box, vert->x);
256                                                 SET_BOXTOP(box, vert->y);
257                                                 break;
258                                         }
259                                         
260                                         /* Now we need to check that the box intersects
261                                           * with any other boxes
262                                           * Assume no intersection... */
263                                         isect = 0;
264                                         
265                                         if (/* Constrain boxes to positive X/Y values */
266                                                 BOXLEFT(box)<0.0f || BOXBOTTOM(box) < 0.0f ||
267                                                 /* check for last intersected */
268                                                 (       vert->isect_cache[j] &&
269                                                         BOXINTERSECT(box, vert->isect_cache[j]) )
270                                            ) {
271                                                 /* Here we check that the last intersected
272                                                  * box will intersect with this one using
273                                                  * isect_cache that can store a pointer to a
274                                                  * box for each quadrant
275                                                  * big speedup */
276                                                 isect = 1;
277                                         } else {
278                                                 /* do a full search for colliding box
279                                                  * this is really slow, some spacialy divided
280                                                  * data-structure would be better */
281                                                 for (box_test=boxarray; box_test != box; box_test++) {
282                                                         if BOXINTERSECT(box, box_test) {
283                                                                 /* Store the last intersecting here as cache
284                                                                  * for faster checking next time around */
285                                                                 vert->isect_cache[j] = box_test;
286                                                                 isect = 1;
287                                                                 break;
288                                                         }
289                                                 }
290                                         }
291                                         
292                                         if (!isect) {
293                                                 
294                                                 /* maintain the total width and height */
295                                                 (*tot_width) = MAX2(BOXRIGHT(box), (*tot_width));
296                                                 (*tot_height) = MAX2(BOXTOP(box), (*tot_height));
297                                                 
298                                                 /* Place the box */
299                                                 vert->free &= ~quad_flags[j];
300                                                 
301                                                 switch (j) {
302                                                 case TR:
303                                                         box->v[BL]= vert;
304                                                         vert->trb = box;
305                                                         break;
306                                                 case TL:
307                                                         box->v[BR]= vert;
308                                                         vert->tlb = box;
309                                                         break;
310                                                 case BR:
311                                                         box->v[TL]= vert;
312                                                         vert->brb = box;
313                                                         break;
314                                                 case BL:
315                                                         box->v[TR]= vert;
316                                                         vert->blb = box;
317                                                         break;
318                                                 }
319                                                 
320                                                 /* Mask free flags for verts that are
321                                                  * on the bottom or side so we don't get
322                                                  * boxes outside the given rectangle ares
323                                                  * 
324                                                  * We can do an else/if here because only the first 
325                                                  * box can be at the very bottom left corner */
326                                                 if (BOXLEFT(box) <= 0) {
327                                                         box->v[TL]->free &= ~(TLF|BLF);
328                                                         box->v[BL]->free &= ~(TLF|BLF);                         
329                                                 } else if (BOXBOTTOM(box) <= 0) {
330                                                         box->v[BL]->free &= ~(BRF|BLF);
331                                                         box->v[BR]->free &= ~(BRF|BLF);
332                                                 }
333                                                 
334                                                 /* The following block of code does a logical
335                                                  * check with 2 adjacent boxes, its possible to
336                                                  * flag verts on one or both of the boxes 
337                                                  * as being used by checking the width or
338                                                  * height of both boxes */
339                                                 if (vert->tlb && vert->trb &&
340                                                                         (box == vert->tlb || box == vert->trb)) {
341                                                         if (vert->tlb->h > vert->trb->h) {
342                                                                 vert->trb->v[TL]->free &= ~(TLF|BLF);
343                                                         } else if (vert->tlb->h < vert->trb->h) {
344                                                                 vert->tlb->v[TR]->free &= ~(TRF|BRF);
345                                                         } else { /*same*/
346                                                                 vert->tlb->v[TR]->free &= ~BLF;
347                                                                 vert->trb->v[TL]->free &= ~BRF;
348                                                         }
349                                                 } else if (vert->blb && vert->brb &&
350                                                                         (box == vert->blb || box == vert->brb)) {
351                                                         if (vert->blb->h > vert->brb->h) {
352                                                                 vert->brb->v[BL]->free &= ~(TLF|BLF);
353                                                         } else if (vert->blb->h < vert->brb->h) {
354                                                                 vert->blb->v[BR]->free &= ~(TRF|BRF);
355                                                         } else { /*same*/
356                                                                 vert->blb->v[BR]->free &= ~TRF;
357                                                                 vert->brb->v[BL]->free &= ~TLF;
358                                                         }
359                                                 }
360                                                 /* Horizontal */
361                                                 if (vert->tlb && vert->blb &&
362                                                                         (box == vert->tlb || box == vert->blb) ) {
363                                                         if (vert->tlb->w > vert->blb->w) {
364                                                                 vert->blb->v[TL]->free &= ~(TLF|TRF);
365                                                         } else if (vert->tlb->w < vert->blb->w) {
366                                                                 vert->tlb->v[BL]->free &= ~(BLF|BRF);
367                                                         } else { /*same*/
368                                                                 vert->blb->v[TL]->free &= ~TRF;
369                                                                 vert->tlb->v[BL]->free &= ~BRF;
370                                                         }
371                                                 } else if (     vert->trb && vert->brb &&
372                                                                         (box == vert->trb || box == vert->brb) ) {
373                                                         if (vert->trb->w > vert->brb->w) {
374                                                                 vert->brb->v[TR]->free &= ~(TRF|TRF);
375                                                         } else if (vert->trb->w < vert->brb->w) {
376                                                                 vert->trb->v[BR]->free &= ~(BLF|BRF);
377                                                         } else { /*same*/
378                                                                 vert->brb->v[TR]->free &= ~TLF;
379                                                                 vert->trb->v[BR]->free &= ~BLF;
380                                                         }
381                                                 }
382                                                 /* End logical check */
383                                                 
384                                                 
385                                                 for (k=0; k<4; k++) {
386                                                         if (box->v[k] != vert) {
387                                                                 vertex_pack_indicies[verts_pack_len] =
388                                                                                         box->v[k]->index; 
389                                                                 verts_pack_len++;
390                                                         }
391                                                 }
392                                                 /* The Box verts are only used internally
393                                                  * Update the box x and y since thats what external
394                                                  * functions will see */
395                                                 box->x = BOXLEFT(box);
396                                                 box->y = BOXBOTTOM(box);
397                                         }
398                                 }       
399                         }
400                 }
401         }
402
403         /* free all the verts, not really needed because they shouldn't be
404          * touched anymore but accessing the pointers would crash blender */
405         for (box_index=0; box_index < len; box_index++) {
406                 box = boxarray+box_index; 
407                 box->v[0] = box->v[1] = box->v[2] = box->v[3] = NULL; 
408         }
409         MEM_freeN(vertex_pack_indicies);
410         MEM_freeN(vertarray);
411 }
412