screeps/objects/impls/
room_object.rs

1use js_sys::Array;
2use wasm_bindgen::prelude::*;
3
4use crate::{
5    constants::EffectType,
6    local::Position,
7    objects::{Room, RoomPosition},
8    prelude::*,
9};
10
11#[wasm_bindgen]
12extern "C" {
13    /// Parent class for all objects in rooms in the game world.
14    ///
15    /// [Screeps documentation](https://docs.screeps.com/api/#Room)
16    #[derive(Clone, Debug)]
17    pub type RoomObject;
18
19    /// Effects applied to the object.
20    ///
21    /// [Screeps documentation](https://docs.screeps.com/api/#RoomObject.effects)
22    #[wasm_bindgen(method, getter = effects)]
23    fn effects_internal(this: &RoomObject) -> Option<Array>;
24
25    /// Gets the [`RoomPosition`] of an object, which is a reference to an
26    /// object in the javascript heap. In most cases, you'll likely want a
27    /// native [`Position`] instead of using this function (see
28    /// [`HasPosition::pos`]), there may be cases where this can provide
29    /// some slight performance benefits due to reducing object churn in the js
30    /// heap, so this is kept public.
31    ///
32    /// [Screeps documentation](https://docs.screeps.com/api/#RoomObject.pos)
33    #[wasm_bindgen(method, getter = pos)]
34    pub fn js_pos(this: &RoomObject) -> RoomPosition;
35
36    /// A link to the room that the object is currently in, or `None` if the
37    /// object is a power creep not spawned on the current shard, or a flag or
38    /// construction site not in a visible room.
39    ///
40    /// [Screeps documentation](https://docs.screeps.com/api/#RoomObject.room)
41    #[wasm_bindgen(method, getter)]
42    pub fn room(this: &RoomObject) -> Option<Room>;
43}
44
45#[wasm_bindgen]
46extern "C" {
47    #[wasm_bindgen]
48    #[derive(Debug)]
49    pub type Effect;
50
51    #[wasm_bindgen(method, getter)]
52    pub fn effect(this: &Effect) -> EffectType;
53
54    #[wasm_bindgen(method, getter)]
55    pub fn level(this: &Effect) -> Option<u8>;
56
57    #[wasm_bindgen(method, getter = ticksRemaining)]
58    pub fn ticks_remaining(this: &Effect) -> u32;
59}
60
61impl<T> HasPosition for T
62where
63    T: AsRef<RoomObject>,
64{
65    fn pos(&self) -> Position {
66        self.as_ref().js_pos().into()
67    }
68}
69
70impl<T> RoomObjectProperties for T
71where
72    T: AsRef<RoomObject>,
73{
74    fn effects(&self) -> Vec<Effect> {
75        RoomObject::effects_internal(self.as_ref())
76            .map(|arr| arr.iter().map(JsCast::unchecked_into).collect())
77            .unwrap_or_default()
78    }
79
80    fn effects_raw(&self) -> Option<Array> {
81        RoomObject::effects_internal(self.as_ref())
82    }
83
84    fn room(&self) -> Option<Room> {
85        RoomObject::room(self.as_ref())
86    }
87}