changeset 658:3a9d82a02c88

Add a contructor for enemy, and a new example.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Sat, 10 Aug 2019 12:48:01 +0200
parents ff7b6355cdf1
children 53786d834444
files examples/eclrenderer.rs src/th06/anm0_vm.rs src/th06/enemy.rs
diffstat 3 files changed, 363 insertions(+), 16 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/examples/eclrenderer.rs
@@ -0,0 +1,250 @@
+use image::GenericImageView;
+use luminance::context::GraphicsContext;
+use luminance::framebuffer::Framebuffer;
+use luminance::pipeline::BoundTexture;
+use luminance::pixel::{NormRGB8UI, Floating};
+use luminance::render_state::RenderState;
+use luminance::shader::program::{Program, Uniform};
+use luminance::tess::{Mode, TessBuilder};
+use luminance::texture::{Dim2, Flat, Sampler, Texture, GenMipmaps};
+use luminance_derive::{Semantics, Vertex, UniformInterface};
+use luminance_glfw::event::{Action, Key, WindowEvent};
+use luminance_glfw::surface::{GlfwSurface, Surface, WindowDim, WindowOpt};
+use touhou::th06::anm0::Anm0;
+use touhou::th06::anm0_vm::{Sprite, Vertex as FakeVertex};
+use touhou::th06::ecl::Ecl;
+use touhou::th06::enemy::{Enemy, Game, Position};
+use touhou::util::math::{perspective, setup_camera};
+use touhou::util::prng::Prng;
+use std::cell::RefCell;
+use std::fs::File;
+use std::io::{BufReader, Read};
+use std::rc::Rc;
+use std::env;
+use std::path::Path;
+
+const VS: &str = r#"
+in ivec3 in_position;
+in vec2 in_texcoord;
+in uvec4 in_color;
+
+uniform mat4 mvp;
+
+out vec2 texcoord;
+out vec4 color;
+
+void main()
+{
+    gl_Position = mvp * vec4(vec3(in_position), 1.0);
+    texcoord = vec2(in_texcoord);
+
+    // Normalized from the u8 being passed.
+    color = vec4(in_color) / 255.;
+}
+"#;
+
+const FS: &str = r#"
+in vec2 texcoord;
+in vec4 color;
+
+uniform sampler2D color_map;
+
+out vec4 frag_color;
+
+void main()
+{
+    frag_color = texture(color_map, texcoord) * color;
+}
+"#;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)]
+pub enum Semantics {
+    #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")]
+    Position,
+
+    #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")]
+    Texcoord,
+
+    #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")]
+    Color,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Vertex)]
+#[vertex(sem = "Semantics")]
+struct Vertex {
+    pos: VertexPosition,
+    uv: VertexTexcoord,
+    rgba: VertexColor,
+}
+
+#[derive(UniformInterface)]
+struct ShaderInterface {
+    // the 'static lifetime acts as “anything” here
+    color_map: Uniform<&'static BoundTexture<'static, Flat, Dim2, Floating>>,
+
+    #[uniform(name = "mvp")]
+    mvp: Uniform<[[f32; 4]; 4]>,
+}
+
+fn main() {
+    // Parse arguments.
+    let args: Vec<_> = env::args().collect();
+    if args.len() != 5 {
+        eprintln!("Usage: {} <ECL file> <sub number> <ANM file> <PNG file>", args[0]);
+        return;
+    }
+    let ecl_filename = &args[1];
+    let sub = args[2].parse().expect("number");
+    let anm_filename = &args[3];
+    let png_filename = &args[4];
+
+    // Open the ECL file.
+    let file = File::open(ecl_filename).unwrap();
+    let mut file = BufReader::new(file);
+    let mut buf = vec![];
+    file.read_to_end(&mut buf).unwrap();
+    let (_, ecl) = Ecl::from_slice(&buf).unwrap();
+
+    // Open the ANM file.
+    let file = File::open(anm_filename).unwrap();
+    let mut file = BufReader::new(file);
+    let mut buf = vec![];
+    file.read_to_end(&mut buf).unwrap();
+    let anm0 = Anm0::from_slice(&buf).unwrap();
+    let anm0 = Rc::new(RefCell::new(anm0));
+
+    if ecl.subs.len() < sub {
+        eprintln!("This ecl doesn’t contain a sub named {}.", sub);
+        return;
+    }
+
+    // TODO: seed this PRNG with a valid seed.
+    let prng = Rc::new(RefCell::new(Prng::new(0)));
+
+    // Create the Game god object.
+    let game = Game::new(prng);
+    let game = Rc::new(RefCell::new(game));
+
+    // And the enemy object.
+    let mut enemy = Enemy::new(Position::new(0., 0.), 500, 0, 640, Rc::downgrade(&anm0), Rc::downgrade(&game));
+    enemy.set_anim(0);
+
+    assert_eq!(std::mem::size_of::<Vertex>(), std::mem::size_of::<FakeVertex>());
+    let vertices: [Vertex; 4] = unsafe { std::mem::uninitialized() };
+
+    let mut surface = GlfwSurface::new(WindowDim::Windowed(384, 448), "Touhou", WindowOpt::default()).unwrap();
+
+    // Open the image atlas matching this ANM.
+    let tex = load_from_disk(&mut surface, Path::new(png_filename)).expect("texture loading");
+
+    // set the uniform interface to our type so that we can read textures from the shader
+    let (program, _) =
+        Program::<Semantics, (), ShaderInterface>::from_strings(None, VS, None, FS).expect("program creation");
+
+    let mut tess = TessBuilder::new(&mut surface)
+        .add_vertices(vertices)
+        .set_mode(Mode::TriangleFan)
+        .build()
+        .unwrap();
+
+    let mut back_buffer = Framebuffer::back_buffer(surface.size());
+
+    let mut frame = 0;
+    'app: loop {
+        for event in surface.poll_events() {
+            match event {
+                WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app,
+
+                WindowEvent::FramebufferSize(width, height) => {
+                    back_buffer = Framebuffer::back_buffer([width as u32, height as u32]);
+                }
+
+                _ => (),
+            }
+        }
+
+        if frame == 60 {
+            break;
+        }
+        frame += 1;
+
+        {
+            let mut slice = tess
+                .as_slice_mut()
+                .unwrap();
+
+            let mut game = game.borrow_mut();
+            game.run_frame();
+            let sprites = game.get_sprites();
+            fill_vertices_ptr(sprites, slice.as_mut_ptr());
+        }
+
+        // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU
+        // and use it in the shader
+        surface
+            .pipeline_builder()
+            .pipeline(&back_buffer, [0., 0., 0., 0.], |pipeline, shd_gate| {
+                // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader
+                let bound_tex = pipeline.bind_texture(&tex);
+
+                shd_gate.shade(&program, |rdr_gate, iface| {
+                    // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU
+                    // to use the texture passed as argument (no allocation or copy is performed)
+                    iface.color_map.update(&bound_tex);
+                    //let mvp = ortho_2d(0., 384., 448., 0.);
+                    let proj = perspective(0.5235987755982988, 384. / 448., 101010101./2010101., 101010101./10101.);
+                    let view = setup_camera(0., 0., 1.);
+                    let mvp = view * proj;
+                    //println!("{:#?}", mvp);
+                    // TODO: check how to pass by reference.
+                    iface.mvp.update(*mvp.borrow_inner());
+
+                    rdr_gate.render(RenderState::default(), |tess_gate| {
+                        // render the tessellation to the surface the regular way and let the vertex shader’s
+                        // magic do the rest!
+                        tess_gate.render(&mut surface, (&tess).into());
+                    });
+                });
+            });
+
+        surface.swap_buffers();
+    }
+}
+
+fn fill_vertices_ptr(sprites: Vec<Rc<RefCell<Sprite>>>, vertices: *mut Vertex) {
+    let mut fake_vertices = unsafe { std::mem::transmute::<*mut Vertex, &mut [FakeVertex; 4]>(vertices) };
+    for sprite in sprites {
+        let sprite = sprite.borrow();
+        sprite.fill_vertices(&mut fake_vertices);
+    }
+}
+
+fn load_from_disk(surface: &mut GlfwSurface, path: &Path) -> Option<Texture<Flat, Dim2, NormRGB8UI>> {
+    // load the texture into memory as a whole bloc (i.e. no streaming)
+    match image::open(&path) {
+        Ok(img) => {
+            let (width, height) = img.dimensions();
+            let texels = img
+                .pixels()
+                .map(|(x, y, rgb)| (rgb[0], rgb[1], rgb[2]))
+                .collect::<Vec<_>>();
+
+            // create the luminance texture; the third argument is the number of mipmaps we want (leave it
+            // to 0 for now) and the latest is a the sampler to use when sampling the texels in the
+            // shader (we’ll just use the default one)
+            let tex =
+                Texture::new(surface, [width, height], 0, &Sampler::default()).expect("luminance texture creation");
+
+            // the first argument disables mipmap generation (we don’t care so far)
+            tex.upload(GenMipmaps::No, &texels);
+
+            Some(tex)
+        }
+
+        Err(e) => {
+            eprintln!("cannot open image {}: {}", path.display(), e);
+            None
+        }
+    }
+}
--- a/src/th06/anm0_vm.rs
+++ b/src/th06/anm0_vm.rs
@@ -252,6 +252,11 @@ impl AnmRunner {
         runner
     }
 
+    /// Get a Rc from the inner Sprite.
+    pub fn get_sprite(&self) -> Rc<RefCell<Sprite>> {
+        self.sprite.clone()
+    }
+
     /// Trigger an interrupt.
     pub fn interrupt(&mut self, interrupt: i32) -> bool {
         let mut new_ip = self.script.interrupts.get(&interrupt);
--- a/src/th06/enemy.rs
+++ b/src/th06/enemy.rs
@@ -8,25 +8,29 @@ use std::cell::RefCell;
 use std::collections::HashMap;
 use std::rc::{Rc, Weak};
 
-#[derive(Debug, Clone, Copy)]
-struct Position {
+/// The 2D position of an object in the game.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Position {
     x: f32,
     y: f32,
 }
 
-#[derive(Debug, Clone, Copy)]
-struct Offset {
+/// An offset which can be added to a Position.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Offset {
     dx: f32,
     dy: f32,
 }
 
 impl Position {
+    /// Create said position.
     pub fn new(x: f32, y: f32) -> Position {
         Position { x, y }
     }
 }
 
 impl Offset {
+    /// Create said offset.
     pub fn new(dx: f32, dy: f32) -> Offset {
         Offset { dx, dy }
     }
@@ -48,29 +52,66 @@ struct Callback;
 #[derive(Debug, Clone)]
 struct Laser;
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Default)]
 struct Process;
 
-struct Game {
-    enemies: Vec<Enemy>,
+/// God struct of our game.
+pub struct Game {
+    enemies: Vec<Rc<RefCell<Enemy>>>,
+    anmrunners: Vec<Rc<RefCell<AnmRunner>>>,
     prng: Rc<RefCell<Prng>>,
 }
 
+impl Game {
+    /// Create said god struct.
+    pub fn new(prng: Rc<RefCell<Prng>>) -> Game {
+        Game {
+            enemies: Vec::new(),
+            anmrunners: Vec::new(),
+            prng,
+        }
+    }
+
+    /// Run the simulation for a single frame.
+    pub fn run_frame(&mut self) {
+        /*
+        for eclrunner in self.eclrunners {
+            eclrunner.run_frame();
+        }
+        */
+
+        for anmrunner in self.anmrunners.iter() {
+            let mut anmrunner = anmrunner.borrow_mut();
+            anmrunner.run_frame();
+        }
+    }
+
+    /// Returns a list of all sprites currently being displayed on screen.
+    pub fn get_sprites(&self) -> Vec<Rc<RefCell<Sprite>>> {
+        let mut sprites = vec![];
+        for anmrunner in self.anmrunners.iter() {
+            let anmrunner = anmrunner.borrow();
+            let sprite = anmrunner.get_sprite();
+            sprites.push(sprite);
+        }
+        sprites
+    }
+}
+
 /// Common to all elements in game.
 struct Element {
     pos: Position,
     removed: bool,
-    sprite: Weak<RefCell<Sprite>>,
     anmrunner: AnmRunner,
 }
 
 /// The enemy struct, containing everything pertaining to an enemy.
+#[derive(Default)]
 pub struct Enemy {
     // Common to all elements in game.
     pos: Position,
     removed: bool,
-    sprite: Rc<RefCell<Sprite>>,
-    anmrunner: Rc<RefCell<AnmRunner>>,
+    anmrunner: Weak<RefCell<AnmRunner>>,
 
     // Specific to enemy.
     // Floats.
@@ -88,8 +129,8 @@ pub struct Enemy {
     life: u32,
     death_flags: u32,
     current_laser_id: u32,
-    low_life_trigger: u32,
-    timeout: u32,
+    low_life_trigger: Option<u32>,
+    timeout: Option<u32>,
     remaining_lives: u32,
     bullet_launch_interval: u32,
     bullet_launch_timer: u32,
@@ -125,6 +166,7 @@ pub struct Enemy {
     laser_by_id: HashMap<u32, Laser>,
 
     // Options.
+    // TODO: actually a 8 element array.
     options: Vec<Element>,
 
     // Interpolators.
@@ -136,15 +178,65 @@ pub struct Enemy {
     process: Rc<RefCell<Process>>,
     game: Weak<RefCell<Game>>,
     prng: Weak<RefCell<Prng>>,
-    hitbox_half_size: (f32, f32),
+    hitbox_half_size: [f32; 2],
 }
 
 impl Enemy {
+    /// Create a new enemy.
+    pub fn new(pos: Position, life: i32, bonus_dropped: u32, die_score: u32, anm0: Weak<RefCell<Anm0>>, game: Weak<RefCell<Game>>) -> Enemy {
+        Enemy {
+            pos,
+            anm0,
+            game,
+            visible: true,
+            bonus_dropped,
+            die_score,
+            life: if life < 0 { 1 } else { life as u32 },
+            touchable: true,
+            collidable: true,
+            damageable: true,
+            difficulty_coeffs: (-0.5, 0.5, 0, 0, 0, 0),
+            ..Default::default()
+        }
+    }
+
     /// Sets the animation to the one indexed by index in the current anm0.
     pub fn set_anim(&mut self, index: u8) {
-        self.sprite = Rc::new(RefCell::new(Sprite::new()));
         let anm0 = self.anm0.upgrade().unwrap();
-        let anmrunner = AnmRunner::new(&*anm0.borrow(), index, self.sprite.clone(), self.prng.clone(), 0);
-        self.anmrunner = Rc::new(RefCell::new(anmrunner));
+        let game = self.game.upgrade().unwrap();
+        let sprite = Rc::new(RefCell::new(Sprite::new()));
+        let anmrunner = AnmRunner::new(&*anm0.borrow(), index, sprite, self.prng.clone(), 0);
+        let anmrunner = Rc::new(RefCell::new(anmrunner));
+        self.anmrunner = Rc::downgrade(&anmrunner);
+        (*game.borrow_mut()).anmrunners.push(anmrunner);
+    }
+
+    /// Sets the hitbox around the enemy.
+    pub fn set_hitbox(&mut self, width: f32, height: f32) {
+        self.hitbox_half_size = [width, height];
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::io::{self, Read};
+    use std::fs::File;
+
+    #[test]
+    fn enemy() {
+        let file = File::open("EoSD/ST/stg1enm.anm").unwrap();
+        let mut file = io::BufReader::new(file);
+        let mut buf = vec![];
+        file.read_to_end(&mut buf).unwrap();
+        let anm0 = Anm0::from_slice(&buf).unwrap();
+        let anm0 = Rc::new(RefCell::new(anm0));
+        let prng = Rc::new(RefCell::new(Prng::new(0)));
+        let game = Game::new(prng);
+        let game = Rc::new(RefCell::new(game));
+        let mut enemy = Enemy::new(Position::new(0., 0.), 500, 0, 640, Rc::downgrade(&anm0), Rc::downgrade(&game));
+        assert!(enemy.anmrunner.upgrade().is_none());
+        enemy.set_anim(0);
+        assert!(enemy.anmrunner.upgrade().is_some());
+    }
+}