2 个稳定版本
1.0.1 | 2023 年 2 月 5 日 |
---|---|
1.0.0 | 2023 年 2 月 3 日 |
#996 in 算法
120KB
2K SLoC
binpack2d
binpack2d
是一个 Rust 库,用于将任意二维矩形集合打包到更大的箱子中。由于该问题本身是难以处理的,因此所有算法都是近似算法,并使用了各种启发式方法。
该实现基于 Jukka Jylänki 的 RectangleBinPack 的原始 C++ 实现。
所有支持的装箱算法及其子变体的比较可以在此找到:这里。
快速入门
# In your Cargo.toml
[dependencies]
binpack2d = "1.0"
这是一个基本示例,将多个矩形打包到箱子中,然后进行一些查询。
use binpack2d::{bin_new, BinType, Dimension};
fn main() {
// Create a number of items to be placed into the bin.
let items_to_place = vec![
// Items with autogenerated identifiers.
// Identifiers start at 1 and increment by 1 per call.
Dimension::new(188, 300),
Dimension::new(32, 32),
Dimension::new(420, 512),
Dimension::new(620, 384),
// Three more items with explicit identifiers: -1, 300, and 9528 respectively
Dimension::with_id(-1, 160, 214, 0),
Dimension::with_id(300, 384, 640, 0),
Dimension::with_id(9528, 400, 200, 0),
];
// Create a bin with the dimensions 1024x1024, using the "MaxRects" bin type.
let mut bin = bin_new(BinType::MaxRects, 1024, 1024);
// Perform the bin packing operation on the list of items.
let (inserted, rejected) = bin.insert_list(&items_to_place);
// Let's see if our item with id=9528 was successfully inserted...
if let Some(rect) = &bin.find_by_id(9528) {
println!("Item with id {} was placed into the bin at position (x: {}, y: {})",
rect.id(), rect.x(), rect.y());
} else {
println!("Item with id 9528 could not be placed into the bin.");
}
// List all successfully inserted rectangles.
if !inserted.is_empty() {
inserted.iter().for_each(|rect| println!("Inserted: {}", rect));
} else {
println!("No rectangles were added to the bin.");
}
// List all items which could not be inserted into the bin.
if !rejected.is_empty() {
rejected.iter().for_each(|item| println!("Rejected: {}", item));
} else {
println!("No items were rejected.");
}
println!("Occupancy of the bin: {:.1} %", bin.occupancy() * 100.0);
}
完整的 API 文档可以在这里找到: https://docs.rs/binpack2d