// FCS Glass - src/core/atlas.cpp. See atlas.h. #include "core/atlas.h" namespace fcs { namespace core { ShelfPacker::ShelfPacker(int width, int max_height, int padding) : width_(width < 1 ? 1 : width), max_height_(max_height < 1 ? 1 : max_height), padding_(padding < 0 ? 0 : padding) {} void ShelfPacker::Reset() { shelves_.clear(); next_y_ = 0; } void ShelfPacker::SetMaxHeight(int max_height) { if (max_height > max_height_) max_height_ = max_height; } bool ShelfPacker::Pack(int w, int h, AtlasRect* out) { if (out == nullptr) return false; *out = AtlasRect(); if (w <= 0 || h <= 0) return true; // nothing to store // Compare before adding the padding so a huge w cannot overflow. if (w > width_ - 2 * padding_ || h > max_height_ - 2 * padding_) return false; const int ow = w + 2 * padding_; const int oh = h + 2 * padding_; // Best fit: the shortest existing shelf that is tall enough and has room. int best = -1; for (int i = 0; i < static_cast(shelves_.size()); ++i) { const Shelf& s = shelves_[static_cast(i)]; if (s.h >= oh && s.x + ow <= width_ && (best < 0 || s.h < shelves_[static_cast(best)].h)) { best = i; } } int cell_x = 0; int cell_y = 0; if (best >= 0) { Shelf& s = shelves_[static_cast(best)]; cell_x = s.x; cell_y = s.y; s.x += ow; } else { if (next_y_ + oh > max_height_) return false; Shelf s; s.y = next_y_; s.h = oh; s.x = ow; shelves_.push_back(s); cell_x = 0; cell_y = next_y_; next_y_ += oh; } out->x = cell_x + padding_; out->y = cell_y + padding_; out->w = w; out->h = h; return true; } } // namespace core } // namespace fcs