thin_engine::input_map_setup

Struct InputMap

Source
pub struct InputMap<F>
where F: Hash + Eq + Clone + Copy,
{ pub binds: HashMap<InputCode, 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.

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, _: DeviceId, event: DeviceEvent) {
        self.input.update_with_device_event(&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, Vec<F>>

Stores what each input code is bound to

§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>
where F: Hash + Eq + Clone + Copy,

Source

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 mut input = Input::new([
    (vec![Input::keycode(KeyCode::KeyW)], Forward),
    (vec![Input::keycode(KeyCode::KeyA)], Pos),
    (vec![Input::keycode(KeyCode::KeyS)], Back),
    (vec![Input::keycode(KeyCode::KeyD)], Neg)
]);
Source

pub fn empty() -> InputMap<()>

Use if you dont want to have any actions and binds. Will still have access to everything else.

Source

pub fn mut_bind(&mut self, input_code: InputCode) -> &mut Vec<F>

Gets a mutable vector of what actions input_code is bound to

Source

pub fn update_with_winit(&mut self, event: &Event<()>)

👎Deprecated: use 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(),
        _ => ()
    }
});
Source

pub fn update_with_device_event(&mut self, event: &DeviceEvent)

Source

pub fn update_with_window_event(&mut self, event: &WindowEvent)

Source

pub fn update_with_gilrs(&mut self, gilrs: &mut Gilrs)

Source

pub fn init(&mut self)

Makes the input map ready to recieve new events.

Source

pub fn pressing(&self, action: F) -> bool

Checks if action is being pressed currently. same as input.action_val(action) >= input.press_sensitivity

Source

pub fn action_val(&self, action: F) -> f32

Checks how much action is being pressed. May be higher than 1 in the case of scroll wheels and mouse movement.

Source

pub fn pressed(&self, action: F) -> bool

checks if action was just pressed

Examples found in repository?
examples/simple.rs (line 68)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("Walk Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let input = {
        use thin_engine::input_map_setup::*;
        input_map!(
            (Jump,    Space,  GamepadButton::South),
            (Exit,    Escape, GamepadButton::Start),
            (Left,    ArrowLeft,  KeyA,  Axis(LeftStickX,  Neg)),
            (Right,   ArrowRight, KeyD,  Axis(LeftStickX,  Pos)),
            (Forward, ArrowUp,    KeyW,  Axis(LeftStickY,  Neg)),
            (Back,    ArrowDown,  KeyS,  Axis(LeftStickY,  Pos)),
            (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
            (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
            (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Neg)),
            (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Pos))
        )
    };

    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        const vec3 albedo = vec3(0.1, 1.0, 0.3);
        void main(){
            float light_level = dot(light, v_normal);
            colour = vec4(albedo * light_level, 1.0);
        }", None,
    ).unwrap();

    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    let mut gravity = 0.0;

    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _settings, target| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        display.resize(window.inner_size().into());
        let mut frame = display.draw();
        let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);

        //handle gravity and jump
        gravity += delta_time * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 7.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view and gravity
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));
        pos.y = (pos.y - gravity * delta_time).max(0.0);

        if input.pressed(Exit) { target.exit() }

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            (&verts, &norms), &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(1.0, -0.9, -1.0).normalise()
            },
            &draw_parameters,
        ).unwrap();

        frame.finish().unwrap();
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 93)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("FXAA Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let mut colour = ResizableTexture2D::default();
    let mut depth = ResizableDepthTexture2D::default();

    let input = { use thin_engine::input_map_setup::*; input_map!(
        (Left,      ArrowLeft, KeyA, Axis(LeftStickX,  Neg)),
        (Right,     ArrowRight,KeyD, Axis(LeftStickX,  Pos)),
        (Forward,   ArrowUp,   KeyW, Axis(LeftStickY,  Neg)),
        (Back,      ArrowDown, KeyS, Axis(LeftStickY,  Pos)),
        (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
        (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
        (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Pos)),
        (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Neg)),
        (FXAA,      KeyF,            GamepadButton::North  )
    ) };
    let (screen_indices, verts, uvs) = mesh!(
        &display, &screen::INDICES, &screen::VERTICES, &screen::UVS
    );
    let screen_mesh = (&verts, &uvs);
    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let teapot_mesh = (&verts, &norms);
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let mut fxaa_on = true;
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        uniform mat4 camera;
        uniform vec3 ambient;
        uniform vec3 albedo;
        uniform float shine;
        void main() {
            vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
            vec3 half_dir = normalize(camera_dir + light);
            float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
            float light_level = max(dot(light, v_normal), 0.0);
            colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
        }", None
    ).unwrap();
    let normal = Program::from_source(
        &display, shaders::SCREEN_VERTEX, 
        "#version 140
        in vec2 uv;
        uniform sampler2D tex;
        out vec4 colour;
        void main() {
            colour = texture(tex, uv);
        }", None
    ).unwrap();
    let fxaa = shaders::fxaa_shader(&display).unwrap();
    
    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    
    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _, _| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        // using a small resolution to better show the effect of fxaa.
        let size = (380, 216);
        display.resize(size);
        depth.resize_to_display(&display);
        colour.resize_to_display(&display);

        //press f to toggle FXAA
        if input.pressed(FXAA) { fxaa_on = !fxaa_on }

        let colour = colour.texture.as_ref().unwrap();
        let depth = depth.texture.as_ref().unwrap();
        let mut frame = SimpleFrameBuffer::with_depth_buffer(
            &display, colour, depth
        ).unwrap();

        let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            teapot_mesh, &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(0.1, 0.25, -1.0).normalise(),
                albedo: vec3(0.5, 0.1, 0.4),
                ambient: vec3(0.0, 0.05, 0.1),
                shine: 50.0f32,
            },
            &draw_parameters,
        ).unwrap();

        let mut frame = display.draw();
        frame.draw(
            screen_mesh, &screen_indices, if fxaa_on { &fxaa } else { &normal },
            &shaders::fxaa_uniforms(colour), &DrawParameters::default()
        ).unwrap();
        frame.finish().unwrap();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
Source

pub fn released(&self, action: F) -> bool

checks if action was just released

Source

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)

Source

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?
examples/simple.rs (line 73)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("Walk Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let input = {
        use thin_engine::input_map_setup::*;
        input_map!(
            (Jump,    Space,  GamepadButton::South),
            (Exit,    Escape, GamepadButton::Start),
            (Left,    ArrowLeft,  KeyA,  Axis(LeftStickX,  Neg)),
            (Right,   ArrowRight, KeyD,  Axis(LeftStickX,  Pos)),
            (Forward, ArrowUp,    KeyW,  Axis(LeftStickY,  Neg)),
            (Back,    ArrowDown,  KeyS,  Axis(LeftStickY,  Pos)),
            (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
            (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
            (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Neg)),
            (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Pos))
        )
    };

    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        const vec3 albedo = vec3(0.1, 1.0, 0.3);
        void main(){
            float light_level = dot(light, v_normal);
            colour = vec4(albedo * light_level, 1.0);
        }", None,
    ).unwrap();

    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    let mut gravity = 0.0;

    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _settings, target| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        display.resize(window.inner_size().into());
        let mut frame = display.draw();
        let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);

        //handle gravity and jump
        gravity += delta_time * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 7.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view and gravity
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));
        pos.y = (pos.y - gravity * delta_time).max(0.0);

        if input.pressed(Exit) { target.exit() }

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            (&verts, &norms), &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(1.0, -0.9, -1.0).normalise()
            },
            &draw_parameters,
        ).unwrap();

        frame.finish().unwrap();
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 104)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("FXAA Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let mut colour = ResizableTexture2D::default();
    let mut depth = ResizableDepthTexture2D::default();

    let input = { use thin_engine::input_map_setup::*; input_map!(
        (Left,      ArrowLeft, KeyA, Axis(LeftStickX,  Neg)),
        (Right,     ArrowRight,KeyD, Axis(LeftStickX,  Pos)),
        (Forward,   ArrowUp,   KeyW, Axis(LeftStickY,  Neg)),
        (Back,      ArrowDown, KeyS, Axis(LeftStickY,  Pos)),
        (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
        (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
        (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Pos)),
        (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Neg)),
        (FXAA,      KeyF,            GamepadButton::North  )
    ) };
    let (screen_indices, verts, uvs) = mesh!(
        &display, &screen::INDICES, &screen::VERTICES, &screen::UVS
    );
    let screen_mesh = (&verts, &uvs);
    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let teapot_mesh = (&verts, &norms);
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let mut fxaa_on = true;
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        uniform mat4 camera;
        uniform vec3 ambient;
        uniform vec3 albedo;
        uniform float shine;
        void main() {
            vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
            vec3 half_dir = normalize(camera_dir + light);
            float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
            float light_level = max(dot(light, v_normal), 0.0);
            colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
        }", None
    ).unwrap();
    let normal = Program::from_source(
        &display, shaders::SCREEN_VERTEX, 
        "#version 140
        in vec2 uv;
        uniform sampler2D tex;
        out vec4 colour;
        void main() {
            colour = texture(tex, uv);
        }", None
    ).unwrap();
    let fxaa = shaders::fxaa_shader(&display).unwrap();
    
    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    
    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _, _| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        // using a small resolution to better show the effect of fxaa.
        let size = (380, 216);
        display.resize(size);
        depth.resize_to_display(&display);
        colour.resize_to_display(&display);

        //press f to toggle FXAA
        if input.pressed(FXAA) { fxaa_on = !fxaa_on }

        let colour = colour.texture.as_ref().unwrap();
        let depth = depth.texture.as_ref().unwrap();
        let mut frame = SimpleFrameBuffer::with_depth_buffer(
            &display, colour, depth
        ).unwrap();

        let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            teapot_mesh, &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(0.1, 0.25, -1.0).normalise(),
                albedo: vec3(0.5, 0.1, 0.4),
                ambient: vec3(0.0, 0.05, 0.1),
                shine: 50.0f32,
            },
            &draw_parameters,
        ).unwrap();

        let mut frame = display.draw();
        frame.draw(
            screen_mesh, &screen_indices, if fxaa_on { &fxaa } else { &normal },
            &shaders::fxaa_uniforms(colour), &DrawParameters::default()
        ).unwrap();
        frame.finish().unwrap();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
Source

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?
examples/simple.rs (line 81)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("Walk Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let input = {
        use thin_engine::input_map_setup::*;
        input_map!(
            (Jump,    Space,  GamepadButton::South),
            (Exit,    Escape, GamepadButton::Start),
            (Left,    ArrowLeft,  KeyA,  Axis(LeftStickX,  Neg)),
            (Right,   ArrowRight, KeyD,  Axis(LeftStickX,  Pos)),
            (Forward, ArrowUp,    KeyW,  Axis(LeftStickY,  Neg)),
            (Back,    ArrowDown,  KeyS,  Axis(LeftStickY,  Pos)),
            (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
            (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
            (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Neg)),
            (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Pos))
        )
    };

    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        const vec3 albedo = vec3(0.1, 1.0, 0.3);
        void main(){
            float light_level = dot(light, v_normal);
            colour = vec4(albedo * light_level, 1.0);
        }", None,
    ).unwrap();

    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    let mut gravity = 0.0;

    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _settings, target| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        display.resize(window.inner_size().into());
        let mut frame = display.draw();
        let view = Mat4::view_matrix_3d(frame.get_dimensions(), 1.0, 1024.0, 0.1);

        //handle gravity and jump
        gravity += delta_time * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 7.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view and gravity
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));
        pos.y = (pos.y - gravity * delta_time).max(0.0);

        if input.pressed(Exit) { target.exit() }

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            (&verts, &norms), &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(1.0, -0.9, -1.0).normalise()
            },
            &draw_parameters,
        ).unwrap();

        frame.finish().unwrap();
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 112)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
fn main() {
    use Action::*;
    let (event_loop, window, display) = thin_engine::set_up().unwrap();
    window.set_title("FXAA Test");
    let _ = window.set_cursor_grab(CursorGrabMode::Locked);
    window.set_cursor_visible(false);

    let mut colour = ResizableTexture2D::default();
    let mut depth = ResizableDepthTexture2D::default();

    let input = { use thin_engine::input_map_setup::*; input_map!(
        (Left,      ArrowLeft, KeyA, Axis(LeftStickX,  Neg)),
        (Right,     ArrowRight,KeyD, Axis(LeftStickX,  Pos)),
        (Forward,   ArrowUp,   KeyW, Axis(LeftStickY,  Neg)),
        (Back,      ArrowDown, KeyS, Axis(LeftStickY,  Pos)),
        (LookRight, MouseMoveX(Pos), Axis(RightStickX, Pos)),
        (LookLeft,  MouseMoveX(Neg), Axis(RightStickX, Neg)),
        (LookUp,    MouseMoveY(Pos), Axis(RightStickY, Pos)),
        (LookDown,  MouseMoveY(Neg), Axis(RightStickY, Neg)),
        (FXAA,      KeyF,            GamepadButton::North  )
    ) };
    let (screen_indices, verts, uvs) = mesh!(
        &display, &screen::INDICES, &screen::VERTICES, &screen::UVS
    );
    let screen_mesh = (&verts, &uvs);
    let (indices, verts, norms) = mesh!(
        &display, &teapot::INDICES, &teapot::VERTICES, &teapot::NORMALS
    );
    let teapot_mesh = (&verts, &norms);
    let draw_parameters = DrawParameters {
        backface_culling: draw_parameters::BackfaceCullingMode::CullClockwise,
        ..params::alias_3d()
    };
    let mut fxaa_on = true;
    let program = Program::from_source(
        &display, shaders::VERTEX,
        "#version 140
        out vec4 colour;
        in vec3 v_normal;
        uniform vec3 light;
        uniform mat4 camera;
        uniform vec3 ambient;
        uniform vec3 albedo;
        uniform float shine;
        void main() {
            vec3 camera_dir = inverse(mat3(camera)) * vec3(0, 0, -1);
            vec3 half_dir = normalize(camera_dir + light);
            float specular = pow(max(dot(half_dir, v_normal), 0.0), shine);
            float light_level = max(dot(light, v_normal), 0.0);
            colour = vec4(albedo * light_level + ambient + vec3(specular), 1.0);
        }", None
    ).unwrap();
    let normal = Program::from_source(
        &display, shaders::SCREEN_VERTEX, 
        "#version 140
        in vec2 uv;
        uniform sampler2D tex;
        out vec4 colour;
        void main() {
            colour = texture(tex, uv);
        }", None
    ).unwrap();
    let fxaa = shaders::fxaa_shader(&display).unwrap();
    
    let mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    
    let mut frame_start = Instant::now();

    thin_engine::run(event_loop, input, Settings::from_fps(60), |input, _, _| {
        let delta_time = frame_start.elapsed().as_secs_f32();
        frame_start = Instant::now();

        // using a small resolution to better show the effect of fxaa.
        let size = (380, 216);
        display.resize(size);
        depth.resize_to_display(&display);
        colour.resize_to_display(&display);

        //press f to toggle FXAA
        if input.pressed(FXAA) { fxaa_on = !fxaa_on }

        let colour = colour.texture.as_ref().unwrap();
        let depth = depth.texture.as_ref().unwrap();
        let mut frame = SimpleFrameBuffer::with_depth_buffer(
            &display, colour, depth
        ).unwrap();

        let view = Mat4::view_matrix_3d(size, 1.0, 1024.0, 0.1);

        //set camera rotation
        let look_move = input.dir(LookRight, LookLeft, LookUp, LookDown);
        rot += look_move.scale(delta_time * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quat::from_y_rot(rot.x);
        let ry = Quat::from_x_rot(rot.y);
        let rot = rx * ry;

        //move player based on view
        let dir = input.dir_max_len_1(Right, Left, Forward, Back);
        let move_dir = vec3(dir.x, 0.0, dir.y).scale(5.0*delta_time);
        pos += move_dir.transform(&Mat3::from_rot(rx));

        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
        //draw teapot
        frame.draw(
            teapot_mesh, &indices,
            &program, &uniform! {
                view: view,
                model: Mat4::from_scale(Vec3::splat(0.1)),
                camera: Mat4::from_inverse_transform(pos, Vec3::ONE, rot),
                light: vec3(0.1, 0.25, -1.0).normalise(),
                albedo: vec3(0.5, 0.1, 0.4),
                ambient: vec3(0.0, 0.05, 0.1),
                shine: 50.0f32,
            },
            &draw_parameters,
        ).unwrap();

        let mut frame = display.draw();
        frame.draw(
            screen_mesh, &screen_indices, if fxaa_on { &fxaa } else { &normal },
            &shaders::fxaa_uniforms(colour), &DrawParameters::default()
        ).unwrap();
        frame.finish().unwrap();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}

Trait Implementations§

Source§

impl<F> Default for InputMap<F>
where F: Hash + Eq + Clone + Copy,

Source§

fn default() -> InputMap<F>

Returns the “default value” for a type. Read more

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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>

Convert 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)

Convert &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)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more