| Crates.io | rlwfc |
| lib.rs | rlwfc |
| version | 0.1.1 |
| created_at | 2025-06-01 14:28:01.903899+00 |
| updated_at | 2025-06-01 14:40:31.168914+00 |
| description | Rust implementation of Wave Function Collapse (WFC) algorithm with type safety and direction-aware grid system |
| homepage | https://github.com/amazcuter/rlwfc |
| repository | https://github.com/amazcuter/rlwfc |
| max_upload_size | |
| id | 1697226 |
| size | 299,357 |
RLWFC是一个基于Rust实现的Wave Function Collapse (WFC)算法库,使用petgraph作为底层图数据结构,提供类型安全和高性能的WFC实现。
修复了边界单元格邻居索引错位的严重bug:
neighbors()返回的索引顺序不一致judge_possibility中访问邻居时发生数组越界或索引对应错误[北, 西, 南, 东]// 新的create_edge API - 支持虚拟边
grid.create_edge(cell, Some(neighbor))?; // 真实邻居
grid.create_edge(cell, None)?; // 虚拟边(边界处理)
// 虚拟节点检测
if !grid.is_virtual_node(neighbor) {
// 处理真实邻居
}
这是对原C++ WFC系统的完整Rust重写,在保持API兼容性的同时,引入了现代Rust的设计理念和安全保证。
在您的 Cargo.toml 中添加:
[dependencies]
rlwfc = "0.1.0"
use rlwfc::{GridSystem, Cell, Direction4, GridError};
fn main() -> Result<(), GridError> {
// 创建网格系统
let mut grid = GridSystem::new();
// 添加单元格
let cell1 = grid.add_cell(Cell::with_id(1));
let cell2 = grid.add_cell(Cell::with_id(2));
// 创建边连接
grid.create_edge(cell1, Some(cell2))?;
// 方向感知查询
if let Some(neighbor) = grid.get_neighbor_by_direction(cell1, Direction4::East) {
println!("Eastern neighbor: {:?}", neighbor);
}
Ok(())
}
use rlwfc::{GridSystem, GridBuilder, Cell, GridError};
struct LinearGridBuilder {
size: usize,
}
impl GridBuilder for LinearGridBuilder {
fn build_grid_system(&mut self, grid: &mut GridSystem) -> Result<(), GridError> {
let mut cells = Vec::new();
for i in 0..self.size {
let cell = grid.add_cell(Cell::with_id(i as u32));
cells.push(cell);
}
for i in 0..self.size - 1 {
grid.create_edge(cells[i], Some(cells[i + 1]))?;
}
Ok(())
}
fn get_dimensions(&self) -> Vec<usize> {
vec![self.size]
}
fn get_grid_type_name(&self) -> &'static str {
"Linear"
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let builder = LinearGridBuilder { size: 5 };
let _grid = GridSystem::from_builder(builder)?;
Ok(())
}
提供基础类型定义、错误处理和方向系统:
CellId, EdgeId, TileId 等Cell, GraphEdge, Tile 等DirectionTrait 和 Direction4实现WFC系统的核心网格管理功能:
GridBuilder trait支持多种网格类型实现WFC算法的瓷砖管理和约束判断:
运行示例程序来了解库的使用:
# 基本的2D正交WFC示例
cargo run --example orthogonal_2d_wfc
# 基本使用示例
cargo run --example basic_usage
# 网格构建器示例
cargo run --example grid_builder_demo
# 瓷砖系统示例
cargo run --example tile_system_demo
查看完整的API文档:
cargo doc --open文档包含:
| 特性 | C++ | Rust |
|---|---|---|
| 内存安全 | 手动管理 | 自动保证 |
| 类型安全 | 运行时检查 | 编译时保证 |
| 错误处理 | 异常/返回码 | Result类型 |
| 多态 | 虚函数继承 | Trait组合 |
| 并发 | 手动同步 | 编译时保证 |
| 方向感知 | 无 | 零成本实现 |
这个库需要Rust 1.70或更高版本。
运行测试套件:
# 单元测试
cargo test
# 文档测试
cargo test --doc
# 集成测试
cargo test --tests
所有核心功能都有对应的单元测试,确保代码质量和正确性。
✅ 基础类型系统
✅ 网格系统和图操作
✅ 方向感知功能
✅ 瓷砖系统
✅ WFC管理器
✅ 构建器模式
✅ 完整的文档
✅ 示例程序
✅ 单元测试
✅ 集成测试
欢迎贡献代码、报告问题或提出改进建议。请确保:
cargo testcargo fmtcargo clippycargo doc