Browse Source

Put ents in an Rc so they can be cross-ref'd

Also add some type aliases for ergonomics, since these types will come
up quite a bit
master
Graham Northup 6 months ago
parent
commit
07a32dfbc6
  1. 5
      src/world/entity/mod.rs
  2. 28
      src/world/mod.rs

5
src/world/entity/mod.rs

@ -131,3 +131,8 @@ pub trait Entity {
fn act(&mut self, _obs: &Observation) -> Action { Action::Wait }
}
pub type EntBox = Box<dyn Entity>;
pub type EntCell = RefCell<EntBox>;
pub type EntRef = Rc<EntCell>;
pub type EntWeak = Weak<EntCell>;

28
src/world/mod.rs

@ -7,7 +7,8 @@ use std::cell::RefCell;
use std::io::{self, Write};
use std::ops::{Deref, DerefMut};
use std::fmt::Debug;
use entity::Entity;
use std::rc::{Rc, Weak};
use entity::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Content {
@ -43,7 +44,8 @@ impl Traversable for Tile {
pub struct World {
cur_region: usize,
regions: Vec<RefCell<Region<Tile>>>,
entities: Vec<RefCell<Box<dyn Entity>>>, // NB: Player is ent 0
entities: Vec<EntRef>, // NB: Player is ent 0
player: EntRef, // Kept alive by virtue of this field
}
impl World {
@ -59,12 +61,16 @@ impl World {
})))
.build().expect("Failed to make World");
// TODO: Worldgen on start_region
let player: EntRef = Rc::new(RefCell::new(Box::new(
entity::player::Player::new(V2i(0, 0), r)
)));
World {
cur_region: 0,
regions: vec![RefCell::new(start_region)],
entities: vec![
RefCell::new(Box::new(entity::player::Player::new(V2i(0, 0), r)))
player.clone(),
],
player,
}
}
@ -76,28 +82,30 @@ impl World {
self.regions[self.cur_region].borrow_mut()
}
pub fn player<'s>(&'s self) -> impl Deref<Target=Box<dyn Entity>> + 's {
pub fn player<'s>(&'s self) -> impl Deref<Target=EntBox> + 's {
self.entities[0].borrow()
}
pub fn player_mut<'s>(&'s mut self) -> impl DerefMut<Target=Box<dyn Entity>> + 's {
pub fn player_mut<'s>(&'s mut self) -> impl DerefMut<Target=EntBox> + 's {
self.entities[0].borrow_mut()
}
pub fn entities(&self) -> impl Iterator<Item=&RefCell<Box<dyn Entity>>> {
pub fn entities(&self) -> impl Iterator<Item=&EntRef> {
self.entities.iter()
}
pub fn entity<'s>(&'s self, idx: usize) -> impl Deref<Target=Box<dyn Entity>> + 's{
pub fn entity<'s>(&'s self, idx: usize) -> impl Deref<Target=EntBox> + 's{
self.entities[idx].borrow()
}
pub fn entity_mut<'s>(&'s self, idx: usize) -> impl DerefMut<Target=Box<dyn Entity>> + 's {
pub fn entity_mut<'s>(&'s self, idx: usize) -> impl DerefMut<Target=EntBox> + 's {
self.entities[idx].borrow_mut()
}
pub fn add_entity(&mut self, ent: Box<dyn Entity>) {
self.entities.push(RefCell::new(ent));
pub fn add_entity(&mut self, ent: EntBox) -> EntWeak {
let ent = Rc::new(RefCell::new(ent));
self.entities.push(Rc::clone(&ent));
Rc::downgrade(&ent)
}
pub fn render<W: Write>(&self, rs: &mut render::RenderState, mut out: &mut W) -> io::Result<()> {

Loading…
Cancel
Save