Welcome to mirror list, hosted at ThFree Co, Russian Federation.

boxpack2d.c « intern « blenlib « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4b51aefbd872b218496f630dc087b3b3f146e8b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contributor(s): Campbell Barton
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/blenlib/intern/boxpack2d.c
 *  \ingroup bli
 */

#include <stdlib.h> /* for qsort */

#include "MEM_guardedalloc.h"
#include "BLI_strict_flags.h"

#include "BLI_boxpack2d.h"  /* own include */

#ifdef __GNUC__
#  pragma GCC diagnostic error "-Wpadded"
#endif

/* BoxPacker for backing 2D rectangles into a square
 * 
 * The defined Below are for internal use only */
typedef struct BoxVert {
	float x;
	float y;

	int free;  /* could be a char */
	unsigned int index;

	struct BoxPack *trb; /* top right box */
	struct BoxPack *blb; /* bottom left box */
	struct BoxPack *brb; /* bottom right box */
	struct BoxPack *tlb; /* top left box */

	/* Store last intersecting boxes here
	 * speedup intersection testing */
	struct BoxPack *isect_cache[4];
} BoxVert;

/* free vert flags */
#define EPSILON 0.0000001f
#define BLF 1
#define TRF 2
#define TLF 4
#define BRF 8
#define CORNERFLAGS (BLF | TRF | TLF | BRF)

#define BL 0
#define TR 1
#define TL 2
#define BR 3

#define BOXLEFT(b)      ((b)->v[BL]->x)
#define BOXRIGHT(b)     ((b)->v[TR]->x)
#define BOXBOTTOM(b)    ((b)->v[BL]->y)
#define BOXTOP(b)       ((b)->v[TR]->y)
#define BOXAREA(b)      ((b)->w * (b)->h)

#define UPDATE_V34X(b)  ((b)->v[TL]->x = (b)->v[BL]->x); \
                        ((b)->v[BR]->x = (b)->v[TR]->x)
#define UPDATE_V34Y(b)  ((b)->v[TL]->y = (b)->v[TR]->y); \
                        ((b)->v[BR]->y = (b)->v[BL]->y)

/* UNUSED */
// #define UPDATE_V34(b) UPDATE_V34X(b); UPDATE_V34Y(b)

#define SET_BOXLEFT(b, f)   (b)->v[TR]->x = f + (b)->w; \
                            (b)->v[BL]->x = f;          \
                            UPDATE_V34X(b)
#define SET_BOXRIGHT(b, f)  (b)->v[BL]->x = f - (b)->w; \
                            (b)->v[TR]->x = f;          \
                            UPDATE_V34X(b)
#define SET_BOXBOTTOM(b, f) (b)->v[TR]->y = f + (b)->h; \
                            (b)->v[BL]->y = f;          \
                            UPDATE_V34Y(b)
#define SET_BOXTOP(b, f)    (b)->v[BL]->y = f - (b)->h; \
                            (b)->v[TR]->y = f;          \
                            UPDATE_V34Y(b)
#define BOXINTERSECT(b1, b2)                 \
    !(BOXLEFT(b1)   + EPSILON >= BOXRIGHT(b2) || \
      BOXBOTTOM(b1) + EPSILON >= BOXTOP(b2)   || \
      BOXRIGHT(b1)  - EPSILON <= BOXLEFT(b2)  || \
      BOXTOP(b1)    - EPSILON <= BOXBOTTOM(b2))

/* compiler should inline */
static float max_ff(const float a, const float b) { return b > a ? b : a; }

#if 0
#define BOXDEBUG(b) \
	printf("\tBox Debug i %i, w:%.3f h:%.3f x:%.3f y:%.3f\n", \
	       b->index, b->w, b->h, b->x, b->y)
#endif

/* qsort function - sort largest to smallest */
static int box_areasort(const void *p1, const void *p2)
{
	const BoxPack *b1 = p1, *b2 = p2;
	const float a1 = BOXAREA(b1);
	const float a2 = BOXAREA(b2);

	if      (a1 < a2) return  1;
	else if (a1 > a2) return -1;
	return 0;
}

/* qsort vertex sorting function
 * sorts from lower left to top right It uses the current box's width and height 
 * as offsets when sorting, this has the result of not placing boxes outside
 * the bounds of the existing backed area where possible
 * */
static float box_width;
static float box_height;
static BoxVert *vertarray;

static int vertex_sort(const void *p1, const void *p2)
{
	BoxVert *v1, *v2;
	float a1, a2;

	v1 = vertarray + ((int *)p1)[0];
	v2 = vertarray + ((int *)p2)[0];

	a1 = max_ff(v1->x + box_width, v1->y + box_height);
	a2 = max_ff(v2->x + box_width, v2->y + box_height);

	/* sort largest to smallest */
	if      (a1 > a2) return 1;
	else if (a1 < a2) return -1;
	return 0;
}
/* Main boxpacking function accessed from other functions
 * This sets boxes x,y to positive values, sorting from 0,0 outwards.
 * There is no limit to the space boxes may take, only that they will be packed
 * tightly into the lower left hand corner (0,0)
 * 
 * boxarray - a pre allocated array of boxes.
 *      only the 'box->x' and 'box->y' are set, 'box->w' and 'box->h' are used,
 *      'box->index' is not used at all, the only reason its there
 *          is that the box array is sorted by area and programs need to be able
 *          to have some way of writing the boxes back to the original data.
 *  len - the number of boxes in the array.
 *	tot_width and tot_height are set so you can normalize the data.
 *  */
void BLI_box_pack_2d(BoxPack *boxarray, const unsigned int len, float *tot_width, float *tot_height)
{
	const int quad_flags[4] = {BLF, TRF, TLF, BRF};  /* use for looping */
	unsigned int box_index, verts_pack_len, i, j, k;
	unsigned int *vertex_pack_indices;  /* an array of indices used for sorting verts */
	bool isect;

	BoxPack *box, *box_test; /*current box and another for intersection tests*/
	BoxVert *vert; /* the current vert */

	if (!len) {
		*tot_width = 0.0f;
		*tot_height = 0.0f;
		return;
	}

	/* Sort boxes, biggest first */
	qsort(boxarray, (size_t)len, sizeof(BoxPack), box_areasort);

	/* add verts to the boxes, these are only used internally  */
	vert = vertarray = MEM_mallocN((size_t)len * 4 * sizeof(BoxVert), "BoxPack Verts");
	vertex_pack_indices = MEM_mallocN((size_t)len * 3 * sizeof(int), "BoxPack Indices");

	for (box = boxarray, box_index = 0, i = 0; box_index < len; box_index++, box++) {

		vert->blb = vert->brb = vert->tlb =
		            vert->isect_cache[0] = vert->isect_cache[1] =
		            vert->isect_cache[2] = vert->isect_cache[3] = NULL;
		vert->free = CORNERFLAGS & ~TRF;
		vert->trb = box;
		vert->index = i++;
		box->v[BL] = vert; vert++;
		
		vert->trb = vert->brb = vert->tlb =
		            vert->isect_cache[0] = vert->isect_cache[1] =
		            vert->isect_cache[2] = vert->isect_cache[3] = NULL;
		vert->free = CORNERFLAGS & ~BLF;
		vert->blb = box;
		vert->index = i++;
		box->v[TR] = vert; vert++;
		
		vert->trb = vert->blb = vert->tlb =
		            vert->isect_cache[0] = vert->isect_cache[1] =
		            vert->isect_cache[2] = vert->isect_cache[3] = NULL;
		vert->free = CORNERFLAGS & ~BRF;
		vert->brb = box;
		vert->index = i++;
		box->v[TL] = vert; vert++;
		
		vert->trb = vert->blb = vert->brb =
		            vert->isect_cache[0] = vert->isect_cache[1] =
		            vert->isect_cache[2] = vert->isect_cache[3] = NULL;
		vert->free = CORNERFLAGS & ~TLF;
		vert->tlb = box; 
		vert->index = i++;
		box->v[BR] = vert; vert++;
	}
	vert = NULL;

	/* Pack the First box!
	 * then enter the main box-packing loop */

	box = boxarray; /* get the first box  */
	/* First time, no boxes packed */
	box->v[BL]->free = 0; /* Can't use any if these */
	box->v[BR]->free &= ~(BLF | BRF);
	box->v[TL]->free &= ~(BLF | TLF);

	*tot_width = box->w;
	*tot_height = box->h;

	/* This sets all the vertex locations */
	SET_BOXLEFT(box, 0.0f);
	SET_BOXBOTTOM(box, 0.0f);
	box->x = box->y = 0.0f;

	for (i = 0; i < 3; i++)
		vertex_pack_indices[i] = box->v[i + 1]->index;
	verts_pack_len = 3;
	box++; /* next box, needed for the loop below */
	/* ...done packing the first box */

	/* Main boxpacking loop */
	for (box_index = 1; box_index < len; box_index++, box++) {

		/* These static floatds are used for sorting */
		box_width = box->w;
		box_height = box->h;

		qsort(vertex_pack_indices, (size_t)verts_pack_len, sizeof(int), vertex_sort);

		/* Pack the box in with the others */
		/* sort the verts */
		isect = true;

		for (i = 0; i < verts_pack_len && isect; i++) {
			vert = vertarray + vertex_pack_indices[i];
			/* printf("\ttesting vert %i %i %i %f %f\n", i,
			 *        vert->free, verts_pack_len, vert->x, vert->y); */

			/* This vert has a free quadrant
			 * Test if we can place the box here
			 * vert->free & quad_flags[j] - Checks 
			 * */

			for (j = 0; (j < 4) && isect; j++) {
				if (vert->free & quad_flags[j]) {
					switch (j) {
						case BL:
							SET_BOXRIGHT(box, vert->x);
							SET_BOXTOP(box, vert->y);
							break;
						case TR:
							SET_BOXLEFT(box, vert->x);
							SET_BOXBOTTOM(box, vert->y);
							break;
						case TL:
							SET_BOXRIGHT(box, vert->x);
							SET_BOXBOTTOM(box, vert->y);
							break;
						case BR:
							SET_BOXLEFT(box, vert->x);
							SET_BOXTOP(box, vert->y);
							break;
					}

					/* Now we need to check that the box intersects
					 * with any other boxes
					 * Assume no intersection... */
					isect = false;
					
					if ( /* Constrain boxes to positive X/Y values */
					    BOXLEFT(box) < 0.0f || BOXBOTTOM(box) < 0.0f ||
					    /* check for last intersected */
					    (vert->isect_cache[j] &&
					     BOXINTERSECT(box, vert->isect_cache[j])))
					{
						/* Here we check that the last intersected
						 * box will intersect with this one using
						 * isect_cache that can store a pointer to a
						 * box for each quadrant
						 * big speedup */
						isect = true;
					}
					else {
						/* do a full search for colliding box
						 * this is really slow, some spatially divided
						 * data-structure would be better */
						for (box_test = boxarray; box_test != box; box_test++) {
							if (BOXINTERSECT(box, box_test)) {
								/* Store the last intersecting here as cache
								 * for faster checking next time around */
								vert->isect_cache[j] = box_test;
								isect = true;
								break;
							}
						}
					}

					if (!isect) {

						/* maintain the total width and height */
						(*tot_width) = max_ff(BOXRIGHT(box), (*tot_width));
						(*tot_height) = max_ff(BOXTOP(box), (*tot_height));

						/* Place the box */
						vert->free &= ~quad_flags[j];

						switch (j) {
							case TR:
								box->v[BL] = vert;
								vert->trb = box;
								break;
							case TL:
								box->v[BR] = vert;
								vert->tlb = box;
								break;
							case BR:
								box->v[TL] = vert;
								vert->brb = box;
								break;
							case BL:
								box->v[TR] = vert;
								vert->blb = box;
								break;
						}

						/* Mask free flags for verts that are
						 * on the bottom or side so we don't get
						 * boxes outside the given rectangle ares
						 * 
						 * We can do an else/if here because only the first 
						 * box can be at the very bottom left corner */
						if (BOXLEFT(box) <= 0) {
							box->v[TL]->free &= ~(TLF | BLF);
							box->v[BL]->free &= ~(TLF | BLF);
						}
						else if (BOXBOTTOM(box) <= 0) {
							box->v[BL]->free &= ~(BRF | BLF);
							box->v[BR]->free &= ~(BRF | BLF);
						}

						/* The following block of code does a logical
						 * check with 2 adjacent boxes, its possible to
						 * flag verts on one or both of the boxes 
						 * as being used by checking the width or
						 * height of both boxes */
						if (vert->tlb && vert->trb && (box == vert->tlb || box == vert->trb)) {
							if (vert->tlb->h > vert->trb->h) {
								vert->trb->v[TL]->free &= ~(TLF | BLF);
							}
							else if (vert->tlb->h < vert->trb->h) {
								vert->tlb->v[TR]->free &= ~(TRF | BRF);
							}
							else { /*same*/
								vert->tlb->v[TR]->free &= ~BLF;
								vert->trb->v[TL]->free &= ~BRF;
							}
						}
						else if (vert->blb && vert->brb && (box == vert->blb || box == vert->brb)) {
							if (vert->blb->h > vert->brb->h) {
								vert->brb->v[BL]->free &= ~(TLF | BLF);
							}
							else if (vert->blb->h < vert->brb->h) {
								vert->blb->v[BR]->free &= ~(TRF | BRF);
							}
							else { /*same*/
								vert->blb->v[BR]->free &= ~TRF;
								vert->brb->v[BL]->free &= ~TLF;
							}
						}
						/* Horizontal */
						if (vert->tlb && vert->blb && (box == vert->tlb || box == vert->blb)) {
							if (vert->tlb->w > vert->blb->w) {
								vert->blb->v[TL]->free &= ~(TLF | TRF);
							}
							else if (vert->tlb->w < vert->blb->w) {
								vert->tlb->v[BL]->free &= ~(BLF | BRF);
							}
							else { /*same*/
								vert->blb->v[TL]->free &= ~TRF;
								vert->tlb->v[BL]->free &= ~BRF;
							}
						}
						else if (vert->trb && vert->brb && (box == vert->trb || box == vert->brb)) {
							if (vert->trb->w > vert->brb->w) {
								vert->brb->v[TR]->free &= ~(TLF | TRF);
							}
							else if (vert->trb->w < vert->brb->w) {
								vert->trb->v[BR]->free &= ~(BLF | BRF);
							}
							else { /*same*/
								vert->brb->v[TR]->free &= ~TLF;
								vert->trb->v[BR]->free &= ~BLF;
							}
						}
						/* End logical check */

						for (k = 0; k < 4; k++) {
							if (box->v[k] != vert) {
								vertex_pack_indices[verts_pack_len] = box->v[k]->index;
								verts_pack_len++;
							}
						}
						/* The Box verts are only used internally
						 * Update the box x and y since thats what external
						 * functions will see */
						box->x = BOXLEFT(box);
						box->y = BOXBOTTOM(box);
					}
				}
			}
		}
	}

	/* free all the verts, not really needed because they shouldn't be
	 * touched anymore but accessing the pointers would crash blender */
	for (box_index = 0; box_index < len; box_index++) {
		box = boxarray + box_index;
		box->v[0] = box->v[1] = box->v[2] = box->v[3] = NULL;
	}
	MEM_freeN(vertex_pack_indices);
	MEM_freeN(vertarray);
}