8000 feat: add f32 feature by jeyum2 · Pull Request #48 · Sollimann/bonsai · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add f32 feature #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bonsai/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ serde = { version = "1.0.137", features = ["derive"], optional = true }

[features]
visualize = ["dep:petgraph"]
f32 = []

[dev-dependencies]
serde_json = { version = "1.0.81" }
Expand Down
17 changes: 11 additions & 6 deletions bonsai/src/behavior.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::Float;

/// Describes a behavior.
///
/// This is used for more complex event logic.
Expand All @@ -10,8 +12,8 @@ use serde::{Deserialize, Serialize};
pub enum Behavior<A> {
/// Waits an amount of time before continuing
///
/// f64: Time in seconds
Wait(f64),
/// Float: Time in seconds
Wait(Float),
/// Wait forever.
WaitForever,
/// A high level description of an action.
Expand Down Expand Up @@ -131,20 +133,23 @@ pub enum Behavior<A> {
#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
use crate::Behavior::{self, Action, Sequence, Wait, WaitForever, WhenAny, While};
use crate::{
Behavior::{self, Action, Sequence, Wait, WaitForever, WhenAny, While},
Float,
};

#[derive(serde::Deserialize, serde::Serialize, Clone, Debug)]
pub(crate) enum EnemyAction {
/// Circles forever around target pos.
Circling,
/// Waits until player is within distance.
PlayerWithinDistance(f64),
PlayerWithinDistance(Float),
/// Fly toward player.
FlyTowardPlayer,
/// Waits until player is far away from target.
PlayerFarAwayFromTarget(f64),
PlayerFarAwayFromTarget(Float),
/// Makes player loose more blood.
AttackPlayer(f64),
AttackPlayer(Float),
}

#[test]
Expand Down
8 changes: 4 additions & 4 deletions bonsai/src/bt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Debug;

use crate::{state::State, ActionArgs, Behavior, Status, UpdateEvent};
use crate::{state::State, ActionArgs, Behavior, Float, Status, UpdateEvent};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -45,15 +45,15 @@ impl<A: Clone, B> BT<A, B> {
/// Passes event, delta time in seconds, action and state to closure.
/// The closure should return a status and remaining delta time.
///
/// return: (Status, f64)
/// return: (Status, Float)
/// function returns the result of the tree traversal, and how long
/// it actually took to complete the traversal and propagate the
/// results back up to the root node
#[inline]
pub fn tick<E, F>(&mut self, e: &E, f: &mut F) -> Option<(Status, f64)>
pub fn tick<E, F>(&mut self, e: &E, f: &mut F) -> Option<(Status, Float)>
where
E: UpdateEvent,
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, f64),
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, Float),
{
if self.finished {
return None;
Expand Down
20 changes: 14 additions & 6 deletions bonsai/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct UpdateArgs {
/// Delta time in seconds.
pub dt: f64,
pub dt: Float,
}

impl UpdateArgs {
Expand Down Expand Up @@ -54,7 +54,7 @@ pub trait UpdateEvent: Sized {
/// Creates an update event.
fn from_update_args(args: &UpdateArgs, old_event: &Self) -> Option<Self>;
/// Creates an update event with delta time.
fn from_dt(dt: f64, old_event: &Self) -> Option<Self> {
fn from_dt(dt: Float, old_event: &Self) -> Option<Self> {
UpdateEvent::from_update_args(&UpdateArgs { dt }, old_event)
}
/// Calls closure if this is an update event.
Expand Down Expand Up @@ -84,6 +84,8 @@ impl UpdateEvent for Event {

use std::time::Instant;

use crate::Float;

/// A monotonic clock/timer that can be used to keep track
/// of the time increments (delta time) between tick/tree traversals
/// and the total duration since the behavior tree was first invoked/traversed
Expand All @@ -101,18 +103,24 @@ impl Timer {
}

/// Compute duration since timer started
pub fn duration_since_start(&self) -> f64 {
pub fn duration_since_start(&self) -> Float {
let new_now: Instant = Instant::now();
let duration = new_now.duration_since(self.start);
duration.as_secs_f64()
#[cfg(feature = "f32")]
return duration.as_secs_f32();
#[cfg(not(feature = "f32"))]
return duration.as_secs_f64();
}

/// Compute time difference last invocation of `get_dt()` function
pub fn get_dt(&mut self) -> f64 {
pub fn get_dt(&mut self) -> Float {
let new_now: Instant = Instant::now();
let duration = new_now.duration_since(self.now);
self.now = new_now;
duration.as_secs_f64()
#[cfg(feature = "f32")]
return duration.as_secs_f32();
#[cfg(not(feature = "f32"))]
return duration.as_secs_f64();
}
}

Expand Down
6 changes: 6 additions & 0 deletions bonsai/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,9 @@ mod when_all;

#[cfg(feature = "visualize")]
mod visualizer;

#[cfg(feature = "f32")]
pub type Float = f32;

#[cfg(not(feature = "f32"))]
pub type Float = f64;
7 changes: 4 additions & 3 deletions bonsai/src/sequence.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::status::Status::*;
use crate::Float;
use crate::{event::UpdateEvent, state::State, ActionArgs, Behavior, Status, RUNNING};

pub struct SequenceArgs<'a, A, E, F, B> {
pub select: bool,
pub upd: Option<f64>,
pub upd: Option<Float>,
pub seq: &'a [Behavior<A>],
pub i: &'a mut usize,
pub cursor: &'a mut Box<State<A>>,
Expand All @@ -16,11 +17,11 @@ pub struct SequenceArgs<'a, A, E, F, B> {
//
// `Sequence` fails if any fails and succeeds when all succeeds.
// `Select` succeeds if any succeeds and fails when all fails.
pub fn sequence<A, E, F, B>(args: SequenceArgs<A, E, F, B>) -> (Status, f64)
pub fn sequence<A, E, F, B>(args: SequenceArgs<A, E, F, B>) -> (Status, Float)
where
A: Clone,
E: UpdateEvent,
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, f64),
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, Float),
{
let SequenceArgs {
select,
Expand Down
16 changes: 8 additions & 8 deletions bonsai/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use crate::sequence::{sequence, SequenceArgs};
use crate::state::State::*;
use crate::status::Status::*;
use crate::when_all::when_all;
use crate::{Behavior, Status};
use crate::{Behavior, Float, Status};
use std::fmt::Debug;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The action is still running, and thus the action consumes
/// all the remaining delta time for the tick
pub const RUNNING: (Status, f64) = (Running, 0.0);
pub const RUNNING: (Status, Float) = (Running, 0.0);

/// The arguments in the action callback.
pub struct ActionArgs<'a, E: 'a, A: 'a> {
Expand All @@ -20,7 +20,7 @@ pub struct ActionArgs<'a, E: 'a, A: 'a> {
/// The remaining delta time. When one action terminates,
/// it can consume some of dt and the remaining is passed
/// onto the next action.
pub dt: f64,
pub dt: Float,
/// The action running.
pub action: &'a A,
}
Expand All @@ -36,7 +36,7 @@ pub(crate) enum State<A> {
/// Ignores failures and always return `Success`.
AlwaysSucceed(Box<State<A>>),
/// Keeps track of waiting for a period of time before continuing.
Wait { time_to_wait: f64, elapsed_time: f64 },
Wait { time_to_wait: Float, elapsed_time: Float },
/// Waits forever.
WaitForever,
/// Keeps track of an `If` behavior.
Expand Down Expand Up @@ -196,14 +196,14 @@ impl<A: Clone> State<A> {
/// Passes event, delta time in seconds, action and state to closure.
/// The closure should return a status and remaining delta time.
///
/// return: (Status, f64)
/// return: (Status, Float)
/// function returns the result of the tree traversal, and how long
/// it actually took to complete the traversal and propagate the
/// results back up to the root node
pub fn tick<E, F, B>(&mut self, e: &E, blackboard: &mut B, f: &mut F) -> (Status, f64)
pub fn tick<E, F, B>(&mut self, e: &E, blackboard: &mut B, f: &mut F) -> (Status, Float)
where
E: UpdateEvent,
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, f64),
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, Float),
{
let upd = e.update(|args| Some(args.dt)).unwrap_or(None);

Expand Down Expand Up @@ -413,7 +413,7 @@ impl<A: Clone> State<A> {
) => {
// println!("In AfterState: {}", next_success_index);
// Get the least delta time left over.
let mut min_dt = f64::MAX;
let mut min_dt = Float::MAX;
for (j, item) in states.iter_mut().enumerate().skip(*next_success_index) {
match item.tick(e, blackboard, f) {
(Running, _) => {
Expand Down
6 changes: 3 additions & 3 deletions bonsai/src/visualizer.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#![allow(dead_code, unused_imports, unused_variables)]
use crate::{state::State, Behavior, Select, Sequence, BT};
use crate::{state::State, Behavior, Float, Select, Sequence, BT};
use petgraph::{graph::Graph, stable_graph::NodeIndex, Direction::Outgoing};
use std::{collections::VecDeque, fmt::Debug};

#[derive(Debug, Clone)]
pub(crate) enum NodeType<A> {
Root,
Wait(f64),
Wait(Float),
WaitForever,
Action(A),
Invert,
Expand Down Expand Up @@ -152,7 +152,7 @@ mod tests {
}

// A test state machine that can increment and decrement.
fn tick(mut acc: i32, dt: f64, bt: &mut BT<TestActions, HashMap<String, i32>>) -> (i32, Status, f64) {
fn tick(mut acc: i32, dt: Float, bt: &mut BT<TestActions, HashMap<String, i32>>) -> (i32, Status, Float) {
let e: Event = UpdateArgs { dt }.into();
let (s, t) = bt
.tick(&e, &mut |args, blackboard| match args.action {
Expand Down
9 changes: 5 additions & 4 deletions bonsai/src/when_all.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::status::Status::*;
use crate::Float;
use crate::{event::UpdateEvent, state::State, ActionArgs, Status, RUNNING};

// `WhenAll` and `WhenAny` share same algorithm.
Expand All @@ -8,16 +9,16 @@ use crate::{event::UpdateEvent, state::State, ActionArgs, Status, RUNNING};
#[rustfmt::skip]
pub fn when_all<A, E, F, B>(
any: bool,
upd: Option<f64>,
upd: Option<Float>,
cursors: &mut [Option<State<A>>],
e: &E,
f: &mut F,
blackboard: &mut B,
) -> (Status, f64)
) -> (Status, Float)
where
A: Clone,
E: UpdateEvent,
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, f64),
F: FnMut(ActionArgs<E, A>, &mut B) -> (Status, Float),
{
let (status, inv_status) = if any {
// `WhenAny`
Expand All @@ -27,7 +28,7 @@ where
(Status::Success, Status::Failure)
};
// Get the least delta time left over.
let mut min_dt = f64::MAX;
let mut min_dt = Float::MAX;
// Count number of terminated events.
let mut terminated = 0;
for cur in cursors.iter_mut() {
Expand Down
8 changes: 4 additions & 4 deletions bonsai/tests/behavior_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::behavior_tests::TestActions::{Dec, Inc, LessThan, LessThanRunningSuccess};
use bonsai_bt::{
Action, ActionArgs, After, AlwaysSucceed, Event, Failure, If, Invert, Select, Sequence, Status::Running, Success,
UpdateArgs, Wait, WaitForever, WhenAll, While, WhileAll, BT,
Action, ActionArgs, After, AlwaysSucceed, Event, Failure, Float, If, Invert, Select, Sequence, Status::Running,
Success, UpdateArgs, Wait, WaitForever, WhenAll, While, WhileAll, BT,
};

/// Some test actions.
Expand All @@ -18,7 +18,7 @@ enum TestActions {
}

// A test state machine that can increment and decrement.
fn tick(mut acc: i32, dt: f64, state: &mut BT<TestActions, ()>) -> (i32, bonsai_bt::Status, f64) {
fn tick(mut acc: i32, dt: Float, state: &mut BT<TestActions, ()>) -> (i32, bonsai_bt::Status, Float) {
let e: Event = UpdateArgs { dt }.into();
println!("acc {}", acc);
let (s, t) = state
Expand Down Expand Up @@ -59,7 +59,7 @@ fn tick(mut acc: i32, dt: f64, state: &mut BT<TestActions, ()>) -> (i32, bonsai_
}

// A test state machine that can increment and decrement.
fn tick_with_ref(acc: &mut i32, dt: f64, state: &mut BT<TestActions, ()>) {
fn tick_with_ref(acc: &mut i32, dt: Float, state: &mut BT<TestActions, ()>) {
let e: Event = UpdateArgs { dt }.into();

state
Expand Down
4 changes: 2 additions & 2 deletions bonsai/tests/blackboard_tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;

use bonsai_bt::{Action, Event, Sequence, Success, UpdateArgs, Wait, BT};
use bonsai_bt::{Action, Event, Float, Sequence, Success, UpdateArgs, Wait, BT};

use crate::blackboard_tests::TestActions::{Dec, Inc};

Expand All @@ -14,7 +14,7 @@ pub enum TestActions {
}

// A test state machine that can increment and decrement.
fn tick(mut acc: i32, dt: f64, bt: &mut BT<TestActions, HashMap<String, i32>>) -> i32 {
fn tick(mut acc: i32, dt: Float, bt: &mut BT<TestActions, HashMap<String, i32>>) -> i32 {
let e: Event = UpdateArgs { dt }.into();

let (_s, _t) = bt
Expand Down
4 changes: 2 additions & 2 deletions bonsai/tests/bt_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use crate::bt_tests::TestActions::{Dec, Inc, LessThan};
use bonsai_bt::{Action, Behavior::Select, Event, Failure, Success, UpdateArgs, BT};
use bonsai_bt::{Action, Behavior::Select, Event, Failure, Float, Success, UpdateArgs, BT};

/// Some test actions.
#[derive(Clone, Debug)]
Expand All @@ -15,7 +15,7 @@ enum TestActions {
}

// A test state machine that can increment and decrement.
fn tick(mut acc: i32, dt: f64, bt: &mut BT<TestActions, HashMap<String, i32>>) -> (i32, bonsai_bt::Status, f64) {
fn tick(mut acc: i32, dt: Float, bt: &mut BT<TestActions, HashMap<String, i32>>) -> (i32, bonsai_bt::Status, Float) {
let e: Event = UpdateArgs { dt }.into();
println!("acc {}", acc);
let (s, t) = bt
Expand Down
8 changes: 4 additions & 4 deletions bonsai/tests/dynamic_behavior_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::dynamic_behavior_tests::TestActions::{DynamicWait, Inc};
use bonsai_bt::{Action, ActionArgs, Event, Success, UpdateArgs, Wait, While, BT, RUNNING};
use bonsai_bt::{Action, ActionArgs, Event, Float, Success, UpdateArgs, Wait, While, BT, RUNNING};

type Times = Vec<f64>;
type Times = Vec<Float>;
/// Some test actions.
#[derive(Clone, Debug)]
enum TestActions {
Expand All @@ -12,7 +12,7 @@ enum TestActions {
}

// A test state machine that can increment and decrement.
fn tick(mut acc: usize, dt: f64, t: &mut f64, counter: &mut usize, state: &mut BT<TestActions, ()>) -> usize {
fn tick(mut acc: usize, dt: Float, t: &mut Float, counter: &mut usize, state: &mut BT<TestActions, ()>) -> usize {
let e: Event = UpdateArgs { dt }.into();

let (_s, _t) = state
Expand Down Expand Up @@ -49,7 +49,7 @@ fn tick(mut acc: usize, dt: f64, t: &mut f64, counter: &mut usize, state: &mut B
fn test_alter_wait_time() {
let a: usize = 0;
let mut counter = 0;
let mut timer: f64 = 0.0;
let mut timer: Float = 0.0;
let rep = While(
Box::new(Wait(50.0)),
vec![Action(DynamicWait(vec![1.0, 2.0, 3.0])), Action(Inc)],
Expand Down
3 changes: 3 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ rand = "0.8"
serde = { version = "1.0.137", features = ["derive"] }
serde_json = "1.0.81"

[features]
f32 = ["bonsai-bt/f32"]

[[bin]]
name = "async_drone"
path = "src/async_drone/main.rs"
Expand Down
Loading
0