refactoring json saving/loading

This commit is contained in:
Dustin Carlino 2018-06-22 11:01:44 -07:00
parent 915ad9f7fe
commit 5ce158cb90
12 changed files with 63 additions and 83 deletions

View File

@ -1,3 +1,3 @@
[workspace]
members = ["control", "convert_osm", "editor", "ezgui", "geom", "headless", "kml", "map_model", "sim"]
members = ["abstutil", "control", "convert_osm", "editor", "ezgui", "geom", "headless", "kml", "map_model", "sim"]

View File

@ -3,7 +3,8 @@
Overlapping with TODO.md and docs/backlog.md, we have... a new list of visible
things needing polish!
- sometimes UI zooms in at once, then unzooms slowly
## Just appearance
- sidewalk paths start in building centers and end in sidewalk centers
- this is probably fine to show agents moving, but at least draw
building layer before sidewalk layer
@ -13,3 +14,7 @@ things needing polish!
- parking with... circled P's and maybe partial horizontal lines to
show spots?
- copy the green Seattle color scheme for bike lanes
## Interaction
- sometimes UI zooms in at once, then unzooms slowly

8
abstutil/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "abstutil"
version = "0.1.0"
authors = ["Dustin Carlino <dabreegster@gmail.com>"]
[dependencies]
serde = "1.0"
serde_json = "1.0"

21
abstutil/src/lib.rs Normal file
View File

@ -0,0 +1,21 @@
extern crate serde;
extern crate serde_json;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fs::File;
use std::io::{Error, Read, Write};
pub fn write_json<T: Serialize>(path: &str, obj: &T) -> Result<(), Error> {
let mut file = File::create(path)?;
file.write_all(serde_json::to_string_pretty(obj).unwrap().as_bytes())?;
Ok(())
}
pub fn read_json<T: DeserializeOwned>(path: &str) -> Result<T, Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let obj: T = serde_json::from_str(&contents).unwrap();
Ok(obj)
}

View File

@ -5,6 +5,7 @@ authors = ["Dustin Carlino <dabreegster@gmail.com>"]
[dependencies]
aabb-quadtree = "0.1.0"
abstutil = { path = "../abstutil" }
control = { path = "../control" }
geo = "0.9.1"
geom = { path = "../geom" }
@ -19,7 +20,6 @@ pistoncore-glutin_window = "*"
rand = "0.5.1"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
sim = { path = "../sim" }
structopt = "0.2"
strum = "0.9.0"

View File

@ -1,12 +1,10 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
extern crate serde_json;
use abstutil;
use graphics::types::Color;
use rand;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{Error, Read, Write};
use std::io::Error;
use strum::IntoEnumIterator;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumString, ToString,
@ -57,17 +55,8 @@ pub struct ColorScheme {
}
impl ColorScheme {
pub fn write(&self, path: &str) -> Result<(), Error> {
let mut file = File::create(path)?;
file.write_all(serde_json::to_string_pretty(self).unwrap().as_bytes())?;
Ok(())
}
pub fn load(path: &str) -> Result<ColorScheme, Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let mut scheme: ColorScheme = serde_json::from_str(&contents).unwrap();
let mut scheme: ColorScheme = abstutil::read_json(path)?;
for color in Colors::iter() {
if !scheme.map.contains_key(&color) {

View File

@ -1,6 +1,7 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
extern crate aabb_quadtree;
extern crate abstutil;
extern crate control;
extern crate ezgui;
extern crate geo;
@ -35,7 +36,6 @@ mod animation;
mod colors;
mod plugins;
mod render;
mod savestate;
mod ui;
#[derive(StructOpt, Debug)]

View File

@ -1,5 +1,6 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
use abstutil;
use control::ControlMap;
use ezgui::input::UserInput;
use geom::GeomMap;
@ -47,14 +48,11 @@ impl SimController {
self.desired_speed += ADJUST_SPEED;
}
if input.unimportant_key_pressed(Key::O, "Press O to save sim state") {
self.sim
.write_savestate("sim_state")
.expect("Writing sim state failed");
abstutil::write_json("sim_state", &self.sim).expect("Writing sim state failed");
println!("Wrote sim_state");
}
if input.unimportant_key_pressed(Key::P, "Press P to load sim state") {
self.sim =
straw_model::Sim::load_savestate("sim_state").expect("Loading sim state failed");
self.sim = abstutil::read_json("sim_state").expect("sim state failed");
}
if self.last_step.is_some() {
if input.unimportant_key_pressed(Key::Space, "Press space to pause sim") {

View File

@ -1,34 +0,0 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
extern crate serde;
extern crate serde_json;
use control::{ModifiedStopSign, ModifiedTrafficSignal};
use map_model::IntersectionID;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Error, Read, Write};
#[derive(Serialize, Deserialize, Debug)]
pub struct EditorState {
pub cam_x: f64,
pub cam_y: f64,
pub cam_zoom: f64,
pub traffic_signals: HashMap<IntersectionID, ModifiedTrafficSignal>,
pub stop_signs: HashMap<IntersectionID, ModifiedStopSign>,
}
pub fn write(path: &str, state: EditorState) -> Result<(), Error> {
let mut file = File::create(path)?;
file.write_all(serde_json::to_string_pretty(&state).unwrap().as_bytes())?;
Ok(())
}
pub fn load(path: &str) -> Result<EditorState, Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let state: EditorState = serde_json::from_str(&contents).unwrap();
Ok(state)
}

View File

@ -3,15 +3,19 @@
// TODO this should just be a way to handle interactions between plugins
extern crate map_model;
extern crate serde;
use abstutil;
use animation;
use colors::{ColorScheme, Colors};
use control::ControlMap;
use control::{ModifiedStopSign, ModifiedTrafficSignal};
use ezgui::ToggleableLayer;
use ezgui::canvas::{Canvas, GfxCtx};
use ezgui::input::UserInput;
use geom;
use graphics::types::Color;
use map_model::IntersectionID;
use piston::input::{Key, MouseCursorEvent};
use piston::window::Size;
use plugins::classification::OsmClassifier;
@ -25,8 +29,8 @@ use plugins::stop_sign_editor::StopSignEditor;
use plugins::traffic_signal_editor::TrafficSignalEditor;
use plugins::turn_colors::TurnColors;
use render;
use savestate;
use sim::CarID;
use std::collections::HashMap;
use std::process;
// TODO ideally these would be tuned kind of dynamically based on rendering speed
@ -115,7 +119,7 @@ impl UI {
cs: ColorScheme::load("color_scheme").unwrap(),
};
match savestate::load("editor_state") {
match abstutil::read_json::<EditorState>("editor_state") {
Ok(state) => {
println!("Loaded previous editor_state");
ui.canvas.cam_x = state.cam_x;
@ -281,7 +285,7 @@ impl UI {
}
if input.unimportant_key_pressed(Key::Escape, "Press escape to quit") {
let state = savestate::EditorState {
let state = EditorState {
cam_x: self.canvas.cam_x,
cam_y: self.canvas.cam_y,
cam_zoom: self.canvas.cam_zoom,
@ -289,10 +293,8 @@ impl UI {
stop_signs: self.control_map.get_stop_signs_savestate(),
};
// TODO maybe make state line up with the map, so loading from a new map doesn't break
savestate::write("editor_state", state).expect("Saving editor_state failed");
self.cs
.write("color_scheme")
.expect("Saving color_scheme failed");
abstutil::write_json("editor_state", &state).expect("Saving editor_state failed");
abstutil::write_json("color_scheme", &self.cs).expect("Saving color_scheme failed");
println!("Saved editor_state and color_scheme");
process::exit(0);
}
@ -571,3 +573,13 @@ impl UI {
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct EditorState {
pub cam_x: f64,
pub cam_y: f64,
pub cam_zoom: f64,
pub traffic_signals: HashMap<IntersectionID, ModifiedTrafficSignal>,
pub stop_signs: HashMap<IntersectionID, ModifiedStopSign>,
}

View File

@ -15,5 +15,4 @@ piston2d-graphics = "*"
rand = { version = "0.5.1", features = ["serde1"] }
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
vecmath = "0.3.1"

View File

@ -1,7 +1,5 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
extern crate serde_json;
use common::{CarID, Tick, SPEED_LIMIT};
use control::ControlMap;
use dimensioned::si;
@ -14,8 +12,6 @@ use multimap::MultiMap;
use rand::{FromEntropy, Rng, SeedableRng, XorShiftRng};
use std::collections::{BTreeMap, HashSet};
use std::f64;
use std::fs::File;
use std::io::{Error, Read, Write};
use std::time::{Duration, Instant};
use straw_intersections::{IntersectionPolicy, StopSign, TrafficSignal};
@ -556,20 +552,6 @@ impl Sim {
b.last_sim_time = self.time;
speed.value_unsafe
}
pub fn write_savestate(&self, path: &str) -> Result<(), Error> {
let mut file = File::create(path)?;
file.write_all(serde_json::to_string_pretty(self).unwrap().as_bytes())?;
Ok(())
}
pub fn load_savestate(path: &str) -> Result<Sim, Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let sim: Sim = serde_json::from_str(&contents).unwrap();
Ok(sim)
}
}
pub struct Benchmark {