mapbox / shelf-pack

A 2D rectangular bin packing data structure that uses the Shelf Best Height Fit heuristic
ISC License
129 stars 17 forks source link

Question: what if growing the amount of width or height instead of doubling #93

Closed cs09g closed 5 years ago

cs09g commented 5 years ago

When it has no room for more shelves, it doubles its width or height. https://github.com/mapbox/shelf-pack/blob/master/index.mjs#L194

So it can potentially waste a lot of space as said on README.

What about to just add bin's width or height instead of double the size? like:

if (w1 <= h1 || w > w1) {   // grow width..
    w2 = Math.max(w, w1) + w;
}
if (h1 < w1 || h > h1) {    // grow height..
    h2 = Math.max(h, h1) + h;
}

It takes less space. May this change make any side-effects?

bhousel commented 5 years ago

Good question! The library works like this because it was originally intended to pack glyphs into graphics texture memory, which tends to prefer the memory being allocated in dimensions that are powers of 2, and also to avoid costly reallocations.

We found that if the maps being shown used mostly Latin characters in the fonts, we didn't need to pack so many glyphs - 26 letters, 10 numbers, and a handful of punctuation. They'd grow to a certain size and then stop and we didn't have to think much about memory. But if the maps being shown used CJK characters, these sprites can grow much larger, so they would grow to fit about the number of glyphs that are being used on the visible map, then as the user panned the map around we'd swap different glyphs into the spritesheet as needed and avoid the reallocations.

cs09g commented 5 years ago

Thanks for the very quick answer! So it can reduce the number of memory re-allocation times. I'm using it to calculate and arrange bins for image sprites that the memory usage is not very critical :)