1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Piston test for the lab (`lab/pistons.sh` builds the layouts and runs the clocks): the bot
//! stands, walks, sprints or jumps (`PROBE=stand|walk|sprint|jump`, default stand) and logs its
//! position every 10 ticks, every server teleport (with the pose the server had before it) and
//! Grim alerts in chat (`ALERT`). Walking goes along the starting yaw, `TURN` ticks (default 40)
//! each way. The pistons need no option: the client runs them from the block-action packets.
//!
//! ```text
//! PROBE=walk cargo run -p ghast --release --example piston_probe -- --host 127.0.0.1 \
//! --port 25618 --username GhastBot4 --version 1.8.9 --minutes 0.5
//! ```
mod support;
use std::time::{Duration, Instant};
use ghast::{Behavior, Controls, Interests, TickContext};
struct Probe {
mode: String,
turn: u64,
n: u64,
/// The yaw the walk keeps (the script's teleport sets it).
yaw: Option<f32>,
alerts: u32,
teleports: u32,
started: Instant,
limit: Option<Duration>,
/// `TRACK=1`: entity tracking on (the client view moves the other entities' copies too).
track: bool,
/// Ticks `piston_uncertain` was raised.
uncertain: u32,
/// `TRACK=1`: the number of other (non-player) entities last logged.
others: usize,
}
impl Behavior for Probe {
fn name(&self) -> &str {
"piston-probe"
}
fn interests(&self) -> Interests {
if self.track {
Interests::CHAT | Interests::ENTITY_TRACKING | Interests::ENTITIES
} else {
Interests::CHAT
}
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
if ctx.piston_uncertain() {
self.uncertain += 1;
}
if self.track
&& let Some(es) = ctx.entities()
{
let others = es.iter().filter(|e| !e.is_player()).count();
if others != self.others || (others > 0 && ctx.tick().is_multiple_of(40)) {
self.others = others;
let list: Vec<String> = es
.iter()
.filter(|e| !e.is_player())
.map(|e| {
let d = e.drawn_position();
format!("{} {:.4} {:.4} {:.4}", e.id(), d[0], d[1], d[2])
})
.collect();
log::info!(
"tick {}: {} other entities: {}",
ctx.tick(),
others,
list.join("; ")
);
}
}
for m in &ctx.events().chat {
let t = m.plain();
if t.contains("Grim") {
self.alerts += 1;
log::warn!("ALERT chat: {t}");
}
}
for t in &ctx.events().teleports {
self.teleports += 1;
let (s, a) = (t.sent_before.pos, t.after.pos);
log::info!(
"tick {}: teleport {}: server had {:.5} {:.5} {:.5}, now {:.5} {:.5} {:.5} (diff {:.5} {:.5} {:.5})",
ctx.tick(),
self.teleports,
s.x,
s.y,
s.z,
a.x,
a.y,
a.z,
a.x - s.x,
a.y - s.y,
a.z - s.z
);
if self.n > 0 {
// After the start: the next yaw is the new one.
self.yaw = None;
}
}
if self.limit.is_some_and(|l| self.started.elapsed() >= l) {
let p = ctx.pose().pos;
log::info!(
"end position {:.5} {:.5} {:.5}; {} teleports, {} alerts, {} piston_uncertain ticks",
p.x,
p.y,
p.z,
self.teleports,
self.alerts,
self.uncertain
);
log::info!(
"tracking {}: {:?} entities",
self.track,
ctx.entities().map(|e| e.len())
);
if self.track
&& let Some(es) = ctx.entities()
{
for e in es.iter().filter(|e| !e.is_player()) {
let d = e.drawn_position();
log::info!(
"entity {} drawn {:.5} {:.5} {:.5} server {:.5} {:.5} {:.5}",
e.id(),
d[0],
d[1],
d[2],
e.position()[0],
e.position()[1],
e.position()[2]
);
}
}
ctx.disconnect("time limit reached");
return;
}
self.n += 1;
if self.n.is_multiple_of(10) {
let p = ctx.pose();
log::info!(
"tick {}: pos {:.5} {:.5} {:.5} motion {:.5} {:.5} {:.5} ground {}",
ctx.tick(),
p.pos.x,
p.pos.y,
p.pos.z,
p.motion.x,
p.motion.y,
p.motion.z,
p.on_ground
);
}
// Wait for the script's teleport (about tick 60) before moving.
if self.n < 80 || self.mode == "stand" {
ctx.set_controls(Controls::NONE);
return;
}
let yaw = *self.yaw.get_or_insert(ctx.pose().yaw);
ctx.set_aim(yaw, 0.0);
let phase = (self.n - 80) / self.turn;
let forward = phase.is_multiple_of(2);
ctx.set_controls(match self.mode.as_str() {
"walk" => Controls {
forward,
back: !forward,
..Controls::NONE
},
"sprint" => Controls {
forward,
back: !forward,
sprint: forward,
..Controls::NONE
},
// Jumps in place (held: a jump on every landing).
_ => Controls {
jump: true,
..Controls::NONE
},
});
}
}
fn main() {
let opts = support::Options::parse();
support::init_logger(opts.verbose);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("tokio runtime");
rt.block_on(async {
let client = match opts.client() {
Ok(c) => c,
Err(e) => {
log::error!("{e}");
std::process::exit(2);
}
};
let mut b = Probe {
mode: std::env::var("PROBE").unwrap_or_else(|_| "stand".into()),
turn: std::env::var("TURN")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(40),
n: 0,
yaw: None,
alerts: 0,
teleports: 0,
started: Instant::now(),
limit: opts.limit(),
track: std::env::var("TRACK").is_ok_and(|v| !v.is_empty()),
uncertain: 0,
others: 0,
};
let shutdown = async {
let _ = tokio::signal::ctrl_c().await;
};
match client.run_until(&mut b, shutdown).await {
Ok(e) => log::info!("session ended: {e:?}; {} alerts", b.alerts),
Err(e) => log::error!("session failed: {e}"),
}
});
}