Tutorials for Piston

Overview

Piston-Tutorials Build Status

This is a repository for examples of Piston projects that have are accompanied by written tutorials explaining core concepts for that tutorial.

Current Tutorials

Getting Started Spinning Square

A "tutorial" with instructions on compiling and running a very simple Piston.

Sudoku (work in progress)

Write a Sudoku game with Piston.

Roguelike (work in progess)

Write a Roguelike game with Piston.

Planned Tutorials

  • graphics
  • piston

Troubleshooting

  • I get ld: library not found for -lSDL2 error on OSX

  • I get "GL context creation failed" when running an example.

    It's likely your hardware or driver doesn't support PistonWindow's default OpenGl spec. Just change it to something you can support at the beginning of the example. See hello_world.rs for an example.

Making changes to the tutorials

Because most of the tutorials will contain heavy amounts of code, TyOverby developed a markdown pre-processor that takes readme.dev.md files and includes code from the surrounding project. This way you don't need to make a change in the code for the tutorial and then also make the same change in the readme.md file; the preprocessor will do that for you!

In order to run the pre-processor, simply invoke cargo run from the root directory (not the sub-tutorial directory) and it will rebuild all the markdown files that it knows about.

How to contribute

Comments
  • error: can't find crate for ...

    error: can't find crate for ...

    ~~I am getting errors in all four lines:~~

    extern crate piston;             // error: can't find crate for 'piston'
    extern crate graphics;           // error: can't find crate for 'graphics'
    extern crate sdl2_window;        // error: can't find crate for 'sdl2_window'
    extern crate opengl_graphics;    // error: can't find crate for 'opengl_graphics'
    

    * Look for the cargo build -v below for the actual problems. *

    opened by KingOfThePirates 28
  • Change window backend over to glutin_window.

    Change window backend over to glutin_window.

    With SDL2 some users have problems (see PistonDevelopers/opengl_graphics#134). GLFW didn't work on Ubuntu through error in Unity (see glfw/glfw#368). Fix there are, but users it will be available only in next Ubuntu release. Is there any reason not to do it?

    discussion 
    opened by Potpourri 11
  • Runtime Error: Shader version not supported

    Runtime Error: Shader version not supported

    I followed the instructions of the tutorial, installed glfw using homebrew (running Mac OSX 10.9.4). Looks like the error is raised here: https://github.com/PistonDevelopers/opengl_graphics/blob/master/src/gl_back_end.rs#L105

    Error output:

    $ ./target/game
    task '<main>' failed at 'compile_shader: ERROR: 0:2: '' :  version '330' is not supported
    ', src/gl_back_end.rs:105
    

    Any thoughts?

    opened by bakkdoor 7
  • Fix Spinning Square Build Status Badge

    Fix Spinning Square Build Status Badge

    The Spinning Square tutorial build status badge is currently broken.

    https://github.com/PistonDevelopers/Piston-Tutorials/blob/master/getting-started/readme.md#spinning-square-

    Perhaps it should be removed in favor of the one on the main README.md?

    opened by indiv0 6
  • Roguelike Tutorial using Piston

    Roguelike Tutorial using Piston

    A tutorial to create a Roguelike game similar to Pokemon Mystery Dungeon using the Piston framework. Currently a work in progress.

    Signed-off-by: Chetan Mistry [email protected]

    opened by cm16161 5
  • Getting Started: Compile failure in `deflate` dependency

    Getting Started: Compile failure in `deflate` dependency

    Hi,

    First thanks for the awesome tutorials. I am a Rust beginner so I'm sure this is just an issue with my setup. I am attempting the compile the Getting Started example and running into a compile failure in the deflate lib. Any help would be greatly appreciated.

    rustc version:

    rustc --version
    rustc 1.14.0 (e8a012324 2016-12-16)
    

    cargo version:

    cargo --version
    cargo 0.15.0-nightly (298a012 2016-12-20)
    

    rustup info:

    rustup show
    active toolchain
    ----------------
    
    stable-x86_64-apple-darwin (default)
    rustc 1.14.0 (e8a012324 2016-12-16)
    

    OS info:

    macOS Sierra
    10.12.6 (16G29)
    

    Error trying run cargo build with the example code Getting Started

    cargo build
       Compiling scopeguard v0.3.2
       Compiling byteorder v0.4.2
       Compiling arrayvec v0.3.23
       Compiling bitflags v0.9.1
       Compiling coco v0.1.1
       Compiling synom v0.11.3
       Compiling xml-rs v0.6.1
       Compiling stb_truetype v0.2.1
       Compiling piston2d-graphics v0.21.1
       Compiling rayon-core v1.2.1
       Compiling rusttype v0.2.1
       Compiling deflate v0.7.17
       Compiling rayon v0.8.2
    error[E0308]: mismatched types
      --> /Users/ryan.mulcahy/.cargo/registry/src/github.com-1ecc6299db9ec823/deflate-0.7.17/src/bitstream.rs:35:40
       |
    35 |                 $s.w.get_unchecked_mut(len..).copy_from_slice(&[$s.acc as u8,
       |                                        ^^^^^ expected usize, found struct `std::ops::RangeFrom`
    ...
    93 |             push!(self);
       |             ------------ in this macro invocation
       |
       = note: expected type `usize`
       = note:    found type `std::ops::RangeFrom<usize>`
    
    error: no method named `copy_from_slice` found for type `&mut u8` in the current scope
      --> /Users/ryan.mulcahy/.cargo/registry/src/github.com-1ecc6299db9ec823/deflate-0.7.17/src/bitstream.rs:35:47
       |
    35 |                 $s.w.get_unchecked_mut(len..).copy_from_slice(&[$s.acc as u8,
       |                                               ^^^^^^^^^^^^^^^
    ...
    93 |             push!(self);
       |             ------------ in this macro invocation
    
    error: aborting due to 2 previous errors
    
    opened by mulchy 5
  • Remove freetype dependancy

    Remove freetype dependancy

    I'm new to Rust/Piston, but I came across this post talking about switching from FreeType to rusttype: https://github.com/PistonDevelopers/conrod/issues/695

    Is is possible to do this yet for the tutorials? Getting FreeType installed correctly is challenging for beginners.

    opened by johnthagen 5
  • Example won't compile

    Example won't compile

    This is the error output I am getting

       Compiling getting-started-spinning-square v0.0.0 (file:///home/lefteris/w/rust_test)
    src/main.rs:29:13: 29:18 error: the trait `graphics::graphics::Graphics` is not implemented for the type `opengl_graphics::back_end::GlGraphics` [E0277]
    src/main.rs:29             clear(GREEN, gl);
                               ^~~~~
    src/main.rs:36:13: 36:22 error: the trait `graphics::graphics::Graphics` is not implemented for the type `opengl_graphics::back_end::GlGraphics` [E0277]
    src/main.rs:36             rectangle(RED, square, transform, gl);
                               ^~~~~~~~~
    error: aborting due to 2 previous errors
    Could not compile `getting-started-spinning-square`.
    

    I am running ArchLinux with rust rustc 1.0.0-dev (built 2015-05-17)

    Any ideas what's wrong?

    bug 
    opened by LefterisJP 5
  • Sudoku tutorial: multiple digits drawn in a cell of the grid

    Sudoku tutorial: multiple digits drawn in a cell of the grid

    Hi, in the Sudoku tutorial, when drawing a character from the keyboard weird things happen: Instead of writing different characters in different cells the graphics engine concatenates the different images of the characters taken from the glyphs and prints them all in every cell. This is what happens. Empty Grid with selected cell: image

    Type "1" on the keyboard: image

    Select another cell: image

    Type "3" on the keyboard: image

    Repeat: image

    And again: image

    Looks like there's a buffer somewhere not emptying? Does anybody have an idea of what it can be? The code is the same as in the tutorial. Appreciate any help, thanks.

    bug 
    opened by JimmyHypi 4
  • square is in the upper-right corner (retina)

    square is in the upper-right corner (retina)

    i copy/pasted from the example, and the square shows up in the corner, instead of the middle.

    can be "fixed" by changing

    c.transform.trans(x, y)
    

    to

    c.transform.trans(x * 0.5,y * 1.5)
    

    i'm on osx, with a retina display. my best guess is that the retina scaling is messing up the viewport.

    the lower left corner is (0,args.height), and the upper right is (args.width/2, args.height/2)

    bug 
    opened by hclarke 4
  • unresolved import: 'std::old_path'

    unresolved import: 'std::old_path'

    I don't know if this is an issue with piston, with the tutorial, or something I'm doing wrong, but when I try to run 'cargo build', I get the following error:

    \rustc-serialize-0.2.12\src\serialize.rs:17:5: 17:26 error: unresolved import 'std::old_path'. There is no 'old_path' in 'std' \rustc-serialize-0.2.12\src\serialize.rs:17: use std::old_path as path;

    This would seem to be an issue with the std library, but I only setup rust the other day, so I'd think I'm at the most recent version.

    As I said, I don't know if this is an issue with Piston, or with the std library not being completely stable yet, or just my own lack of knowledge in all things rust yet, but some help would be nice.

    opened by Plasticcaz 4
  • Unable to run the example code

    Unable to run the example code

    Every time I try to run the example code. The application runs for a bit then dies, I then get this error message:

    thread 'main' panicked at 'attempted to leave type \`platform::platform::x11::util::input::PointerState\` uninitialized, which is invalid
    

    Here is my Cargo.toml:

    [package]
    name = "game_of_life"
    version = "0.1.0"
    authors = ["Nathan Hare <[email protected]>"]
    edition = "2018"
    
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    
    [dependencies]
    piston = "0.52.0"
    piston2d-graphics = "0.39.0"
    pistoncore-glutin_window = "0.67.0"
    piston2d-opengl_graphics = "0.76.0"
    

    And main.rs:

    extern crate glutin_window;
    extern crate graphics;
    extern crate opengl_graphics;
    extern crate piston;
    
    use glutin_window::GlutinWindow as Window;
    use opengl_graphics::{GlGraphics, OpenGL};
    use piston::event_loop::{EventSettings, Events};
    use piston::input::{RenderArgs, RenderEvent, UpdateArgs, UpdateEvent};
    use piston::window::WindowSettings;
    
    pub struct App {
        gl: GlGraphics, // OpenGL drawing backend.
        rotation: f64,  // Rotation for the square.
    }
    
    impl App {
        fn render(&mut self, args: &RenderArgs) {
            use graphics::*;
    
            const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
            const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
    
            let square = rectangle::square(0.0, 0.0, 50.0);
            let rotation = self.rotation;
            let (x, y) = (args.window_size[0] / 2.0, args.window_size[1] / 2.0);
    
            self.gl.draw(args.viewport(), |c, gl| {
                // Clear the screen.
                clear(GREEN, gl);
    
                let transform = c
                    .transform
                    .trans(x, y)
                    .rot_rad(rotation)
                    .trans(-25.0, -25.0);
    
                // Draw a box rotating around the middle of the screen.
                rectangle(RED, square, transform, gl);
            });
        }
    
        fn update(&mut self, args: &UpdateArgs) {
            // Rotate 2 radians per second.
            self.rotation += 2.0 * args.dt;
        }
    }
    
    fn main() {
        // Change this to OpenGL::V2_1 if not working.
        let opengl = OpenGL::V3_2;
    
        // Create an Glutin window.
        let mut window: Window = WindowSettings::new("spinning-square", [200, 200])
            .graphics_api(opengl)
            .exit_on_esc(true)
            .build()
            .unwrap();
    
        // Create a new game and run it.
        let mut app = App {
            gl: GlGraphics::new(opengl),
            rotation: 0.0,
        };
    
        let mut events = Events::new(EventSettings::new());
        while let Some(e) = events.next(&mut window) {
            if let Some(args) = e.render_args() {
                app.render(&args);
            }
    
            if let Some(args) = e.update_args() {
                app.update(&args);
            }
        }
    }
    

    I am using:

    • Rust: rustc 1.48.0 (7eac88abb 2020-11-16)
    • OS: Ubuntu 20.04.1 LTS x86_64, kernel 5.4.0-58-generic
    • DE: KDE Plasma 5.18.5
    • Graphics Card: Nvidia GeForce GTX 1660 Super
    • Graphics Driver: Nvidia-driver- 450 (proprietary)
    opened by LaSpruca 1
  • Spinning square demo stutters on Windows 10

    Spinning square demo stutters on Windows 10

    Hi, thanks for your great demo. I recorded the spinning square using a high framerate video camera (I used my phone at 240fps) and noticed that there is a brief pause every 10 frames or so. At normal speeds this manifests itself as a slightly jerky rotation. This happens on both low and high DPI screens but it is more obvious on high DPI screens because the square is sharper. I have a decent graphics card and cpu. Has anyone else noticed this?

    discussion 
    opened by ninjasource 5
  • There is something goes wrong with if let Some(pos) = e.mouse_cursor_args()

    There is something goes wrong with if let Some(pos) = e.mouse_cursor_args()

    /// Handles events.
      pub fn event<E: GenericEvent>(&mut self, pos: [f64; 2], size: f64, e: &E) {
          use piston::input::{Button, MouseButton};
    
          if let Some(pos) = e.mouse_cursor_args() {
    ______________________________________________________________________________________________________________
              ///////// Did not run here,  SOMEBODY can help me? thank you.///////!!!!!!!!!!!
    ------------------------------------------------------------------------------------------------------------------
              self.cursor_pos = pos;
          }
    
          if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
              // Find coordinates relative to upper left corner.
              let x = self.cursor_pos[0] - pos[0];
              let y = self.cursor_pos[1] - pos[1];
              // Check that coordinates are inside board boundaries.
              if x >= 0.0 && x < size && y >= 0.0 && y < size {
                  // Compute the cell position.
                  let cell_x = (x / size * 9.0) as usize;
                  let cell_y = (y / size * 9.0) as usize;
                  self.selected_cell = Some([cell_x, cell_y]);
              }
          }
      }
    
    opened by ZacRenis 0
  • spinning square does not compile.

    spinning square does not compile.

    I get 'unable to get package from source error'

    error: unable to get packages from source

    Caused by: failed to parse manifest at ~/.cargo/registry/src/github.com-1ecc6299db9ec823/stb_truetype-0.2.5/Cargo.toml

    Caused by: editions are unstable

    Caused by: feature edition is required

    consider adding cargo-features = ["edition"] to the manifest

    opened by nilinswap 0
  • Glob uses make tutorials hard to understand.

    Glob uses make tutorials hard to understand.

    In the getting-started tutorial, glob imports are pervasive. While these are generally not the best practice (the modules maybe should have preludes to make this easier), they also make it difficult to figure out which library/module many types come from. For example, when writing the render function in the impl App block, It becomes necessary to use IDE tooling to figure out which module RenderArgs comes from. I recomend removing ::* in as many places as possible to make the tutorial easier to read.

    easy 
    opened by WebsterWing 0
Owner
PistonDevelopers
The Piston game engine organization for maintenance and research
PistonDevelopers
A no-frills Tetris implementation written in Rust with the Piston game engine, and Rodio for music.

rustris A no-frills Tetris implementation written in Rust with the Piston game engine, and Rodio for music. (C) 2020 Ben Cantrick. This code is distri

Ben Cantrick 17 Aug 18, 2022
A simple Minecraft written in Rust with the Piston game engine

hematite A simple Minecraft written in Rust with the Piston game engine How To Open a World This method is only for personal use. Never distribute cop

PistonDevelopers 1.7k Dec 22, 2022
Operating System development tutorials in Rust on the Raspberry Pi

Operating System development tutorials in Rust on the Raspberry Pi

Rust Embedded 10k Jan 9, 2023
This is the repository with the tutorials of Learning Rust series in @Leticia-maria Youtube channel

Rust Tutorials This repository contains the information of Learning Rust playlist in my youtube channel. Learning Rust(part. 1)! Installation on Ubunt

Letícia Maria Pequeno Madureira 10 May 24, 2022
Awesome books, tutorials, courses, and resources for the Tokio asynchronous runtime ecosystem. ⚡

Awesome Tokio Tokio is an asynchronous runtime for the Rust programming language. It provides the building blocks needed for writing network applicati

Marcus Cvjeticanin 59 Oct 27, 2023