comparison examples/menu.rs @ 746:0ebf6467e4ff

examples: Add a menu example.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Sat, 18 Jan 2020 19:19:51 +0100
parents
children 8a022334a4c4
comparison
equal deleted inserted replaced
745:90e907859bae 746:0ebf6467e4ff
1 use luminance::blending::{Equation, Factor};
2 use luminance::context::GraphicsContext;
3 use luminance::pipeline::{BoundTexture, PipelineState};
4 use luminance::pixel::NormUnsigned;
5 use luminance::render_state::RenderState;
6 use luminance::shader::program::{Program, Uniform};
7 use luminance::tess::{Mode, TessBuilder};
8 use luminance::texture::{Dim2, Flat};
9 use luminance_derive::{Semantics, Vertex, UniformInterface};
10 use luminance_glfw::{Action, Key, WindowEvent, GlfwSurface, Surface, WindowDim, WindowOpt};
11 use touhou::th06::pbg3;
12 use touhou::th06::anm0::Anm0;
13 use touhou::th06::anm0_vm::{AnmRunner, Sprite, Vertex as FakeVertex};
14 use touhou::util::math::{perspective, setup_camera, ortho_2d};
15 use touhou::util::prng::Prng;
16 use std::cell::RefCell;
17 use std::rc::Rc;
18 use std::env;
19 use std::path::Path;
20
21 #[path = "common.rs"]
22 mod common;
23 use common::LoadedTexture;
24
25 const VS: &str = r#"
26 in ivec3 in_position;
27 in vec2 in_texcoord;
28 in vec4 in_color;
29
30 uniform mat4 mvp;
31
32 out vec2 texcoord;
33 out vec4 color;
34
35 void main()
36 {
37 gl_Position = mvp * vec4(vec3(in_position), 1.0);
38 texcoord = vec2(in_texcoord);
39
40 // It’s already normalized from the u8 being passed.
41 color = in_color;
42 }
43 "#;
44
45 const FS: &str = r#"
46 in vec2 texcoord;
47 in vec4 color;
48
49 uniform sampler2D color_map;
50
51 out vec4 frag_color;
52
53 void main()
54 {
55 frag_color = texture(color_map, texcoord) * color;
56 }
57 "#;
58
59 #[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)]
60 pub enum Semantics {
61 #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")]
62 Position,
63
64 #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")]
65 Texcoord,
66
67 #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")]
68 Color,
69 }
70
71 #[repr(C)]
72 #[derive(Clone, Copy, Debug, PartialEq, Vertex)]
73 #[vertex(sem = "Semantics")]
74 struct Vertex {
75 pos: VertexPosition,
76 uv: VertexTexcoord,
77 #[vertex(normalized = "true")]
78 rgba: VertexColor,
79 }
80
81 #[derive(UniformInterface)]
82 struct ShaderInterface {
83 // the 'static lifetime acts as “anything” here
84 color_map: Uniform<&'static BoundTexture<'static, Flat, Dim2, NormUnsigned>>,
85
86 #[uniform(name = "mvp")]
87 mvp: Uniform<[[f32; 4]; 4]>,
88 }
89
90 const DEFAULT_VERTICES: [Vertex; 4] = [
91 Vertex::new(VertexPosition::new([0, 0, 0]), VertexTexcoord::new([0., 0.]), VertexColor::new([255, 255, 255, 255])),
92 Vertex::new(VertexPosition::new([640, 0, 0]), VertexTexcoord::new([1., 0.]), VertexColor::new([255, 255, 255, 255])),
93 Vertex::new(VertexPosition::new([640, 480, 0]), VertexTexcoord::new([1., 1.]), VertexColor::new([255, 255, 255, 255])),
94 Vertex::new(VertexPosition::new([0, 480, 0]), VertexTexcoord::new([0., 1.]), VertexColor::new([255, 255, 255, 255])),
95 ];
96
97 fn main() {
98 // Parse arguments.
99 let args: Vec<_> = env::args().collect();
100 if args.len() != 2 {
101 eprintln!("Usage: {} <unarchived directory>", args[0]);
102 return;
103 }
104 let directory = Path::new(&args[1]);
105
106 let in_dat = directory.join("IN.DAT");
107 // Since GLFW can be slow to create its window, let’s decode the splash screen in another
108 // thread in the meantime.
109 let jpeg_thread = std::thread::spawn(|| {
110 let mut in_pbg3 = pbg3::from_path_buffered(in_dat).expect("IN.DAT present");
111 let jpeg = in_pbg3.get_file("th06logo.jpg", true).expect("th06logo.jpg in IN.DAT");
112 let image = common::load_from_data(&jpeg).expect("th06logo.jpg decodable");
113 image
114 });
115
116 let mut surface = GlfwSurface::new(WindowDim::Windowed(640, 480), "Touhou", WindowOpt::default()).expect("GLFW window");
117
118 let image = jpeg_thread.join().expect("image loading");
119 let tex = common::upload_texture_from_rgb_image(&mut surface, image).expect("image loading");
120
121 // set the uniform interface to our type so that we can read textures from the shader
122 let program =
123 Program::<Semantics, (), ShaderInterface>::from_strings(None, VS, None, FS).expect("program creation").ignore_warnings();
124
125 let mut tess = TessBuilder::new(&mut surface)
126 .add_vertices(DEFAULT_VERTICES)
127 .set_mode(Mode::TriangleFan)
128 .build()
129 .unwrap();
130
131 let mut back_buffer = surface.back_buffer().unwrap();
132 let mut resize = false;
133
134 'app: loop {
135 for event in surface.poll_events() {
136 match event {
137 WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app,
138
139 WindowEvent::FramebufferSize(..) => {
140 resize = true;
141 }
142
143 _ => (),
144 }
145 }
146
147 if resize {
148 back_buffer = surface.back_buffer().unwrap();
149 resize = false;
150 }
151
152 // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU
153 // and use it in the shader
154 surface
155 .pipeline_builder()
156 .pipeline(&back_buffer, &PipelineState::default(), |pipeline, mut shd_gate| {
157 // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader
158 let bound_tex = match &tex {
159 LoadedTexture::Rgb(tex) => pipeline.bind_texture(tex),
160 LoadedTexture::Rgba(tex) => pipeline.bind_texture(tex),
161 };
162
163 shd_gate.shade(&program, |iface, mut rdr_gate| {
164 // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU
165 // to use the texture passed as argument (no allocation or copy is performed)
166 iface.color_map.update(&bound_tex);
167 let mvp = ortho_2d(0., 640., 480., 0.);
168 // TODO: check how to pass by reference.
169 iface.mvp.update(*mvp.borrow_inner());
170
171 let render_state = RenderState::default()
172 .set_blending((Equation::Additive, Factor::SrcAlpha, Factor::SrcAlphaComplement));
173
174 rdr_gate.render(&render_state, |mut tess_gate| {
175 tess_gate.render(&tess);
176 });
177 });
178 });
179
180 surface.swap_buffers();
181 }
182 }