Struct bevy::math::prelude::Quat

source ·
pub struct Quat(/* private fields */);
Expand description

A quaternion representing an orientation.

This quaternion is intended to be of unit length but may denormalize due to floating point “error creep” which can occur when successive quaternion operations are applied.

SIMD vector types are used for storage on supported platforms.

This type is 16 byte aligned.

Implementations§

source§

impl Quat

source

pub const IDENTITY: Quat = _

The identity quaternion. Corresponds to no rotation.

source

pub const NAN: Quat = _

All NANs.

source

pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Quat

Creates a new rotation quaternion.

This should generally not be called manually unless you know what you are doing. Use one of the other constructors instead such as identity or from_axis_angle.

from_xyzw is mostly used by unit tests and serde deserialization.

§Preconditions

This function does not check if the input is normalized, it is up to the user to provide normalized input or to normalized the resulting quaternion.

Examples found in repository?
examples/math/custom_primitives.rs (line 52)
49
50
51
52
53
54
const TRANSFORM_3D: Transform = Transform {
    translation: Vec3::ZERO,
    // The camera is pointing at the 3D shape
    rotation: Quat::from_xyzw(-0.14521316, -0.0, -0.0, 0.98940045),
    scale: Vec3::ONE,
};
More examples
Hide additional examples
examples/3d/parallax_mapping.rs (line 163)
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
const CAMERA_POSITIONS: &[Transform] = &[
    Transform {
        translation: Vec3::new(1.5, 1.5, 1.5),
        rotation: Quat::from_xyzw(-0.279, 0.364, 0.115, 0.880),
        scale: Vec3::ONE,
    },
    Transform {
        translation: Vec3::new(2.4, 0.0, 0.2),
        rotation: Quat::from_xyzw(0.094, 0.676, 0.116, 0.721),
        scale: Vec3::ONE,
    },
    Transform {
        translation: Vec3::new(2.4, 2.6, -4.3),
        rotation: Quat::from_xyzw(0.170, 0.908, 0.308, 0.225),
        scale: Vec3::ONE,
    },
    Transform {
        translation: Vec3::new(-1.0, 0.8, -1.2),
        rotation: Quat::from_xyzw(-0.004, 0.909, 0.247, -0.335),
        scale: Vec3::ONE,
    },
];
source

pub const fn from_array(a: [f32; 4]) -> Quat

Creates a rotation quaternion from an array.

§Preconditions

This function does not check if the input is normalized, it is up to the user to provide normalized input or to normalized the resulting quaternion.

source

pub const fn from_vec4(v: Vec4) -> Quat

Creates a new rotation quaternion from a 4D vector.

§Preconditions

This function does not check if the input is normalized, it is up to the user to provide normalized input or to normalized the resulting quaternion.

source

pub fn from_slice(slice: &[f32]) -> Quat

Creates a rotation quaternion from a slice.

§Preconditions

This function does not check if the input is normalized, it is up to the user to provide normalized input or to normalized the resulting quaternion.

§Panics

Panics if slice length is less than 4.

source

pub fn write_to_slice(self, slice: &mut [f32])

Writes the quaternion to an unaligned slice.

§Panics

Panics if slice length is less than 4.

source

pub fn from_axis_angle(axis: Vec3, angle: f32) -> Quat

Create a quaternion for a normalized rotation axis and angle (in radians).

The axis must be a unit vector.

§Panics

Will panic if axis is not normalized when glam_assert is enabled.

Examples found in repository?
examples/ui/overflow_debug.rs (line 71)
70
71
72
    fn update(&self, t: f32, transform: &mut Transform) {
        transform.rotation = Quat::from_axis_angle(Vec3::Z, ((t * TAU).cos() * 45.0).to_radians());
    }
More examples
Hide additional examples
examples/gizmos/axes.rs (line 199)
195
196
197
198
199
200
fn random_rotation(rng: &mut impl Rng) -> Quat {
    let dir = random_direction(rng);
    let angle = rng.gen::<f32>() * 2. * PI;

    Quat::from_axis_angle(dir, angle)
}
examples/shader/shader_material_screenspace_texture.rs (line 66)
61
62
63
64
65
66
67
68
69
fn rotate_camera(mut camera: Query<&mut Transform, With<MainCamera>>, time: Res<Time>) {
    let cam_transform = camera.single_mut().into_inner();

    cam_transform.rotate_around(
        Vec3::ZERO,
        Quat::from_axis_angle(Vec3::Y, 45f32.to_radians() * time.delta_seconds()),
    );
    cam_transform.look_at(Vec3::ZERO, Vec3::Y);
}
examples/3d/split_screen.rs (line 205)
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
fn button_system(
    interaction_query: Query<
        (&Interaction, &TargetCamera, &RotateCamera),
        (Changed<Interaction>, With<Button>),
    >,
    mut camera_query: Query<&mut Transform, With<Camera>>,
) {
    for (interaction, target_camera, RotateCamera(direction)) in &interaction_query {
        if let Interaction::Pressed = *interaction {
            // Since TargetCamera propagates to the children, we can use it to find
            // which side of the screen the button is on.
            if let Ok(mut camera_transform) = camera_query.get_mut(target_camera.entity()) {
                let angle = match direction {
                    Direction::Left => -0.1,
                    Direction::Right => 0.1,
                };
                camera_transform.rotate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, angle));
            }
        }
    }
}
examples/3d/ssr.rs (line 343)
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
fn move_camera(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut mouse_wheel_input: EventReader<MouseWheel>,
    mut cameras: Query<&mut Transform, With<Camera>>,
) {
    let (mut distance_delta, mut theta_delta) = (0.0, 0.0);

    // Handle keyboard events.
    if keyboard_input.pressed(KeyCode::KeyW) {
        distance_delta -= CAMERA_KEYBOARD_ZOOM_SPEED;
    }
    if keyboard_input.pressed(KeyCode::KeyS) {
        distance_delta += CAMERA_KEYBOARD_ZOOM_SPEED;
    }
    if keyboard_input.pressed(KeyCode::KeyA) {
        theta_delta += CAMERA_KEYBOARD_ORBIT_SPEED;
    }
    if keyboard_input.pressed(KeyCode::KeyD) {
        theta_delta -= CAMERA_KEYBOARD_ORBIT_SPEED;
    }

    // Handle mouse events.
    for mouse_wheel_event in mouse_wheel_input.read() {
        distance_delta -= mouse_wheel_event.y * CAMERA_MOUSE_WHEEL_ZOOM_SPEED;
    }

    // Update transforms.
    for mut camera_transform in cameras.iter_mut() {
        let local_z = camera_transform.local_z().as_vec3().normalize_or_zero();
        if distance_delta != 0.0 {
            camera_transform.translation = (camera_transform.translation.length() + distance_delta)
                .clamp(CAMERA_ZOOM_RANGE.start, CAMERA_ZOOM_RANGE.end)
                * local_z;
        }
        if theta_delta != 0.0 {
            camera_transform
                .translate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, theta_delta));
            camera_transform.look_at(Vec3::ZERO, Vec3::Y);
        }
    }
}
examples/animation/animated_transform.rs (line 79)
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut animations: ResMut<Assets<AnimationClip>>,
    mut graphs: ResMut<Assets<AnimationGraph>>,
) {
    // Camera
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
        ..default()
    });

    // Light
    commands.spawn(PointLightBundle {
        point_light: PointLight {
            intensity: 500_000.0,
            ..default()
        },
        transform: Transform::from_xyz(0.0, 2.5, 0.0),
        ..default()
    });

    // Let's use the `Name` component to target entities. We can use anything we
    // like, but names are convenient.
    let planet = Name::new("planet");
    let orbit_controller = Name::new("orbit_controller");
    let satellite = Name::new("satellite");

    // Creating the animation
    let mut animation = AnimationClip::default();
    // A curve can modify a single part of a transform, here the translation
    let planet_animation_target_id = AnimationTargetId::from_name(&planet);
    animation.add_curve_to_target(
        planet_animation_target_id,
        VariableCurve {
            keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
            keyframes: Keyframes::Translation(vec![
                Vec3::new(1.0, 0.0, 1.0),
                Vec3::new(-1.0, 0.0, 1.0),
                Vec3::new(-1.0, 0.0, -1.0),
                Vec3::new(1.0, 0.0, -1.0),
                // in case seamless looping is wanted, the last keyframe should
                // be the same as the first one
                Vec3::new(1.0, 0.0, 1.0),
            ]),
            interpolation: Interpolation::Linear,
        },
    );
    // Or it can modify the rotation of the transform.
    // To find the entity to modify, the hierarchy will be traversed looking for
    // an entity with the right name at each level
    let orbit_controller_animation_target_id =
        AnimationTargetId::from_names([planet.clone(), orbit_controller.clone()].iter());
    animation.add_curve_to_target(
        orbit_controller_animation_target_id,
        VariableCurve {
            keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
            keyframes: Keyframes::Rotation(vec![
                Quat::IDENTITY,
                Quat::from_axis_angle(Vec3::Y, PI / 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
                Quat::IDENTITY,
            ]),
            interpolation: Interpolation::Linear,
        },
    );
    // If a curve in an animation is shorter than the other, it will not repeat
    // until all other curves are finished. In that case, another animation should
    // be created for each part that would have a different duration / period
    let satellite_animation_target_id = AnimationTargetId::from_names(
        [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
    );
    animation.add_curve_to_target(
        satellite_animation_target_id,
        VariableCurve {
            keyframe_timestamps: vec![0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],
            keyframes: Keyframes::Scale(vec![
                Vec3::splat(0.8),
                Vec3::splat(1.2),
                Vec3::splat(0.8),
                Vec3::splat(1.2),
                Vec3::splat(0.8),
                Vec3::splat(1.2),
                Vec3::splat(0.8),
                Vec3::splat(1.2),
                Vec3::splat(0.8),
            ]),
            interpolation: Interpolation::Linear,
        },
    );
    // There can be more than one curve targeting the same entity path
    animation.add_curve_to_target(
        AnimationTargetId::from_names(
            [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
        ),
        VariableCurve {
            keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
            keyframes: Keyframes::Rotation(vec![
                Quat::IDENTITY,
                Quat::from_axis_angle(Vec3::Y, PI / 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
                Quat::IDENTITY,
            ]),
            interpolation: Interpolation::Linear,
        },
    );

    // Create the animation graph
    let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));

    // Create the animation player, and set it to repeat
    let mut player = AnimationPlayer::default();
    player.play(animation_index).repeat();

    // Create the scene that will be animated
    // First entity is the planet
    let planet_entity = commands
        .spawn((
            PbrBundle {
                mesh: meshes.add(Sphere::default()),
                material: materials.add(Color::srgb(0.8, 0.7, 0.6)),
                ..default()
            },
            // Add the animation graph and player
            planet,
            graphs.add(graph),
            player,
        ))
        .id();
    commands
        .entity(planet_entity)
        .insert(AnimationTarget {
            id: planet_animation_target_id,
            player: planet_entity,
        })
        .with_children(|p| {
            // This entity is just used for animation, but doesn't display anything
            p.spawn((
                SpatialBundle::INHERITED_IDENTITY,
                orbit_controller,
                AnimationTarget {
                    id: orbit_controller_animation_target_id,
                    player: planet_entity,
                },
            ))
            .with_children(|p| {
                // The satellite, placed at a distance of the planet
                p.spawn((
                    PbrBundle {
                        transform: Transform::from_xyz(1.5, 0.0, 0.0),
                        mesh: meshes.add(Cuboid::new(0.5, 0.5, 0.5)),
                        material: materials.add(Color::srgb(0.3, 0.9, 0.3)),
                        ..default()
                    },
                    AnimationTarget {
                        id: satellite_animation_target_id,
                        player: planet_entity,
                    },
                    satellite,
                ));
            });
        });
}
source

pub fn from_scaled_axis(v: Vec3) -> Quat

Create a quaternion that rotates v.length() radians around v.normalize().

from_scaled_axis(Vec3::ZERO) results in the identity quaternion.

source

pub fn from_rotation_x(angle: f32) -> Quat

Creates a quaternion from the angle (in radians) around the x axis.

Examples found in repository?
examples/math/sampling_primitives.rs (line 690)
687
688
689
690
691
692
693
694
fn update_camera(mut camera: Query<(&mut Transform, &CameraRig), Changed<CameraRig>>) {
    for (mut transform, rig) in camera.iter_mut() {
        let looking_direction =
            Quat::from_rotation_y(-rig.yaw) * Quat::from_rotation_x(rig.pitch) * Vec3::Z;
        transform.translation = rig.target - rig.distance * looking_direction;
        transform.look_at(rig.target, Dir3::Y);
    }
}
More examples
Hide additional examples
examples/3d/3d_scene.rs (line 22)
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
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    // circular base
    commands.spawn(PbrBundle {
        mesh: meshes.add(Circle::new(4.0)),
        material: materials.add(Color::WHITE),
        transform: Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
        ..default()
    });
    // cube
    commands.spawn(PbrBundle {
        mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
        material: materials.add(Color::srgb_u8(124, 144, 255)),
        transform: Transform::from_xyz(0.0, 0.5, 0.0),
        ..default()
    });
    // light
    commands.spawn(PointLightBundle {
        point_light: PointLight {
            shadows_enabled: true,
            ..default()
        },
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..default()
    });
    // camera
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
        ..default()
    });
}
examples/animation/animation_graph.rs (line 249)
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
fn setup_scene(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(-10.0, 5.0, 13.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
        ..default()
    });

    commands.spawn(PointLightBundle {
        point_light: PointLight {
            intensity: 10_000_000.0,
            shadows_enabled: true,
            ..default()
        },
        transform: Transform::from_xyz(-4.0, 8.0, 13.0),
        ..default()
    });

    commands.spawn(SceneBundle {
        scene: asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")),
        transform: Transform::from_scale(Vec3::splat(0.07)),
        ..default()
    });

    // Ground

    commands.spawn(PbrBundle {
        mesh: meshes.add(Circle::new(7.0)),
        material: materials.add(Color::srgb(0.3, 0.5, 0.3)),
        transform: Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
        ..default()
    });
}
examples/3d/skybox.rs (line 69)
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
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // directional 'sun' light
    commands.spawn(DirectionalLightBundle {
        directional_light: DirectionalLight {
            illuminance: 32000.0,
            ..default()
        },
        transform: Transform::from_xyz(0.0, 2.0, 0.0)
            .with_rotation(Quat::from_rotation_x(-PI / 4.)),
        ..default()
    });

    let skybox_handle = asset_server.load(CUBEMAPS[0].0);
    // camera
    commands.spawn((
        Camera3dBundle {
            transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
            ..default()
        },
        CameraController::default(),
        Skybox {
            image: skybox_handle.clone(),
            brightness: 1000.0,
        },
    ));

    // ambient light
    // NOTE: The ambient light is used to scale how bright the environment map is so with a bright
    // environment map, use an appropriate color and brightness to match
    commands.insert_resource(AmbientLight {
        color: Color::srgb_u8(210, 220, 240),
        brightness: 1.0,
    });

    commands.insert_resource(Cubemap {
        is_loaded: false,
        index: 0,
        image_handle: skybox_handle,
    });
}
examples/gizmos/3d_gizmos.rs (line 88)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
fn draw_example_collection(
    mut gizmos: Gizmos,
    mut my_gizmos: Gizmos<MyRoundGizmos>,
    time: Res<Time>,
) {
    gizmos.grid(
        Vec3::ZERO,
        Quat::from_rotation_x(PI / 2.),
        UVec2::splat(20),
        Vec2::new(2., 2.),
        // Light gray
        LinearRgba::gray(0.65),
    );

    gizmos.cuboid(
        Transform::from_translation(Vec3::Y * 0.5).with_scale(Vec3::splat(1.25)),
        BLACK,
    );
    gizmos.rect(
        Vec3::new(time.elapsed_seconds().cos() * 2.5, 1., 0.),
        Quat::from_rotation_y(PI / 2.),
        Vec2::splat(2.),
        LIME,
    );

    gizmos.cross(Vec3::new(-1., 1., 1.), Quat::IDENTITY, 0.5, FUCHSIA);

    my_gizmos.sphere(Vec3::new(1., 0.5, 0.), Quat::IDENTITY, 0.5, RED);

    my_gizmos
        .rounded_cuboid(
            Vec3::new(-2.0, 0.75, -0.75),
            Quat::IDENTITY,
            Vec3::splat(0.9),
            TURQUOISE,
        )
        .edge_radius(0.1)
        .arc_resolution(4);

    for y in [0., 0.5, 1.] {
        gizmos.ray(
            Vec3::new(1., y, 0.),
            Vec3::new(-3., (time.elapsed_seconds() * 3.).sin(), 0.),
            BLUE,
        );
    }

    my_gizmos
        .arc_3d(
            180.0_f32.to_radians(),
            0.2,
            Vec3::ONE,
            Quat::from_rotation_arc(Vec3::Y, Vec3::ONE.normalize()),
            ORANGE,
        )
        .resolution(10);

    // Circles have 32 line-segments by default.
    my_gizmos.circle(Vec3::ZERO, Dir3::Y, 3., BLACK);
    // You may want to increase this for larger circles or spheres.
    my_gizmos
        .circle(Vec3::ZERO, Dir3::Y, 3.1, NAVY)
        .resolution(64);
    my_gizmos
        .sphere(Vec3::ZERO, Quat::IDENTITY, 3.2, BLACK)
        .resolution(64);

    gizmos.arrow(Vec3::ZERO, Vec3::ONE * 1.5, YELLOW);

    // You can create more complex arrows using the arrow builder.
    gizmos
        .arrow(Vec3::new(2., 0., 2.), Vec3::new(2., 2., 2.), ORANGE_RED)
        .with_double_end()
        .with_tip_length(0.5);
}
examples/app/headless_renderer.rs (line 166)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
    mut scene_controller: ResMut<SceneController>,
    render_device: Res<RenderDevice>,
) {
    let render_target = setup_render_target(
        &mut commands,
        &mut images,
        &render_device,
        &mut scene_controller,
        // pre_roll_frames should be big enough for full scene render,
        // but the bigger it is, the longer example will run.
        // To visualize stages of scene rendering change this param to 0
        // and change AppConfig::single_image to false in main
        // Stages are:
        // 1. Transparent image
        // 2. Few black box images
        // 3. Fully rendered scene images
        // Exact number depends on device speed, device load and scene size
        40,
        "main_scene".into(),
    );

    // Scene example for non black box picture
    // circular base
    commands.spawn(PbrBundle {
        mesh: meshes.add(Circle::new(4.0)),
        material: materials.add(Color::WHITE),
        transform: Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
        ..default()
    });
    // cube
    commands.spawn(PbrBundle {
        mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
        material: materials.add(Color::srgb_u8(124, 144, 255)),
        transform: Transform::from_xyz(0.0, 0.5, 0.0),
        ..default()
    });
    // light
    commands.spawn(PointLightBundle {
        point_light: PointLight {
            shadows_enabled: true,
            ..default()
        },
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..default()
    });

    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
        tonemapping: Tonemapping::None,
        camera: Camera {
            // render to image
            target: render_target,
            ..default()
        },
        ..default()
    });
}
source

pub fn from_rotation_y(angle: f32) -> Quat

Creates a quaternion from the angle (in radians) around the y axis.

Examples found in repository?
examples/gizmos/3d_gizmos.rs (line 78)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
fn rotate_camera(mut query: Query<&mut Transform, With<Camera>>, time: Res<Time>) {
    let mut transform = query.single_mut();

    transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_seconds() / 2.));
}

fn draw_example_collection(
    mut gizmos: Gizmos,
    mut my_gizmos: Gizmos<MyRoundGizmos>,
    time: Res<Time>,
) {
    gizmos.grid(
        Vec3::ZERO,
        Quat::from_rotation_x(PI / 2.),
        UVec2::splat(20),
        Vec2::new(2., 2.),
        // Light gray
        LinearRgba::gray(0.65),
    );

    gizmos.cuboid(
        Transform::from_translation(Vec3::Y * 0.5).with_scale(Vec3::splat(1.25)),
        BLACK,
    );
    gizmos.rect(
        Vec3::new(time.elapsed_seconds().cos() * 2.5, 1., 0.),
        Quat::from_rotation_y(PI / 2.),
        Vec2::splat(2.),
        LIME,
    );

    gizmos.cross(Vec3::new(-1., 1., 1.), Quat::IDENTITY, 0.5, FUCHSIA);

    my_gizmos.sphere(Vec3::new(1., 0.5, 0.), Quat::IDENTITY, 0.5, RED);

    my_gizmos
        .rounded_cuboid(
            Vec3::new(-2.0, 0.75, -0.75),
            Quat::IDENTITY,
            Vec3::splat(0.9),
            TURQUOISE,
        )
        .edge_radius(0.1)
        .arc_resolution(4);

    for y in [0., 0.5, 1.] {
        gizmos.ray(
            Vec3::new(1., y, 0.),
            Vec3::new(-3., (time.elapsed_seconds() * 3.).sin(), 0.),
            BLUE,
        );
    }

    my_gizmos
        .arc_3d(
            180.0_f32.to_radians(),
            0.2,
            Vec3::ONE,
            Quat::from_rotation_arc(Vec3::Y, Vec3::ONE.normalize()),
            ORANGE,
        )
        .resolution(10);

    // Circles have 32 line-segments by default.
    my_gizmos.circle(Vec3::ZERO, Dir3::Y, 3., BLACK);
    // You may want to increase this for larger circles or spheres.
    my_gizmos
        .circle(Vec3::ZERO, Dir3::Y, 3.1, NAVY)
        .resolution(64);
    my_gizmos
        .sphere(Vec3::ZERO, Quat::IDENTITY, 3.2, BLACK)
        .resolution(64);

    gizmos.arrow(Vec3::ZERO, Vec3::ONE * 1.5, YELLOW);

    // You can create more complex arrows using the arrow builder.
    gizmos
        .arrow(Vec3::new(2., 0., 2.), Vec3::new(2., 2., 2.), ORANGE_RED)
        .with_double_end()
        .with_tip_length(0.5);
}
More examples
Hide additional examples
examples/gizmos/light_gizmos.rs (line 151)
148
149
150
151
152
fn rotate_camera(mut query: Query<&mut Transform, With<Camera>>, time: Res<Time>) {
    let mut transform = query.single_mut();

    transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_seconds() / 2.));
}
examples/3d/clearcoat.rs (line 271)
268
269
270
271
272
273
fn animate_spheres(mut spheres: Query<&mut Transform, With<ExampleSphere>>, time: Res<Time>) {
    let now = time.elapsed_seconds();
    for mut transform in spheres.iter_mut() {
        transform.rotation = Quat::from_rotation_y(SPHERE_ROTATION_SPEED * now);
    }
}
examples/math/sampling_primitives.rs (line 690)
687
688
689
690
691
692
693
694
fn update_camera(mut camera: Query<(&mut Transform, &CameraRig), Changed<CameraRig>>) {
    for (mut transform, rig) in camera.iter_mut() {
        let looking_direction =
            Quat::from_rotation_y(-rig.yaw) * Quat::from_rotation_x(rig.pitch) * Vec3::Z;
        transform.translation = rig.target - rig.distance * looking_direction;
        transform.look_at(rig.target, Dir3::Y);
    }
}
examples/3d/spotlight.rs (line 209)
200
201
202
203
204
205
206
207
208
209
210
211
212
213
fn rotation(
    mut query: Query<&mut Transform, With<Camera>>,
    input: Res<ButtonInput<KeyCode>>,
    time: Res<Time>,
) {
    let mut transform = query.single_mut();
    let delta = time.delta_seconds();

    if input.pressed(KeyCode::ArrowLeft) {
        transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(delta));
    } else if input.pressed(KeyCode::ArrowRight) {
        transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(-delta));
    }
}
examples/3d/anisotropy.rs (line 154)
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
fn rotate_camera(
    mut camera: Query<&mut Transform, With<Camera>>,
    app_status: Res<AppStatus>,
    time: Res<Time>,
    mut stopwatch: Local<Stopwatch>,
) {
    if app_status.light_mode == LightMode::EnvironmentMap {
        stopwatch.tick(time.delta());
    }

    let now = stopwatch.elapsed_secs();
    for mut transform in camera.iter_mut() {
        *transform = Transform::from_translation(
            Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
        )
        .looking_at(Vec3::ZERO, Vec3::Y);
    }
}
source

pub fn from_rotation_z(angle: f32) -> Quat

Creates a quaternion from the angle (in radians) around the z axis.

Examples found in repository?
examples/tools/gamepad_viewer.rs (line 105)
104
105
106
107
    pub fn with_rotation(mut self, angle: f32) -> Self {
        self.mesh_bundle.transform.rotation = Quat::from_rotation_z(angle);
        self
    }
More examples
Hide additional examples
examples/2d/bounding_2d.rs (line 37)
35
36
37
38
39
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
    for mut transform in query.iter_mut() {
        transform.rotation *= Quat::from_rotation_z(time.delta_seconds() / 5.);
    }
}
examples/animation/custom_skinned_mesh.rs (line 170)
168
169
170
171
172
fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) {
    for mut transform in &mut query {
        transform.rotation = Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
    }
}
examples/2d/text2d.rs (line 181)
176
177
178
179
180
181
182
183
fn animate_rotation(
    time: Res<Time>,
    mut query: Query<&mut Transform, (With<Text>, With<AnimateRotation>)>,
) {
    for mut transform in &mut query {
        transform.rotation = Quat::from_rotation_z(time.elapsed_seconds().cos());
    }
}
examples/shader/shader_prepass.rs (line 193)
190
191
192
193
194
195
fn rotate(mut q: Query<&mut Transform, With<Rotates>>, time: Res<Time>) {
    for mut t in q.iter_mut() {
        let rot = (time.elapsed_seconds().sin() * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
        t.rotation = Quat::from_rotation_z(rot);
    }
}
examples/math/custom_primitives.rs (line 189)
185
186
187
188
189
190
191
fn rotate_2d_shapes(mut shapes: Query<&mut Transform, With<Shape2d>>, time: Res<Time>) {
    let elapsed_seconds = time.elapsed_seconds();

    for mut transform in shapes.iter_mut() {
        transform.rotation = Quat::from_rotation_z(elapsed_seconds);
    }
}
source

pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Quat

Creates a quaternion from the given Euler rotation sequence and the angles (in radians).

Examples found in repository?
examples/3d/ssr.rs (line 302)
297
298
299
300
301
302
303
304
fn rotate_model(
    mut query: Query<&mut Transform, Or<(With<CubeModel>, With<FlightHelmetModel>)>>,
    time: Res<Time>,
) {
    for mut transform in query.iter_mut() {
        transform.rotation = Quat::from_euler(EulerRot::XYZ, 0.0, time.elapsed_seconds(), 0.0);
    }
}
More examples
Hide additional examples
examples/3d/load_gltf.rs (lines 61-66)
56
57
58
59
60
61
62
63
64
65
66
67
68
fn animate_light_direction(
    time: Res<Time>,
    mut query: Query<&mut Transform, With<DirectionalLight>>,
) {
    for mut transform in &mut query {
        transform.rotation = Quat::from_euler(
            EulerRot::ZYX,
            0.0,
            time.elapsed_seconds() * PI / 5.0,
            -FRAC_PI_4,
        );
    }
}
examples/3d/spotlight.rs (lines 151-156)
149
150
151
152
153
154
155
156
157
158
159
160
161
fn light_sway(time: Res<Time>, mut query: Query<(&mut Transform, &mut SpotLight)>) {
    for (mut transform, mut angles) in query.iter_mut() {
        transform.rotation = Quat::from_euler(
            EulerRot::XYZ,
            -FRAC_PI_2 + (time.elapsed_seconds() * 0.67 * 3.0).sin() * 0.5,
            (time.elapsed_seconds() * 3.0).sin() * 0.5,
            0.0,
        );
        let angle = ((time.elapsed_seconds() * 1.2).sin() + 1.0) * (FRAC_PI_4 - 0.1);
        angles.inner_angle = angle * 0.8;
        angles.outer_angle = angle;
    }
}
examples/tools/scene_viewer/scene_viewer_plugin.rs (lines 160-165)
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
fn update_lights(
    key_input: Res<ButtonInput<KeyCode>>,
    time: Res<Time>,
    mut query: Query<(&mut Transform, &mut DirectionalLight)>,
    mut animate_directional_light: Local<bool>,
) {
    for (_, mut light) in &mut query {
        if key_input.just_pressed(KeyCode::KeyU) {
            light.shadows_enabled = !light.shadows_enabled;
        }
    }

    if key_input.just_pressed(KeyCode::KeyL) {
        *animate_directional_light = !*animate_directional_light;
    }
    if *animate_directional_light {
        for (mut transform, _) in &mut query {
            transform.rotation = Quat::from_euler(
                EulerRot::ZYX,
                0.0,
                time.elapsed_seconds() * PI / 15.0,
                -FRAC_PI_4,
            );
        }
    }
}
examples/asset/multi_asset_sync.rs (line 217)
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
fn setup_scene(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    // Camera
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(10.0, 10.0, 15.0)
            .looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
        ..default()
    });

    // Light
    commands.spawn(DirectionalLightBundle {
        transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
        directional_light: DirectionalLight {
            shadows_enabled: true,
            ..default()
        },
        ..default()
    });

    // Plane
    commands.spawn((
        PbrBundle {
            mesh: meshes.add(Plane3d::default().mesh().size(50000.0, 50000.0)),
            material: materials.add(Color::srgb(0.7, 0.2, 0.2)),
            ..default()
        },
        Loading,
    ));
}
examples/3d/volumetric_fog.rs (line 116)
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
fn move_directional_light(
    input: Res<ButtonInput<KeyCode>>,
    mut directional_lights: Query<&mut Transform, With<DirectionalLight>>,
) {
    let mut delta_theta = Vec2::ZERO;
    if input.pressed(KeyCode::KeyW) || input.pressed(KeyCode::ArrowUp) {
        delta_theta.y += DIRECTIONAL_LIGHT_MOVEMENT_SPEED;
    }
    if input.pressed(KeyCode::KeyS) || input.pressed(KeyCode::ArrowDown) {
        delta_theta.y -= DIRECTIONAL_LIGHT_MOVEMENT_SPEED;
    }
    if input.pressed(KeyCode::KeyA) || input.pressed(KeyCode::ArrowLeft) {
        delta_theta.x += DIRECTIONAL_LIGHT_MOVEMENT_SPEED;
    }
    if input.pressed(KeyCode::KeyD) || input.pressed(KeyCode::ArrowRight) {
        delta_theta.x -= DIRECTIONAL_LIGHT_MOVEMENT_SPEED;
    }

    if delta_theta == Vec2::ZERO {
        return;
    }

    let delta_quat = Quat::from_euler(EulerRot::XZY, delta_theta.y, 0.0, delta_theta.x);
    for mut transform in directional_lights.iter_mut() {
        transform.rotate(delta_quat);
    }
}
source

pub fn from_mat3(mat: &Mat3) -> Quat

Creates a quaternion from a 3x3 rotation matrix.

Examples found in repository?
examples/math/render_primitives.rs (line 617)
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
fn rotate_primitive_2d_meshes(
    mut primitives_2d: Query<
        (&mut Transform, &ViewVisibility),
        (With<PrimitiveData>, With<MeshDim2>),
    >,
    time: Res<Time>,
) {
    let rotation_2d = Quat::from_mat3(&Mat3::from_angle(time.elapsed_seconds()));
    primitives_2d
        .iter_mut()
        .filter(|(_, vis)| vis.get())
        .for_each(|(mut transform, _)| {
            transform.rotation = rotation_2d;
        });
}
source

pub fn from_mat3a(mat: &Mat3A) -> Quat

Creates a quaternion from a 3x3 SIMD aligned rotation matrix.

source

pub fn from_mat4(mat: &Mat4) -> Quat

Creates a quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix.

source

pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Quat

Gets the minimal rotation for transforming from to to. The rotation is in the plane spanned by the two vectors. Will rotate at most 180 degrees.

The inputs must be unit vectors.

from_rotation_arc(from, to) * from ≈ to.

For near-singular cases (from≈to and from≈-to) the current implementation is only accurate to about 0.001 (for f32).

§Panics

Will panic if from or to are not normalized when glam_assert is enabled.

Examples found in repository?
examples/math/render_primitives.rs (lines 633-642)
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
fn rotate_primitive_3d_meshes(
    mut primitives_3d: Query<
        (&mut Transform, &ViewVisibility),
        (With<PrimitiveData>, With<MeshDim3>),
    >,
    time: Res<Time>,
) {
    let rotation_3d = Quat::from_rotation_arc(
        Vec3::Z,
        Vec3::new(
            time.elapsed_seconds().sin(),
            time.elapsed_seconds().cos(),
            time.elapsed_seconds().sin() * 0.5,
        )
        .try_normalize()
        .unwrap_or(Vec3::Z),
    );
    primitives_3d
        .iter_mut()
        .filter(|(_, vis)| vis.get())
        .for_each(|(mut transform, _)| {
            transform.rotation = rotation_3d;
        });
}

fn draw_gizmos_3d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time: Res<Time>) {
    const POSITION: Vec3 = Vec3::new(LEFT_RIGHT_OFFSET_3D, 0.0, 0.0);
    let rotation = Quat::from_rotation_arc(
        Vec3::Z,
        Vec3::new(
            time.elapsed_seconds().sin(),
            time.elapsed_seconds().cos(),
            time.elapsed_seconds().sin() * 0.5,
        )
        .try_normalize()
        .unwrap_or(Vec3::Z),
    );
    let color = Color::WHITE;
    let resolution = 10;

    match state.get() {
        PrimitiveSelected::RectangleAndCuboid => {
            gizmos.primitive_3d(&CUBOID, POSITION, rotation, color);
        }
        PrimitiveSelected::CircleAndSphere => drop(
            gizmos
                .primitive_3d(&SPHERE, POSITION, rotation, color)
                .resolution(resolution),
        ),
        PrimitiveSelected::Ellipse => {}
        PrimitiveSelected::Triangle => gizmos.primitive_3d(&TRIANGLE_3D, POSITION, rotation, color),
        PrimitiveSelected::Plane => drop(gizmos.primitive_3d(&PLANE_3D, POSITION, rotation, color)),
        PrimitiveSelected::Line => gizmos.primitive_3d(&LINE3D, POSITION, rotation, color),
        PrimitiveSelected::Segment => gizmos.primitive_3d(&SEGMENT_3D, POSITION, rotation, color),
        PrimitiveSelected::Polyline => gizmos.primitive_3d(&POLYLINE_3D, POSITION, rotation, color),
        PrimitiveSelected::Polygon => {}
        PrimitiveSelected::RegularPolygon => {}
        PrimitiveSelected::Capsule => drop(
            gizmos
                .primitive_3d(&CAPSULE_3D, POSITION, rotation, color)
                .resolution(resolution),
        ),
        PrimitiveSelected::Cylinder => drop(
            gizmos
                .primitive_3d(&CYLINDER, POSITION, rotation, color)
                .resolution(resolution),
        ),
        PrimitiveSelected::Cone => drop(
            gizmos
                .primitive_3d(&CONE, POSITION, rotation, color)
                .resolution(resolution),
        ),
        PrimitiveSelected::ConicalFrustum => {
            gizmos.primitive_3d(&CONICAL_FRUSTUM, POSITION, rotation, color);
        }

        PrimitiveSelected::Torus => drop(
            gizmos
                .primitive_3d(&TORUS, POSITION, rotation, color)
                .minor_resolution(resolution)
                .major_resolution(resolution),
        ),
        PrimitiveSelected::Tetrahedron => {
            gizmos.primitive_3d(&TETRAHEDRON, POSITION, rotation, color);
        }

        PrimitiveSelected::Arc => {}
        PrimitiveSelected::CircularSector => {}
        PrimitiveSelected::CircularSegment => {}
    }
}
More examples
Hide additional examples
examples/2d/rotation.rs (line 173)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
fn snap_to_player_system(
    mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,
    player_query: Query<&Transform, With<Player>>,
) {
    let player_transform = player_query.single();
    // get the player translation in 2D
    let player_translation = player_transform.translation.xy();

    for mut enemy_transform in &mut query {
        // get the vector from the enemy ship to the player ship in 2D and normalize it.
        let to_player = (player_translation - enemy_transform.translation.xy()).normalize();

        // get the quaternion to rotate from the initial enemy facing direction to the direction
        // facing the player
        let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));

        // rotate the enemy to face the player
        enemy_transform.rotation = rotate_to_player;
    }
}
examples/gizmos/3d_gizmos.rs (line 133)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
fn draw_example_collection(
    mut gizmos: Gizmos,
    mut my_gizmos: Gizmos<MyRoundGizmos>,
    time: Res<Time>,
) {
    gizmos.grid(
        Vec3::ZERO,
        Quat::from_rotation_x(PI / 2.),
        UVec2::splat(20),
        Vec2::new(2., 2.),
        // Light gray
        LinearRgba::gray(0.65),
    );

    gizmos.cuboid(
        Transform::from_translation(Vec3::Y * 0.5).with_scale(Vec3::splat(1.25)),
        BLACK,
    );
    gizmos.rect(
        Vec3::new(time.elapsed_seconds().cos() * 2.5, 1., 0.),
        Quat::from_rotation_y(PI / 2.),
        Vec2::splat(2.),
        LIME,
    );

    gizmos.cross(Vec3::new(-1., 1., 1.), Quat::IDENTITY, 0.5, FUCHSIA);

    my_gizmos.sphere(Vec3::new(1., 0.5, 0.), Quat::IDENTITY, 0.5, RED);

    my_gizmos
        .rounded_cuboid(
            Vec3::new(-2.0, 0.75, -0.75),
            Quat::IDENTITY,
            Vec3::splat(0.9),
            TURQUOISE,
        )
        .edge_radius(0.1)
        .arc_resolution(4);

    for y in [0., 0.5, 1.] {
        gizmos.ray(
            Vec3::new(1., y, 0.),
            Vec3::new(-3., (time.elapsed_seconds() * 3.).sin(), 0.),
            BLUE,
        );
    }

    my_gizmos
        .arc_3d(
            180.0_f32.to_radians(),
            0.2,
            Vec3::ONE,
            Quat::from_rotation_arc(Vec3::Y, Vec3::ONE.normalize()),
            ORANGE,
        )
        .resolution(10);

    // Circles have 32 line-segments by default.
    my_gizmos.circle(Vec3::ZERO, Dir3::Y, 3., BLACK);
    // You may want to increase this for larger circles or spheres.
    my_gizmos
        .circle(Vec3::ZERO, Dir3::Y, 3.1, NAVY)
        .resolution(64);
    my_gizmos
        .sphere(Vec3::ZERO, Quat::IDENTITY, 3.2, BLACK)
        .resolution(64);

    gizmos.arrow(Vec3::ZERO, Vec3::ONE * 1.5, YELLOW);

    // You can create more complex arrows using the arrow builder.
    gizmos
        .arrow(Vec3::new(2., 0., 2.), Vec3::new(2., 2., 2.), ORANGE_RED)
        .with_double_end()
        .with_tip_length(0.5);
}
source

pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Quat

Gets the minimal rotation for transforming from to either to or -to. This means that the resulting quaternion will rotate from so that it is colinear with to.

The rotation is in the plane spanned by the two vectors. Will rotate at most 90 degrees.

The inputs must be unit vectors.

to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1.

§Panics

Will panic if from or to are not normalized when glam_assert is enabled.

source

pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Quat

Gets the minimal rotation for transforming from to to. The resulting rotation is around the z axis. Will rotate at most 180 degrees.

The inputs must be unit vectors.

from_rotation_arc_2d(from, to) * from ≈ to.

For near-singular cases (from≈to and from≈-to) the current implementation is only accurate to about 0.001 (for f32).

§Panics

Will panic if from or to are not normalized when glam_assert is enabled.

source

pub fn to_axis_angle(self) -> (Vec3, f32)

Returns the rotation axis (normalized) and angle (in radians) of self.

source

pub fn to_scaled_axis(self) -> Vec3

Returns the rotation axis scaled by the rotation in radians.

Examples found in repository?
examples/math/custom_primitives.rs (line 201)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
fn bounding_shapes_2d(
    shapes: Query<&Transform, With<Shape2d>>,
    mut gizmos: Gizmos,
    bounding_shape: Res<State<BoundingShape>>,
) {
    for transform in shapes.iter() {
        // Get the rotation angle from the 3D rotation.
        let rotation = transform.rotation.to_scaled_axis().z;

        match bounding_shape.get() {
            BoundingShape::None => (),
            BoundingShape::BoundingBox => {
                // Get the AABB of the primitive with the rotation and translation of the mesh.
                let aabb = HEART.aabb_2d(transform.translation.xy(), rotation);

                gizmos.rect_2d(aabb.center(), 0., aabb.half_size() * 2., WHITE);
            }
            BoundingShape::BoundingSphere => {
                // Get the bounding sphere of the primitive with the rotation and translation of the mesh.
                let bounding_circle = HEART.bounding_circle(transform.translation.xy(), rotation);

                gizmos
                    .circle_2d(bounding_circle.center(), bounding_circle.radius(), WHITE)
                    .resolution(64);
            }
        }
    }
}
source

pub fn to_euler(self, euler: EulerRot) -> (f32, f32, f32)

Returns the rotation angles for the given euler rotation sequence.

Examples found in repository?
examples/2d/mesh2d_arcs.rs (line 116)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
fn draw_bounds<Shape: Bounded2d + Send + Sync + 'static>(
    q: Query<(&DrawBounds<Shape>, &GlobalTransform)>,
    mut gizmos: Gizmos,
) {
    for (shape, transform) in &q {
        let (_, rotation, translation) = transform.to_scale_rotation_translation();
        let translation = translation.truncate();
        let rotation = rotation.to_euler(EulerRot::XYZ).2;

        let aabb = shape.0.aabb_2d(translation, rotation);
        gizmos.rect_2d(aabb.center(), 0.0, aabb.half_size() * 2.0, RED);

        let bounding_circle = shape.0.bounding_circle(translation, rotation);
        gizmos.circle_2d(bounding_circle.center, bounding_circle.radius(), BLUE);
    }
}
More examples
Hide additional examples
examples/2d/bounding_2d.rs (line 103)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
    let color = GRAY;
    for (shape, transform) in query.iter() {
        let translation = transform.translation.xy();
        let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
        match shape {
            Shape::Rectangle(r) => {
                gizmos.primitive_2d(r, translation, rotation, color);
            }
            Shape::Circle(c) => {
                gizmos.primitive_2d(c, translation, rotation, color);
            }
            Shape::Triangle(t) => {
                gizmos.primitive_2d(t, translation, rotation, color);
            }
            Shape::Line(l) => {
                gizmos.primitive_2d(l, translation, rotation, color);
            }
            Shape::Capsule(c) => {
                gizmos.primitive_2d(c, translation, rotation, color);
            }
            Shape::Polygon(p) => {
                gizmos.primitive_2d(p, translation, rotation, color);
            }
        }
    }
}

#[derive(Component)]
enum DesiredVolume {
    Aabb,
    Circle,
}

#[derive(Component, Debug)]
enum CurrentVolume {
    Aabb(Aabb2d),
    Circle(BoundingCircle),
}

fn update_volumes(
    mut commands: Commands,
    query: Query<
        (Entity, &DesiredVolume, &Shape, &Transform),
        Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
    >,
) {
    for (entity, desired_volume, shape, transform) in query.iter() {
        let translation = transform.translation.xy();
        let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
        match desired_volume {
            DesiredVolume::Aabb => {
                let aabb = match shape {
                    Shape::Rectangle(r) => r.aabb_2d(translation, rotation),
                    Shape::Circle(c) => c.aabb_2d(translation, rotation),
                    Shape::Triangle(t) => t.aabb_2d(translation, rotation),
                    Shape::Line(l) => l.aabb_2d(translation, rotation),
                    Shape::Capsule(c) => c.aabb_2d(translation, rotation),
                    Shape::Polygon(p) => p.aabb_2d(translation, rotation),
                };
                commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
            }
            DesiredVolume::Circle => {
                let circle = match shape {
                    Shape::Rectangle(r) => r.bounding_circle(translation, rotation),
                    Shape::Circle(c) => c.bounding_circle(translation, rotation),
                    Shape::Triangle(t) => t.bounding_circle(translation, rotation),
                    Shape::Line(l) => l.bounding_circle(translation, rotation),
                    Shape::Capsule(c) => c.bounding_circle(translation, rotation),
                    Shape::Polygon(p) => p.bounding_circle(translation, rotation),
                };
                commands
                    .entity(entity)
                    .insert(CurrentVolume::Circle(circle));
            }
        }
    }
}
examples/3d/../helpers/camera_controller.rs (line 116)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
fn run_camera_controller(
    time: Res<Time>,
    mut windows: Query<&mut Window>,
    mut mouse_events: EventReader<MouseMotion>,
    mut scroll_events: EventReader<MouseWheel>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    key_input: Res<ButtonInput<KeyCode>>,
    mut toggle_cursor_grab: Local<bool>,
    mut mouse_cursor_grab: Local<bool>,
    mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
    let dt = time.delta_seconds();

    if let Ok((mut transform, mut controller)) = query.get_single_mut() {
        if !controller.initialized {
            let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
            controller.yaw = yaw;
            controller.pitch = pitch;
            controller.initialized = true;
            info!("{}", *controller);
        }
        if !controller.enabled {
            mouse_events.clear();
            return;
        }

        let mut scroll = 0.0;
        for scroll_event in scroll_events.read() {
            let amount = match scroll_event.unit {
                MouseScrollUnit::Line => scroll_event.y,
                MouseScrollUnit::Pixel => scroll_event.y / 16.0,
            };
            scroll += amount;
        }
        controller.walk_speed += scroll * controller.scroll_factor * controller.walk_speed;
        controller.run_speed = controller.walk_speed * 3.0;

        // Handle key input
        let mut axis_input = Vec3::ZERO;
        if key_input.pressed(controller.key_forward) {
            axis_input.z += 1.0;
        }
        if key_input.pressed(controller.key_back) {
            axis_input.z -= 1.0;
        }
        if key_input.pressed(controller.key_right) {
            axis_input.x += 1.0;
        }
        if key_input.pressed(controller.key_left) {
            axis_input.x -= 1.0;
        }
        if key_input.pressed(controller.key_up) {
            axis_input.y += 1.0;
        }
        if key_input.pressed(controller.key_down) {
            axis_input.y -= 1.0;
        }

        let mut cursor_grab_change = false;
        if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
            *toggle_cursor_grab = !*toggle_cursor_grab;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = true;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = false;
            cursor_grab_change = true;
        }
        let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;

        // Apply movement update
        if axis_input != Vec3::ZERO {
            let max_speed = if key_input.pressed(controller.key_run) {
                controller.run_speed
            } else {
                controller.walk_speed
            };
            controller.velocity = axis_input.normalize() * max_speed;
        } else {
            let friction = controller.friction.clamp(0.0, 1.0);
            controller.velocity *= 1.0 - friction;
            if controller.velocity.length_squared() < 1e-6 {
                controller.velocity = Vec3::ZERO;
            }
        }
        let forward = *transform.forward();
        let right = *transform.right();
        transform.translation += controller.velocity.x * dt * right
            + controller.velocity.y * dt * Vec3::Y
            + controller.velocity.z * dt * forward;

        // Handle cursor grab
        if cursor_grab_change {
            if cursor_grab {
                for mut window in &mut windows {
                    if !window.focused {
                        continue;
                    }

                    window.cursor.grab_mode = CursorGrabMode::Locked;
                    window.cursor.visible = false;
                }
            } else {
                for mut window in &mut windows {
                    window.cursor.grab_mode = CursorGrabMode::None;
                    window.cursor.visible = true;
                }
            }
        }

        // Handle mouse input
        let mut mouse_delta = Vec2::ZERO;
        if cursor_grab {
            for mouse_event in mouse_events.read() {
                mouse_delta += mouse_event.delta;
            }
        } else {
            mouse_events.clear();
        }

        if mouse_delta != Vec2::ZERO {
            // Apply look update
            controller.pitch = (controller.pitch
                - mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
                .clamp(-PI / 2., PI / 2.);
            controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
            transform.rotation =
                Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
        }
    }
}
source

pub fn to_array(&self) -> [f32; 4]

[x, y, z, w]

source

pub fn xyz(self) -> Vec3

Returns the vector part of the quaternion.

source

pub fn conjugate(self) -> Quat

Returns the quaternion conjugate of self. For a unit quaternion the conjugate is also the inverse.

source

pub fn inverse(self) -> Quat

Returns the inverse of a normalized quaternion.

Typically quaternion inverse returns the conjugate of a normalized quaternion. Because self is assumed to already be unit length this method does not normalize before returning the conjugate.

§Panics

Will panic if self is not normalized when glam_assert is enabled.

source

pub fn dot(self, rhs: Quat) -> f32

Computes the dot product of self and rhs. The dot product is equal to the cosine of the angle between two quaternion rotations.

source

pub fn length(self) -> f32

Computes the length of self.

source

pub fn length_squared(self) -> f32

Computes the squared length of self.

This is generally faster than length() as it avoids a square root operation.

source

pub fn length_recip(self) -> f32

Computes 1.0 / length().

For valid results, self must not be of length zero.

source

pub fn normalize(self) -> Quat

Returns self normalized to length 1.0.

For valid results, self must not be of length zero.

Panics

Will panic if self is zero length when glam_assert is enabled.

source

pub fn is_finite(self) -> bool

Returns true if, and only if, all elements are finite. If any element is either NaN, positive or negative infinity, this will return false.

source

pub fn is_nan(self) -> bool

source

pub fn is_normalized(self) -> bool

Returns whether self of length 1.0 or not.

Uses a precision threshold of 1e-6.

source

pub fn is_near_identity(self) -> bool

source

pub fn angle_between(self, rhs: Quat) -> f32

Returns the angle (in radians) for the minimal rotation for transforming this quaternion into another.

Both quaternions must be normalized.

§Panics

Will panic if self or rhs are not normalized when glam_assert is enabled.

source

pub fn abs_diff_eq(self, rhs: Quat, max_abs_diff: f32) -> bool

Returns true if the absolute difference of all elements between self and rhs is less than or equal to max_abs_diff.

This can be used to compare if two quaternions contain similar elements. It works best when comparing with a known value. The max_abs_diff that should be used used depends on the values being compared against.

For more see comparing floating point numbers.

source

pub fn lerp(self, end: Quat, s: f32) -> Quat

Performs a linear interpolation between self and rhs based on the value s.

When s is 0.0, the result will be equal to self. When s is 1.0, the result will be equal to rhs.

§Panics

Will panic if self or end are not normalized when glam_assert is enabled.

Examples found in repository?
examples/ecs/iter_combinations.rs (line 166)
157
158
159
160
161
162
163
164
165
166
167
168
fn look_at_star(
    mut camera: Query<&mut Transform, (With<Camera>, Without<Star>)>,
    star: Query<&Transform, With<Star>>,
) {
    let mut camera = camera.single_mut();
    let star = star.single();
    let new_rotation = camera
        .looking_at(star.translation, Vec3::Y)
        .rotation
        .lerp(camera.rotation, 0.1);
    camera.rotation = new_rotation;
}
More examples
Hide additional examples
examples/transforms/transform.rs (line 126)
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
fn rotate_cube(
    mut cubes: Query<(&mut Transform, &mut CubeState), Without<Center>>,
    center_spheres: Query<&Transform, With<Center>>,
    timer: Res<Time>,
) {
    // Calculate the point to circle around. (The position of the center_sphere)
    let mut center: Vec3 = Vec3::ZERO;
    for sphere in &center_spheres {
        center += sphere.translation;
    }
    // Update the rotation of the cube(s).
    for (mut transform, cube) in &mut cubes {
        // Calculate the rotation of the cube if it would be looking at the sphere in the center.
        let look_at_sphere = transform.looking_at(center, *transform.local_y());
        // Interpolate between the current rotation and the fully turned rotation
        // when looking a the sphere,  with a given turn speed to get a smooth motion.
        // With higher speed the curvature of the orbit would be smaller.
        let incremental_turn_weight = cube.turn_speed * timer.delta_seconds();
        let old_rotation = transform.rotation;
        transform.rotation = old_rotation.lerp(look_at_sphere.rotation, incremental_turn_weight);
    }
}
source

pub fn slerp(self, end: Quat, s: f32) -> Quat

Performs a spherical linear interpolation between self and end based on the value s.

When s is 0.0, the result will be equal to self. When s is 1.0, the result will be equal to end.

§Panics

Will panic if self or end are not normalized when glam_assert is enabled.

Examples found in repository?
examples/gizmos/axes.rs (line 220)
218
219
220
221
222
223
224
225
226
227
228
fn interpolate_transforms(t1: Transform, t2: Transform, t: f32) -> Transform {
    let translation = t1.translation.lerp(t2.translation, t);
    let rotation = t1.rotation.slerp(t2.rotation, t);
    let scale = elerp(t1.scale, t2.scale, t);

    Transform {
        translation,
        rotation,
        scale,
    }
}
More examples
Hide additional examples
examples/transforms/align.rs (line 163)
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
fn rotate_ship(mut ship: Query<(&mut Ship, &mut Transform)>) {
    let (mut ship, mut ship_transform) = ship.single_mut();

    if !ship.in_motion {
        return;
    }

    let start = ship.initial_transform.rotation;
    let end = ship.target_transform.rotation;

    let p: f32 = ship.progress.into();
    let t = p / 100.;

    *ship_transform = Transform::from_rotation(start.slerp(end, t));

    if ship.progress == 100 {
        ship.in_motion = false;
    } else {
        ship.progress += 1;
    }
}
examples/3d/parallax_mapping.rs (line 194)
183
184
185
186
187
188
189
190
191
192
193
194
195
fn move_camera(
    mut camera: Query<&mut Transform, With<CameraController>>,
    mut current_view: Local<usize>,
    button: Res<ButtonInput<MouseButton>>,
) {
    let mut camera = camera.single_mut();
    if button.just_pressed(MouseButton::Left) {
        *current_view = (*current_view + 1) % CAMERA_POSITIONS.len();
    }
    let target = CAMERA_POSITIONS[*current_view];
    camera.translation = camera.translation.lerp(target.translation, 0.2);
    camera.rotation = camera.rotation.slerp(target.rotation, 0.2);
}
source

pub fn mul_vec3(self, rhs: Vec3) -> Vec3

Multiplies a quaternion and a 3D vector, returning the rotated vector.

§Panics

Will panic if self is not normalized when glam_assert is enabled.

Examples found in repository?
examples/3d/anisotropy.rs (line 154)
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
fn rotate_camera(
    mut camera: Query<&mut Transform, With<Camera>>,
    app_status: Res<AppStatus>,
    time: Res<Time>,
    mut stopwatch: Local<Stopwatch>,
) {
    if app_status.light_mode == LightMode::EnvironmentMap {
        stopwatch.tick(time.delta());
    }

    let now = stopwatch.elapsed_secs();
    for mut transform in camera.iter_mut() {
        *transform = Transform::from_translation(
            Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
        )
        .looking_at(Vec3::ZERO, Vec3::Y);
    }
}
source

pub fn mul_quat(self, rhs: Quat) -> Quat

Multiplies two quaternions. If they each represent a rotation, the result will represent the combined rotation.

Note that due to floating point rounding the result may not be perfectly normalized.

§Panics

Will panic if self or rhs are not normalized when glam_assert is enabled.

source

pub fn from_affine3(a: &Affine3A) -> Quat

Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.

source

pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A

Multiplies a quaternion and a 3D vector, returning the rotated vector.

source

pub fn as_dquat(self) -> DQuat

source

pub fn as_f64(self) -> DQuat

👎Deprecated since 0.24.2: Use as_dquat() instead

Trait Implementations§

source§

impl Add for Quat

source§

fn add(self, rhs: Quat) -> Quat

Adds two quaternions.

The sum is not guaranteed to be normalized.

Note that addition is not the same as combining the rotations represented by the two quaternions! That corresponds to multiplication.

§

type Output = Quat

The resulting type after applying the + operator.
§

impl Animatable for Quat

§

fn interpolate(a: &Quat, b: &Quat, t: f32) -> Quat

Performs a slerp to smoothly interpolate between quaternions.

§

fn blend(inputs: impl Iterator<Item = BlendInput<Quat>>) -> Quat

Blends one or more values together. Read more
§

fn post_process(&mut self, _world: &World)

Post-processes the value using resources in the World. Most animatable types do not need to implement this.
source§

impl AsRef<[f32; 4]> for Quat

Available on non-target_arch="spirv" only.
source§

fn as_ref(&self) -> &[f32; 4]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Clone for Quat

source§

fn clone(&self) -> Quat

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 Quat

Available on non-target_arch="spirv" only.
source§

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

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

impl Default for Quat

source§

fn default() -> Quat

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

impl Deref for Quat

§

type Target = Vec4<f32>

The resulting type after dereferencing.
source§

fn deref(&self) -> &<Quat as Deref>::Target

Dereferences the value.
source§

impl DerefMut for Quat

source§

fn deref_mut(&mut self) -> &mut <Quat as Deref>::Target

Mutably dereferences the value.
source§

impl<'de> Deserialize<'de> for Quat

source§

fn deserialize<D>( deserializer: D, ) -> Result<Quat, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Quat

Available on non-target_arch="spirv" only.
source§

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

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

impl Div<f32> for Quat

source§

fn div(self, rhs: f32) -> Quat

Divides a quaternion by a scalar value. The quotient is not guaranteed to be normalized.

§

type Output = Quat

The resulting type after applying the / operator.
source§

impl From<Quat> for [f32; 4]

source§

fn from(q: Quat) -> [f32; 4]

Converts to this type from the input type.
source§

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

source§

fn from(q: Quat) -> (f32, f32, f32, f32)

Converts to this type from the input type.
source§

impl From<Quat> for Vec4

source§

fn from(q: Quat) -> Vec4

Converts to this type from the input type.
source§

impl From<Quat> for __m128

source§

fn from(q: Quat) -> __m128

Converts to this type from the input type.
§

impl FromReflect for Quat
where Quat: Any + Send + Sync, f32: FromReflect + TypePath + RegisterForReflection,

§

fn from_reflect(reflect: &(dyn Reflect + 'static)) -> Option<Quat>

Constructs a concrete instance of Self from a reflected value.
§

fn take_from_reflect( reflect: Box<dyn Reflect>, ) -> Result<Self, Box<dyn Reflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
§

impl FromRng for Quat

§

fn from_rng<R>(rng: &mut R) -> Self
where R: Rng + ?Sized,

Construct a value of this type uniformly at random using rng as the source of randomness.
§

impl GetTypeRegistration for Quat
where Quat: Any + Send + Sync, f32: FromReflect + TypePath + RegisterForReflection,

§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
§

impl Mul<Dir3> for Quat

§

fn mul(self, direction: Dir3) -> <Quat as Mul<Dir3>>::Output

Rotates the Dir3 using a Quat.

§

type Output = Dir3

The resulting type after applying the * operator.
§

impl Mul<Dir3A> for Quat

§

fn mul(self, direction: Dir3A) -> <Quat as Mul<Dir3A>>::Output

Rotates the Dir3A using a Quat.

§

type Output = Dir3A

The resulting type after applying the * operator.
source§

impl Mul<Vec3> for Quat

source§

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

Multiplies a quaternion and a 3D vector, returning the rotated vector.

§Panics

Will panic if self is not normalized when glam_assert is enabled.

§

type Output = Vec3

The resulting type after applying the * operator.
source§

impl Mul<Vec3A> for Quat

§

type Output = Vec3A

The resulting type after applying the * operator.
source§

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

Performs the * operation. Read more
source§

impl Mul<f32> for Quat

source§

fn mul(self, rhs: f32) -> Quat

Multiplies a quaternion by a scalar value.

The product is not guaranteed to be normalized.

§

type Output = Quat

The resulting type after applying the * operator.
source§

impl Mul for Quat

source§

fn mul(self, rhs: Quat) -> Quat

Multiplies two quaternions. If they each represent a rotation, the result will represent the combined rotation.

Note that due to floating point rounding the result may not be perfectly normalized.

§Panics

Will panic if self or rhs are not normalized when glam_assert is enabled.

§

type Output = Quat

The resulting type after applying the * operator.
source§

impl MulAssign for Quat

source§

fn mul_assign(&mut self, rhs: Quat)

Multiplies two quaternions. If they each represent a rotation, the result will represent the combined rotation.

Note that due to floating point rounding the result may not be perfectly normalized.

§Panics

Will panic if self or rhs are not normalized when glam_assert is enabled.

source§

impl Neg for Quat

§

type Output = Quat

The resulting type after applying the - operator.
source§

fn neg(self) -> Quat

Performs the unary - operation. Read more
source§

impl PartialEq for Quat

source§

fn eq(&self, rhs: &Quat) -> 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<'a> Product<&'a Quat> for Quat

source§

fn product<I>(iter: I) -> Quat
where I: Iterator<Item = &'a Quat>,

Method which takes an iterator and generates Self from the elements by multiplying the items.
source§

impl Product for Quat

source§

fn product<I>(iter: I) -> Quat
where I: Iterator<Item = Quat>,

Method which takes an iterator and generates Self from the elements by multiplying the items.
§

impl Reflect for Quat
where Quat: Any + Send + Sync, f32: FromReflect + TypePath + RegisterForReflection,

§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
§

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

Returns the value as a Box<dyn Any>.
§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any.
§

fn into_reflect(self: Box<Quat>) -> Box<dyn Reflect>

Casts this type to a boxed reflected value.
§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a reflected value.
§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable reflected value.
§

fn clone_value(&self) -> Box<dyn Reflect>

Clones the value as a Reflect trait object. Read more
§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
§

fn try_apply( &mut self, value: &(dyn Reflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
§

fn reflect_owned(self: Box<Quat>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
§

fn reflect_partial_eq(&self, value: &(dyn Reflect + 'static)) -> Option<bool>

Returns a “partial equality” comparison result. Read more
§

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

Debug formatter for the value. Read more
§

fn apply(&mut self, value: &(dyn Reflect + 'static))

Applies a reflected value to this value. Read more
§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
§

fn serializable(&self) -> Option<Serializable<'_>>

Returns a serializable version of the value. Read more
§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
source§

impl Serialize for Quat

source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
§

impl StableInterpolate for Quat

§

fn interpolate_stable(&self, other: &Quat, t: f32) -> Quat

Interpolate between this value and the other given value using the parameter t. At t = 0.0, a value equivalent to self is recovered, while t = 1.0 recovers a value equivalent to other, with intermediate values interpolating between the two. See the trait-level documentation for details.
§

fn interpolate_stable_assign(&mut self, other: &Self, t: f32)

A version of interpolate_stable that assigns the result to self for convenience.
§

fn smooth_nudge(&mut self, target: &Self, decay_rate: f32, delta: f32)

Smoothly nudge this value towards the target at a given decay rate. The decay_rate parameter controls how fast the distance between self and target decays relative to the units of delta; the intended usage is for decay_rate to generally remain fixed, while delta is something like delta_time from an updating system. This produces a smooth following of the target that is independent of framerate. Read more
§

impl Struct for Quat
where Quat: Any + Send + Sync, f32: FromReflect + TypePath + RegisterForReflection,

§

fn field(&self, name: &str) -> Option<&(dyn Reflect + 'static)>

Returns a reference to the value of the field named name as a &dyn Reflect.
§

fn field_mut(&mut self, name: &str) -> Option<&mut (dyn Reflect + 'static)>

Returns a mutable reference to the value of the field named name as a &mut dyn Reflect.
§

fn field_at(&self, index: usize) -> Option<&(dyn Reflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn Reflect.
§

fn field_at_mut(&mut self, index: usize) -> Option<&mut (dyn Reflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn Reflect.
§

fn name_at(&self, index: usize) -> Option<&str>

Returns the name of the field with index index.
§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
§

fn clone_dynamic(&self) -> DynamicStruct

Clones the struct into a DynamicStruct.
source§

impl Sub for Quat

source§

fn sub(self, rhs: Quat) -> Quat

Subtracts the rhs quaternion from self.

The difference is not guaranteed to be normalized.

§

type Output = Quat

The resulting type after applying the - operator.
source§

impl<'a> Sum<&'a Quat> for Quat

source§

fn sum<I>(iter: I) -> Quat
where I: Iterator<Item = &'a Quat>,

Method which takes an iterator and generates Self from the elements by “summing up” the items.
source§

impl Sum for Quat

source§

fn sum<I>(iter: I) -> Quat
where I: Iterator<Item = Quat>,

Method which takes an iterator and generates Self from the elements by “summing up” the items.
§

impl TypePath for Quat
where Quat: Any + Send + Sync,

§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
§

impl Typed for Quat
where Quat: Any + Send + Sync, f32: FromReflect + TypePath + RegisterForReflection,

§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
source§

impl Zeroable for Quat

§

fn zeroed() -> Self

source§

impl Copy for Quat

source§

impl Pod for Quat

Auto Trait Implementations§

§

impl Freeze for Quat

§

impl RefUnwindSafe for Quat

§

impl Send for Quat

§

impl Sync for Quat

§

impl Unpin for Quat

§

impl UnwindSafe for Quat

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
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
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
§

impl<T> CheckedBitPattern for T
where T: AnyBitPattern,

§

type Bits = T

Self must have the same layout as the specified Bits except for the possible invalid bit patterns being checked during is_valid_bit_pattern.
§

fn is_valid_bit_pattern(_bits: &T) -> bool

If this function returns true, then it must be valid to reinterpret bits as &Self.
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

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

§

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.
§

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.
§

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.
§

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.
§

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

§

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.
§

impl<T> DynamicTypePath for T
where T: TypePath,

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
§

impl<S> GetField for S
where S: Struct,

§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field named name, downcast to T.
§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field named name, downcast to T.
§

impl<T> GetPath for T
where T: Reflect + ?Sized,

§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
§

impl<T> Instrument for T

§

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

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

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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

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
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

§

impl<T> ToSmolStr for T
where T: Display + ?Sized,

§

fn to_smolstr(&self) -> SmolStr

source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. 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.
§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

§

fn clone_type_data(&self) -> Box<dyn TypeData>

§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> AnyBitPattern for T
where T: Pod,

§

impl<T> ConditionalSend for T
where T: Send,

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> NoUninit for T
where T: Pod,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,