pub struct InputMap<F>{
pub binds: HashMap<InputCode, (f32, Vec<F>)>,
pub mouse_pos: Vec2,
pub recently_pressed: Option<InputCode>,
pub text_typed: Option<String>,
pub mouse_scale: f32,
pub scroll_scale: f32,
pub press_sensitivity: f32,
/* private fields */
}
Expand description
A struct that handles all your input needs once you’ve hooked it up to winit and gilrs.
use gilrs::Gilrs;
use winit::{event::*, application::*, window::*, event_loop::*};
use winit_input_map::*;
struct App {
window: Option<Window>,
input: InputMap<()>,
gilrs: Gilrs
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
self.input.update_with_window_event(&event);
if let WindowEvent::CloseRequested = &event { event_loop.exit() }
}
fn device_event(&mut self, _: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
self.input.update_with_device_event(id, &event);
}
fn about_to_wait(&mut self, _: &ActiveEventLoop) {
self.input.update_with_gilrs(&mut self.gilrs);
// put your code here
self.input.init();
}
}
Fields§
§binds: HashMap<InputCode, (f32, Vec<F>)>
Stores what each input code is bound to and its previous press value
mouse_pos: Vec2
The mouse position
recently_pressed: Option<InputCode>
The last input event, even if it isn’t in the binds. Useful for handling rebinding
text_typed: Option<String>
The text typed this loop
mouse_scale: f32
Since most values are from 0-1 reducing the mouse sensitivity will result in better consistancy
scroll_scale: f32
Since most values are from 0-1 reducing the scroll sensitivity will result in better consistancy
press_sensitivity: f32
The minimum value something has to be at to count as being pressed. Values over 1 will result in regular buttons being unusable
Implementations§
Source§impl<F> InputMap<F>
impl<F> InputMap<F>
Sourcepub fn new(binds: &[(F, Vec<InputCode>)]) -> InputMap<F>
pub fn new(binds: &[(F, Vec<InputCode>)]) -> InputMap<F>
Create new input system. It’s recommended to use the input_map!
macro to reduce boilerplate
and increase readability.
use Action::*;
use winit_input_map::*;
use winit::keyboard::KeyCode;
#[derive(Hash, PartialEq, Eq, Clone, Copy)]
enum Action {
Forward,
Back,
Pos,
Neg
}
//doesnt have to be the same ordered as the enum.
let input = InputMap::new(&[
(Forward, vec![KeyCode::KeyW.into()]),
(Pos, vec![KeyCode::KeyA.into()]),
(Back, vec![KeyCode::KeyS.into()]),
(Neg, vec![KeyCode::KeyD.into()])
]);
Sourcepub fn empty() -> InputMap<()>
pub fn empty() -> InputMap<()>
Use if you dont want to have any actions and binds. Will still have access to everything else.
Sourcepub fn mut_bind(&mut self, input_code: InputCode) -> &mut Vec<F>
pub fn mut_bind(&mut self, input_code: InputCode) -> &mut Vec<F>
Gets a mutable vector of what actions input_code is bound to
Sourcepub fn update_with_winit(&mut self, event: &Event<()>)
👎Deprecated: use update_with_window_event
and update_with_device_event
pub fn update_with_winit(&mut self, event: &Event<()>)
update_with_window_event
and update_with_device_event
Updates the input map using a winit event. Make sure to call input.init()
when your done with
the input this loop.
use winit::{event::*, window::Window, event_loop::EventLoop};
use winit_input_map::InputMap;
let mut event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(winit::event_loop::ControlFlow::Poll);
let _window = Window::new(&event_loop).unwrap();
let mut input = input_map!();
event_loop.run(|event, target|{
input.update_with_winit(&event);
match &event{
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => target.exit(),
Event::AboutToWait => input.init(),
_ => ()
}
});
pub fn update_with_device_event(&mut self, id: DeviceId, event: &DeviceEvent)
pub fn update_with_window_event(&mut self, event: &WindowEvent)
pub fn update_with_gilrs(&mut self, gilrs: &mut Gilrs)
Sourcepub fn pressing(&self, action: F) -> bool
pub fn pressing(&self, action: F) -> bool
Checks if action is being pressed currently. same as input.action_val(action) >= input.press_sensitivity
Sourcepub fn action_val(&self, action: F) -> f32
pub fn action_val(&self, action: F) -> f32
Checks how wheremuch action is being pressed. May be higher than 1 in the case of scroll wheels and mouse movement.
Sourcepub fn pressed(&self, action: F) -> bool
pub fn pressed(&self, action: F) -> bool
checks if action was just pressed
Examples found in repository?
9fn main() {
10 use Action::*;
11 let event_loop = EventLoop::new().unwrap();
12 event_loop.set_control_flow(ControlFlow::Poll);
13
14 let input = { use base_input_codes::*; input_map!(
15 (Jump, Space, GamepadInput::South),
16 (Exit, Escape, GamepadInput::Start),
17 (Left, ArrowLeft, KeyA, LeftStickLeft ),
18 (Right, ArrowRight, KeyD, LeftStickRight),
19 (Forward, ArrowUp, KeyW, LeftStickUp ),
20 (Back, ArrowDown, KeyS, LeftStickDown ),
21 (LookRight, MouseMoveRight, RightStickRight),
22 (LookLeft, MouseMoveLeft, RightStickLeft ),
23 (LookUp, MouseMoveUp, RightStickUp ),
24 (LookDown, MouseMoveDown, RightStickDown )
25 )};
26
27 struct Graphics {
28 program: Program,
29 indices: IndexBuffer<u16>,
30 vertices: VertexBuffer<Vertex>,
31 normals: VertexBuffer<Normal>
32 }
33 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::new(RefCell::new(None));
34 let graphics_setup = graphics.clone();
35
36 let draw_parameters = DrawParameters {
37 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
38 ..params::alias_3d()
39 };
40
41 let mut pos = vec3(0.0, 0.0, -30.0);
42 let mut rot = vec2(0.0, 0.0);
43 let mut gravity = 0.0;
44
45 let mut frame_start = Instant::now();
46
47 thin_engine::builder(input).with_setup(|display, window, _| {
48 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
49 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
50 window.set_cursor_visible(false);
51 window.set_title("Walk Test");
52
53 let (indices, vertices, normals) = mesh!(
54 display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
55 );
56 let program = Program::from_source(
57 display, shaders::VERTEX,
58 "#version 140
59 out vec4 colour;
60 in vec3 v_normal;
61 uniform vec3 light;
62 const vec3 albedo = vec3(0.1, 1.0, 0.3);
63 void main(){
64 float light_level = dot(light, v_normal);
65 colour = vec4(albedo * light_level, 1.0);
66 }", None,
67 ).unwrap();
68 graphics_setup.replace(Some(Graphics { program, indices, vertices, normals }));
69 }).with_update(|input, display, _, target, _| {
70 let graphics = graphics.borrow();
71 let Graphics { vertices, indices, normals, program } = graphics.as_ref().unwrap();
72 let delta_time = frame_start.elapsed().as_secs_f32();
73 frame_start = Instant::now();
74
75 let mut frame = display.draw();
76 let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);
77
78 //handle gravity and jump
79 gravity += delta_time * 9.5;
80 if input.pressed(Jump) { gravity = -10.0 }
81
82 //set camera rotation
83 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
84 rot += look_move.scale(delta_time * 20.0);
85 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
86 let rx = Quat::from_y_rot(rot.x);
87 let ry = Quat::from_x_rot(rot.y);
88 let rot = rx * ry;
89
90 //move player based on view and gravity
91 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
92 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
93 pos += move_dir.transform(&Mat3::from_rot(rx));
94 pos.y = (pos.y - gravity * delta_time).max(0.0);
95
96 if input.pressed(Exit) { target.exit() }
97
98 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
99 //draw teapot
100 frame.draw(
101 (vertices, normals), indices,
102 program, &uniform! {
103 view: view,
104 model: Mat4::from_scale(Vec3::splat(0.1)),
105 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
106 light: vec3(1.0, -0.9, -1.0).normalise()
107 },
108 &draw_parameters,
109 ).unwrap();
110
111 frame.finish().unwrap();
112 }).build(event_loop).unwrap();
113}
More examples
13fn main() {
14 use Action::*;
15 let event_loop = EventLoop::new().unwrap();
16 event_loop.set_control_flow(ControlFlow::Poll);
17
18 let mut colour = ResizableTexture2d::default();
19 let mut depth = ResizableDepthTexture2d::default();
20
21 let input = { use base_input_codes::*; input_map!(
22 (Left, ArrowLeft, KeyA, LeftStickLeft ),
23 (Right, ArrowRight, KeyD, LeftStickRight),
24 (Forward, ArrowUp, KeyW, LeftStickUp ),
25 (Back, ArrowDown, KeyS, LeftStickDown ),
26 (LookRight, MouseMoveRight, RightStickRight),
27 (LookLeft, MouseMoveLeft, RightStickLeft ),
28 (LookUp, MouseMoveUp, RightStickUp ),
29 (LookDown, MouseMoveDown, RightStickDown ),
30 (FXAA, KeyF, GamepadInput::North)
31 ) };
32 struct Graphics {
33 screen_indices: IndexBuffer<u32>,
34 screen_vertices: VertexBuffer<Vertex>,
35 screen_uvs: VertexBuffer<TextureCoords>,
36
37 teapot_indices: IndexBuffer<u16>,
38 teapot_vertices: VertexBuffer<Vertex>,
39 teapot_uvs: VertexBuffer<TextureCoords>,
40 teapot_normals: VertexBuffer<Normal>,
41
42 fxaa: Program, normal: Program, program: Program
43 }
44 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::default();
45 let graphics_setup = graphics.clone();
46
47 let draw_parameters = DrawParameters {
48 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
49 ..params::alias_3d()
50 };
51 let mut fxaa_on = true;
52
53 let mut pos = vec3(0.0, 0.0, -30.0);
54 let mut rot = vec2(0.0, 0.0);
55
56 let mut frame_start = Instant::now();
57
58 thin_engine::builder(input).with_setup(|display, window, _| {
59 window.set_title("FXAA Test");
60 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
61 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
62 window.set_cursor_visible(false);
63
64 let (screen_indices, screen_vertices, screen_uvs) = mesh!(
65 display, &screen::INDICES, &screen::VERTICES, &screen::UVS
66 );
67 let (teapot_indices, teapot_vertices, teapot_uvs, teapot_normals) = mesh!(
68 display, &teapot::INDICES, &teapot::VERTICES, &[] as &[TextureCoords; 0], &teapot::NORMALS
69 );
70
71 let program = Program::from_source(
72 display, shaders::VERTEX,
73 "#version 140
74 out vec4 colour;
75 in vec3 v_normal;
76 uniform vec3 light;
77 uniform mat4 camera;
78 uniform vec3 ambient;
79 uniform vec3 albedo;
80 uniform float shine;
81 void main() {
82 vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
83 vec3 half_dir = normalize(camera_dir + light);
84 float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
85 float light_level = max(dot(light, v_normal), 0.0);
86 colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
87 }", None
88 ).unwrap();
89 let fxaa = shaders::fxaa_shader(display).unwrap();
90 let normal = Program::from_source(
91 display, shaders::SCREEN_VERTEX,
92 "#version 140
93 in vec2 uv;
94 uniform sampler2D tex;
95 out vec4 colour;
96 void main() {
97 colour = texture(tex, uv);
98 }", None
99 ).unwrap();
100 graphics_setup.replace(Some(Graphics {
101 screen_indices, screen_vertices, screen_uvs,
102 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
103 program, normal, fxaa
104 }));
105 }).with_update(|input, display, _, _, _| {
106 let graphics = graphics.borrow();
107 let Graphics {
108 screen_indices, screen_vertices, screen_uvs,
109 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
110 program, normal, fxaa
111 } = graphics.as_ref().unwrap();
112 let teapot_mesh = (teapot_vertices, teapot_normals, teapot_uvs);
113 let screen_mesh = (screen_vertices, screen_uvs);
114
115 let delta_time = frame_start.elapsed().as_secs_f32();
116 frame_start = Instant::now();
117
118 // using a small resolution to better show the effect of fxaa.
119 let size = (380, 216);
120 display.resize(size);
121 depth.resize_to_display(&display);
122 colour.resize_to_display(&display);
123
124 // press f to toggle FXAA
125 if input.pressed(FXAA) { fxaa_on = !fxaa_on }
126
127 let colour = colour.texture();
128 let depth = depth.texture();
129 let mut frame = SimpleFrameBuffer::with_depth_buffer(
130 display, colour, depth
131 ).unwrap();
132
133 let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);
134
135 // set camera rotation
136 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
137 rot += look_move.scale(delta_time * 20.0);
138 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
139 let rx = Quat::from_y_rot(rot.x);
140 let ry = Quat::from_x_rot(rot.y);
141 let rot = rx * ry;
142
143 // move player based on view
144 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
145 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
146 pos += move_dir.transform(&Mat3::from_rot(rx));
147
148 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
149 // draw teapot
150 frame.draw(
151 teapot_mesh, teapot_indices,
152 program, &uniform! {
153 view: view,
154 model: Mat4::from_scale(Vec3::splat(0.1)),
155 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
156 light: vec3(0.1, 0.25, -1.0).normalise(),
157 albedo: vec3(0.5, 0.1, 0.4),
158 ambient: vec3(0.0, 0.05, 0.1),
159 shine: 50.0f32,
160 },
161 &draw_parameters,
162 ).unwrap();
163
164 let mut frame = display.draw();
165 frame.draw(
166 screen_mesh, screen_indices, if fxaa_on { fxaa } else { normal },
167 &shaders::fxaa_uniforms(colour), &DrawParameters::default()
168 ).unwrap();
169 frame.finish().unwrap();
170 }).build(event_loop).unwrap();
171}
Sourcepub fn axis(&self, pos: F, neg: F) -> f32
pub fn axis(&self, pos: F, neg: F) -> f32
Returns f32 based on how much pos and neg are pressed. may return values higher than 1.0 in
the case of mouse movement and scrolling. usefull for movement controls. for 2d values see
[dir]
and [dir_max_len_1]
let move_dir = input.axis(Neg, Pos);
same as input.action_val(pos) - input.action_val(neg)
Sourcepub fn dir(&self, pos_x: F, neg_x: F, pos_y: F, neg_y: F) -> Vec2
pub fn dir(&self, pos_x: F, neg_x: F, pos_y: F, neg_y: F) -> Vec2
Returns a vector based off of x and y axis. For movement controls see dir_max_len_1
Examples found in repository?
9fn main() {
10 use Action::*;
11 let event_loop = EventLoop::new().unwrap();
12 event_loop.set_control_flow(ControlFlow::Poll);
13
14 let input = { use base_input_codes::*; input_map!(
15 (Jump, Space, GamepadInput::South),
16 (Exit, Escape, GamepadInput::Start),
17 (Left, ArrowLeft, KeyA, LeftStickLeft ),
18 (Right, ArrowRight, KeyD, LeftStickRight),
19 (Forward, ArrowUp, KeyW, LeftStickUp ),
20 (Back, ArrowDown, KeyS, LeftStickDown ),
21 (LookRight, MouseMoveRight, RightStickRight),
22 (LookLeft, MouseMoveLeft, RightStickLeft ),
23 (LookUp, MouseMoveUp, RightStickUp ),
24 (LookDown, MouseMoveDown, RightStickDown )
25 )};
26
27 struct Graphics {
28 program: Program,
29 indices: IndexBuffer<u16>,
30 vertices: VertexBuffer<Vertex>,
31 normals: VertexBuffer<Normal>
32 }
33 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::new(RefCell::new(None));
34 let graphics_setup = graphics.clone();
35
36 let draw_parameters = DrawParameters {
37 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
38 ..params::alias_3d()
39 };
40
41 let mut pos = vec3(0.0, 0.0, -30.0);
42 let mut rot = vec2(0.0, 0.0);
43 let mut gravity = 0.0;
44
45 let mut frame_start = Instant::now();
46
47 thin_engine::builder(input).with_setup(|display, window, _| {
48 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
49 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
50 window.set_cursor_visible(false);
51 window.set_title("Walk Test");
52
53 let (indices, vertices, normals) = mesh!(
54 display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
55 );
56 let program = Program::from_source(
57 display, shaders::VERTEX,
58 "#version 140
59 out vec4 colour;
60 in vec3 v_normal;
61 uniform vec3 light;
62 const vec3 albedo = vec3(0.1, 1.0, 0.3);
63 void main(){
64 float light_level = dot(light, v_normal);
65 colour = vec4(albedo * light_level, 1.0);
66 }", None,
67 ).unwrap();
68 graphics_setup.replace(Some(Graphics { program, indices, vertices, normals }));
69 }).with_update(|input, display, _, target, _| {
70 let graphics = graphics.borrow();
71 let Graphics { vertices, indices, normals, program } = graphics.as_ref().unwrap();
72 let delta_time = frame_start.elapsed().as_secs_f32();
73 frame_start = Instant::now();
74
75 let mut frame = display.draw();
76 let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);
77
78 //handle gravity and jump
79 gravity += delta_time * 9.5;
80 if input.pressed(Jump) { gravity = -10.0 }
81
82 //set camera rotation
83 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
84 rot += look_move.scale(delta_time * 20.0);
85 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
86 let rx = Quat::from_y_rot(rot.x);
87 let ry = Quat::from_x_rot(rot.y);
88 let rot = rx * ry;
89
90 //move player based on view and gravity
91 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
92 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
93 pos += move_dir.transform(&Mat3::from_rot(rx));
94 pos.y = (pos.y - gravity * delta_time).max(0.0);
95
96 if input.pressed(Exit) { target.exit() }
97
98 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
99 //draw teapot
100 frame.draw(
101 (vertices, normals), indices,
102 program, &uniform! {
103 view: view,
104 model: Mat4::from_scale(Vec3::splat(0.1)),
105 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
106 light: vec3(1.0, -0.9, -1.0).normalise()
107 },
108 &draw_parameters,
109 ).unwrap();
110
111 frame.finish().unwrap();
112 }).build(event_loop).unwrap();
113}
More examples
13fn main() {
14 use Action::*;
15 let event_loop = EventLoop::new().unwrap();
16 event_loop.set_control_flow(ControlFlow::Poll);
17
18 let mut colour = ResizableTexture2d::default();
19 let mut depth = ResizableDepthTexture2d::default();
20
21 let input = { use base_input_codes::*; input_map!(
22 (Left, ArrowLeft, KeyA, LeftStickLeft ),
23 (Right, ArrowRight, KeyD, LeftStickRight),
24 (Forward, ArrowUp, KeyW, LeftStickUp ),
25 (Back, ArrowDown, KeyS, LeftStickDown ),
26 (LookRight, MouseMoveRight, RightStickRight),
27 (LookLeft, MouseMoveLeft, RightStickLeft ),
28 (LookUp, MouseMoveUp, RightStickUp ),
29 (LookDown, MouseMoveDown, RightStickDown ),
30 (FXAA, KeyF, GamepadInput::North)
31 ) };
32 struct Graphics {
33 screen_indices: IndexBuffer<u32>,
34 screen_vertices: VertexBuffer<Vertex>,
35 screen_uvs: VertexBuffer<TextureCoords>,
36
37 teapot_indices: IndexBuffer<u16>,
38 teapot_vertices: VertexBuffer<Vertex>,
39 teapot_uvs: VertexBuffer<TextureCoords>,
40 teapot_normals: VertexBuffer<Normal>,
41
42 fxaa: Program, normal: Program, program: Program
43 }
44 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::default();
45 let graphics_setup = graphics.clone();
46
47 let draw_parameters = DrawParameters {
48 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
49 ..params::alias_3d()
50 };
51 let mut fxaa_on = true;
52
53 let mut pos = vec3(0.0, 0.0, -30.0);
54 let mut rot = vec2(0.0, 0.0);
55
56 let mut frame_start = Instant::now();
57
58 thin_engine::builder(input).with_setup(|display, window, _| {
59 window.set_title("FXAA Test");
60 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
61 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
62 window.set_cursor_visible(false);
63
64 let (screen_indices, screen_vertices, screen_uvs) = mesh!(
65 display, &screen::INDICES, &screen::VERTICES, &screen::UVS
66 );
67 let (teapot_indices, teapot_vertices, teapot_uvs, teapot_normals) = mesh!(
68 display, &teapot::INDICES, &teapot::VERTICES, &[] as &[TextureCoords; 0], &teapot::NORMALS
69 );
70
71 let program = Program::from_source(
72 display, shaders::VERTEX,
73 "#version 140
74 out vec4 colour;
75 in vec3 v_normal;
76 uniform vec3 light;
77 uniform mat4 camera;
78 uniform vec3 ambient;
79 uniform vec3 albedo;
80 uniform float shine;
81 void main() {
82 vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
83 vec3 half_dir = normalize(camera_dir + light);
84 float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
85 float light_level = max(dot(light, v_normal), 0.0);
86 colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
87 }", None
88 ).unwrap();
89 let fxaa = shaders::fxaa_shader(display).unwrap();
90 let normal = Program::from_source(
91 display, shaders::SCREEN_VERTEX,
92 "#version 140
93 in vec2 uv;
94 uniform sampler2D tex;
95 out vec4 colour;
96 void main() {
97 colour = texture(tex, uv);
98 }", None
99 ).unwrap();
100 graphics_setup.replace(Some(Graphics {
101 screen_indices, screen_vertices, screen_uvs,
102 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
103 program, normal, fxaa
104 }));
105 }).with_update(|input, display, _, _, _| {
106 let graphics = graphics.borrow();
107 let Graphics {
108 screen_indices, screen_vertices, screen_uvs,
109 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
110 program, normal, fxaa
111 } = graphics.as_ref().unwrap();
112 let teapot_mesh = (teapot_vertices, teapot_normals, teapot_uvs);
113 let screen_mesh = (screen_vertices, screen_uvs);
114
115 let delta_time = frame_start.elapsed().as_secs_f32();
116 frame_start = Instant::now();
117
118 // using a small resolution to better show the effect of fxaa.
119 let size = (380, 216);
120 display.resize(size);
121 depth.resize_to_display(&display);
122 colour.resize_to_display(&display);
123
124 // press f to toggle FXAA
125 if input.pressed(FXAA) { fxaa_on = !fxaa_on }
126
127 let colour = colour.texture();
128 let depth = depth.texture();
129 let mut frame = SimpleFrameBuffer::with_depth_buffer(
130 display, colour, depth
131 ).unwrap();
132
133 let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);
134
135 // set camera rotation
136 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
137 rot += look_move.scale(delta_time * 20.0);
138 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
139 let rx = Quat::from_y_rot(rot.x);
140 let ry = Quat::from_x_rot(rot.y);
141 let rot = rx * ry;
142
143 // move player based on view
144 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
145 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
146 pos += move_dir.transform(&Mat3::from_rot(rx));
147
148 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
149 // draw teapot
150 frame.draw(
151 teapot_mesh, teapot_indices,
152 program, &uniform! {
153 view: view,
154 model: Mat4::from_scale(Vec3::splat(0.1)),
155 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
156 light: vec3(0.1, 0.25, -1.0).normalise(),
157 albedo: vec3(0.5, 0.1, 0.4),
158 ambient: vec3(0.0, 0.05, 0.1),
159 shine: 50.0f32,
160 },
161 &draw_parameters,
162 ).unwrap();
163
164 let mut frame = display.draw();
165 frame.draw(
166 screen_mesh, screen_indices, if fxaa_on { fxaa } else { normal },
167 &shaders::fxaa_uniforms(colour), &DrawParameters::default()
168 ).unwrap();
169 frame.finish().unwrap();
170 }).build(event_loop).unwrap();
171}
Sourcepub fn dir_max_len_1(&self, pos_x: F, neg_x: F, pos_y: F, neg_y: F) -> Vec2
pub fn dir_max_len_1(&self, pos_x: F, neg_x: F, pos_y: F, neg_y: F) -> Vec2
Returns a vector based off of x and y axis with a maximum length of 1 (the same as a normalised
vector). If this undesirable see dir
Examples found in repository?
9fn main() {
10 use Action::*;
11 let event_loop = EventLoop::new().unwrap();
12 event_loop.set_control_flow(ControlFlow::Poll);
13
14 let input = { use base_input_codes::*; input_map!(
15 (Jump, Space, GamepadInput::South),
16 (Exit, Escape, GamepadInput::Start),
17 (Left, ArrowLeft, KeyA, LeftStickLeft ),
18 (Right, ArrowRight, KeyD, LeftStickRight),
19 (Forward, ArrowUp, KeyW, LeftStickUp ),
20 (Back, ArrowDown, KeyS, LeftStickDown ),
21 (LookRight, MouseMoveRight, RightStickRight),
22 (LookLeft, MouseMoveLeft, RightStickLeft ),
23 (LookUp, MouseMoveUp, RightStickUp ),
24 (LookDown, MouseMoveDown, RightStickDown )
25 )};
26
27 struct Graphics {
28 program: Program,
29 indices: IndexBuffer<u16>,
30 vertices: VertexBuffer<Vertex>,
31 normals: VertexBuffer<Normal>
32 }
33 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::new(RefCell::new(None));
34 let graphics_setup = graphics.clone();
35
36 let draw_parameters = DrawParameters {
37 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
38 ..params::alias_3d()
39 };
40
41 let mut pos = vec3(0.0, 0.0, -30.0);
42 let mut rot = vec2(0.0, 0.0);
43 let mut gravity = 0.0;
44
45 let mut frame_start = Instant::now();
46
47 thin_engine::builder(input).with_setup(|display, window, _| {
48 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
49 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
50 window.set_cursor_visible(false);
51 window.set_title("Walk Test");
52
53 let (indices, vertices, normals) = mesh!(
54 display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
55 );
56 let program = Program::from_source(
57 display, shaders::VERTEX,
58 "#version 140
59 out vec4 colour;
60 in vec3 v_normal;
61 uniform vec3 light;
62 const vec3 albedo = vec3(0.1, 1.0, 0.3);
63 void main(){
64 float light_level = dot(light, v_normal);
65 colour = vec4(albedo * light_level, 1.0);
66 }", None,
67 ).unwrap();
68 graphics_setup.replace(Some(Graphics { program, indices, vertices, normals }));
69 }).with_update(|input, display, _, target, _| {
70 let graphics = graphics.borrow();
71 let Graphics { vertices, indices, normals, program } = graphics.as_ref().unwrap();
72 let delta_time = frame_start.elapsed().as_secs_f32();
73 frame_start = Instant::now();
74
75 let mut frame = display.draw();
76 let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);
77
78 //handle gravity and jump
79 gravity += delta_time * 9.5;
80 if input.pressed(Jump) { gravity = -10.0 }
81
82 //set camera rotation
83 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
84 rot += look_move.scale(delta_time * 20.0);
85 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
86 let rx = Quat::from_y_rot(rot.x);
87 let ry = Quat::from_x_rot(rot.y);
88 let rot = rx * ry;
89
90 //move player based on view and gravity
91 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
92 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
93 pos += move_dir.transform(&Mat3::from_rot(rx));
94 pos.y = (pos.y - gravity * delta_time).max(0.0);
95
96 if input.pressed(Exit) { target.exit() }
97
98 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
99 //draw teapot
100 frame.draw(
101 (vertices, normals), indices,
102 program, &uniform! {
103 view: view,
104 model: Mat4::from_scale(Vec3::splat(0.1)),
105 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
106 light: vec3(1.0, -0.9, -1.0).normalise()
107 },
108 &draw_parameters,
109 ).unwrap();
110
111 frame.finish().unwrap();
112 }).build(event_loop).unwrap();
113}
More examples
13fn main() {
14 use Action::*;
15 let event_loop = EventLoop::new().unwrap();
16 event_loop.set_control_flow(ControlFlow::Poll);
17
18 let mut colour = ResizableTexture2d::default();
19 let mut depth = ResizableDepthTexture2d::default();
20
21 let input = { use base_input_codes::*; input_map!(
22 (Left, ArrowLeft, KeyA, LeftStickLeft ),
23 (Right, ArrowRight, KeyD, LeftStickRight),
24 (Forward, ArrowUp, KeyW, LeftStickUp ),
25 (Back, ArrowDown, KeyS, LeftStickDown ),
26 (LookRight, MouseMoveRight, RightStickRight),
27 (LookLeft, MouseMoveLeft, RightStickLeft ),
28 (LookUp, MouseMoveUp, RightStickUp ),
29 (LookDown, MouseMoveDown, RightStickDown ),
30 (FXAA, KeyF, GamepadInput::North)
31 ) };
32 struct Graphics {
33 screen_indices: IndexBuffer<u32>,
34 screen_vertices: VertexBuffer<Vertex>,
35 screen_uvs: VertexBuffer<TextureCoords>,
36
37 teapot_indices: IndexBuffer<u16>,
38 teapot_vertices: VertexBuffer<Vertex>,
39 teapot_uvs: VertexBuffer<TextureCoords>,
40 teapot_normals: VertexBuffer<Normal>,
41
42 fxaa: Program, normal: Program, program: Program
43 }
44 let graphics: Rc<RefCell<Option<Graphics>>> = Rc::default();
45 let graphics_setup = graphics.clone();
46
47 let draw_parameters = DrawParameters {
48 backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
49 ..params::alias_3d()
50 };
51 let mut fxaa_on = true;
52
53 let mut pos = vec3(0.0, 0.0, -30.0);
54 let mut rot = vec2(0.0, 0.0);
55
56 let mut frame_start = Instant::now();
57
58 thin_engine::builder(input).with_setup(|display, window, _| {
59 window.set_title("FXAA Test");
60 let _ = window.set_cursor_grab(CursorGrabMode::Confined);
61 let _ = window.set_cursor_grab(CursorGrabMode::Locked);
62 window.set_cursor_visible(false);
63
64 let (screen_indices, screen_vertices, screen_uvs) = mesh!(
65 display, &screen::INDICES, &screen::VERTICES, &screen::UVS
66 );
67 let (teapot_indices, teapot_vertices, teapot_uvs, teapot_normals) = mesh!(
68 display, &teapot::INDICES, &teapot::VERTICES, &[] as &[TextureCoords; 0], &teapot::NORMALS
69 );
70
71 let program = Program::from_source(
72 display, shaders::VERTEX,
73 "#version 140
74 out vec4 colour;
75 in vec3 v_normal;
76 uniform vec3 light;
77 uniform mat4 camera;
78 uniform vec3 ambient;
79 uniform vec3 albedo;
80 uniform float shine;
81 void main() {
82 vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
83 vec3 half_dir = normalize(camera_dir + light);
84 float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
85 float light_level = max(dot(light, v_normal), 0.0);
86 colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
87 }", None
88 ).unwrap();
89 let fxaa = shaders::fxaa_shader(display).unwrap();
90 let normal = Program::from_source(
91 display, shaders::SCREEN_VERTEX,
92 "#version 140
93 in vec2 uv;
94 uniform sampler2D tex;
95 out vec4 colour;
96 void main() {
97 colour = texture(tex, uv);
98 }", None
99 ).unwrap();
100 graphics_setup.replace(Some(Graphics {
101 screen_indices, screen_vertices, screen_uvs,
102 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
103 program, normal, fxaa
104 }));
105 }).with_update(|input, display, _, _, _| {
106 let graphics = graphics.borrow();
107 let Graphics {
108 screen_indices, screen_vertices, screen_uvs,
109 teapot_indices, teapot_vertices, teapot_uvs, teapot_normals,
110 program, normal, fxaa
111 } = graphics.as_ref().unwrap();
112 let teapot_mesh = (teapot_vertices, teapot_normals, teapot_uvs);
113 let screen_mesh = (screen_vertices, screen_uvs);
114
115 let delta_time = frame_start.elapsed().as_secs_f32();
116 frame_start = Instant::now();
117
118 // using a small resolution to better show the effect of fxaa.
119 let size = (380, 216);
120 display.resize(size);
121 depth.resize_to_display(&display);
122 colour.resize_to_display(&display);
123
124 // press f to toggle FXAA
125 if input.pressed(FXAA) { fxaa_on = !fxaa_on }
126
127 let colour = colour.texture();
128 let depth = depth.texture();
129 let mut frame = SimpleFrameBuffer::with_depth_buffer(
130 display, colour, depth
131 ).unwrap();
132
133 let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);
134
135 // set camera rotation
136 let look_move = input.dir(LookLeft, LookRight, LookUp, LookDown);
137 rot += look_move.scale(delta_time * 20.0);
138 rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
139 let rx = Quat::from_y_rot(rot.x);
140 let ry = Quat::from_x_rot(rot.y);
141 let rot = rx * ry;
142
143 // move player based on view
144 let dir = input.dir_max_len_1(Right, Left, Forward, Back);
145 let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
146 pos += move_dir.transform(&Mat3::from_rot(rx));
147
148 frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
149 // draw teapot
150 frame.draw(
151 teapot_mesh, teapot_indices,
152 program, &uniform! {
153 view: view,
154 model: Mat4::from_scale(Vec3::splat(0.1)),
155 camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
156 light: vec3(0.1, 0.25, -1.0).normalise(),
157 albedo: vec3(0.5, 0.1, 0.4),
158 ambient: vec3(0.0, 0.05, 0.1),
159 shine: 50.0f32,
160 },
161 &draw_parameters,
162 ).unwrap();
163
164 let mut frame = display.draw();
165 frame.draw(
166 screen_mesh, screen_indices, if fxaa_on { fxaa } else { normal },
167 &shaders::fxaa_uniforms(colour), &DrawParameters::default()
168 ).unwrap();
169 frame.finish().unwrap();
170 }).build(event_loop).unwrap();
171}
Trait Implementations§
Auto Trait Implementations§
impl<F> Freeze for InputMap<F>
impl<F> RefUnwindSafe for InputMap<F>where
F: RefUnwindSafe,
impl<F> Send for InputMap<F>where
F: Send,
impl<F> Sync for InputMap<F>where
F: Sync,
impl<F> Unpin for InputMap<F>where
F: Unpin,
impl<F> UnwindSafe for InputMap<F>where
F: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.