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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use base::world::{Chunk, ChunkProvider, World};
use super::GameContext;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::mem::replace;
use std::thread;
use std::cell::{Ref, RefCell};
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
use base::world::{CHUNK_SIZE, ChunkIndex};
use base::math::*;
use world::WorldView;
use std::cell::RefMut;

#[derive(Clone)]
pub struct WorldManager {
    shared: Rc<RefCell<Shared>>,
    chunk_requests: Sender<ChunkIndex>,
    context: Rc<GameContext>,
}

struct Shared {
    world: World,
    world_view: WorldView,
    provided_chunks: Receiver<(ChunkIndex, Chunk)>,
    sent_requests: HashSet<ChunkIndex>,
    load_distance: f32,
    player_chunk: ChunkIndex,
}

impl WorldManager {
    pub fn new(provider: Box<ChunkProvider>, game_context: Rc<GameContext>) -> Self {
        // Create two channels to send chunk positions and receive chunks.
        let (chunk_request_sender, chunk_request_recv) = channel();
        let (chunk_sender, chunk_recv) = channel();

        let this = WorldManager {
            shared: Rc::new(RefCell::new(Shared {
                world: World::empty(),
                world_view: WorldView::new(game_context.clone(), provider.get_plant_list()),
                sent_requests: HashSet::new(),
                provided_chunks: chunk_recv,
                // TODO: load this from the config!
                load_distance: 10.0,
                player_chunk: ChunkIndex(AxialPoint::new(0, 0)),
            })),
            chunk_requests: chunk_request_sender,
            context: game_context,
        };

        // Spawn worker thread, which will detach from the main thread. But
        // that is no problem: once the last sender is destroyed, the worker
        // thread will quit.
        thread::spawn(move || {
            worker_thread(provider, chunk_request_recv, chunk_sender);
        });

        this.update_player_chunk();
        this
    }

    /// Called when the player moves to a different chunk.
    ///
    /// This unloads all currently loaded chunks that are too far away from the
    /// player, and loads all chunks close enough to the player (if they aren't
    /// already requested).
    fn update_player_chunk(&self) {
        let mut shared = self.shared.borrow_mut();
        let load_distance = shared.load_distance;
        let player_chunk = shared.player_chunk.0;
        let radius = load_distance as i32;

        let is_chunk_in_range = |chunk_pos: AxialPoint| {
            let chunk_center = chunk_pos * CHUNK_SIZE as i32 +
                               AxialVector::new(CHUNK_SIZE as i32 / 2, CHUNK_SIZE as i32 / 2);
            let player_center = player_chunk * CHUNK_SIZE as i32 +
                                AxialVector::new(CHUNK_SIZE as i32 / 2, CHUNK_SIZE as i32 / 2);
            (chunk_center - player_center).to_real().distance(Vector2f::zero()) <
            load_distance * CHUNK_SIZE as f32
        };

        // Load new range
        for qd in -radius..radius + 1 {
            for rd in -radius..radius + 1 {
                let chunk_pos = AxialPoint::new(player_chunk.q + qd, player_chunk.r + rd);
                if is_chunk_in_range(chunk_pos) {
                    let chunk_index = ChunkIndex(chunk_pos);

                    if !shared.world.chunks.contains_key(&chunk_index) {
                        if !shared.sent_requests.contains(&chunk_index) {
                            self.chunk_requests.send(chunk_index).unwrap();
                            shared.sent_requests.insert(chunk_index);
                        }
                    }
                }
            }
        }

        // Drop unneeded chunks from world
        let chunks = replace(&mut shared.world.chunks, HashMap::new());
        let mut new_chunks = HashMap::new();
        for (index, chunk) in chunks {
            let chunk_pos = index.0;
            if is_chunk_in_range(chunk_pos) {
                // Still in range
                new_chunks.insert(index, chunk);
            } else {
                // Remove
                shared.world_view.remove_chunk(index);
            }
        }
        shared.world.chunks = new_chunks;
    }


    /// Returns an immutable reference to the world.
    ///
    /// *Note*: since the world manager uses a `RefCell` to save the world, a
    /// `Ref` is returned. But thanks to deref coercions you can use it like a
    /// standard reference.
    pub fn get_world(&self) -> Ref<World> {
        Ref::map(self.shared.borrow(), |shared| &shared.world)
    }

    pub fn mut_world(&self) -> RefMut<World> {
        RefMut::map(self.shared.borrow_mut(), |shared| &mut shared.world)
    }

    /// Returns an immutable reference to the world view.
    pub fn get_view(&self) -> Ref<WorldView> {
        Ref::map(self.shared.borrow(), |shared| &shared.world_view)
    }

    /// Returns an mutable reference to the world view.
    pub fn get_mut_view(&self) -> RefMut<WorldView> {
        RefMut::map(self.shared.borrow_mut(), |shared| &mut shared.world_view)
    }

    pub fn get_context(&self) -> &Rc<GameContext> {
        &self.context
    }

    /// Starts to generate all chunks within `load_distance` (config parameter)
    /// around `pos`.
    fn load_world_around(&self, pos: Point2f) {
        let axial_pos = AxialPoint::from_real(pos);
        let chunk_pos = AxialPoint::new(axial_pos.q / CHUNK_SIZE as i32,
                                        axial_pos.r / CHUNK_SIZE as i32);

        let mut shared = self.shared.borrow_mut();
        if shared.player_chunk.0 != chunk_pos {
            shared.player_chunk = ChunkIndex(chunk_pos);
            debug!("player moved to chunk {:?} (player at {:?})",
                   chunk_pos,
                   pos);
            drop(shared);

            self.update_player_chunk();
        }
    }

    /// Applies all queued updated to the actual world. Notably, all generated
    /// chunks are added.
    pub fn update_world(&self, player_pos: Point3f) {
        self.load_world_around(Point2f::new(player_pos.x, player_pos.y));

        let mut shared = self.shared.borrow_mut();
        let mut changed = false;

        loop {
            let (pos, chunk) = match shared.provided_chunks.try_recv() {
                Err(TryRecvError::Empty) => {
                    // No new chunks for us, we will check again next time ;-)
                    break;
                }
                Err(TryRecvError::Disconnected) => {
                    // The worker thread has shut down: this should never happen
                    // thus we can just panic, too.
                    error!("chunk providing worker thread shut down");
                    panic!("chunk providing worker thread shut down");
                }
                Ok(val) => val,
            };

            changed = true;
            shared.world_view.refresh_chunk(pos, &chunk, self.context.get_facade());

            shared.sent_requests.remove(&pos);
            let res = shared.world.add_chunk(pos, chunk);
            if res.is_err() {
                warn!("chunk at {:?} already exists!", pos);
            }
        }

        if changed {
            debug!("{} chunks loaded", shared.world.chunks.len());
        }
    }

    pub fn recalculate_chunk(&mut self, pos: AxialPoint) {
        use std::ops::DerefMut;

        let mut shared_tmp = self.shared.borrow_mut();
        let shared = shared_tmp.deref_mut();

        let chunk_pos = AxialPoint::new(pos.q / CHUNK_SIZE as i32, pos.r / CHUNK_SIZE as i32);
        let index = ChunkIndex(chunk_pos);

        shared.world_view.refresh_chunk(index,
                                        shared.world.chunk_at(index).unwrap(),
                                        self.context.get_facade());
    }
}


fn worker_thread(provider: Box<ChunkProvider>,
                 commands: Receiver<ChunkIndex>,
                 chunks: Sender<(ChunkIndex, Chunk)>) {
    loop {
        let requested_chunk = match commands.recv() {
            Err(_) => {
                // The other side has hung up, so we can stop working, too.
                break;
            }
            Ok(index) => index,
        };

        debug!("chunk provider thread: received request to generate chunk {:?}",
               requested_chunk.0);

        match provider.load_chunk(requested_chunk) {
            Some(chunk) => {
                debug!("chunk provider thread: chunk at {:?} successfully loaded",
                       requested_chunk);
                chunks.send((requested_chunk, chunk)).expect("main thread has hung up");
            }
            None => {
                warn!("chunk provider thread: failed to load chunk at {:?}",
                      requested_chunk)
            }
        }
    }

    info!("chunk provider thread: now stopping ...")
}