Added some trait functions

master
hheik 2026-04-24 09:17:15 +03:00
parent 28c57905a3
commit 5c0ed07fb2
2 changed files with 19 additions and 6 deletions

View File

@ -16,7 +16,3 @@ Trait for a struct that holds spatial data
### Ruleset ### Ruleset
Trait for a ruleset Trait for a ruleset
### Node
Trait for any data that

View File

@ -15,13 +15,30 @@ pub trait GraphLike<Node, NodeId> {
fn iter_empty(&self) -> impl Iterator<Item = NodeId> where NodeId: Copy { fn iter_empty(&self) -> impl Iterator<Item = NodeId> where NodeId: Copy {
self.iter_ids().filter(|id| self.get_node(*id).is_none()) self.iter_ids().filter(|id| self.get_node(*id).is_none())
} }
fn iter_neighbour_nodes(&self, id: NodeId) -> Vec<(NodeId, Option<&Node>)> where NodeId: Copy { fn iter_neighbour_nodes(&self, id: NodeId) -> Vec<(NodeId, Option<&Node>)> where NodeId: Copy {
self.iter_neighbor_ids(id).map(|id| (id, self.get_node(id))).collect() self.iter_neighbor_ids(id).map(|id| (id, self.get_node(id))).collect()
} }
/// TODO: Replace return type with a result that explains the reason for failure. This could
/// help with rollback to recover from impossible generation
fn collapse_one(&mut self, rules: &impl Ruleset<Node, NodeId>) -> Option<NodeId> where NodeId: Copy, Self: Sized {
let id = rules.find_lowest_entropy(self)?;
rules.choose(self, id);
None
}
} }
pub trait Ruleset<Node, NodeId> { pub trait Ruleset<Node, NodeId> {
fn entropy(&self, graph: &impl GraphLike<Node, NodeId>, id: NodeId) -> f32 where NodeId: Copy; fn entropy(&self, graph: &impl GraphLike<Node, NodeId>, id: NodeId) -> Option<f32> where NodeId: Copy;
fn choose(&self, graph: &impl GraphLike<Node, NodeId>, id: NodeId) -> Node where NodeId: Copy; fn choose(&self, graph: &impl GraphLike<Node, NodeId>, id: NodeId) -> Node where NodeId: Copy;
fn find_lowest_entropy(&self, graph: &impl GraphLike<Node, NodeId>) -> Option<NodeId> where NodeId: Copy {
graph.iter_empty()
.map(|id| (id, self.entropy(graph, id)))
// Option<f32> apparently implements PartialOrd
// None is considered smaller than any Some value
// This works out, since we want to find impossible nodes (entropy returns None)
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(id, _)| id)
}
} }