Struct thin_engine::prelude::Vec3

source ·
pub struct Vec3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}
Expand description

a vector made from a x, y and z coordinate.

Fields§

§x: f32§y: f32§z: f32

Implementations§

source§

impl Vec3

source

pub const ZERO: Vec3 = _

a zero vector

source

pub const ONE: Vec3 = _

a vector full of ones

source

pub const X: Vec3 = _

the x axis

source

pub const Y: Vec3 = _

the y axis

source

pub const Z: Vec3 = _

the z axis

source

pub fn new(x: f32, y: f32, z: f32) -> Vec3

source

pub fn extend(self, w: f32) -> Vec4

source

pub fn truncate(self) -> Vec2

source

pub fn splat(value: f32) -> Vec3

create a vector where x, y and z equals value.

Examples found in repository?
examples/simple.rs (line 88)
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
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::Space)], Jump),
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back)
    ]);

    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;

    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        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 * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

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

        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();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 123)
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
141
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back),
        (vec![Input::keycode(KeyCode::KeyF)], FXAA),
        (vec![Input::keycode(KeyCode::Space)], Jump)
    ]);
    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 fxaa = shaders::fxaa_shader(&display).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 mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        // using a small resolution to show the effect.
        // `let size = window.inner_size().into();` 
        // can be used isntead to set resolution to window size
        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
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

        //move player based on view
        let x = input.axis(Right, Left);
        let y = input.axis(Forward, Back);
        let move_dir = vec3(x, 0.0, y).normalise().scale(5.0*DELTA);
        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: 10.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 length_squared(self) -> f32

the length of the vector before being square rooted.

source

pub fn length(self) -> f32

length of the vector.

source

pub fn distance_squared(self, other: Vec3) -> f32

distance between two vectors before being square rooted.

source

pub fn distance(self, other: Vec3) -> f32

distance between two vectors.

source

pub fn dot(self, other: Vec3) -> f32

get the dot product of 2 vectors. equal to the cosign of the angle between vectors.

source

pub fn cross(&self, other: Vec3) -> Vec3

get the cross product of 2 vectors. equal to the vector that is perpendicular to both input vectors. the output vector is not normalised.

use glium_types::vectors::{Vec3, vec3};
let x = vec3(1.0, 0.0, 0.0);
let y = vec3(0.0, 1.0, 0.0);
let z = vec3(0.0, 0.0, 1.0);
assert!(x.cross(y) == z);
source

pub fn scale(self, scalar: f32) -> Vec3

multiplies each value by the scalar.

Examples found in repository?
examples/simple.rs (line 79)
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
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::Space)], Jump),
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back)
    ]);

    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;

    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        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 * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

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

        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();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 114)
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
141
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back),
        (vec![Input::keycode(KeyCode::KeyF)], FXAA),
        (vec![Input::keycode(KeyCode::Space)], Jump)
    ]);
    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 fxaa = shaders::fxaa_shader(&display).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 mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        // using a small resolution to show the effect.
        // `let size = window.inner_size().into();` 
        // can be used isntead to set resolution to window size
        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
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

        //move player based on view
        let x = input.axis(Right, Left);
        let y = input.axis(Forward, Back);
        let move_dir = vec3(x, 0.0, y).normalise().scale(5.0*DELTA);
        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: 10.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 normalise(self) -> Vec3

makes the length of the vector equal to 1. on fail returns vec3 of zeros

Examples found in repository?
examples/simple.rs (line 78)
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
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::Space)], Jump),
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back)
    ]);

    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;

    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        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 * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

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

        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();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 114)
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
141
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back),
        (vec![Input::keycode(KeyCode::KeyF)], FXAA),
        (vec![Input::keycode(KeyCode::Space)], Jump)
    ]);
    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 fxaa = shaders::fxaa_shader(&display).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 mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        // using a small resolution to show the effect.
        // `let size = window.inner_size().into();` 
        // can be used isntead to set resolution to window size
        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
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

        //move player based on view
        let x = input.axis(Right, Left);
        let y = input.axis(Forward, Back);
        let move_dir = vec3(x, 0.0, y).normalise().scale(5.0*DELTA);
        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: 10.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 transform(self, matrix: &Mat3) -> Vec3

transforms vector by the matrix

Examples found in repository?
examples/simple.rs (line 79)
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
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::Space)], Jump),
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back)
    ]);

    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;

    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        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 * 9.5;
        if input.pressed(Jump) {
            gravity = -10.0;
        }

        //set camera rotation
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

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

        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();
        thread::sleep(Duration::from_millis(16));
    }).unwrap();
}
More examples
Hide additional examples
examples/simple-fxaa.rs (line 115)
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
141
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 mut input = InputMap::new([
        (vec![Input::keycode(KeyCode::ArrowLeft), Input::keycode(KeyCode::KeyA)], Left),
        (vec![Input::keycode(KeyCode::ArrowRight), Input::keycode(KeyCode::KeyD)], Right),
        (vec![Input::keycode(KeyCode::ArrowUp), Input::keycode(KeyCode::KeyW)], Forward),
        (vec![Input::keycode(KeyCode::ArrowDown), Input::keycode(KeyCode::KeyS)], Back),
        (vec![Input::keycode(KeyCode::KeyF)], FXAA),
        (vec![Input::keycode(KeyCode::Space)], Jump)
    ]);
    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 fxaa = shaders::fxaa_shader(&display).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 mut pos = vec3(0.0, 0.0, -30.0);
    let mut rot = vec2(0.0, 0.0);
    const DELTA: f32 = 0.016;

    thin_engine::run(event_loop, &mut input, |input| {
        // using a small resolution to show the effect.
        // `let size = window.inner_size().into();` 
        // can be used isntead to set resolution to window size
        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
        rot += input.mouse_move.scale(DELTA * 2.0);
        rot.y = rot.y.clamp(-PI / 2.0, PI / 2.0);
        let rx = Quaternion::from_y_rotation(rot.x);
        let ry = Quaternion::from_x_rotation(rot.y);
        let rot = rx * ry;

        //move player based on view
        let x = input.axis(Right, Left);
        let y = input.axis(Forward, Back);
        let move_dir = vec3(x, 0.0, y).normalise().scale(5.0*DELTA);
        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: 10.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 Add for Vec3

source§

fn add(self, rhs: Vec3) -> <Vec3 as Add>::Output

Performs the + operation. Read more
§

type Output = Vec3

The resulting type after applying the + operator.
source§

impl AddAssign for Vec3

source§

fn add_assign(&mut self, rhs: Vec3)

Performs the += operation. Read more
source§

impl AsUniformValue for Vec3

source§

fn as_uniform_value(&self) -> UniformValue<'_>

Builds a UniformValue.
source§

impl Clone for Vec3

source§

fn clone(&self) -> Vec3

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Vec3

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Div for Vec3

source§

fn div(self, rhs: Vec3) -> <Vec3 as Div>::Output

Performs the / operation. Read more
§

type Output = Vec3

The resulting type after applying the / operator.
source§

impl DivAssign for Vec3

source§

fn div_assign(&mut self, rhs: Vec3)

Performs the /= operation. Read more
source§

impl From<[f32; 3]> for Vec3

source§

fn from(value: [f32; 3]) -> Vec3

Converts to this type from the input type.
source§

impl From<(f32, f32, f32)> for Vec3

source§

fn from(value: (f32, f32, f32)) -> Vec3

Converts to this type from the input type.
source§

impl From<Vec3> for DVec3

source§

fn from(value: Vec3) -> DVec3

Converts to this type from the input type.
source§

impl From<Vec3> for IVec3

source§

fn from(value: Vec3) -> IVec3

Converts to this type from the input type.
source§

impl Mul for Vec3

source§

fn mul(self, rhs: Vec3) -> <Vec3 as Mul>::Output

Performs the * operation. Read more
§

type Output = Vec3

The resulting type after applying the * operator.
source§

impl MulAssign for Vec3

source§

fn mul_assign(&mut self, rhs: Vec3)

Performs the *= operation. Read more
source§

impl Neg for Vec3

§

type Output = Vec3

The resulting type after applying the - operator.
source§

fn neg(self) -> <Vec3 as Neg>::Output

Performs the unary - operation. Read more
source§

impl PartialEq for Vec3

source§

fn eq(&self, other: &Vec3) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for Vec3

source§

fn partial_cmp(&self, other: &Vec3) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Rem for Vec3

source§

fn rem(self, rhs: Vec3) -> <Vec3 as Rem>::Output

Performs the % operation. Read more
§

type Output = Vec3

The resulting type after applying the % operator.
source§

impl RemAssign for Vec3

source§

fn rem_assign(&mut self, rhs: Vec3)

Performs the %= operation. Read more
source§

impl Sub for Vec3

source§

fn sub(self, rhs: Vec3) -> <Vec3 as Sub>::Output

Performs the - operation. Read more
§

type Output = Vec3

The resulting type after applying the - operator.
source§

impl SubAssign for Vec3

source§

fn sub_assign(&mut self, rhs: Vec3)

Performs the -= operation. Read more
source§

impl Copy for Vec3

source§

impl StructuralPartialEq for Vec3

Auto Trait Implementations§

§

impl Freeze for Vec3

§

impl RefUnwindSafe for Vec3

§

impl Send for Vec3

§

impl Sync for Vec3

§

impl Unpin for Vec3

§

impl UnwindSafe for Vec3

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> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> CloneToUninit for T
where T: Copy,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> Content for T
where T: Copy,

§

type Owned = T

A type that holds a sized version of the content.
source§

unsafe fn read<F, E>(size: usize, f: F) -> Result<T, E>
where F: FnOnce(&mut T) -> Result<(), E>,

Prepares an output buffer, then turns this buffer into an Owned. User-provided closure F must only write to and not read from &mut Self.
source§

fn get_elements_size() -> usize

Returns the size of each element.
source§

fn to_void_ptr(&self) -> *const ()

Produces a pointer to the data.
source§

fn ref_from_ptr<'a>(ptr: *mut (), size: usize) -> Option<*mut T>

Builds a pointer to this type from a raw pointer.
source§

fn is_size_suitable(size: usize) -> bool

Returns true if the size is suitable to store a type like this.
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> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

§

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

§

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