1use std::collections::{HashSet, VecDeque};
10use std::future::Future;
11use std::panic::{AssertUnwindSafe, catch_unwind};
12use std::pin::Pin;
13use std::sync::{Arc, Mutex, MutexGuard, Weak};
14use std::task::{Context, Poll, Wake, Waker};
15
16use ghast_client::{Behavior, GameMode, GameVersion, Health, Interests, Pose, TickContext, Vec3};
17
18use crate::Error;
19use crate::events::{Event, SubState};
20
21pub(crate) type Request = Box<dyn FnOnce(&mut TickContext<'_>) + Send>;
23type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
24type Factory = Box<dyn FnMut(Bot) -> BoxFuture<Result<(), Error>> + Send>;
25type PanicHook = Box<dyn FnOnce(String) + Send>;
27
28const MAX_ROUNDS: usize = 256;
31
32#[derive(Debug, Clone)]
34pub(crate) struct Snapshot {
35 pub(crate) version: GameVersion,
36 pub(crate) ctx_tick: u64,
37 pub(crate) pose: Pose,
38 pub(crate) sent: Pose,
39 pub(crate) eyes: Vec3,
40 pub(crate) health: Health,
41 pub(crate) dead: bool,
42 pub(crate) game_mode: GameMode,
43 pub(crate) held_slot: u8,
44 pub(crate) open_window: Option<i32>,
45 pub(crate) entity_id: i32,
46 pub(crate) dimension: String,
47}
48
49impl Snapshot {
50 fn empty() -> Self {
51 Snapshot {
52 version: GameVersion::V1_8_9,
53 ctx_tick: 0,
54 pose: Pose::default(),
55 sent: Pose::default(),
56 eyes: Vec3::default(),
57 health: Health::default(),
58 dead: false,
59 game_mode: GameMode::Survival,
60 held_slot: 0,
61 open_window: None,
62 entity_id: 0,
63 dimension: String::new(),
64 }
65 }
66
67 fn refresh(&mut self, ctx: &TickContext<'_>) {
68 self.version = ctx.version();
69 self.ctx_tick = ctx.tick();
70 self.pose = *ctx.pose();
71 self.sent = *ctx.sent();
72 self.eyes = ctx.eyes(ctx.pose());
73 self.health = ctx.health();
74 self.dead = ctx.is_dead();
75 self.game_mode = ctx.game_mode();
76 self.held_slot = ctx.held_slot();
77 self.open_window = ctx.open_window();
78 self.entity_id = ctx.entity_id();
79 if self.dimension != ctx.dimension() {
80 ctx.dimension().clone_into(&mut self.dimension);
81 }
82 }
83}
84
85pub(crate) struct Shared {
87 pub(crate) session: u64,
89 pub(crate) closed: Option<String>,
91 pub(crate) tick: u64,
93 pub(crate) snap: Snapshot,
94 pub(crate) requests: VecDeque<Request>,
95 pub(crate) tick_wakers: Vec<Waker>,
96 pub(crate) spawned: Vec<(u64, BoxFuture<()>, PanicHook)>,
97 pub(crate) aborted: Vec<u64>,
98 pub(crate) next_task: u64,
99 pub(crate) subs: Vec<Weak<Mutex<SubState>>>,
100 pub(crate) teleports: u64,
102 pub(crate) deaths: u64,
103 pub(crate) extra_interests: Interests,
105 entity_ids: Option<HashSet<i32>>,
107 pub(crate) interrupt_on_teleport: bool,
108}
109
110impl Shared {
111 fn new() -> Self {
112 Shared {
113 session: 0,
114 closed: Some("not started".into()),
115 tick: 0,
116 snap: Snapshot::empty(),
117 requests: VecDeque::new(),
118 tick_wakers: Vec::new(),
119 spawned: Vec::new(),
120 aborted: Vec::new(),
121 next_task: 1,
122 subs: Vec::new(),
123 teleports: 0,
124 deaths: 0,
125 extra_interests: Interests::NONE,
126 entity_ids: None,
127 interrupt_on_teleport: true,
128 }
129 }
130
131 fn wake_ticks(&mut self) {
132 for w in self.tick_wakers.drain(..) {
133 w.wake();
134 }
135 }
136
137 fn wake_subs(&mut self) {
138 self.subs.retain(|s| s.strong_count() > 0);
139 for s in &self.subs {
140 if let Some(s) = s.upgrade() {
141 let mut s = lock(&s);
142 if let Some(w) = s.waker.take() {
143 w.wake();
144 }
145 }
146 }
147 }
148
149 fn publish(&mut self, ctx: &TickContext<'_>) {
151 self.subs.retain(|s| s.strong_count() > 0);
152 if self.subs.is_empty() {
153 self.entity_ids = None;
154 return;
155 }
156 let ev = ctx.events();
157 let mut out = Vec::new();
158 if ev.joined {
159 out.push(Event::Joined);
160 }
161 if ev.respawned {
162 out.push(Event::Respawned);
163 }
164 for t in &ev.teleports {
165 out.push(Event::Teleport(*t));
166 }
167 if ev.died {
168 out.push(Event::Died);
169 }
170 if ev.health_changed {
171 out.push(Event::Health(ctx.health()));
172 }
173 if ev.game_mode_changed {
174 out.push(Event::GameMode(ctx.game_mode()));
175 }
176 for m in &ev.chat {
177 out.push(Event::Chat(m.clone()));
178 }
179 if let Some(id) = ev.inventory.opened {
180 out.push(Event::WindowOpened(id));
181 }
182 if ev.inventory.closed {
183 out.push(Event::WindowClosed);
184 }
185 if ev.inventory.player_changed {
186 out.push(Event::InventoryChanged);
187 }
188 for c in &ev.inventory.clicks {
189 out.push(Event::Click(*c));
190 }
191 for (pos, raw) in &ev.block_updates {
192 out.push(Event::BlockUpdate {
193 pos: *pos,
194 raw: *raw,
195 });
196 }
197 if let Some(es) = ctx.entities() {
198 let me = es.self_id();
199 let now: HashSet<i32> = es
200 .iter()
201 .map(|e| e.id())
202 .filter(|id| Some(*id) != me)
203 .collect();
204 if let Some(before) = &self.entity_ids {
205 for id in now.difference(before) {
206 if let Some(e) = crate::find::entity_info(ctx, *id) {
207 out.push(Event::EntitySpawned(e));
208 }
209 }
210 for id in before.difference(&now) {
211 out.push(Event::EntityGone(*id));
212 }
213 }
214 self.entity_ids = Some(now);
215 } else {
216 self.entity_ids = None;
217 }
218 if out.is_empty() {
219 return;
220 }
221 for s in &self.subs {
222 if let Some(s) = s.upgrade() {
223 let mut s = lock(&s);
224 s.queue.extend(out.iter().cloned());
225 if let Some(w) = s.waker.take() {
226 w.wake();
227 }
228 }
229 }
230 }
231}
232
233pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
235 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
236}
237
238#[derive(Clone)]
248pub struct Bot {
249 pub(crate) shared: Arc<Mutex<Shared>>,
250}
251
252impl std::fmt::Debug for Bot {
253 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
254 let s = lock(&self.shared);
255 f.debug_struct("Bot")
256 .field("session", &s.session)
257 .field("tick", &s.tick)
258 .field("pos", &s.snap.pose.pos)
259 .finish_non_exhaustive()
260 }
261}
262
263impl Bot {
264 fn new() -> Self {
265 Bot {
266 shared: Arc::new(Mutex::new(Shared::new())),
267 }
268 }
269
270 pub(crate) fn lock(&self) -> MutexGuard<'_, Shared> {
271 lock(&self.shared)
272 }
273
274 #[must_use]
287 pub fn tick(&self) -> u64 {
288 self.lock().tick
289 }
290
291 #[must_use]
299 pub fn version(&self) -> GameVersion {
300 self.lock().snap.version
301 }
302
303 #[must_use]
312 pub fn pose(&self) -> Pose {
313 self.lock().snap.pose
314 }
315
316 #[must_use]
324 pub fn sent(&self) -> Pose {
325 self.lock().snap.sent
326 }
327
328 #[must_use]
336 pub fn eyes(&self) -> Vec3 {
337 self.lock().snap.eyes
338 }
339
340 #[must_use]
348 pub fn health(&self) -> Health {
349 self.lock().snap.health
350 }
351
352 #[must_use]
360 pub fn is_dead(&self) -> bool {
361 self.lock().snap.dead
362 }
363
364 #[must_use]
372 pub fn game_mode(&self) -> GameMode {
373 self.lock().snap.game_mode
374 }
375
376 #[must_use]
384 pub fn held_slot(&self) -> u8 {
385 self.lock().snap.held_slot
386 }
387
388 #[must_use]
396 pub fn open_window(&self) -> Option<i32> {
397 self.lock().snap.open_window
398 }
399
400 #[must_use]
408 pub fn entity_id(&self) -> i32 {
409 self.lock().snap.entity_id
410 }
411
412 #[must_use]
420 pub fn dimension(&self) -> String {
421 self.lock().snap.dimension.clone()
422 }
423
424 pub fn with<R, F>(&self, f: F) -> With<R>
445 where
446 R: Send + 'static,
447 F: FnOnce(&mut TickContext<'_>) -> R + Send + 'static,
448 {
449 let slot = Arc::new(Mutex::new(WithSlot {
450 result: None,
451 waker: None,
452 dropped: false,
453 }));
454 let s2 = slot.clone();
455 let guard = DropWake(slot.clone());
456 let req: Request = Box::new(move |ctx| {
457 let r = catch_unwind(AssertUnwindSafe(|| f(ctx)));
458 let mut s = lock(&s2);
459 s.result = Some(r);
460 if let Some(w) = s.waker.take() {
461 w.wake();
462 }
463 drop(s);
464 std::mem::forget(guard);
465 });
466 With {
467 bot: self.clone(),
468 session: self.lock().session,
469 req: Some(req),
470 slot,
471 }
472 }
473
474 pub fn act<F>(&self, f: F)
483 where
484 F: FnOnce(&mut TickContext<'_>) + Send + 'static,
485 {
486 let mut s = self.lock();
487 if s.closed.is_none() {
488 s.requests.push_back(Box::new(f));
489 }
490 }
491
492 pub fn wait_ticks(&self, n: u64) -> WaitTicks {
501 let s = self.lock();
502 WaitTicks {
503 bot: self.clone(),
504 session: s.session,
505 until: s.tick + n,
506 }
507 }
508
509 pub fn next_tick(&self) -> WaitTicks {
520 self.wait_ticks(1)
521 }
522
523 pub fn sleep(&self, d: std::time::Duration) -> WaitTicks {
531 let ms = d.as_millis();
532 self.wait_ticks(u64::try_from(ms.div_ceil(50)).unwrap_or(u64::MAX))
533 }
534
535 pub fn timeout<F: Future>(&self, ticks: u64, fut: F) -> Timeout<F> {
545 Timeout {
546 fut: Box::pin(fut),
547 wait: self.wait_ticks(ticks),
548 }
549 }
550
551 pub async fn wait_until<F>(&self, cond: F) -> Result<(), Error>
560 where
561 F: Fn(&TickContext<'_>) -> bool + Send + Sync + 'static,
562 {
563 let cond = Arc::new(cond);
564 loop {
565 let c = cond.clone();
566 if self.with(move |ctx| c(ctx)).await? {
567 return Ok(());
568 }
569 self.next_tick().await;
570 }
571 }
572
573 pub fn spawn<T, F>(&self, fut: F) -> JoinHandle<T>
590 where
591 T: Send + 'static,
592 F: Future<Output = T> + Send + 'static,
593 {
594 let slot = Arc::new(Mutex::new(JoinSlot {
595 result: None,
596 waker: None,
597 }));
598 let done = Completer(slot.clone());
599 let on_panic = slot.clone();
600 let hook: PanicHook = Box::new(move |msg| {
601 let mut s = lock(&on_panic);
602 if s.result.is_none()
604 || matches!(&s.result, Some(Err(Error::Panicked(m))) if m.is_empty())
605 {
606 s.result = Some(Err(Error::Panicked(msg)));
607 if let Some(w) = s.waker.take() {
608 w.wake();
609 }
610 }
611 });
612 let wrapped = async move {
613 let v = fut.await;
614 done.complete(Ok(v));
615 };
616 let mut s = self.lock();
617 let id = s.next_task;
618 s.next_task += 1;
619 if s.closed.is_some() {
620 drop(s);
621 lock(&slot).result = Some(Err(Error::Disconnected));
622 } else {
623 s.spawned.push((id, Box::pin(wrapped), hook));
624 }
625 JoinHandle {
626 bot: self.clone(),
627 id,
628 slot,
629 }
630 }
631
632 pub fn require(&self, interests: Interests) {
642 let mut s = self.lock();
643 s.extra_interests |= interests;
644 }
645
646 pub(crate) fn mark(&self) -> Mark {
648 let s = self.lock();
649 Mark {
650 teleports: s.teleports,
651 deaths: s.deaths,
652 }
653 }
654
655 pub(crate) fn check(&self, m: Mark) -> Result<(), Error> {
658 let s = self.lock();
659 if s.closed.is_some() {
660 return Err(Error::Disconnected);
661 }
662 if s.deaths != m.deaths {
663 return Err(Error::Died);
664 }
665 if s.interrupt_on_teleport && s.teleports != m.teleports {
666 return Err(Error::Teleported);
667 }
668 Ok(())
669 }
670}
671
672#[derive(Debug, Clone, Copy)]
674pub(crate) struct Mark {
675 teleports: u64,
676 deaths: u64,
677}
678
679struct WithSlot<R> {
680 result: Option<std::thread::Result<R>>,
681 waker: Option<Waker>,
682 dropped: bool,
684}
685
686struct DropWake<R>(Arc<Mutex<WithSlot<R>>>);
688
689impl<R> Drop for DropWake<R> {
690 fn drop(&mut self) {
691 let mut s = lock(&self.0);
692 s.dropped = true;
693 if let Some(w) = s.waker.take() {
694 w.wake();
695 }
696 }
697}
698
699#[must_use = "futures do nothing unless awaited"]
701pub struct With<R> {
702 bot: Bot,
703 session: u64,
704 req: Option<Request>,
705 slot: Arc<Mutex<WithSlot<R>>>,
706}
707
708impl<R> std::fmt::Debug for With<R> {
709 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
710 f.debug_struct("With")
711 .field("sent", &self.req.is_none())
712 .finish()
713 }
714}
715
716impl<R> Future for With<R> {
717 type Output = Result<R, Error>;
718
719 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
720 let this = &mut *self;
721 if let Some(req) = this.req.take() {
722 let mut s = this.bot.lock();
723 if s.closed.is_some() || s.session != this.session {
724 return Poll::Ready(Err(Error::Disconnected));
725 }
726 lock(&this.slot).waker = Some(cx.waker().clone());
727 s.requests.push_back(req);
728 return Poll::Pending;
729 }
730 let mut slot = lock(&this.slot);
731 match slot.result.take() {
732 Some(Ok(v)) => Poll::Ready(Ok(v)),
733 Some(Err(panic)) => {
734 drop(slot);
735 std::panic::resume_unwind(panic)
736 }
737 None if slot.dropped => Poll::Ready(Err(Error::Disconnected)),
738 None => {
739 slot.waker = Some(cx.waker().clone());
740 Poll::Pending
741 }
742 }
743 }
744}
745
746#[must_use = "futures do nothing unless awaited"]
748#[derive(Debug)]
749pub struct WaitTicks {
750 bot: Bot,
751 session: u64,
752 until: u64,
753}
754
755impl Future for WaitTicks {
756 type Output = ();
757
758 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
759 let mut s = self.bot.lock();
760 if s.closed.is_some() || s.session != self.session || s.tick >= self.until {
761 return Poll::Ready(());
762 }
763 if !s.tick_wakers.iter().any(|w| w.will_wake(cx.waker())) {
764 s.tick_wakers.push(cx.waker().clone());
765 }
766 Poll::Pending
767 }
768}
769
770#[must_use = "futures do nothing unless awaited"]
772pub struct Timeout<F> {
773 fut: Pin<Box<F>>,
774 wait: WaitTicks,
775}
776
777impl<F> std::fmt::Debug for Timeout<F> {
778 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779 f.debug_struct("Timeout")
780 .field("until", &self.wait.until)
781 .finish()
782 }
783}
784
785impl<F: Future> Future for Timeout<F> {
786 type Output = Result<F::Output, Error>;
787
788 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
789 let this = self.get_mut();
790 if let Poll::Ready(v) = this.fut.as_mut().poll(cx) {
791 return Poll::Ready(Ok(v));
792 }
793 let closed = {
794 let s = this.wait.bot.lock();
795 s.closed.is_some() || s.session != this.wait.session
796 };
797 match Pin::new(&mut this.wait).poll(cx) {
798 Poll::Ready(()) if closed => Poll::Ready(Err(Error::Disconnected)),
799 Poll::Ready(()) => Poll::Ready(Err(Error::Timeout)),
800 Poll::Pending => Poll::Pending,
801 }
802 }
803}
804
805struct JoinSlot<T> {
806 result: Option<Result<T, Error>>,
807 waker: Option<Waker>,
808}
809
810struct Completer<T>(Arc<Mutex<JoinSlot<T>>>);
813
814impl<T> Completer<T> {
815 fn complete(self, r: Result<T, Error>) {
816 let mut s = lock(&self.0);
817 s.result = Some(r);
818 if let Some(w) = s.waker.take() {
819 w.wake();
820 }
821 }
822}
823
824impl<T> Drop for Completer<T> {
825 fn drop(&mut self) {
826 let mut s = lock(&self.0);
827 if s.result.is_none() {
828 s.result = Some(Err(if std::thread::panicking() {
830 Error::Panicked(String::new())
831 } else {
832 Error::Cancelled
833 }));
834 if let Some(w) = s.waker.take() {
835 w.wake();
836 }
837 }
838 }
839}
840
841#[must_use = "dropping the handle detaches the task"]
844pub struct JoinHandle<T> {
845 bot: Bot,
846 id: u64,
847 slot: Arc<Mutex<JoinSlot<T>>>,
848}
849
850impl<T> std::fmt::Debug for JoinHandle<T> {
851 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
852 f.debug_struct("JoinHandle").field("id", &self.id).finish()
853 }
854}
855
856impl<T> JoinHandle<T> {
857 pub fn abort(&self) {
866 self.bot.lock().aborted.push(self.id);
867 }
868
869 #[must_use]
879 pub fn is_finished(&self) -> bool {
880 lock(&self.slot).result.is_some()
881 }
882}
883
884impl<T> Future for JoinHandle<T> {
885 type Output = Result<T, Error>;
886
887 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
888 let mut s = lock(&self.slot);
889 match s.result.take() {
890 Some(r) => Poll::Ready(r),
891 None => {
892 s.waker = Some(cx.waker().clone());
893 Poll::Pending
894 }
895 }
896 }
897}
898
899struct TaskWaker {
901 id: u64,
902 ready: Arc<Mutex<Vec<u64>>>,
903}
904
905impl Wake for TaskWaker {
906 fn wake(self: Arc<Self>) {
907 lock(&self.ready).push(self.id);
908 }
909
910 fn wake_by_ref(self: &Arc<Self>) {
911 lock(&self.ready).push(self.id);
912 }
913}
914
915struct Task {
916 id: u64,
917 fut: BoxFuture<()>,
918 waker: Waker,
919 on_panic: Option<PanicHook>,
920}
921
922#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
924#[non_exhaustive]
925pub enum WhenDone {
926 #[default]
929 Disconnect,
930 Stay,
933}
934
935pub struct Ext {
960 name: String,
961 factory: Factory,
962 interests: Interests,
963 when_done: WhenDone,
964 auto_respawn: bool,
965 interrupt_on_teleport: bool,
966 bot: Bot,
967 tasks: Vec<Task>,
968 ready: Arc<Mutex<Vec<u64>>>,
969 main: Option<JoinHandle<Result<(), Error>>>,
970 result: Option<Result<(), Error>>,
971 finished: bool,
972 started: bool,
973}
974
975impl std::fmt::Debug for Ext {
976 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
977 f.debug_struct("Ext")
978 .field("name", &self.name)
979 .field("tasks", &self.tasks.len())
980 .field("result", &self.result)
981 .finish_non_exhaustive()
982 }
983}
984
985impl Ext {
986 pub fn new<F, Fut>(mut main: F) -> Self
995 where
996 F: FnMut(Bot) -> Fut + Send + 'static,
997 Fut: Future<Output = Result<(), Error>> + Send + 'static,
998 {
999 Ext {
1000 name: "ext".into(),
1001 factory: Box::new(move |bot| Box::pin(main(bot))),
1002 interests: Interests::CHAT,
1003 when_done: WhenDone::Disconnect,
1004 auto_respawn: false,
1005 interrupt_on_teleport: true,
1006 bot: Bot::new(),
1007 tasks: Vec::new(),
1008 ready: Arc::new(Mutex::new(Vec::new())),
1009 main: None,
1010 result: None,
1011 finished: false,
1012 started: false,
1013 }
1014 }
1015
1016 #[must_use]
1023 pub fn name(mut self, name: impl Into<String>) -> Self {
1024 self.name = name.into();
1025 self
1026 }
1027
1028 #[must_use]
1038 pub fn interests(mut self, interests: Interests) -> Self {
1039 self.interests = interests;
1040 self
1041 }
1042
1043 #[must_use]
1050 pub fn when_done(mut self, when: WhenDone) -> Self {
1051 self.when_done = when;
1052 self
1053 }
1054
1055 #[must_use]
1063 pub fn auto_respawn(mut self, on: bool) -> Self {
1064 self.auto_respawn = on;
1065 self
1066 }
1067
1068 #[must_use]
1077 pub fn interrupt_on_teleport(mut self, on: bool) -> Self {
1078 self.interrupt_on_teleport = on;
1079 self
1080 }
1081
1082 #[must_use]
1091 pub fn bot(&self) -> Bot {
1092 self.bot.clone()
1093 }
1094
1095 #[must_use]
1103 pub fn result(&self) -> Option<&Result<(), Error>> {
1104 self.result.as_ref()
1105 }
1106
1107 fn begin_session(&mut self, ctx: &TickContext<'_>) {
1108 self.tasks.clear();
1109 lock(&self.ready).clear();
1110 self.result = None;
1111 self.finished = false;
1112 {
1113 let mut s = self.bot.lock();
1114 s.session += 1;
1115 s.closed = None;
1116 s.tick = 0;
1117 s.requests.clear();
1118 s.spawned.clear();
1119 s.aborted.clear();
1120 s.teleports = 0;
1121 s.deaths = 0;
1122 s.interrupt_on_teleport = self.interrupt_on_teleport;
1123 s.snap.refresh(ctx);
1124 }
1125 let fut = (self.factory)(self.bot.clone());
1126 self.main = Some(self.bot.spawn(fut));
1127 }
1128
1129 fn end_session(&mut self, reason: &str) {
1130 let mut s = self.bot.lock();
1131 s.closed = Some(reason.to_owned());
1132 let reqs: Vec<Request> = s.requests.drain(..).collect();
1133 let spawned = std::mem::take(&mut s.spawned);
1134 s.wake_ticks();
1135 s.wake_subs();
1136 drop(s);
1137 drop(reqs);
1139 drop(spawned);
1140 self.tasks.clear();
1141 }
1142
1143 fn run(&mut self, ctx: &mut TickContext<'_>) {
1145 for _ in 0..MAX_ROUNDS {
1146 let (spawned, aborted) = {
1148 let mut s = self.bot.lock();
1149 (
1150 std::mem::take(&mut s.spawned),
1151 std::mem::take(&mut s.aborted),
1152 )
1153 };
1154 if !aborted.is_empty() {
1155 self.tasks.retain(|t| !aborted.contains(&t.id));
1156 }
1157 for (id, fut, on_panic) in spawned {
1158 let waker = Waker::from(Arc::new(TaskWaker {
1159 id,
1160 ready: self.ready.clone(),
1161 }));
1162 self.tasks.push(Task {
1163 id,
1164 fut,
1165 waker,
1166 on_panic: Some(on_panic),
1167 });
1168 lock(&self.ready).push(id);
1169 }
1170 let mut ready = std::mem::take(&mut *lock(&self.ready));
1171 ready.sort_unstable();
1172 ready.dedup();
1173 for id in ready {
1174 let Some(i) = self.tasks.iter().position(|t| t.id == id) else {
1175 continue;
1176 };
1177 let t = &mut self.tasks[i];
1178 let mut cx = Context::from_waker(&t.waker);
1179 match catch_unwind(AssertUnwindSafe(|| t.fut.as_mut().poll(&mut cx))) {
1180 Ok(Poll::Pending) => {}
1181 Ok(Poll::Ready(())) => {
1182 self.tasks.swap_remove(i);
1183 }
1184 Err(p) => {
1185 let msg = panic_message(&*p);
1186 log::error!("[{}] task {id} panicked: {msg}", self.name);
1187 let mut t = self.tasks.swap_remove(i);
1188 if let Some(h) = t.on_panic.take() {
1189 h(msg);
1190 }
1191 }
1192 }
1193 }
1194 let mut ran = false;
1196 loop {
1197 let r = self.bot.lock().requests.pop_front();
1198 let Some(r) = r else { break };
1199 ran = true;
1200 r(ctx);
1201 }
1202 if ran {
1203 self.bot.lock().snap.refresh(ctx);
1204 }
1205 let idle = lock(&self.ready).is_empty() && {
1206 let s = self.bot.lock();
1207 s.spawned.is_empty() && s.aborted.is_empty() && s.requests.is_empty()
1208 };
1209 if idle {
1210 return;
1211 }
1212 }
1213 log::warn!(
1214 "[{}] t{} tasks still busy after {MAX_ROUNDS} rounds: continuing next tick",
1215 self.name,
1216 ctx.tick()
1217 );
1218 }
1219}
1220
1221pub(crate) fn panic_message(p: &(dyn std::any::Any + Send)) -> String {
1223 if let Some(s) = p.downcast_ref::<&str>() {
1224 (*s).to_owned()
1225 } else if let Some(s) = p.downcast_ref::<String>() {
1226 s.clone()
1227 } else {
1228 "unknown panic".to_owned()
1229 }
1230}
1231
1232impl Behavior for Ext {
1233 fn name(&self) -> &str {
1234 &self.name
1235 }
1236
1237 fn interests(&self) -> Interests {
1238 self.interests | self.bot.lock().extra_interests
1239 }
1240
1241 fn start(&mut self, ctx: &mut TickContext<'_>) {
1242 if self.started {
1243 self.end_session("new session");
1244 }
1245 self.started = true;
1246 self.begin_session(ctx);
1247 }
1248
1249 fn tick(&mut self, ctx: &mut TickContext<'_>) {
1250 {
1251 let mut s = self.bot.lock();
1252 s.tick += 1;
1253 s.snap.refresh(ctx);
1254 let ev = ctx.events();
1255 s.teleports += ev.teleports.len() as u64;
1256 if ev.died {
1257 s.deaths += 1;
1258 }
1259 s.publish(ctx);
1260 s.wake_ticks();
1261 }
1262 if self.auto_respawn && ctx.is_dead() {
1263 ctx.respawn();
1264 }
1265 self.run(ctx);
1266 if self.result.is_none()
1268 && let Some(h) = &self.main
1269 && h.is_finished()
1270 {
1271 let r = lock(&h.slot).result.take();
1272 let r = match r {
1273 Some(Ok(r)) => r,
1274 Some(Err(e)) => Err(e),
1275 None => Err(Error::Cancelled),
1276 };
1277 self.main = None;
1278 match (&r, self.when_done) {
1279 (Ok(()), WhenDone::Disconnect) => ctx.disconnect("done"),
1280 (Err(e), WhenDone::Disconnect) => ctx.disconnect(format!("failed: {e}")),
1281 (Ok(()), WhenDone::Stay) => {
1282 log::info!("[{}] main task done", self.name);
1283 }
1284 (Err(e), WhenDone::Stay) => log::warn!("[{}] main task failed: {e}", self.name),
1285 }
1286 self.result = Some(r);
1287 }
1288 if self.result.is_some() && self.when_done == WhenDone::Stay && self.tasks.is_empty() {
1289 self.finished = true;
1290 }
1291 }
1292
1293 fn running(&self) -> bool {
1294 !self.finished
1295 }
1296
1297 fn stop(&mut self, reason: &str) {
1298 self.end_session(reason);
1299 if self.result.is_none() && self.main.take().is_some() {
1300 self.result = Some(Err(Error::Disconnected));
1301 }
1302 self.started = false;
1303 }
1304}