A bit more reorganizing, almost no sim code in main

This commit is contained in:
2020-05-31 20:56:55 +02:00
parent eaa595b963
commit b4b9dc1d55
2 changed files with 28 additions and 28 deletions

View File

@@ -1,10 +1,12 @@
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use legion::prelude::*;
use rand::prelude::*;
use crate::state::{WrappedState, Object};
use crate::state::{State, WrappedState, Object};
#[derive(Clone, Debug, PartialEq)]
struct Name {
@@ -25,6 +27,7 @@ struct Velocity {
pub struct Simulation {
world: World,
pub state: WrappedState,
}
impl Simulation {
@@ -47,7 +50,13 @@ impl Simulation {
}),
);
Self {world}
let mut result = Self {world, state: Arc::new(Mutex::new(State {
iteration: 0, objects: vec![]
}))};
result.render();
result
}
pub fn update(&mut self) {
@@ -56,26 +65,24 @@ impl Simulation {
pos.x += vel.dx;
pos.y += vel.dy;
}
self.state.lock().unwrap().iteration += 1;
}
fn render(&mut self) -> Vec<Object> {
let mut result: Vec<Object> = vec![];
fn render(&mut self) {
let mut state = self.state.lock().unwrap();
state.objects = vec![];
for (name, pos) in <(Read<Name>, Read<Position>)>::query().iter(&mut self.world) {
result.push(Object{ name: name.name.clone(), x: pos.x, y: pos.y });
state.objects.push(Object{ name: name.name.clone(), x: pos.x, y: pos.y });
}
result
}
pub fn run(&mut self, wrapped_state: WrappedState) {
pub fn run(&mut self) {
loop {
self.update();
{
let mut state = wrapped_state.lock().unwrap();
(*state).iteration += 1;
(*state).objects = self.render();
}
self.render();
thread::sleep(Duration::from_secs(1))
}
}