Browse Source

lesson 1, working with sdl2 0.30

jmelesky 7 years ago
parent
commit
8bdd2d005e
2 changed files with 78 additions and 0 deletions
  1. 7 0
      lesson01/Cargo.toml
  2. 71 0
      lesson01/src/main.rs

+ 7 - 0
lesson01/Cargo.toml

@@ -0,0 +1,7 @@
+[package]
+name = "lesson01"
+version = "0.1.0"
+authors = ["jmelesky <code@phaedrusdeinus.org>"]
+
+[dependencies]
+sdl2 = "0.30.0"

+ 71 - 0
lesson01/src/main.rs

@@ -0,0 +1,71 @@
+extern crate sdl2;
+
+use sdl2::pixels::Color;
+use std::time::Duration;
+use std::thread::sleep;
+
+
+
+// using a different window size than lazyfoo, due to high-density screen
+const WIDTH:u32  = 1280;
+const HEIGHT:u32 =  960;
+
+
+
+fn main() {
+    // sdl2 functions return an SdlResult: Ok(result) | Err(error)
+
+    // The "SDL_Init" process is less straightforward, but also less
+    // mystical, in rust. We need to grab a context, then grab the
+    // video subsystem (which initializes it, and serves as an anchor
+    // for future calls).
+    let context = match sdl2::init() {
+        Ok(context) => context,
+        Err(err)    => panic!("Could not initialize SDL2. Error: {}", err),
+    };
+
+    let video = match context.video() {
+        Ok(video) => video,
+        Err(err)  => panic!("Could not gain access to the SDL2 video subsystem. Error: {}", err),
+    };
+
+    // Using the subsystem, create a window
+    //
+    // position is not passed through the constructor, but modifies the result
+    // not sure why we need the opengl bit
+    // everything that does stuff seems to need to be .build()'ed
+    let window = match video.window("SDL Tutorial, lesson 01", WIDTH, HEIGHT)
+        .position_centered()
+        .opengl()
+        .build() {
+            Ok(window) => window,
+            Err(err)   => panic!("Could not create window. Error: {}", err),
+        };
+
+    // sdl2 0.30 removed the Renderer and replaced it with a Canvas and a
+    // TextureCreator. Going to try the Canvas first.
+
+    // Request the Canvas from the window.
+    let mut canvas = match window.into_canvas()
+        .build() {
+            Ok(canvas) => canvas,
+            Err(err)   => panic!("Could not create renderer from window. Error: {}", err),
+        };
+
+    // Okay, we have a window on the screen, and now we can use the canvas
+    // to make stuff happen in it.
+
+    // These are fairly straightforward draw commands.
+    // The present() is needed to make the changes visible.
+    canvas.set_draw_color(Color::RGB(255,255,128));
+    canvas.clear();
+    canvas.present();
+
+
+    // This works! But it disappears immediately (no event loop, etc)
+    // Hack some pause before it goes
+
+    sleep(Duration::new(2,0));
+
+
+}