Skip to content
This repository was archived by the owner on Dec 24, 2024. It is now read-only.

Commit c33edcc

Browse files
committed
update command system
1 parent 00ecda3 commit c33edcc

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+446
-510
lines changed

Cargo.lock

+185-194
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+18-6
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ hematite-nbt = "0.5"
101101
swarm-bot-packets = { path = "packets", version = "0.2.0" }
102102

103103
# so we don't have to use v-tables
104-
enum_dispatch = "0.3"
105104
tokio-tungstenite = "0.20.1"
106105

107106
futures = "0.3"
@@ -118,6 +117,7 @@ tungstenite = "0.20.1"
118117
generic-array = "1.0.0"
119118
typenum = "1.17.0"
120119
rustix = "0.38.25"
120+
tracing = "0.1.40"
121121

122122
[dev-dependencies]
123123
assert_matches = "1.5"
@@ -129,10 +129,22 @@ rustix = "0.38.25"
129129
members = ["packets", "interfaces", "swarmbot-cli"]
130130

131131
[profile.dev]
132-
split-debuginfo = "unpacked"
133-
opt-level = 1
132+
#split-debuginfo = "unpacked"
133+
#opt-level = 1
134134

135135

136-
[profile.release]
137-
lto = "fat"
138-
codegen-units = 1
136+
#[profile.release]
137+
#lto = "fat"
138+
#codegen-units = 1
139+
140+
[lints.clippy]
141+
complexity = { level = "deny", priority = -1 }
142+
nursery = { level = "deny", priority = -1 }
143+
pedantic = { level = "deny", priority = -1 }
144+
perf = { level = "deny", priority = -1 }
145+
style = { level = "deny", priority = -1 }
146+
suspicious = { level = "deny", priority = -1 }
147+
148+
module_name_repetitions = "allow"
149+
future_not_send = "allow"
150+

interfaces/src/lib.rs

+37-23
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,25 @@ pub mod types;
99

1010
type Id = u64;
1111

12+
pub trait Tag: Serialize {
13+
const PATH: &'static str;
14+
15+
fn encode(&self) -> String {
16+
let mut v = serde_json::to_value(self).unwrap();
17+
18+
let Some(map) = v.as_object_mut() else {
19+
panic!("expected object")
20+
};
21+
22+
map.insert(
23+
"path".to_string(),
24+
serde_json::Value::String(Self::PATH.to_string()),
25+
);
26+
27+
serde_json::to_string(&v).unwrap()
28+
}
29+
}
30+
1231
/// The mine command.
1332
/// Mine the given selection.
1433
/// A global command. The process should allocate appropriately to children.
@@ -17,18 +36,30 @@ pub struct Mine {
1736
pub sel: Selection2D,
1837
}
1938

39+
impl Tag for Mine {
40+
const PATH: &'static str = "mine";
41+
}
42+
2043
/// A navigation command to go to the given block location
2144
#[derive(Serialize, Deserialize, Debug)]
2245
pub struct GoTo {
2346
pub location: BlockLocation,
2447
}
2548

49+
impl Tag for GoTo {
50+
const PATH: &'static str = "goto";
51+
}
52+
2653
/// Attack a given player
2754
#[derive(Serialize, Deserialize, Debug)]
2855
pub struct Attack {
2956
pub name: String,
3057
}
3158

59+
impl Tag for Attack {
60+
const PATH: &'static str = "attack";
61+
}
62+
3263
#[derive(Serialize, Deserialize, Debug)]
3364
pub struct Cancelled {
3465
pub id: Id,
@@ -39,29 +70,11 @@ pub struct Finished {
3970
pub id: Id,
4071
}
4172

42-
macro_rules! commands {
43-
(
44-
$($command: ident),*
45-
) =>
46-
{
47-
#[derive(Serialize, Deserialize, Debug)]
48-
#[serde(rename_all = "lowercase")]
49-
#[serde(tag = "path")]
50-
pub enum CommandData {
51-
$($command($command)),*
52-
}
53-
54-
};
55-
}
56-
57-
commands! {
58-
Mine, GoTo, Attack, Cancelled, Finished
59-
}
60-
6173
#[derive(Serialize, Deserialize, Debug)]
6274
pub struct Command {
6375
id: u64,
64-
data: CommandData,
76+
path: String,
77+
data: serde_json::Value,
6578
}
6679

6780
pub struct Comm {
@@ -174,14 +187,15 @@ impl Comm {
174187

175188
#[cfg(test)]
176189
mod tests {
177-
use crate::{Attack, Command, CommandData};
190+
use crate::Command;
178191

179192
#[test]
180193
fn test() {
181194
let command = Command {
182195
id: 123,
183-
data: CommandData::Attack(Attack {
184-
name: "hello".to_string(),
196+
path: "attack".to_string(),
197+
data: serde_json::json!({
198+
"name": "hello"
185199
}),
186200
};
187201

rust-toolchain.toml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[toolchain]
2+
channel = "nightly-2024-07-04"

src/bootstrap/dns.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,8 @@ async fn dns_lookup(host: &str) -> anyhow::Result<Address> {
3030
/// Normalizes the address. Some servers like 2b2t have a separate address for
3131
/// minecraft since they have a special mc record
3232
pub async fn normalize_address(host: &str, port: u16) -> Address {
33-
match dns_lookup(host).await {
34-
Ok(res) => res,
35-
Err(_) => Address {
36-
host: host.to_string(),
37-
port,
38-
},
39-
}
33+
(dns_lookup(host).await).unwrap_or_else(|_| Address {
34+
host: host.to_string(),
35+
port,
36+
})
4037
}

src/bootstrap/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ async fn obtain_connection(
7373

7474
conn.into_inner()
7575
} else {
76+
println!("connecting to {target}");
7677
TcpStream::connect(target.as_str()).await.unwrap()
7778
};
7879

src/bootstrap/mojang.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,7 @@ impl TryFrom<Option<&Proxy>> for MojangClient {
4242
type Error = anyhow::Error;
4343

4444
fn try_from(value: Option<&Proxy>) -> Result<Self, Self::Error> {
45-
match value {
46-
None => Ok(Self::default()),
47-
Some(proxy) => Self::try_from(proxy),
48-
}
45+
value.map_or_else(|| Ok(Self::default()), Self::try_from)
4946
}
5047
}
5148

src/bootstrap/opts.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub struct CliOptions {
2828
pub port: u16,
2929

3030
/// The port of the web socket that is used to communicate bot commands
31-
/// to. This is used to interface with the SwarmBot mod, although it
31+
/// to. This is used to interface with the `SwarmBot` mod, although it
3232
/// can be used for anything.
3333
#[clap(long, default_value = "8080")]
3434
pub ws_port: u16,
@@ -67,7 +67,7 @@ pub struct CliOptions {
6767

6868
/// if we are launching in offline mode
6969
#[clap(long)]
70-
pub offline: bool,
70+
pub online: bool,
7171
}
7272

7373
impl CliOptions {

src/client/bot.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::{
1111
state::{global::GlobalState, local::LocalState},
1212
tasks::{
1313
compound::CompoundTask, eat::EatTask, fall_bucket::FallBucketTask, mine::MineTask,
14-
navigate::BlockTravelTask, Task, TaskTrait,
14+
navigate::BlockTravelTask, Task,
1515
},
1616
},
1717
protocol::{EventQueue, Face, InterfaceOut},
@@ -24,13 +24,13 @@ use crate::{
2424
pub struct ActionState {
2525
/// the task. In the future, this might change to be a priority queue of
2626
/// tasks
27-
task: Option<Task>,
27+
task: Option<Box<dyn Task>>,
2828
}
2929

3030
impl ActionState {
3131
/// schedule a task
32-
pub fn schedule<T: Into<Task>>(&mut self, task: T) {
33-
self.task = Some(task.into());
32+
pub fn schedule(&mut self, task: impl Task + 'static) {
33+
self.task = Some(Box::new(task));
3434
}
3535
/// clear the task list
3636
pub fn clear(&mut self) {
@@ -102,7 +102,7 @@ pub fn process_command(
102102
local: &mut LocalState,
103103
global: &mut GlobalState,
104104
actions: &mut ActionState,
105-
out: &mut impl InterfaceOut,
105+
out: &mut dyn InterfaceOut,
106106
) -> anyhow::Result<()> {
107107
macro_rules! msg {
108108
() => {{
@@ -153,7 +153,7 @@ pub fn process_command(
153153
// }
154154
"eat" => {
155155
let eat_task = EatTask::default();
156-
actions.task = Some(eat_task.into());
156+
actions.task = Some(Box::new(eat_task));
157157
}
158158
"slot" => {
159159
if let [number] = args {

src/client/commands.rs

+29-24
Original file line numberDiff line numberDiff line change
@@ -2,59 +2,64 @@ use std::sync::mpsc::{Receiver, Sender};
22

33
use anyhow::{bail, Context};
44
use futures::StreamExt;
5-
use interfaces::CommandData;
65
use serde_json::Value;
76
use tokio::net::{TcpListener, TcpStream};
87
use tokio_tungstenite::WebSocketStream;
8+
use tracing::error;
99

1010
/// commands received over websocket (typically forge mod)
1111
pub struct CommandReceiver {
12-
pub pending: Receiver<CommandData>,
12+
pub pending: Receiver<TaggedValue>,
1313
}
1414

15-
fn process(path: &str, value: Value) -> Option<CommandData> {
16-
macro_rules! parse {
17-
() => {{
18-
serde_json::from_value(value).unwrap()
19-
}};
20-
}
15+
struct Processor {
16+
value: Value,
17+
}
2118

22-
match path {
23-
"mine" => Some(CommandData::Mine(parse!())),
24-
"goto" => Some(CommandData::GoTo(parse!())),
25-
"attack" => Some(CommandData::Attack(parse!())),
19+
pub struct TaggedValue {
20+
pub path: String,
21+
pub value: Value,
22+
}
2623

27-
path => {
28-
println!("invalid {path}");
29-
None
30-
}
24+
impl TaggedValue {
25+
pub fn parse<T>(self) -> Result<T, serde_json::Error>
26+
where
27+
T: serde::de::DeserializeOwned,
28+
{
29+
serde_json::from_value(self.value)
3130
}
3231
}
3332

3433
async fn command_receiver(
35-
tx: Sender<CommandData>,
34+
tx: Sender<TaggedValue>,
3635
mut ws: WebSocketStream<TcpStream>,
3736
) -> anyhow::Result<()> {
38-
'wloop: while let Some(msg) = ws.next().await {
37+
while let Some(msg) = ws.next().await {
3938
let msg = msg.context("error reading next web socket message (websocket disconnect?)")?;
4039

4140
let text = msg.into_text().unwrap();
4241

43-
let mut v: Value = match serde_json::from_str(&text) {
42+
let v: Value = match serde_json::from_str(&text) {
4443
Ok(v) => v,
45-
Err(_e) => continue 'wloop,
44+
Err(e) => {
45+
error!("invalid json {e}");
46+
continue;
47+
}
4648
};
4749

48-
let Value::Object(map) = &mut v else {
49-
bail!("invalid value")
50+
let Value::Object(mut map) = v else {
51+
bail!("expected object")
5052
};
5153

5254
let Value::String(path) = map.remove("path").expect("no path elem") else {
5355
bail!("invalid path")
5456
};
5557

56-
let command = process(&path, v).expect("invalid command");
57-
tx.send(command).unwrap();
58+
let value = Value::Object(map);
59+
60+
let elem = TaggedValue { path, value };
61+
62+
tx.send(elem).unwrap();
5863
}
5964
Ok(())
6065
}

src/client/pathfind/implementations/no_vehicle.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ impl Heuristic for ChunkHeuristic {
125125
fn heuristic(&self, input: &MoveNode) -> f64 {
126126
let dx = f64::from(input.location.x - self.center_x);
127127
let dz = f64::from(input.location.z - self.center_z);
128-
let dist2 = dx * dx + dz * dz;
128+
let dist2 = dx.mul_add(dx, dz * dz);
129129
dist2.sqrt() * self.move_cost * 0.2
130130
}
131131
}

src/client/pathfind/incremental/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -132,14 +132,14 @@ impl<T: Debug> Debug for PathResult<T> {
132132
}
133133

134134
impl<T> PathResult<T> {
135-
fn complete(value: Vec<T>) -> Self {
135+
const fn complete(value: Vec<T>) -> Self {
136136
Self {
137137
complete: true,
138138
value,
139139
}
140140
}
141141

142-
fn incomplete(value: Vec<T>) -> Self {
142+
const fn incomplete(value: Vec<T>) -> Self {
143143
Self {
144144
complete: false,
145145
value,

src/client/physics/mod.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -348,8 +348,12 @@ impl Physics {
348348
let sideways = horizontal.cross(UNIT_Y);
349349

350350
let move_mults = [
351-
horizontal.dx * forward_change + sideways.dx * strafe_change,
352-
horizontal.dz * forward_change + sideways.dz * strafe_change,
351+
horizontal
352+
.dx
353+
.mul_add(forward_change, sideways.dx * strafe_change),
354+
horizontal
355+
.dz
356+
.mul_add(forward_change, sideways.dz * strafe_change),
353357
];
354358

355359
let effect_mult = effects_multiplier(0.0, 0.0);
@@ -380,7 +384,7 @@ impl Physics {
380384
let downwards_force = feet_flowing || head_flowing;
381385

382386
// TODO: remove 0.014
383-
let res = self.prev.y_vel * WATER_SLOW_DOWN - 0.02
387+
let res = self.prev.y_vel.mul_add(WATER_SLOW_DOWN, -0.02)
384388
+ if self.pending.jump { 0.04 } else { 0. }
385389
- if downwards_force { 0.014 } else { 0. };
386390

0 commit comments

Comments
 (0)