Skip to main content

Entity

Struct Entity 

Source
pub struct Entity {
Show 15 fields pub id: u32, pub creator_id: Uuid, pub orientation: Vec2<f32>, pub position: Vec3<f32>, pub tilt: f32, pub action: EntityAction, pub attributes: ValueContainer, pub dirty_flags: u8, pub dirty_attributes: FxHashSet<String>, pub inventory: Vec<Option<Item>>, pub inventory_additions: FxHashMap<usize, Item>, pub inventory_removals: FxHashSet<usize>, pub inventory_updates: FxHashMap<usize, ItemUpdate>, pub equipped: IndexMap<String, Item>, pub wallet: Wallet,
}
Expand description

The Rust representation of an Entity. The real entity class lives in Python, this class is the Rust side instantiation (to avoid unnecessary Python look ups for common attributes). The class gets synced with the Python side.

Fields§

§id: u32

The id of the entity in the entity manager

§creator_id: Uuid

Maps the entity to a creator id

§orientation: Vec2<f32>

The XZ orientation

§position: Vec3<f32>

The position in the map

§tilt: f32

The vertical camera tilt, 0.0 means flat, no tilt.

§action: EntityAction

The current action, server side.

§attributes: ValueContainer

Attributes

§dirty_flags: u8

Dirty static attributes The dirty_flags field is a bitmask representing changes to various components of the entity. Each bit corresponds to a specific type of change:

  • 0b00000001 (1): Position changed
  • 0b00000010 (2): Orientation changed
  • 0b00000100 (4): Tilt changed
  • 0b00001000 (8): Inventory changed
  • 0b00010000 (16): Equipped items changed
  • 0b00100000 (32): Wallet changed
§dirty_attributes: FxHashSet<String>

Dirty Attributes

§inventory: Vec<Option<Item>>

Inventory: A container for the entity’s items

§inventory_additions: FxHashMap<usize, Item>

Track added items

§inventory_removals: FxHashSet<usize>

Track removed items

§inventory_updates: FxHashMap<usize, ItemUpdate>

Track updated items

§equipped: IndexMap<String, Item>

Equipped items

§wallet: Wallet

Wallet

Implementations§

Source§

impl Entity

Source

pub fn new() -> Self

Source

pub fn get_mode(&self) -> String

Get the entity mode.

Source

pub fn get_pos_xz(&self) -> Vec2<f32>

Get the XZ position.

Source

pub fn camera_look_at(&self) -> Vec3<f32>

Computes the look-at target based on position, orientation, and vertical tilt (tilt).

Source

pub fn forward(&self) -> Vec3<f32>

A forward direction vector for the entity.

Source

pub fn turn_left(&mut self, degrees: f32)

Rotates the entity to the left by a certain degree.

Examples found in repository?
examples/map.rs (line 101)
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
Source

pub fn turn_right(&mut self, degrees: f32)

Rotates the entity to the right by a certain degree.

Examples found in repository?
examples/map.rs (line 104)
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
Source

pub fn move_forward(&mut self, distance: f32)

Moves the entity forward along its current orientation.

Examples found in repository?
examples/map.rs (line 95)
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
Source

pub fn move_backward(&mut self, distance: f32)

Moves the entity backward along its current orientation.

Examples found in repository?
examples/map.rs (line 98)
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
Source

pub fn get_forward_pos(&mut self, distance: f32) -> Vec2<f32>

Gets the position in the direction of the entity’s orientation by a given distance.

Source

pub fn apply_to_camera( &self, camera: &mut Box<dyn D3Camera>, firstp_eye_level: f32, )

Applies the camera’s position and look-at parameters based on the entity’s state.

Source

pub fn set_position(&mut self, new_position: Vec3<f32>)

Set the position and mark it as dirty

Source

pub fn set_pos_xz(&mut self, new_position: Vec2<f32>)

Set the position as a Vec2 and mark it as dirty

Source

pub fn set_orientation(&mut self, new_orientation: Vec2<f32>)

Set the orientation and mark it as dirty

Source

pub fn set_tilt(&mut self, new_tilt: f32)

Set the tilt and mark it as dirty

Source

pub fn set_tilt_from_screen_coordinate(&mut self, screen_y: f32)

Maps a normalized screen coordinate (0.0 to 1.0) to a tilt angle. 0.0 -> maximum downward tilt, 1.0 -> maximum upward tilt.

Examples found in repository?
examples/map.rs (line 148)
140    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
141        if self.camera.id() == "orbit" {
142            self.camera.set_parameter_vec2(
143                "from_normalized",
144                Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
145            );
146        } else if self.camera.id() == "firstp" {
147            self.entity
148                .set_tilt_from_screen_coordinate(1.0 - y / ctx.height as f32);
149        }
150        true
151    }
Source

pub fn add_item(&mut self, item: Item) -> Result<usize, String>

Add an item to the entity’s inventory and track additions

Source

pub fn remove_item_from_slot(&mut self, slot: usize) -> Option<Item>

Remove an item from the given slot.

Source

pub fn remove_item(&mut self, id: u32) -> Option<Item>

Remove an item from the entity’s inventory and track removals

Source

pub fn get_item_in_slot(&self, slot: usize) -> Option<&Item>

Get a reference to an item in a given slot.

Source

pub fn get_item_in_slot_mut(&mut self, slot: usize) -> Option<&mut Item>

Get a mutable reference to an item in a given slot.

Source

pub fn get_item(&self, item_id: u32) -> Option<&Item>

Get a reference to an item by its ID

Source

pub fn get_item_mut(&mut self, item_id: u32) -> Option<&mut Item>

Get a mutable reference to an item by its ID

Source

pub fn get_item_slot(&self, item_id: u32) -> Option<usize>

Get the slot index of an item by its ID

Source

pub fn equip_item(&mut self, item_id: u32, slot: &str) -> Result<(), String>

Equip an item into a specific slot

Source

pub fn unequip_item(&mut self, slot: &str) -> Result<Item, String>

Unequip an item from a specific slot

Source

pub fn get_equipped_item(&self, slot: &str) -> Option<&Item>

Get a reference of an item equipped in a specific slot

Source

pub fn get_equipped_item_mut(&mut self, slot: &str) -> Option<&mut Item>

Get the mutable reference of an item equipped in a specific slot

Source

pub fn add_currency( &mut self, symbol: &str, amount: i64, currencies: &Currencies, ) -> Result<(), String>

Add the given currency to the wallet.

Source

pub fn add_base_currency( &mut self, amount: i64, currencies: &Currencies, ) -> Result<(), String>

Add the given base currency to the wallet.

Source

pub fn spend_currency( &mut self, base_amount: i64, currencies: &Currencies, ) -> Result<(), String>

Spend the given currency.

Source

pub fn set_attribute(&mut self, key: &str, value: Value)

Set a dynamic attribute and mark it as dirty

Source

pub fn get_attr_string(&self, key: &str) -> Option<String>

Get the given String

Source

pub fn get_attr_uuid(&self, key: &str) -> Option<Uuid>

Get the given Uuid

Source

pub fn is_player(&self) -> bool

Returns true if this entity is a player

Source

pub fn mark_dirty_attribute(&mut self, key: &str)

Mark a dynamic attribute as dirty

Source

pub fn mark_all_dirty(&mut self)

Mark all fields and attributes as dirty.

Source

pub fn is_dirty(&mut self) -> bool

Check if the entity is dirty and generate item updates as needed.

Source

pub fn set_static_dirty(&mut self)

Mark all static fields as dirty

Source

pub fn clear_dirty(&mut self)

Clear all dirty flags and attributes

Source

pub fn get_update(&self) -> EntityUpdate

Get a partial update containing only dirty fields and attributes

Source

pub fn apply_update(&mut self, update: EntityUpdate) -> bool

Apply an update to the entity. Returns true if the entities appearance has changed and needs to be updated.

Source

pub fn face_east(&mut self)

Sets the orientation to face east.

Source

pub fn face_west(&mut self)

Sets the orientation to face west.

Source

pub fn face_north(&mut self)

Sets the orientation to face north.

Source

pub fn face_south(&mut self)

Sets the orientation to face south.

Source

pub fn face_at(&mut self, target: Vec2<f32>)

Sets the orientation to face a specific point.

Source

pub fn face_random(&mut self)

Sets the orientation to face a random direction.

Source

pub fn iter_inventory(&self) -> impl Iterator<Item = (usize, &Item)>

Create an iterator over the inventory.

Source

pub fn iter_inventory_mut(&mut self) -> impl Iterator<Item = (usize, &mut Item)>

Create a mutable iterator over the inventory.

Trait Implementations§

Source§

impl Clone for Entity

Source§

fn clone(&self) -> Entity

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Entity

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Entity

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Entity

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Entity

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,