├── resources ├── fonts │ └── DejaVuSerif.ttf └── images │ ├── astromonaut.ase │ ├── astromonaut.png │ ├── astromonaut0.png │ ├── astromonaut1.png │ └── astromonaut2.png ├── src ├── scenes │ ├── mod.rs │ ├── menu.rs │ └── level.rs ├── util.rs ├── error.rs ├── input.rs ├── components.rs ├── world.rs ├── resources.rs ├── main.rs └── systems.rs ├── README.md ├── .gitignore ├── Cargo.toml ├── LICENSE-MIT └── LICENSE-APACHE /resources/fonts/DejaVuSerif.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/fonts/DejaVuSerif.ttf -------------------------------------------------------------------------------- /resources/images/astromonaut.ase: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/images/astromonaut.ase -------------------------------------------------------------------------------- /resources/images/astromonaut.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/images/astromonaut.png -------------------------------------------------------------------------------- /resources/images/astromonaut0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/images/astromonaut0.png -------------------------------------------------------------------------------- /resources/images/astromonaut1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/images/astromonaut1.png -------------------------------------------------------------------------------- /resources/images/astromonaut2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icefoxen/ld42/HEAD/resources/images/astromonaut2.png -------------------------------------------------------------------------------- /src/scenes/mod.rs: -------------------------------------------------------------------------------- 1 | use ggez_goodies::scene; 2 | 3 | use input; 4 | use world::World; 5 | 6 | pub mod level; 7 | pub mod menu; 8 | 9 | // Shortcuts for our scene type. 10 | pub type FSceneSwitch = scene::SceneSwitch; 11 | pub type FSceneStack = scene::SceneStack; 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LD42 game 2 | 3 | Woohoo! Theme: "Running out of space". 4 | 5 | 6 | 7 | # Annoying bits about nalgebra 8 | 9 | Create a Vector2 from distance and angle? 10 | 11 | Project onto a vector (isn't there, would be nice so I don't have to look the damn thing up) 12 | 13 | Isometry typing is never what you want it to be tbh (UnitComplex for rotation for example.) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # Log file 13 | debug.log 14 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | //! Random utility functions go here. 2 | //! 3 | //! Every project ends up with a few. 4 | 5 | // I wanna use ncollide2d and that means using nalgebra 0.15 6 | // which means using a different version than is in ggez 0.4.3 7 | use nalgebra as na; 8 | use ncollide2d as nc; 9 | use specs; 10 | 11 | pub type Point2 = na::Point2; 12 | pub type Vector2 = na::Vector2; 13 | pub type CollisionWorld = nc::world::CollisionWorld; 14 | pub type CollisionObject = nc::world::CollisionObject; 15 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! Basic error types. 2 | 3 | use ggez; 4 | use specs; 5 | 6 | #[derive(Debug, Fail)] 7 | pub enum Err { 8 | #[fail(display = "ggez error: {:?}", err)] 9 | GgezError { err: ggez::GameError }, 10 | 11 | #[fail(display = "specs error: {:?}", err)] 12 | SpecsError { err: specs::error::Error }, 13 | } 14 | 15 | impl From for Err { 16 | fn from(err: ggez::GameError) -> Self { 17 | Err::GgezError { err } 18 | } 19 | } 20 | 21 | impl From for Err { 22 | fn from(err: specs::error::Error) -> Self { 23 | Err::SpecsError { err } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "running_into_space" 3 | version = "0.1.0" 4 | authors = ["Simon Heath "] 5 | license = "MIT OR Apache-2.0" 6 | readme = "README.md" 7 | 8 | [profile.dev] 9 | opt-level = 1 10 | 11 | [dependencies] 12 | # Game stuff 13 | ggez = "0.4" 14 | ggez-goodies = { git = "https://github.com/ggez/ggez-goodies", rev = "aacd12867d886b0331478ab616dcb35e337643a8" } 15 | specs = "0.12" 16 | specs-derive = "0.2" 17 | warmy = "0.7" 18 | nalgebra = "0.16" 19 | ncollide2d = "0.17" 20 | 21 | # Utility stuff 22 | log = "0.4" 23 | fern = {version = "0.5", features = ["colored"] } 24 | chrono = "0.4" 25 | failure = "0.1" 26 | rand = "0.5" -------------------------------------------------------------------------------- /src/input.rs: -------------------------------------------------------------------------------- 1 | //! Typedefs for input shortcuts. 2 | use ggez::event::*; 3 | use ggez_goodies::input; 4 | 5 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] 6 | pub enum Button { 7 | Jump, 8 | Menu, 9 | } 10 | 11 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] 12 | pub enum Axis { 13 | Vert, 14 | Horz, 15 | } 16 | 17 | pub type InputBinding = input::InputBinding; 18 | pub type InputEvent = input::InputEffect; 19 | pub type InputState = input::InputState; 20 | 21 | /// Create the default keybindings for our input state. 22 | pub fn create_input_binding() -> input::InputBinding { 23 | input::InputBinding::new() 24 | .bind_key_to_axis(Keycode::Up, Axis::Vert, true) 25 | .bind_key_to_axis(Keycode::Down, Axis::Vert, false) 26 | .bind_key_to_axis(Keycode::Left, Axis::Horz, false) 27 | .bind_key_to_axis(Keycode::Right, Axis::Horz, true) 28 | .bind_key_to_button(Keycode::Z, Button::Jump) 29 | .bind_key_to_button(Keycode::Escape, Button::Menu) 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 the ggez developers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/scenes/menu.rs: -------------------------------------------------------------------------------- 1 | use ggez; 2 | use ggez::graphics; 3 | use ggez_goodies::scene; 4 | use input; 5 | use scenes::*; 6 | use world::World; 7 | 8 | 9 | pub struct MenuScene { 10 | done: bool, 11 | } 12 | 13 | impl MenuScene { 14 | pub fn new() -> Self { 15 | Self { 16 | done: false, 17 | } 18 | } 19 | } 20 | 21 | 22 | impl scene::Scene for MenuScene { 23 | fn update(&mut self, gameworld: &mut World) -> FSceneSwitch { 24 | if self.done { 25 | // See https://github.com/ggez/ggez-goodies/issues/11 26 | // We work around that... 27 | scene::SceneSwitch::Pop 28 | } else { 29 | scene::SceneSwitch::None 30 | } 31 | } 32 | 33 | fn draw(&mut self, _gameworld: &mut World, ctx: &mut ggez::Context) -> ggez::GameResult<()> { 34 | let t = 35 | ggez::graphics::TextCached::new(r#" 36 | Running In To Space 37 | 38 | 39 | You are an astronaut trapped on a remote planet and need to 40 | run your way into orbit! 41 | 42 | Not actually done, but close! There's no win condition 43 | detection, and there were supposed to be more levels and 44 | different hazards and such. 45 | 46 | 47 | 48 | Directions: You will start running, just press Z to jump 49 | over obstacles. 50 | Escape key quits. 51 | 52 | 53 | 54 | Press Z to begin! 55 | "#)?; 56 | 57 | t.queue(ctx, graphics::Point2::new(200.0, 100.0), Some(graphics::WHITE)); 58 | 59 | graphics::TextCached::draw_queued(ctx, graphics::DrawParam::default())?; 60 | Ok(()) 61 | } 62 | 63 | fn name(&self) -> &str { 64 | "MenuScene" 65 | } 66 | 67 | fn input(&mut self, gameworld: &mut World, _ev: input::InputEvent, _started: bool) { 68 | if gameworld.input.get_button_pressed(input::Button::Jump) { 69 | self.done = true; 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /src/components.rs: -------------------------------------------------------------------------------- 1 | use ggez; 2 | use ncollide2d as nc; 3 | use specs::*; 4 | use util::*; 5 | 6 | /// /////////////////////////////////////////////////////////////////////// 7 | /// Components 8 | /// /////////////////////////////////////////////////////////////////////// 9 | #[derive(Clone, Debug, Component)] 10 | #[storage(VecStorage)] 11 | pub struct Motion { 12 | pub velocity: Vector2, 13 | pub acceleration: Vector2, 14 | } 15 | 16 | /// Objects without one won't get affected by the `Gravity` system. 17 | #[derive(Clone, Debug, Component)] 18 | #[storage(VecStorage)] 19 | pub struct Mass {} 20 | 21 | /// Just a marker that a particular entity is the player. 22 | #[derive(Clone, Debug, Component)] 23 | #[storage(HashMapStorage)] 24 | pub struct Player { 25 | pub on_ground: bool, 26 | pub jumping: bool, 27 | pub jump_force: f32, 28 | pub velocity: f32, 29 | pub run_acceleration: f32, 30 | pub tumbling_timer: f32, 31 | pub friction: f32, 32 | } 33 | 34 | /// NCollide collision object handle. 35 | /// This also stores position and orientation info. 36 | #[derive(Clone, Debug, Component)] 37 | #[storage(VecStorage)] 38 | pub struct Collider { 39 | pub object_handle: nc::world::CollisionObjectHandle, 40 | } 41 | 42 | /// Sprite marker. 43 | /// Should someday say something about what sprite to draw. 44 | #[derive(Clone, Debug, Component)] 45 | #[storage(VecStorage)] 46 | pub struct Sprite { 47 | //image: warmy::Res, 48 | } 49 | 50 | /// Mesh 51 | #[derive(Clone, Debug, Component)] 52 | #[storage(VecStorage)] 53 | pub struct Mesh { 54 | pub mesh: ggez::graphics::Mesh, 55 | } 56 | 57 | /// Gravity force; needs to go along with a Collider component. 58 | #[derive(Clone, Debug, Component)] 59 | #[storage(HashMapStorage)] 60 | pub struct Gravity { 61 | pub force: f32, 62 | } 63 | 64 | /// Something getting in your way 65 | #[derive(Clone, Debug, Component)] 66 | #[storage(HashMapStorage)] 67 | pub struct Obstacle {} 68 | -------------------------------------------------------------------------------- /src/world.rs: -------------------------------------------------------------------------------- 1 | //! This file defines the `World`, 2 | //! as well as some handy utility methods and structs. 3 | //! The `World` contains shared state that will be available 4 | //! to every `Scene`: specs objects, input state, asset cache. 5 | 6 | use ggez; 7 | use ggez_goodies::input as ginput; 8 | use ncollide2d as nc; 9 | use specs; 10 | 11 | use warmy; 12 | 13 | use std::path; 14 | 15 | use components::*; 16 | use input; 17 | use util::*; 18 | 19 | pub struct World { 20 | pub assets: warmy::Store, 21 | pub input: input::InputState, 22 | pub specs_world: specs::World, 23 | pub quit: bool, 24 | } 25 | 26 | impl World { 27 | fn register_components(&mut self) { 28 | self.specs_world.register::(); 29 | self.specs_world.register::(); 30 | self.specs_world.register::(); 31 | self.specs_world.register::(); 32 | self.specs_world.register::(); 33 | self.specs_world.register::(); 34 | self.specs_world.register::(); 35 | self.specs_world.register::(); 36 | } 37 | 38 | pub fn new(ctx: &mut ggez::Context, resource_dir: Option) -> Self { 39 | // We to bridge the gap between ggez and warmy path 40 | // handling here; ggez assumes its own absolute paths, warmy 41 | // assumes system-absolute paths; so, we make warmy look in 42 | // the specified resource dir (normally 43 | // $CARGO_MANIFEST_DIR/resources) or the ggez default resource 44 | // dir. 45 | let resource_pathbuf: path::PathBuf = match resource_dir { 46 | Some(s) => s, 47 | None => ctx.filesystem.get_resources_dir().to_owned(), 48 | }; 49 | info!("Setting up resource path: {:?}", resource_pathbuf); 50 | let opt = warmy::StoreOpt::default().set_root(resource_pathbuf); 51 | let store = warmy::Store::new(opt) 52 | .expect("Could not create asset store? Does the directory exist?"); 53 | 54 | let mut w = specs::World::new(); 55 | let collide_world: CollisionWorld = nc::world::CollisionWorld::new(0.02); 56 | w.add_resource(collide_world); 57 | 58 | let mut the_world = Self { 59 | assets: store, 60 | input: ginput::InputState::new(), 61 | specs_world: w, 62 | quit: false, 63 | }; 64 | 65 | the_world.register_components(); 66 | 67 | the_world 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/resources.rs: -------------------------------------------------------------------------------- 1 | //! Example of integrating ggez types with the `warmy` resource loader. 2 | 3 | use std::path; 4 | 5 | use failure::{self, Fail}; 6 | use ggez::{self, audio, graphics}; 7 | use warmy; 8 | 9 | use error::*; 10 | 11 | /// Warmy hands our `load()` method an absolute path, while ggez takes absolute 12 | /// paths into its VFS directory. Warmy needs to know the real absolute path so 13 | /// it can watch for reloads, so this function strips the path prefix of the warmy 14 | /// Store's root off of the given absolute path and turns it into the style of path 15 | /// that ggez expects. 16 | /// 17 | /// Because of this, ggez will have several places that resources *may* live but 18 | /// warmy will only watch for reloads in one of them. However, that isn't a huge 19 | /// problem: for development you generally want all your assets in one place to 20 | /// begin with, and for deployment you don't need the hotloading functionality. 21 | /// 22 | /// TODO: With warmy 0.7 this should not be necessary, figure it out. 23 | fn warmy_to_ggez_path(path: &path::Path, root: &path::Path) -> path::PathBuf { 24 | let stripped_path = path 25 | .strip_prefix(root) 26 | .expect("warmy path is outside of the warmy store? Should never happen."); 27 | path::Path::new("/").join(stripped_path) 28 | } 29 | 30 | /// Just a test asset that does nothing. 31 | #[derive(Debug, Copy, Clone)] 32 | pub struct TestAsset; 33 | 34 | impl warmy::Load for TestAsset { 35 | type Key = warmy::key::LogicalKey; 36 | type Error = failure::Compat; 37 | fn load( 38 | key: Self::Key, 39 | _store: &mut warmy::Storage, 40 | _ctx: &mut C, 41 | ) -> Result, Self::Error> { 42 | debug!("Loading test asset: {:?}", key); 43 | Ok(TestAsset.into()) 44 | } 45 | } 46 | 47 | /// A wrapper for a ggez Image, so we can implement warmy's `Load` trait on it. 48 | #[derive(Debug, Clone)] 49 | pub struct Image(pub graphics::Image); 50 | impl warmy::Load for Image { 51 | type Key = warmy::FSKey; 52 | type Error = failure::Compat; 53 | fn load( 54 | key: Self::Key, 55 | store: &mut warmy::Storage, 56 | ctx: &mut ggez::Context, 57 | ) -> Result, Self::Error> { 58 | println!("key: {:?}, path: {:?}", key, store.root()); 59 | let path = warmy_to_ggez_path(key.as_path(), store.root()); 60 | debug!("Loading image {:?} from file {:?}", path, key.as_path()); 61 | graphics::Image::new(ctx, path) 62 | .map(|x| warmy::Loaded::from(Image(x))) 63 | .map_err(|e| Err::from(e).compat()) 64 | } 65 | } 66 | 67 | /// A wrapper for a ggez SoundData, so we can implement warmy's `Load` trait on it. 68 | #[derive(Debug, Clone)] 69 | pub struct SoundData(pub audio::SoundData); 70 | impl warmy::Load for SoundData { 71 | type Key = warmy::FSKey; 72 | type Error = failure::Compat; 73 | fn load( 74 | key: Self::Key, 75 | store: &mut warmy::Storage, 76 | ctx: &mut ggez::Context, 77 | ) -> Result, Self::Error> { 78 | let path = warmy_to_ggez_path(key.as_path(), store.root()); 79 | debug!("Loading sound {:?} from file {:?}", path, key.as_path()); 80 | 81 | audio::SoundData::new(ctx, path) 82 | .map(|x| warmy::Loaded::from(SoundData(x))) 83 | .map_err(|e| Err::from(e).compat()) 84 | } 85 | } 86 | 87 | /// A wrapper for a ggez Font, so we can implement warmy's `Load` trait on it. 88 | /// 89 | /// Currently it just forces the font size to 12 pt; we should implement a specific 90 | /// key type for it that includes a font size. 91 | #[derive(Debug, Clone)] 92 | pub struct Font(pub graphics::Font); 93 | impl warmy::Load for Font { 94 | type Key = warmy::FSKey; 95 | type Error = failure::Compat; 96 | fn load( 97 | key: Self::Key, 98 | store: &mut warmy::Storage, 99 | ctx: &mut ggez::Context, 100 | ) -> Result, Self::Error> { 101 | let path = warmy_to_ggez_path(key.as_path(), store.root()); 102 | debug!("Loading font {:?} from file {:?}", path, key.as_path()); 103 | 104 | graphics::Font::new(ctx, path, 12) 105 | .map(|x| warmy::Loaded::from(Font(x))) 106 | .map_err(|e| Err::from(e).compat()) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | //! Game setup and very basic main loop. 2 | //! All the actual work gets done in the Scene. 3 | 4 | extern crate chrono; 5 | #[macro_use] 6 | extern crate failure; 7 | extern crate fern; 8 | extern crate ggez; 9 | extern crate ggez_goodies; 10 | #[macro_use] 11 | extern crate log; 12 | extern crate nalgebra; 13 | extern crate ncollide2d; 14 | extern crate rand; 15 | extern crate specs; 16 | #[macro_use] 17 | extern crate specs_derive; 18 | extern crate warmy; 19 | 20 | use ggez::conf; 21 | use ggez::event; 22 | use ggez::*; 23 | 24 | use ggez::event::*; 25 | use ggez::graphics; 26 | use ggez::timer; 27 | 28 | use std::path; 29 | 30 | // Modules that define actual content 31 | mod components; 32 | mod scenes; 33 | mod systems; 34 | mod world; 35 | 36 | // Modules that define utility stuff. 37 | mod error; 38 | mod input; 39 | mod resources; 40 | mod util; 41 | 42 | /// Function to set up logging. 43 | /// We write all debug messages (which will be a log) 44 | /// to both stdout and a log file. 45 | /// See the ggez logging example for a more sophisticated 46 | /// setup, we should incorporate some of that here. 47 | /// 48 | /// TODO: Don't output colors to the log file. 49 | fn setup_logger() -> Result<(), fern::InitError> { 50 | use fern::colors::{Color, ColoredLevelConfig}; 51 | // I'm used to Python's logging colors and format, 52 | // so let's do something like that. 53 | let colors = ColoredLevelConfig::default() 54 | .info(Color::Green) 55 | .debug(Color::BrightMagenta) 56 | .trace(Color::BrightBlue); 57 | fern::Dispatch::new() 58 | .format(move |out, message, record| { 59 | out.finish(format_args!( 60 | "[{}][{:<14}][{}] {}", 61 | chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), 62 | colors.color(record.level()).to_string(), 63 | record.target(), 64 | message 65 | )) 66 | }) 67 | // gfx_device_gl is very chatty on info loglevel, so 68 | // filter that a bit more strictly. 69 | .level_for("gfx_device_gl", log::LevelFilter::Warn) 70 | .level_for("ggez", log::LevelFilter::Warn) 71 | .level(log::LevelFilter::Debug) 72 | .chain(std::io::stdout()) 73 | .chain(std::fs::OpenOptions::new() 74 | .write(true) 75 | .create(true) 76 | .truncate(true) 77 | .open("debug.log")?) 78 | .apply()?; 79 | Ok(()) 80 | } 81 | 82 | /// Main game state. This holds all our STUFF, 83 | /// but most of the actual game data are 84 | /// in `Scenes`, and the `FSceneStack` contains them 85 | /// plus global game state. 86 | pub struct MainState { 87 | scenes: scenes::FSceneStack, 88 | input_binding: input::InputBinding, 89 | } 90 | 91 | impl MainState { 92 | pub fn new(resource_dir: Option, ctx: &mut Context) -> Self { 93 | let world = world::World::new(ctx, resource_dir.clone()); 94 | let mut scenestack = scenes::FSceneStack::new(ctx, world); 95 | let level_scene = scenes::level::LevelScene::new(ctx, &mut scenestack.world) 96 | .expect("Could not create initial scene?!"); 97 | graphics::set_background_color(ctx, graphics::BLACK); 98 | scenestack.push(Box::new(level_scene)); 99 | let menu_scene = scenes::menu::MenuScene::new(); 100 | scenestack.push(Box::new(menu_scene)); 101 | MainState { 102 | scenes: scenestack, 103 | input_binding: input::create_input_binding(), 104 | } 105 | } 106 | } 107 | 108 | impl EventHandler for MainState { 109 | fn update(&mut self, ctx: &mut Context) -> GameResult<()> { 110 | const DESIRED_FPS: u32 = 60; 111 | while timer::check_update_time(ctx, DESIRED_FPS) { 112 | self.scenes.update(); 113 | } 114 | self.scenes.world.assets.sync(ctx); 115 | self.scenes.world.input.update(1.0 / 60.0); 116 | 117 | if self.scenes.world.quit { 118 | info!("Exiting due to world quit flag."); 119 | ctx.quit()?; 120 | } 121 | 122 | Ok(()) 123 | } 124 | 125 | fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { 126 | graphics::clear(ctx); 127 | self.scenes.draw(ctx); 128 | graphics::present(ctx); 129 | Ok(()) 130 | } 131 | 132 | fn key_down_event( 133 | &mut self, 134 | _ctx: &mut Context, 135 | keycode: Keycode, 136 | _keymod: Mod, 137 | _repeat: bool, 138 | ) { 139 | if let Some(ev) = self.input_binding.resolve(keycode) { 140 | self.scenes.world.input.update_effect(ev, true); 141 | self.scenes.input(ev, true); 142 | } 143 | } 144 | 145 | fn key_up_event(&mut self, _ctx: &mut Context, keycode: Keycode, _keymod: Mod, _repeat: bool) { 146 | if let Some(ev) = self.input_binding.resolve(keycode) { 147 | self.scenes.world.input.update_effect(ev, false); 148 | self.scenes.input(ev, false); 149 | } 150 | } 151 | } 152 | 153 | pub fn main() { 154 | setup_logger().expect("Could not set up logging!"); 155 | let mut cb = ContextBuilder::new("ld42", "icefoxen") 156 | .window_setup(conf::WindowSetup::default().title("Running In To Space")) 157 | .window_mode(conf::WindowMode::default().dimensions(800, 600)); 158 | 159 | // We add the CARGO_MANIFEST_DIR/resources to the filesystems paths so 160 | // we we look in the cargo project for files. 161 | // And save it so we can feed there result into warmy 162 | 163 | let cargo_path: Option = option_env!("CARGO_MANIFEST_DIR").map(|env_path| { 164 | let mut res_path = path::PathBuf::from(env_path); 165 | res_path.push("resources"); 166 | res_path 167 | }); 168 | // If we have such a path then add it to the context builder too 169 | // (modifying the cb from inside a closure gets sticky) 170 | if let Some(ref s) = cargo_path { 171 | cb = cb.add_resource_path(s); 172 | } 173 | 174 | 175 | let ctx = &mut cb.build().unwrap(); 176 | // This None could be cargo_path 177 | // but only in dev mode; blarg. Need to make the filesystem shit better still. 178 | let state = &mut MainState::new(None, ctx); 179 | if let Err(e) = event::run(ctx, state) { 180 | println!("Error encountered: {}", e); 181 | } else { 182 | println!("Game exited cleanly."); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/systems.rs: -------------------------------------------------------------------------------- 1 | //! specs systems. 2 | use nalgebra as na; 3 | use specs::{self, Join}; 4 | use util::*; 5 | 6 | use components::*; 7 | 8 | pub struct GravitySystem {} 9 | 10 | impl<'a> specs::System<'a> for GravitySystem { 11 | type SystemData = ( 12 | specs::WriteStorage<'a, Motion>, 13 | specs::ReadStorage<'a, Gravity>, 14 | specs::ReadStorage<'a, Collider>, 15 | specs::ReadStorage<'a, Mass>, 16 | specs::Read<'a, CollisionWorld, specs::shred::PanicHandler>, 17 | ); 18 | 19 | fn run(&mut self, (mut motion, gravity, collider, mass, ncollide_world): Self::SystemData) { 20 | // I know we'll only ever have one gravity source in the game, 21 | // shut up. 22 | let mut gravity_sources: Vec<(Point2, f32)> = Vec::new(); 23 | for (collider, gravity) in (&collider, &gravity).join() { 24 | let grav_position = { 25 | let collision_obj = ncollide_world 26 | .collision_object(collider.object_handle) 27 | .expect( 28 | "Invalid collision object; was it removed from ncollide but not specs?", 29 | ); 30 | Point2 { 31 | coords: collision_obj.position().translation.vector, 32 | } 33 | }; 34 | gravity_sources.push((grav_position, gravity.force)); 35 | } 36 | 37 | for (motion, collider, _mass) in (&mut motion, &collider, &mass).join() { 38 | let other_position = { 39 | let collision_obj = ncollide_world 40 | .collision_object(collider.object_handle) 41 | .expect( 42 | "Invalid collision object; was it removed from ncollide but not specs?", 43 | ); 44 | Point2 { 45 | coords: collision_obj.position().translation.vector, 46 | } 47 | }; 48 | 49 | for (grav_position, grav_force) in &gravity_sources { 50 | let offset = grav_position - other_position; 51 | let distance = na::norm(&offset); 52 | // avoid punishingly small distances 53 | if !distance.is_nan() && distance > 0.1 { 54 | motion.acceleration += offset * (grav_force / (distance * distance)); 55 | } else { 56 | debug!( 57 | "Something horrible happened in GravitySystem: distance {}", 58 | distance 59 | ); 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | /// Makes the player tumble and slow down after they've 67 | /// hit something. 68 | pub struct PlayerTumbleSystem {} 69 | 70 | impl<'a> specs::System<'a> for PlayerTumbleSystem { 71 | type SystemData = (specs::WriteStorage<'a, Player>,); 72 | 73 | fn run(&mut self, (mut player,): Self::SystemData) { 74 | for (player,) in (&mut player,).join() { 75 | if player.tumbling_timer > 0.0 { 76 | // BUGGO: TODO: Aieeee, time 77 | player.tumbling_timer -= 0.1; 78 | player.friction = 0.1; 79 | } else { 80 | player.friction = 0.0; 81 | } 82 | } 83 | } 84 | } 85 | 86 | pub struct NCollideMotionSystem {} 87 | 88 | impl<'a> specs::System<'a> for NCollideMotionSystem { 89 | type SystemData = ( 90 | specs::WriteStorage<'a, Collider>, 91 | specs::WriteStorage<'a, Motion>, 92 | // Gotta use the panic handler here 'cause there is no default 93 | // we can provide for CollisionWorld, I guess. 94 | specs::Write<'a, CollisionWorld, specs::shred::PanicHandler>, 95 | ); 96 | 97 | fn run(&mut self, (mut collider, mut motion, mut ncollide_world): Self::SystemData) { 98 | for (collider, motion) in (&mut collider, &mut motion).join() { 99 | motion.velocity += motion.acceleration; 100 | motion.acceleration = na::zero(); 101 | 102 | let new_position = { 103 | let collision_obj = ncollide_world 104 | .collision_object(collider.object_handle) 105 | .expect( 106 | "Invalid collision object; was it removed from ncollide but not specs?", 107 | ); 108 | let mut new_position = collision_obj.position().clone(); 109 | new_position.append_translation_mut(&na::Translation::from_vector(motion.velocity)); 110 | new_position 111 | }; 112 | ncollide_world.set_position(collider.object_handle, new_position); 113 | } 114 | } 115 | } 116 | 117 | /* 118 | #[allow(dead_code)] 119 | pub struct PlayerMotionSystem {} 120 | 121 | impl<'a> specs::System<'a> for PlayerMotionSystem { 122 | type SystemData = ( 123 | specs::ReadStorage<'a, Player>, 124 | specs::WriteStorage<'a, Collider>, 125 | specs::WriteStorage<'a, Motion>, 126 | // Gotta use the panic handler here 'cause there is no default 127 | // we can provide for CollisionWorld, I guess. 128 | specs::Write<'a, CollisionWorld, specs::shred::PanicHandler>, 129 | ); 130 | 131 | fn run(&mut self, (player, mut colliders, mut motions, mut ncollide_world): Self::SystemData) { 132 | for (player, collider, motion) in (&player, &mut colliders, &mut motions).join() { 133 | let planet_collider = colliders.get(player.planet_entity); 134 | if player.on_ground { 135 | motion.velocity = na::zero(); 136 | motion.acceleration = na::zero(); 137 | if player.jumping { 138 | motion.velocity = Vector2::new(1.0, 0.0); 139 | } 140 | } 141 | motion.velocity += motion.acceleration; 142 | motion.acceleration = na::zero(); 143 | 144 | let new_position = { 145 | let collision_obj = ncollide_world 146 | .collision_object(collider.object_handle) 147 | .expect( 148 | "Invalid collision object; was it removed from ncollide but not specs?", 149 | ); 150 | let mut new_position = collision_obj.position().clone(); 151 | new_position.append_translation_mut(&na::Translation::from_vector(motion.velocity)); 152 | new_position 153 | }; 154 | ncollide_world.set_position(collider.object_handle, new_position); 155 | } 156 | } 157 | } 158 | */ 159 | 160 | #[allow(dead_code)] 161 | pub struct DebugPrinterSystem {} 162 | 163 | impl<'a> specs::System<'a> for DebugPrinterSystem { 164 | type SystemData = ( 165 | specs::ReadStorage<'a, Motion>, 166 | specs::ReadStorage<'a, Collider>, 167 | specs::Read<'a, CollisionWorld, specs::shred::PanicHandler>, 168 | ); 169 | 170 | fn run(&mut self, (motion, collider, ncollide_world): Self::SystemData) { 171 | for (motion, collider) in (&motion, &collider).join() { 172 | let collision_obj = ncollide_world 173 | .collision_object(collider.object_handle) 174 | .expect("Invalid collision object; was it removed from ncollide but not specs?"); 175 | let new_position = collision_obj.position().clone(); 176 | debug!( 177 | "Object position {:?}, velocity <{},{}>", 178 | new_position, motion.velocity.x, motion.velocity.y 179 | ); 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | Limitations under the License. 202 | -------------------------------------------------------------------------------- /src/scenes/level.rs: -------------------------------------------------------------------------------- 1 | use ggez; 2 | use ggez::graphics; 3 | use ggez_goodies::scene; 4 | use nalgebra as na; 5 | use ncollide2d as nc; 6 | use rand; 7 | use specs::{self, Builder, Join}; 8 | use warmy; 9 | 10 | use std::f32; 11 | 12 | use components::*; 13 | use error::Err; 14 | use input; 15 | use resources; 16 | use scenes::*; 17 | use systems::*; 18 | use util::*; 19 | use world::World; 20 | 21 | pub struct LevelScene { 22 | done: bool, 23 | sprites: Vec>, 24 | sprite_idx: usize, 25 | dispatcher: specs::Dispatcher<'static, 'static>, 26 | player_entity: specs::Entity, 27 | planet_entity: specs::Entity, 28 | camera_focus: Point2, 29 | background_mesh: graphics::Mesh, 30 | } 31 | 32 | const CAMERA_WIDTH: f32 = 800.0; 33 | const CAMERA_HEIGHT: f32 = 600.0; 34 | 35 | const PLANET_COLLISION_GROUP: usize = 1; 36 | const PLAYER_COLLISION_GROUP: usize = 2; 37 | const OBSTACLE_COLLISION_GROUP: usize = 3; 38 | 39 | impl LevelScene { 40 | pub fn new(ctx: &mut ggez::Context, world: &mut World) -> Result { 41 | let done = false; 42 | let sprite_files = vec![ 43 | "/images/astromonaut0.png", 44 | "/images/astromonaut1.png", 45 | "/images/astromonaut0.png", 46 | "/images/astromonaut2.png", 47 | ]; 48 | let sprites = sprite_files 49 | .iter() 50 | .map(|filename| { 51 | world 52 | .assets 53 | .get::<_, resources::Image>(&warmy::FSKey::new(filename), ctx) 54 | .unwrap() 55 | }) 56 | .collect(); 57 | 58 | let dispatcher = Self::register_systems(); 59 | 60 | let planet_radius = 2000.0; 61 | let planet_entity = Self::create_planet(ctx, world, planet_radius)?; 62 | let player_entity = Self::create_player(ctx, world, planet_radius)?; 63 | for _i in 0..20 { 64 | let obstacle_offset = rand::random::() * 2.0 * f32::consts::PI; 65 | let _ = Self::create_obstacle( 66 | ctx, 67 | world, 68 | planet_radius, 69 | obstacle_offset, 70 | )?; 71 | } 72 | 73 | let background_mesh = Self::create_background_mesh(ctx)?; 74 | 75 | Ok(LevelScene { 76 | done, 77 | sprites, 78 | sprite_idx: 0, 79 | dispatcher, 80 | player_entity, 81 | planet_entity, 82 | background_mesh, 83 | camera_focus: na::origin(), 84 | }) 85 | } 86 | 87 | fn register_systems() -> specs::Dispatcher<'static, 'static> { 88 | let gravity = GravitySystem {}; 89 | specs::DispatcherBuilder::new() 90 | .with(gravity, "sys_gravity", &[]) 91 | .with(PlayerTumbleSystem {}, "sys_tumble", &[]) 92 | // .with(NCollideMotionSystem {}, "sys_motion", &[]) 93 | // .with(DebugPrinterSystem {}, "sys_debugprint", &[]) 94 | .build() 95 | } 96 | 97 | fn create_background_mesh(ctx: &mut ggez::Context) -> Result { 98 | let num_stars = 10000; 99 | let star_max_bounds = 10000.0; 100 | let mut mb = graphics::MeshBuilder::new(); 101 | for _ in 0..num_stars { 102 | let x = rand::random::() * star_max_bounds - (star_max_bounds / 2.0); 103 | let y = rand::random::() * star_max_bounds - (star_max_bounds / 2.0); 104 | mb.circle( 105 | graphics::DrawMode::Fill, 106 | graphics::Point2::new(x, y), 107 | 2.0, 108 | 2.0, 109 | ); 110 | } 111 | mb.build(ctx).map_err(Err::from) 112 | } 113 | 114 | fn create_player( 115 | ctx: &mut ggez::Context, 116 | world: &mut World, 117 | planet_radius: f32, 118 | ) -> Result { 119 | let player_halfwidth = 8.0; 120 | let player_halfheight = 16.0; 121 | let run_acceleration = 0.005; 122 | let player_offset = planet_radius + player_halfheight * 3.0; 123 | // Make the player entity 124 | let entity = world 125 | .specs_world 126 | .create_entity() 127 | .with(Player { 128 | on_ground: false, 129 | jumping: false, 130 | jump_force: 3.0, 131 | velocity: 0.0, 132 | run_acceleration, 133 | tumbling_timer: 0.0, 134 | friction: 0.0, 135 | }) 136 | .with(Motion { 137 | velocity: Vector2::new(1.5, 0.0), 138 | acceleration: Vector2::new(0.0, 0.0), 139 | }) 140 | .with(Mass {}) 141 | .with(Sprite {}) 142 | .build(); 143 | 144 | // Player collision info 145 | let shape = nc::shape::Cuboid::new(Vector2::new(player_halfwidth, player_halfheight)); 146 | let mut player_collide_group = nc::world::CollisionGroups::new(); 147 | player_collide_group.set_membership(&[PLAYER_COLLISION_GROUP]); 148 | let query_type = nc::world::GeometricQueryType::Contacts(0.0, 0.0); 149 | 150 | let player_collider = { 151 | let mut collide_world = world.specs_world.write_resource::(); 152 | let player_handle = collide_world.add( 153 | na::Isometry2::new(na::Vector2::new(0.0, -player_offset), na::zero()), 154 | nc::shape::ShapeHandle::new(shape.clone()), 155 | player_collide_group, 156 | query_type, 157 | entity, 158 | ); 159 | 160 | Collider { 161 | object_handle: player_handle, 162 | } 163 | }; 164 | // Insert the collider. 165 | world 166 | .specs_world 167 | .write_storage::() 168 | .insert(entity, player_collider)?; 169 | Ok(entity) 170 | } 171 | 172 | fn create_planet( 173 | ctx: &mut ggez::Context, 174 | world: &mut World, 175 | planet_radius: f32, 176 | ) -> Result { 177 | let gravity = 200.0; 178 | // Make the world entity 179 | let entity = world 180 | .specs_world 181 | .create_entity() 182 | .with(Mesh { 183 | mesh: graphics::MeshBuilder::default() 184 | .circle( 185 | graphics::DrawMode::Fill, 186 | graphics::Point2::new(0.0, 0.0), 187 | planet_radius, 188 | 0.1, 189 | ) 190 | .build(ctx)?, 191 | }) 192 | .with(Gravity { force: gravity }) 193 | .build(); 194 | 195 | // Planet collision info 196 | let ball = nc::shape::Ball::new(planet_radius); 197 | let mut terrain_collide_group = nc::world::CollisionGroups::new(); 198 | terrain_collide_group.set_membership(&[PLANET_COLLISION_GROUP]); 199 | let query_type = nc::world::GeometricQueryType::Contacts(0.0, 0.0); 200 | 201 | let planet_collider = { 202 | let mut collide_world = world.specs_world.write_resource::(); 203 | let planet_handle = collide_world.add( 204 | na::Isometry2::new(Vector2::new(0.0, 0.0), na::zero()), 205 | nc::shape::ShapeHandle::new(ball.clone()), 206 | terrain_collide_group, 207 | query_type, 208 | entity, 209 | ); 210 | 211 | Collider { 212 | object_handle: planet_handle, 213 | } 214 | }; 215 | // Insert the collider. 216 | world 217 | .specs_world 218 | .write_storage::() 219 | .insert(entity, planet_collider)?; 220 | Ok(entity) 221 | } 222 | 223 | /// Creates an obstacle on the planet at the given angle. 224 | /// Assumes the planet is at 0,0 I guess 225 | fn create_obstacle( 226 | ctx: &mut ggez::Context, 227 | world: &mut World, 228 | planet_radius: f32, 229 | angle: f32, 230 | ) -> Result { 231 | let obstacle_halfwidth = 10.0; 232 | let obstacle_offset = planet_radius + obstacle_halfwidth; 233 | // Make the player entity 234 | let entity = world 235 | .specs_world 236 | .create_entity() 237 | .with(Obstacle {}) 238 | .with(Mesh { 239 | mesh: graphics::MeshBuilder::default() 240 | .polygon( 241 | graphics::DrawMode::Line(2.0), 242 | &[ 243 | graphics::Point2::new(-obstacle_halfwidth, -obstacle_halfwidth), 244 | graphics::Point2::new(-obstacle_halfwidth, obstacle_halfwidth), 245 | graphics::Point2::new(obstacle_halfwidth, obstacle_halfwidth), 246 | graphics::Point2::new(obstacle_halfwidth, -obstacle_halfwidth), 247 | ], 248 | ) 249 | .build(ctx)?, 250 | }) 251 | .build(); 252 | 253 | // collision info 254 | let shape = nc::shape::Cuboid::new(Vector2::new(obstacle_halfwidth, obstacle_halfwidth)); 255 | // TODO: Wait do we create multiple groups here? I think so... 256 | // Also we gotta make sure we keep the things straight. 257 | // TODO: Figure out membership; must collide with player but not 258 | // the planet. 259 | let mut obstacle_collide_group = nc::world::CollisionGroups::new(); 260 | obstacle_collide_group.set_membership(&[OBSTACLE_COLLISION_GROUP]); 261 | // obstacle_collide_group.set_whitelist(&[PLAYER_COLLISION_GROUP]); 262 | // obstacle_collide_group.set_blacklist(&[PLANET_COLLISION_GROUP]); 263 | let query_type = nc::world::GeometricQueryType::Contacts(0.0, 0.0); 264 | 265 | let obstacle_collider = { 266 | let mut collide_world = world.specs_world.write_resource::(); 267 | // sigh 268 | let x = f32::cos(angle) * obstacle_offset; 269 | let y = f32::sin(angle) * obstacle_offset; 270 | let handle = collide_world.add( 271 | na::Isometry2::new(na::Vector2::new(x, y), angle), 272 | nc::shape::ShapeHandle::new(shape.clone()), 273 | obstacle_collide_group, 274 | query_type, 275 | entity, 276 | ); 277 | 278 | Collider { 279 | object_handle: handle, 280 | } 281 | }; 282 | // Insert the collider. 283 | world 284 | .specs_world 285 | .write_storage::() 286 | .insert(entity, obstacle_collider)?; 287 | Ok(entity) 288 | } 289 | 290 | fn handle_contact_events(&mut self, gameworld: &mut World) { 291 | let mut collide_world = gameworld.specs_world.write_resource::(); 292 | collide_world.update(); 293 | let mut player_storage = gameworld.specs_world.write_storage::(); 294 | 295 | // Save and reuse the same vec each run of the loop so we only allocate once. 296 | let contacts_list = &mut Vec::new(); 297 | for e in collide_world.contact_events() { 298 | contacts_list.clear(); 299 | match e { 300 | nc::events::ContactEvent::Started(cobj_handle1, cobj_handle2) => { 301 | // It's apparently possible for the collision pair to have 302 | // no contacts... 303 | // Possibly if one object is entirely inside another? 304 | if let Some(pair) = (&*collide_world).contact_pair(*cobj_handle1, *cobj_handle2) 305 | { 306 | pair.contacts(contacts_list); 307 | let cobj1 = collide_world 308 | .collision_object(*cobj_handle1) 309 | .expect("Invalid collision object handle?"); 310 | let cobj2 = collide_world 311 | .collision_object(*cobj_handle2) 312 | .expect("Invalid collision object handle?"); 313 | 314 | // Get the entities out of the collision data 315 | let mut do_collision = 316 | |cobj1: &CollisionObject, cobj2: &CollisionObject| { 317 | let e1 = cobj1.data(); 318 | if let Some(player) = player_storage.get_mut(*e1) { 319 | // Are we colliding with terrain? 320 | if cobj2 321 | .collision_groups() 322 | .is_member_of(PLANET_COLLISION_GROUP) 323 | { 324 | player.on_ground = true; 325 | } else if cobj2 326 | .collision_groups() 327 | .is_member_of(OBSTACLE_COLLISION_GROUP) 328 | && (player.tumbling_timer <= 0.0) 329 | { 330 | player.tumbling_timer = 5.0; 331 | } 332 | } 333 | }; 334 | 335 | // Same query twice, just inverted... 336 | // TODO: this is annoying, how do we resolve this? 337 | do_collision(cobj1, cobj2); 338 | do_collision(cobj2, cobj1); 339 | } 340 | } 341 | nc::events::ContactEvent::Stopped(cobj_handle1, cobj_handle2) => { 342 | if let Some(pair) = (&*collide_world).contact_pair(*cobj_handle1, *cobj_handle2) 343 | { 344 | pair.contacts(contacts_list); 345 | let cobj1 = collide_world 346 | .collision_object(*cobj_handle1) 347 | .expect("Invalid collision object handle?"); 348 | let cobj2 = collide_world 349 | .collision_object(*cobj_handle2) 350 | .expect("Invalid collision object handle?"); 351 | 352 | // Get the entities out of the collision data 353 | let mut do_collision = 354 | |cobj1: &CollisionObject, cobj2: &CollisionObject| { 355 | let e1 = cobj1.data(); 356 | if let Some(player) = player_storage.get_mut(*e1) { 357 | // Are we colliding with terrain? 358 | if cobj2 359 | .collision_groups() 360 | .is_member_of(PLANET_COLLISION_GROUP) 361 | { 362 | player.on_ground = false; 363 | } 364 | } 365 | }; 366 | 367 | // Same query twice, just inverted... 368 | // TODO: this is annoying, how do we resolve this? 369 | do_collision(cobj1, cobj2); 370 | do_collision(cobj2, cobj1); 371 | } 372 | } 373 | } 374 | } 375 | } 376 | 377 | /// This is really hard to express as a specs System so we roll our own. 378 | fn run_player_motion(&mut self, world: &mut World) { 379 | if let Some(player) = world 380 | .specs_world 381 | .write_storage::() 382 | .get_mut(self.player_entity) 383 | { 384 | let mut colliders = world.specs_world.write_storage::(); 385 | let mut motions = world.specs_world.write_storage::(); 386 | let mut ncollide_world = world.specs_world.write_resource::(); 387 | 388 | let player_motion = motions 389 | .get_mut(self.player_entity) 390 | .expect("Player w/o motion?"); 391 | let player_collider = colliders 392 | .get(self.player_entity) 393 | .expect("Player w/o motion?"); 394 | let (player_position, _player_rotation) = 395 | collision_object_position(&*ncollide_world, &player_collider); 396 | let planet_collider = colliders 397 | .get(self.planet_entity) 398 | .expect("Planet w/o collider?"); 399 | let (planet_position, _planet_rotation) = 400 | collision_object_position(&*ncollide_world, planet_collider); 401 | 402 | let offset = player_position - planet_position; 403 | let normal = offset / na::norm(&offset); 404 | if player.on_ground { 405 | // We only want to zero the Y component 406 | // of the velocity... that is, the portion 407 | // towards the planet. 408 | // So we take the projection of velocity onto 409 | // the toward-the-planet offset vector. 410 | let projection = na::dot(&player_motion.velocity, &(offset / na::norm(&offset))); 411 | // debug!("Projection is {:?}, offset is {:?}, velocity is {}", projection, offset, player_motion.velocity); 412 | 413 | player_motion.velocity -= na::normalize(&offset) * projection; 414 | 415 | player_motion.acceleration = na::zero(); 416 | // Jump 417 | if player.jumping { 418 | player_motion.acceleration += normal * player.jump_force; 419 | player.on_ground = false; 420 | } 421 | 422 | // Walk 423 | let rot = na::Rotation2::new(f32::consts::PI / 2.0); 424 | let run_speed = rot * (normal * player.velocity); 425 | player_motion.acceleration += run_speed * player.run_acceleration; 426 | } 427 | // The friction term is probably wrong since it will probably slow falling 428 | // as well, but fuck it, it doesn't seem to make the player go backwards. 429 | player.velocity += player.run_acceleration - (player.velocity * player.friction); 430 | 431 | player_motion.velocity += 432 | player_motion.acceleration - (player_motion.velocity * player.friction); 433 | player_motion.acceleration = na::zero(); 434 | 435 | // Rotate to stand upright on planet. 436 | let player_angle = f32::atan2(offset.x, -offset.y); 437 | 438 | let new_position = { 439 | let collision_obj = ncollide_world 440 | .collision_object(player_collider.object_handle) 441 | .expect( 442 | "Invalid collision object; was it removed from ncollide but not specs?", 443 | ); 444 | let mut new_position = collision_obj.position().clone(); 445 | new_position 446 | .append_translation_mut(&na::Translation::from_vector(player_motion.velocity)); 447 | new_position.rotation = na::UnitComplex::from_angle(player_angle); 448 | new_position 449 | }; 450 | ncollide_world.set_position(player_collider.object_handle, new_position); 451 | self.camera_focus = Point2::new( 452 | new_position.translation.vector.x, 453 | new_position.translation.vector.y, 454 | ); 455 | } 456 | } 457 | } 458 | 459 | /// Takes a collision object handle and returns the location and orientation 460 | /// of the object. 461 | fn collision_object_position( 462 | ncollide_world: &CollisionWorld, 463 | collider: &Collider, 464 | ) -> (Point2, f32) { 465 | let collision_object = ncollide_world 466 | .collision_object(collider.object_handle) 467 | .expect("Invalid collision object; was it removed from ncollide but not specs?"); 468 | let isometry = collision_object.position(); 469 | let annoying_new_pos = 470 | Point2::new(isometry.translation.vector.x, isometry.translation.vector.y); 471 | let annoying_new_angle = isometry.rotation.angle(); 472 | (annoying_new_pos, annoying_new_angle) 473 | } 474 | 475 | /// augh 476 | /// 477 | /// Mainly used for drawing, so it returns ggez's Point type rather than ncollide's. 478 | fn ggez_collision_object_position( 479 | ncollide_world: &CollisionWorld, 480 | collider: &Collider, 481 | ) -> (graphics::Point2, f32) { 482 | let (point, rotation) = collision_object_position(ncollide_world, collider); 483 | (graphics::Point2::new(point.x, point.y), rotation) 484 | } 485 | 486 | impl scene::Scene for LevelScene { 487 | fn update(&mut self, gameworld: &mut World) -> FSceneSwitch { 488 | self.run_player_motion(gameworld); 489 | self.dispatcher.dispatch(&mut gameworld.specs_world.res); 490 | 491 | self.handle_contact_events(gameworld); 492 | self.sprite_idx += 1; 493 | if self.done { 494 | scene::SceneSwitch::Pop 495 | } else { 496 | scene::SceneSwitch::None 497 | } 498 | } 499 | 500 | fn draw(&mut self, gameworld: &mut World, ctx: &mut ggez::Context) -> ggez::GameResult<()> { 501 | // Focus view on player. 502 | let screen_rect = graphics::Rect { 503 | x: self.camera_focus.x - CAMERA_WIDTH / 2.0, 504 | y: self.camera_focus.y - CAMERA_HEIGHT / 2.0, 505 | w: CAMERA_WIDTH, 506 | h: CAMERA_HEIGHT, 507 | }; 508 | graphics::set_screen_coordinates(ctx, screen_rect)?; 509 | 510 | // Draw background 511 | graphics::draw(ctx, &self.background_mesh, ggez::nalgebra::origin(), 0.0)?; 512 | 513 | let sprite = gameworld.specs_world.read_storage::(); 514 | let player = gameworld.specs_world.read_storage::(); 515 | let mesh = gameworld.specs_world.read_storage::(); 516 | let collider = gameworld.specs_world.read_storage::(); 517 | let ncollide_world = gameworld.specs_world.read_resource::(); 518 | for (c, _, player) in (&collider, &sprite, &player).join() { 519 | let (pos, angle) = ggez_collision_object_position(&*ncollide_world, c); 520 | let corrected_pos = pos; // - graphics::Vector2::new(8.0, 16.0); 521 | // BUGGO: Behold, the shittiest animation timing known to man or god 522 | graphics::draw_ex( 523 | ctx, 524 | &(self.sprites[(self.sprite_idx / 10) % self.sprites.len()].borrow().0), 525 | graphics::DrawParam { 526 | dest: corrected_pos, 527 | rotation: angle - player.tumbling_timer, 528 | offset: graphics::Point2::new(0.5, 0.5), 529 | ..graphics::DrawParam::default() 530 | }, 531 | )?; 532 | } 533 | 534 | for (c, mesh) in (&collider, &mesh).join() { 535 | let (pos, angle) = ggez_collision_object_position(&*ncollide_world, c); 536 | graphics::draw_ex( 537 | ctx, 538 | &mesh.mesh, 539 | graphics::DrawParam { 540 | dest: pos, 541 | rotation: angle, 542 | ..graphics::DrawParam::default() 543 | }, 544 | )?; 545 | } 546 | 547 | let player_storage = gameworld.specs_world.read_storage::(); 548 | let player_component = player_storage.get(self.player_entity).expect("No player?"); 549 | 550 | // let text_point = graphics::Point2::new(10.0, 10.0); 551 | let velocity_point = graphics::Point2::new(10.0, 10.0); 552 | let text_color = Some(graphics::WHITE); 553 | // if player_component.on_ground { 554 | // let t = ggez::graphics::TextCached::new("On ground")?; 555 | // t.queue(ctx, text_point, text_color); 556 | // } else { 557 | // let t = ggez::graphics::TextCached::new("Not on ground")?; 558 | // t.queue(ctx, text_point, text_color); 559 | // } 560 | let t = 561 | ggez::graphics::TextCached::new(format!("Velocity: {:0.1}", player_component.velocity))?; 562 | 563 | // Ghetto text outline 564 | let outline_distance = 1.0; 565 | t.queue(ctx, velocity_point + graphics::Vector2::new(outline_distance, 0.0), Some(graphics::BLACK)); 566 | t.queue(ctx, velocity_point + graphics::Vector2::new(-outline_distance, 0.0), Some(graphics::BLACK)); 567 | t.queue(ctx, velocity_point + graphics::Vector2::new(0.0, outline_distance), Some(graphics::BLACK)); 568 | t.queue(ctx, velocity_point + graphics::Vector2::new(0.0, -outline_distance), Some(graphics::BLACK)); 569 | 570 | 571 | t.queue(ctx, velocity_point, text_color); 572 | graphics::TextCached::draw_queued(ctx, graphics::DrawParam::default())?; 573 | Ok(()) 574 | } 575 | 576 | fn name(&self) -> &str { 577 | "LevelScene" 578 | } 579 | 580 | fn input(&mut self, gameworld: &mut World, _ev: input::InputEvent, _started: bool) { 581 | if gameworld.input.get_button_pressed(input::Button::Menu) { 582 | gameworld.quit = true; 583 | } 584 | if let Some(player) = gameworld 585 | .specs_world 586 | .write_storage::() 587 | .get_mut(self.player_entity) 588 | { 589 | player.jumping = gameworld.input.get_button_pressed(input::Button::Jump); 590 | // player.walk_direction = gameworld.input.get_axis(input::Axis::Horz); 591 | } 592 | } 593 | } 594 | --------------------------------------------------------------------------------