goap_rs/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/piot/goap-rs
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use mash_rs::murmur3_32;
6use std::collections::HashSet;
7
8pub struct PropertyId(u32);
9
10impl PropertyId {
11    pub fn new(name: &str) -> Self {
12        Self(murmur3_32(name.as_bytes(), 0))
13    }
14}
15
16#[derive(PartialEq, Eq, Hash)]
17pub struct ConditionId {
18    id: u64,
19    debug_str: String,
20}
21
22impl ConditionId {
23    pub fn new(name: &str, value: bool) -> Self {
24        let property = PropertyId::new(name);
25        let calculated_value = property.0 << 1 | if value { 1 } else { 0 };
26
27        Self {
28            id: calculated_value as u64,
29            debug_str: Default::default(),
30        }
31    }
32}
33
34#[derive(Default)]
35pub struct State(HashSet<ConditionId>);
36
37impl State {
38    pub fn new() -> Self {
39        Self(Default::default())
40    }
41    pub fn push(mut self, name: &str, value: bool) -> Self {
42        self.0.insert(ConditionId::new(name, value));
43        self
44    }
45}
46
47type Cost = u32;
48
49#[derive(PartialEq)]
50pub enum ActionStatus {
51    Done,
52    NotReady,
53    Cancelled,
54}
55
56pub trait ActionTrait {
57    fn start(&mut self);
58    fn update(&mut self) -> ActionStatus;
59}
60
61#[allow(unused)]
62pub struct Action {
63    pre_conditions: State,
64    effects: State,
65    cost: u32,
66    debug_name: String,
67    implementation: Box<dyn ActionTrait>,
68}
69
70impl Action {
71    pub fn new(
72        pre_conditions: State,
73        effects: State,
74        cost: Cost,
75        implementation: Box<dyn ActionTrait>,
76    ) -> Self {
77        Self {
78            pre_conditions,
79            effects,
80            cost,
81            debug_name: Default::default(),
82            implementation,
83        }
84    }
85
86    pub fn with_debug_name(mut self, name: &str) -> Self {
87        self.debug_name = name.to_string();
88        self
89    }
90
91    pub fn start(&mut self) {
92        self.implementation.start()
93    }
94
95    pub fn update(&mut self) -> ActionStatus {
96        self.implementation.update()
97    }
98}