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
impl Quat
Sourcepub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Quat
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?
More examples
164const CAMERA_POSITIONS: &[Transform] = &[
165 Transform {
166 translation: Vec3::new(1.5, 1.5, 1.5),
167 rotation: Quat::from_xyzw(-0.279, 0.364, 0.115, 0.880),
168 scale: Vec3::ONE,
169 },
170 Transform {
171 translation: Vec3::new(2.4, 0.0, 0.2),
172 rotation: Quat::from_xyzw(0.094, 0.676, 0.116, 0.721),
173 scale: Vec3::ONE,
174 },
175 Transform {
176 translation: Vec3::new(2.4, 2.6, -4.3),
177 rotation: Quat::from_xyzw(0.170, 0.908, 0.308, 0.225),
178 scale: Vec3::ONE,
179 },
180 Transform {
181 translation: Vec3::new(-1.0, 0.8, -1.2),
182 rotation: Quat::from_xyzw(-0.004, 0.909, 0.247, -0.335),
183 scale: Vec3::ONE,
184 },
185];
58fn setup(
59 mut commands: Commands,
60 asset_server: Res<AssetServer>,
61 args: Res<Args>,
62 #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option<
63 Res<DlssRayReconstructionSupported>,
64 >,
65) {
66 commands
67 .spawn((
68 SceneRoot(
69 asset_server.load(
70 GltfAssetLabel::Scene(0)
71 .from_asset("https://github.com/bevyengine/bevy_asset_files/raw/2a5950295a8b6d9d051d59c0df69e87abcda58c3/pica_pica/mini_diorama_01.glb")
72 ),
73 ),
74 Transform::from_scale(Vec3::splat(10.0)),
75 ))
76 .observe(add_raytracing_meshes_on_scene_load);
77
78 commands
79 .spawn((
80 SceneRoot(asset_server.load(
81 GltfAssetLabel::Scene(0).from_asset("https://github.com/bevyengine/bevy_asset_files/raw/2a5950295a8b6d9d051d59c0df69e87abcda58c3/pica_pica/robot_01.glb")
82 )),
83 Transform::from_scale(Vec3::splat(2.0))
84 .with_translation(Vec3::new(-2.0, 0.05, -2.1))
85 .with_rotation(Quat::from_rotation_y(PI / 2.0)),
86 PatrolPath {
87 path: vec![
88 (Vec3::new(-2.0, 0.05, -2.1), Quat::from_rotation_y(PI / 2.0)),
89 (Vec3::new(2.2, 0.05, -2.1), Quat::from_rotation_y(0.0)),
90 (
91 Vec3::new(2.2, 0.05, 2.1),
92 Quat::from_rotation_y(3.0 * PI / 2.0),
93 ),
94 (Vec3::new(-2.0, 0.05, 2.1), Quat::from_rotation_y(PI)),
95 ],
96 i: 0,
97 },
98 ))
99 .observe(add_raytracing_meshes_on_scene_load);
100
101 commands.spawn((
102 DirectionalLight {
103 illuminance: light_consts::lux::FULL_DAYLIGHT,
104 shadows_enabled: false, // Solari replaces shadow mapping
105 ..default()
106 },
107 Transform::from_rotation(Quat::from_xyzw(
108 -0.13334629,
109 -0.86597735,
110 -0.3586996,
111 0.3219264,
112 )),
113 ));
114
115 let mut camera = commands.spawn((
116 Camera3d::default(),
117 Camera {
118 clear_color: ClearColorConfig::Custom(Color::BLACK),
119 ..default()
120 },
121 CameraController {
122 walk_speed: 3.0,
123 run_speed: 10.0,
124 ..Default::default()
125 },
126 Transform::from_translation(Vec3::new(0.219417, 2.5764852, 6.9718704)).with_rotation(
127 Quat::from_xyzw(-0.1466768, 0.013738206, 0.002037309, 0.989087),
128 ),
129 // Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari
130 CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
131 Msaa::Off,
132 ));
133
134 if args.pathtracer == Some(true) {
135 camera.insert(Pathtracer::default());
136 } else {
137 camera.insert(SolariLighting::default());
138 }
139
140 // Using DLSS Ray Reconstruction for denoising (and cheaper rendering via upscaling) is _highly_ recommended when using Solari
141 #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
142 if dlss_rr_supported.is_some() {
143 camera.insert(Dlss::<DlssRayReconstructionFeature> {
144 perf_quality_mode: Default::default(),
145 reset: Default::default(),
146 _phantom_data: Default::default(),
147 });
148 }
149
150 commands.spawn((
151 Text::default(),
152 Node {
153 position_type: PositionType::Absolute,
154 bottom: Val::Px(12.0),
155 left: Val::Px(12.0),
156 ..default()
157 },
158 ));
159}
160
161fn add_raytracing_meshes_on_scene_load(
162 scene_ready: On<SceneInstanceReady>,
163 children: Query<&Children>,
164 mesh_query: Query<(
165 &Mesh3d,
166 &MeshMaterial3d<StandardMaterial>,
167 Option<&GltfMaterialName>,
168 )>,
169 mut meshes: ResMut<Assets<Mesh>>,
170 mut materials: ResMut<Assets<StandardMaterial>>,
171 mut commands: Commands,
172 args: Res<Args>,
173) {
174 for descendant in children.iter_descendants(scene_ready.entity) {
175 if let Ok((Mesh3d(mesh_handle), MeshMaterial3d(material_handle), material_name)) =
176 mesh_query.get(descendant)
177 {
178 // Add raytracing mesh component
179 commands
180 .entity(descendant)
181 .insert(RaytracingMesh3d(mesh_handle.clone()));
182
183 // Ensure meshes are Solari compatible
184 let mesh = meshes.get_mut(mesh_handle).unwrap();
185 if !mesh.contains_attribute(Mesh::ATTRIBUTE_UV_0) {
186 let vertex_count = mesh.count_vertices();
187 mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; vertex_count]);
188 mesh.insert_attribute(
189 Mesh::ATTRIBUTE_TANGENT,
190 vec![[0.0, 0.0, 0.0, 0.0]; vertex_count],
191 );
192 }
193 if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT) {
194 mesh.generate_tangents().unwrap();
195 }
196 if mesh.contains_attribute(Mesh::ATTRIBUTE_UV_1) {
197 mesh.remove_attribute(Mesh::ATTRIBUTE_UV_1);
198 }
199
200 // Prevent rasterization if using pathtracer
201 if args.pathtracer == Some(true) {
202 commands.entity(descendant).remove::<Mesh3d>();
203 }
204
205 // Adjust scene materials to better demo Solari features
206 if material_name.map(|s| s.0.as_str()) == Some("material") {
207 let material = materials.get_mut(material_handle).unwrap();
208 material.emissive = LinearRgba::BLACK;
209 }
210 if material_name.map(|s| s.0.as_str()) == Some("Lights") {
211 let material = materials.get_mut(material_handle).unwrap();
212 material.emissive =
213 LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0;
214 material.alpha_mode = AlphaMode::Opaque;
215 material.specular_transmission = 0.0;
216
217 commands.insert_resource(RobotLightMaterial(material_handle.clone()));
218 }
219 if material_name.map(|s| s.0.as_str()) == Some("Glass_Dark_01") {
220 let material = materials.get_mut(material_handle).unwrap();
221 material.alpha_mode = AlphaMode::Opaque;
222 material.specular_transmission = 0.0;
223 }
224 }
225 }
226}
227
228fn pause_scene(mut time: ResMut<Time<Virtual>>, key_input: Res<ButtonInput<KeyCode>>) {
229 if key_input.just_pressed(KeyCode::Space) {
230 if time.is_paused() {
231 time.unpause();
232 } else {
233 time.pause();
234 }
235 }
236}
237
238#[derive(Resource)]
239struct RobotLightMaterial(Handle<StandardMaterial>);
240
241fn toggle_lights(
242 key_input: Res<ButtonInput<KeyCode>>,
243 robot_light_material: Option<Res<RobotLightMaterial>>,
244 mut materials: ResMut<Assets<StandardMaterial>>,
245 directional_light: Query<Entity, With<DirectionalLight>>,
246 mut commands: Commands,
247) {
248 if key_input.just_pressed(KeyCode::Digit1) {
249 if let Ok(directional_light) = directional_light.single() {
250 commands.entity(directional_light).despawn();
251 } else {
252 commands.spawn((
253 DirectionalLight {
254 illuminance: light_consts::lux::FULL_DAYLIGHT,
255 shadows_enabled: false, // Solari replaces shadow mapping
256 ..default()
257 },
258 Transform::from_rotation(Quat::from_xyzw(
259 -0.13334629,
260 -0.86597735,
261 -0.3586996,
262 0.3219264,
263 )),
264 ));
265 }
266 }
267
268 if key_input.just_pressed(KeyCode::Digit2)
269 && let Some(robot_light_material) = robot_light_material
270 {
271 let material = materials.get_mut(&robot_light_material.0).unwrap();
272 if material.emissive == LinearRgba::BLACK {
273 material.emissive = LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0;
274 } else {
275 material.emissive = LinearRgba::BLACK;
276 }
277 }
278}
Sourcepub const fn from_array(a: [f32; 4]) -> Quat
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.
Examples found in repository?
179fn spawn_light(commands: &mut Commands, app_status: &AppStatus) {
180 // Because this light can become a directional light, point light, or spot
181 // light depending on the settings, we add the union of the components
182 // necessary for this light to behave as all three of those.
183 commands
184 .spawn((
185 create_directional_light(app_status),
186 Transform::from_rotation(Quat::from_array([
187 0.6539259,
188 -0.34646285,
189 0.36505926,
190 -0.5648683,
191 ]))
192 .with_translation(vec3(57.693, 34.334, -6.422)),
193 ))
194 // These two are needed for point lights.
195 .insert(CubemapVisibleEntities::default())
196 .insert(CubemapFrusta::default())
197 // These two are needed for spot lights.
198 .insert(VisibleMeshEntities::default())
199 .insert(Frustum::default());
200}
Sourcepub const fn from_vec4(v: Vec4) -> Quat
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.
Sourcepub fn from_slice(slice: &[f32]) -> Quat
pub fn from_slice(slice: &[f32]) -> Quat
Sourcepub fn write_to_slice(self, slice: &mut [f32])
pub fn write_to_slice(self, slice: &mut [f32])
Sourcepub fn from_axis_angle(axis: Vec3, angle: f32) -> Quat
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?
More examples
181fn button_system(
182 interaction_query: Query<
183 (&Interaction, &ComputedUiTargetCamera, &RotateCamera),
184 (Changed<Interaction>, With<Button>),
185 >,
186 mut camera_query: Query<&mut Transform, With<Camera>>,
187) {
188 for (interaction, computed_target, RotateCamera(direction)) in &interaction_query {
189 if let Interaction::Pressed = *interaction {
190 // Since TargetCamera propagates to the children, we can use it to find
191 // which side of the screen the button is on.
192 if let Some(mut camera_transform) = computed_target
193 .get()
194 .and_then(|camera| camera_query.get_mut(camera).ok())
195 {
196 let angle = match direction {
197 Direction::Left => -0.1,
198 Direction::Right => 0.1,
199 };
200 camera_transform.rotate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, angle));
201 }
202 }
203 }
204}
300fn move_camera(
301 keyboard_input: Res<ButtonInput<KeyCode>>,
302 mut mouse_wheel_reader: MessageReader<MouseWheel>,
303 mut cameras: Query<&mut Transform, With<Camera>>,
304) {
305 let (mut distance_delta, mut theta_delta) = (0.0, 0.0);
306
307 // Handle keyboard events.
308 if keyboard_input.pressed(KeyCode::KeyW) {
309 distance_delta -= CAMERA_KEYBOARD_ZOOM_SPEED;
310 }
311 if keyboard_input.pressed(KeyCode::KeyS) {
312 distance_delta += CAMERA_KEYBOARD_ZOOM_SPEED;
313 }
314 if keyboard_input.pressed(KeyCode::KeyA) {
315 theta_delta += CAMERA_KEYBOARD_ORBIT_SPEED;
316 }
317 if keyboard_input.pressed(KeyCode::KeyD) {
318 theta_delta -= CAMERA_KEYBOARD_ORBIT_SPEED;
319 }
320
321 // Handle mouse events.
322 for mouse_wheel in mouse_wheel_reader.read() {
323 distance_delta -= mouse_wheel.y * CAMERA_MOUSE_WHEEL_ZOOM_SPEED;
324 }
325
326 // Update transforms.
327 for mut camera_transform in cameras.iter_mut() {
328 let local_z = camera_transform.local_z().as_vec3().normalize_or_zero();
329 if distance_delta != 0.0 {
330 camera_transform.translation = (camera_transform.translation.length() + distance_delta)
331 .clamp(CAMERA_ZOOM_RANGE.start, CAMERA_ZOOM_RANGE.end)
332 * local_z;
333 }
334 if theta_delta != 0.0 {
335 camera_transform
336 .translate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, theta_delta));
337 camera_transform.look_at(Vec3::ZERO, Vec3::Y);
338 }
339 }
340}
24fn setup(
25 mut commands: Commands,
26 mut meshes: ResMut<Assets<Mesh>>,
27 mut standard_materials: ResMut<Assets<StandardMaterial>>,
28 mut decal_standard_materials: ResMut<Assets<ForwardDecalMaterial<StandardMaterial>>>,
29 asset_server: Res<AssetServer>,
30) {
31 // Spawn the forward decal
32 commands.spawn((
33 Name::new("Decal"),
34 ForwardDecal,
35 MeshMaterial3d(decal_standard_materials.add(ForwardDecalMaterial {
36 base: StandardMaterial {
37 base_color_texture: Some(asset_server.load("textures/uv_checker_bw.png")),
38 ..default()
39 },
40 extension: ForwardDecalMaterialExt {
41 depth_fade_factor: 1.0,
42 },
43 })),
44 Transform::from_scale(Vec3::splat(4.0)),
45 ));
46
47 commands.spawn((
48 Name::new("Camera"),
49 Camera3d::default(),
50 CameraController::default(),
51 // Must enable the depth prepass to render forward decals
52 DepthPrepass,
53 // Must disable MSAA to use decals on WebGPU
54 Msaa::Off,
55 // FXAA is a fine alternative to MSAA for anti-aliasing
56 Fxaa::default(),
57 Transform::from_xyz(2.0, 9.5, 2.5).looking_at(Vec3::ZERO, Vec3::Y),
58 ));
59
60 let white_material = standard_materials.add(Color::WHITE);
61
62 commands.spawn((
63 Name::new("Floor"),
64 Mesh3d(meshes.add(Rectangle::from_length(10.0))),
65 MeshMaterial3d(white_material.clone()),
66 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
67 ));
68
69 // Spawn a few cube with random rotations to showcase how the decals behave with non-flat geometry
70 let num_obs = 10;
71 let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
72 for i in 0..num_obs {
73 for j in 0..num_obs {
74 let rotation_axis: [f32; 3] = rng.random();
75 let rotation_vec: Vec3 = rotation_axis.into();
76 let rotation: u32 = rng.random_range(0..360);
77 let transform = Transform::from_xyz(
78 (-num_obs + 1) as f32 / 2.0 + i as f32,
79 -0.2,
80 (-num_obs + 1) as f32 / 2.0 + j as f32,
81 )
82 .with_rotation(Quat::from_axis_angle(
83 rotation_vec.normalize_or_zero(),
84 (rotation as f32).to_radians(),
85 ));
86
87 commands.spawn((
88 Mesh3d(meshes.add(Cuboid::from_length(0.6))),
89 MeshMaterial3d(white_material.clone()),
90 transform,
91 ));
92 }
93 }
94
95 commands.spawn((
96 Name::new("Light"),
97 PointLight {
98 shadows_enabled: true,
99 ..default()
100 },
101 Transform::from_xyz(4.0, 8.0, 4.0),
102 ));
103}
22fn setup(
23 mut commands: Commands,
24 mut meshes: ResMut<Assets<Mesh>>,
25 mut materials: ResMut<Assets<StandardMaterial>>,
26 mut animations: ResMut<Assets<AnimationClip>>,
27 mut graphs: ResMut<Assets<AnimationGraph>>,
28) {
29 // Camera
30 commands.spawn((
31 Camera3d::default(),
32 Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
33 ));
34
35 // Light
36 commands.spawn((
37 PointLight {
38 intensity: 500_000.0,
39 ..default()
40 },
41 Transform::from_xyz(0.0, 2.5, 0.0),
42 ));
43
44 // Let's use the `Name` component to target entities. We can use anything we
45 // like, but names are convenient.
46 let planet = Name::new("planet");
47 let orbit_controller = Name::new("orbit_controller");
48 let satellite = Name::new("satellite");
49
50 // Creating the animation
51 let mut animation = AnimationClip::default();
52 // A curve can modify a single part of a transform: here, the translation.
53 let planet_animation_target_id = AnimationTargetId::from_name(&planet);
54 animation.add_curve_to_target(
55 planet_animation_target_id,
56 AnimatableCurve::new(
57 animated_field!(Transform::translation),
58 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
59 Vec3::new(1.0, 0.0, 1.0),
60 Vec3::new(-1.0, 0.0, 1.0),
61 Vec3::new(-1.0, 0.0, -1.0),
62 Vec3::new(1.0, 0.0, -1.0),
63 // in case seamless looping is wanted, the last keyframe should
64 // be the same as the first one
65 Vec3::new(1.0, 0.0, 1.0),
66 ]))
67 .expect("should be able to build translation curve because we pass in valid samples"),
68 ),
69 );
70 // Or it can modify the rotation of the transform.
71 // To find the entity to modify, the hierarchy will be traversed looking for
72 // an entity with the right name at each level.
73 let orbit_controller_animation_target_id =
74 AnimationTargetId::from_names([planet.clone(), orbit_controller.clone()].iter());
75 animation.add_curve_to_target(
76 orbit_controller_animation_target_id,
77 AnimatableCurve::new(
78 animated_field!(Transform::rotation),
79 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
80 Quat::IDENTITY,
81 Quat::from_axis_angle(Vec3::Y, PI / 2.),
82 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
83 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
84 Quat::IDENTITY,
85 ]))
86 .expect("Failed to build rotation curve"),
87 ),
88 );
89 // If a curve in an animation is shorter than the other, it will not repeat
90 // until all other curves are finished. In that case, another animation should
91 // be created for each part that would have a different duration / period.
92 let satellite_animation_target_id = AnimationTargetId::from_names(
93 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
94 );
95 animation.add_curve_to_target(
96 satellite_animation_target_id,
97 AnimatableCurve::new(
98 animated_field!(Transform::scale),
99 UnevenSampleAutoCurve::new(
100 [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
101 .into_iter()
102 .zip([
103 Vec3::splat(0.8),
104 Vec3::splat(1.2),
105 Vec3::splat(0.8),
106 Vec3::splat(1.2),
107 Vec3::splat(0.8),
108 Vec3::splat(1.2),
109 Vec3::splat(0.8),
110 Vec3::splat(1.2),
111 Vec3::splat(0.8),
112 ]),
113 )
114 .expect("Failed to build scale curve"),
115 ),
116 );
117 // There can be more than one curve targeting the same entity path.
118 animation.add_curve_to_target(
119 AnimationTargetId::from_names(
120 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
121 ),
122 AnimatableCurve::new(
123 animated_field!(Transform::rotation),
124 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
125 Quat::IDENTITY,
126 Quat::from_axis_angle(Vec3::Y, PI / 2.),
127 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
128 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
129 Quat::IDENTITY,
130 ]))
131 .expect("should be able to build translation curve because we pass in valid samples"),
132 ),
133 );
134
135 // Create the animation graph
136 let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
137
138 // Create the animation player, and set it to repeat
139 let mut player = AnimationPlayer::default();
140 player.play(animation_index).repeat();
141
142 // Create the scene that will be animated
143 // First entity is the planet
144 let planet_entity = commands
145 .spawn((
146 Mesh3d(meshes.add(Sphere::default())),
147 MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
148 // Add the animation graph and player
149 planet,
150 AnimationGraphHandle(graphs.add(graph)),
151 player,
152 ))
153 .id();
154 commands.entity(planet_entity).insert((
155 AnimationTarget {
156 id: planet_animation_target_id,
157 player: planet_entity,
158 },
159 children![(
160 Transform::default(),
161 Visibility::default(),
162 orbit_controller,
163 AnimationTarget {
164 id: orbit_controller_animation_target_id,
165 player: planet_entity,
166 },
167 children![(
168 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
169 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.9, 0.3))),
170 Transform::from_xyz(1.5, 0.0, 0.0),
171 AnimationTarget {
172 id: satellite_animation_target_id,
173 player: planet_entity,
174 },
175 satellite,
176 )],
177 )],
178 ));
179}
Sourcepub fn from_scaled_axis(v: Vec3) -> Quat
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.
Examples found in repository?
71fn setup(
72 mut commands: Commands,
73 mut meshes: ResMut<Assets<Mesh>>,
74 mut materials: ResMut<Assets<StandardMaterial>>,
75) {
76 // Make a box of planes facing inward so the laser gets trapped inside
77 let plane_mesh = meshes.add(Plane3d::default());
78 let plane_material = materials.add(Color::from(css::GRAY).with_alpha(0.01));
79 let create_plane = move |translation, rotation| {
80 (
81 Transform::from_translation(translation)
82 .with_rotation(Quat::from_scaled_axis(rotation)),
83 Mesh3d(plane_mesh.clone()),
84 MeshMaterial3d(plane_material.clone()),
85 )
86 };
87
88 commands.spawn(create_plane(vec3(0.0, 0.5, 0.0), Vec3::X * PI));
89 commands.spawn(create_plane(vec3(0.0, -0.5, 0.0), Vec3::ZERO));
90 commands.spawn(create_plane(vec3(0.5, 0.0, 0.0), Vec3::Z * FRAC_PI_2));
91 commands.spawn(create_plane(vec3(-0.5, 0.0, 0.0), Vec3::Z * -FRAC_PI_2));
92 commands.spawn(create_plane(vec3(0.0, 0.0, 0.5), Vec3::X * -FRAC_PI_2));
93 commands.spawn(create_plane(vec3(0.0, 0.0, -0.5), Vec3::X * FRAC_PI_2));
94
95 // Light
96 commands.spawn((
97 DirectionalLight::default(),
98 Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.1, 0.2, 0.0)),
99 ));
100
101 // Camera
102 commands.spawn((
103 Camera3d::default(),
104 Transform::from_xyz(1.5, 1.5, 1.5).looking_at(Vec3::ZERO, Vec3::Y),
105 Tonemapping::TonyMcMapface,
106 Bloom::default(),
107 ));
108}
Sourcepub fn from_rotation_x(angle: f32) -> Quat
pub fn from_rotation_x(angle: f32) -> Quat
Creates a quaternion from the angle
(in radians) around the x axis.
Examples found in repository?
More examples
357fn draw_gizmos(mut gizmos: Gizmos, spotlight: Query<(&GlobalTransform, &SpotLight, &Visibility)>) {
358 if let Ok((global_transform, spotlight, visibility)) = spotlight.single()
359 && visibility != Visibility::Hidden
360 {
361 gizmos.primitive_3d(
362 &Cone::new(7.0 * spotlight.outer_angle, 7.0),
363 Isometry3d {
364 rotation: global_transform.rotation() * Quat::from_rotation_x(FRAC_PI_2),
365 translation: global_transform.translation_vec3a() * 0.5,
366 },
367 YELLOW,
368 );
369 }
370}
388fn draw_camera_gizmo(cameras: Query<(&Camera, &GlobalTransform)>, mut gizmos: Gizmos) {
389 for (camera, transform) in &cameras {
390 // As above, we use the order as a cheap tag to tell the depth texture
391 // apart from the main texture.
392 if camera.order >= 0 {
393 continue;
394 }
395
396 // Draw a cone representing the camera.
397 gizmos.primitive_3d(
398 &Cone {
399 radius: 1.0,
400 height: 3.0,
401 },
402 Isometry3d::new(
403 transform.translation(),
404 // We have to rotate here because `Cone` primitives are oriented
405 // along +Y and cameras point along +Z.
406 transform.rotation() * Quat::from_rotation_x(FRAC_PI_2),
407 ),
408 LIME,
409 );
410 }
411}
13fn setup(
14 mut commands: Commands,
15 mut meshes: ResMut<Assets<Mesh>>,
16 mut materials: ResMut<Assets<StandardMaterial>>,
17) {
18 // circular base
19 commands.spawn((
20 Mesh3d(meshes.add(Circle::new(4.0))),
21 MeshMaterial3d(materials.add(Color::WHITE)),
22 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
23 ));
24 // cube
25 commands.spawn((
26 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
27 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
28 Transform::from_xyz(0.0, 0.5, 0.0),
29 ));
30 // light
31 commands.spawn((
32 PointLight {
33 shadows_enabled: true,
34 ..default()
35 },
36 Transform::from_xyz(4.0, 8.0, 4.0),
37 ));
38 // camera
39 commands.spawn((
40 Camera3d::default(),
41 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
42 ));
43}
221fn setup_scene(
222 mut commands: Commands,
223 asset_server: Res<AssetServer>,
224 mut meshes: ResMut<Assets<Mesh>>,
225 mut materials: ResMut<Assets<StandardMaterial>>,
226) {
227 commands.spawn((
228 Camera3d::default(),
229 Transform::from_xyz(-10.0, 5.0, 13.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
230 ));
231
232 commands.spawn((
233 PointLight {
234 intensity: 10_000_000.0,
235 shadows_enabled: true,
236 ..default()
237 },
238 Transform::from_xyz(-4.0, 8.0, 13.0),
239 ));
240
241 commands.spawn((
242 SceneRoot(
243 asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")),
244 ),
245 Transform::from_scale(Vec3::splat(0.07)),
246 ));
247
248 // Ground
249
250 commands.spawn((
251 Mesh3d(meshes.add(Circle::new(7.0))),
252 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
253 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
254 ));
255}
26fn setup(
27 mut commands: Commands,
28 mut meshes: ResMut<Assets<Mesh>>,
29 mut materials: ResMut<Assets<StandardMaterial>>,
30) {
31 // circular base
32 commands.spawn((
33 Mesh3d(meshes.add(Circle::new(4.0))),
34 MeshMaterial3d(materials.add(Color::WHITE)),
35 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
36 ));
37
38 // cube
39 commands.spawn((
40 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
41 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
42 Transform::from_xyz(0.0, 0.5, 0.0),
43 Cube(1.0),
44 ));
45
46 // test resource
47 commands.insert_resource(TestResource {
48 foo: Vec2::new(1.0, -1.0),
49 bar: false,
50 });
51
52 // light
53 commands.spawn((
54 PointLight {
55 shadows_enabled: true,
56 ..default()
57 },
58 Transform::from_xyz(4.0, 8.0, 4.0),
59 ));
60
61 // camera
62 commands.spawn((
63 Camera3d::default(),
64 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
65 ));
66}
- examples/animation/animation_masks.rs
- examples/camera/custom_projection.rs
- examples/diagnostics/log_diagnostics.rs
- examples/3d/skybox.rs
- examples/shader_advanced/custom_render_phase.rs
- examples/picking/simple_picking.rs
- examples/picking/debug_picking.rs
- examples/animation/custom_skinned_mesh.rs
- examples/math/custom_primitives.rs
- examples/app/headless_renderer.rs
- examples/3d/specular_tint.rs
- examples/testbed/3d.rs
- examples/stress_tests/many_cameras_lights.rs
- examples/3d/texture.rs
- examples/3d/decal.rs
- examples/3d/render_to_texture.rs
- examples/gizmos/light_gizmos.rs
- examples/gizmos/3d_gizmos.rs
- examples/3d/3d_shapes.rs
- examples/picking/mesh_picking.rs
- examples/ui/render_ui_to_texture.rs
- examples/3d/lighting.rs
Sourcepub fn from_rotation_y(angle: f32) -> Quat
pub fn from_rotation_y(angle: f32) -> Quat
Creates a quaternion from the angle
(in radians) around the y axis.
Examples found in repository?
More examples
- examples/3d/rotate_environment_map.rs
- examples/math/sampling_primitives.rs
- examples/3d/spotlight.rs
- examples/3d/anisotropy.rs
- examples/shader/shader_material_wesl.rs
- examples/transforms/scale.rs
- examples/transforms/align.rs
- examples/math/random_sampling.rs
- examples/3d/post_processing.rs
- examples/3d/color_grading.rs
- examples/3d/tonemapping.rs
- examples/transforms/transform.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/auto_exposure.rs
- examples/3d/atmosphere.rs
- examples/animation/eased_motion.rs
- examples/3d/blend_modes.rs
- examples/games/alien_cake_addict.rs
- examples/3d/meshlet.rs
- examples/gizmos/3d_gizmos.rs
- examples/3d/solari.rs
- examples/stress_tests/many_foxes.rs
Sourcepub fn from_rotation_z(angle: f32) -> Quat
pub fn from_rotation_z(angle: f32) -> Quat
Creates a quaternion from the angle
(in radians) around the z axis.
Examples found in repository?
More examples
- examples/ecs/fallible_params.rs
- examples/animation/morph_targets.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/stress_tests/many_sprites.rs
- examples/testbed/2d.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/animation/custom_skinned_mesh.rs
- examples/stress_tests/many_text2d.rs
- examples/3d/motion_blur.rs
- examples/picking/sprite_picking.rs
- examples/2d/mesh2d_arcs.rs
Sourcepub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Quat
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?
More examples
370fn spin_large_cube(mut large_cubes: Query<&mut Transform, With<LargeCube>>) {
371 for mut transform in &mut large_cubes {
372 transform.rotate(Quat::from_euler(
373 EulerRot::XYZ,
374 0.13 * ROTATION_SPEED,
375 0.29 * ROTATION_SPEED,
376 0.35 * ROTATION_SPEED,
377 ));
378 }
379}
380
381/// Spawns a directional light to illuminate the scene.
382fn spawn_light(commands: &mut Commands) {
383 commands
384 .spawn(DirectionalLight::default())
385 .insert(Transform::from_rotation(Quat::from_euler(
386 EulerRot::ZYX,
387 0.0,
388 PI * -0.15,
389 PI * -0.15,
390 )));
391}
51fn animate_light_direction(
52 time: Res<Time>,
53 mut query: Query<&mut Transform, With<DirectionalLight>>,
54) {
55 for mut transform in &mut query {
56 transform.rotation = Quat::from_euler(
57 EulerRot::ZYX,
58 0.0,
59 time.elapsed_secs() * PI / 5.0,
60 -FRAC_PI_4,
61 );
62 }
63}
54fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
55 commands.spawn((
56 Camera3d::default(),
57 Transform::from_xyz(4.0, 4.0, 12.0).looking_at(Vec3::new(0.0, 0.0, 0.5), Vec3::Y),
58 ));
59
60 commands.spawn((
61 Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
62 DirectionalLight::default(),
63 ));
64
65 commands.spawn(SceneRoot(asset_server.load(
66 GltfAssetLabel::Scene(0).from_asset("models/GltfPrimitives/gltf_primitives.glb"),
67 )));
68}
137fn light_sway(time: Res<Time>, mut query: Query<(&mut Transform, &mut SpotLight)>) {
138 for (mut transform, mut angles) in query.iter_mut() {
139 transform.rotation = Quat::from_euler(
140 EulerRot::XYZ,
141 -FRAC_PI_2 + ops::sin(time.elapsed_secs() * 0.67 * 3.0) * 0.5,
142 ops::sin(time.elapsed_secs() * 3.0) * 0.5,
143 0.0,
144 );
145 let angle = (ops::sin(time.elapsed_secs() * 1.2) + 1.0) * (FRAC_PI_4 - 0.1);
146 angles.inner_angle = angle * 0.8;
147 angles.outer_angle = angle;
148 }
149}
- examples/asset/multi_asset_sync.rs
- examples/animation/animated_mesh.rs
- examples/3d/volumetric_fog.rs
- examples/3d/post_processing.rs
- examples/3d/pcss.rs
- examples/3d/color_grading.rs
- examples/3d/tonemapping.rs
- examples/stress_tests/many_materials.rs
- examples/testbed/3d.rs
- examples/3d/mesh_ray_cast.rs
- examples/movement/physics_in_fixed_timestep.rs
- examples/camera/camera_orbit.rs
- examples/3d/ssao.rs
- examples/animation/animated_mesh_events.rs
- examples/3d/clustered_decals.rs
- examples/camera/first_person_view_model.rs
- examples/3d/visibility_range.rs
- examples/3d/light_textures.rs
- examples/animation/animated_mesh_control.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/anti_aliasing.rs
- examples/3d/meshlet.rs
- examples/3d/split_screen.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/deferred_rendering.rs
- examples/3d/transmission.rs
- examples/helpers/camera_controller.rs
Sourcepub fn from_mat3(mat: &Mat3) -> Quat
pub fn from_mat3(mat: &Mat3) -> Quat
Creates a quaternion from a 3x3 rotation matrix.
Note if the input matrix contain scales, shears, or other non-rotation transformations then the resulting quaternion will be ill-defined.
§Panics
Will panic if any input matrix column is not normalized when glam_assert
is enabled.
Examples found in repository?
591fn rotate_primitive_2d_meshes(
592 mut primitives_2d: Query<
593 (&mut Transform, &ViewVisibility),
594 (With<PrimitiveData>, With<MeshDim2>),
595 >,
596 time: Res<Time>,
597) {
598 let rotation_2d = Quat::from_mat3(&Mat3::from_angle(time.elapsed_secs()));
599 primitives_2d
600 .iter_mut()
601 .filter(|(_, vis)| vis.get())
602 .for_each(|(mut transform, _)| {
603 transform.rotation = rotation_2d;
604 });
605}
More examples
136fn track_targets(
137 // `Single` ensures the system runs ONLY when exactly one matching entity exists.
138 mut player: Single<(&mut Transform, &Player)>,
139 // `Option<Single>` never prevents the system from running, but will be `None` if there is not exactly one matching entity.
140 enemy: Option<Single<&Transform, (With<Enemy>, Without<Player>)>>,
141 time: Res<Time>,
142) {
143 let (player_transform, player) = &mut *player;
144 if let Some(enemy_transform) = enemy {
145 // Enemy found, rotate and move towards it.
146 let delta = enemy_transform.translation - player_transform.translation;
147 let distance = delta.length();
148 let front = delta / distance;
149 let up = Vec3::Z;
150 let side = front.cross(up);
151 player_transform.rotation = Quat::from_mat3(&Mat3::from_cols(side, front, up));
152 let max_step = distance - player.min_follow_radius;
153 if 0.0 < max_step {
154 let velocity = (player.speed * time.delta_secs()).min(max_step);
155 player_transform.translation += front * velocity;
156 }
157 } else {
158 // 0 or multiple enemies found, keep searching.
159 player_transform.rotate_axis(Dir3::Z, player.rotation_speed * time.delta_secs());
160 }
161}
Sourcepub fn from_mat3a(mat: &Mat3A) -> Quat
pub fn from_mat3a(mat: &Mat3A) -> Quat
Creates a quaternion from a 3x3 SIMD aligned rotation matrix.
Note if the input matrix contain scales, shears, or other non-rotation transformations then the resulting quaternion will be ill-defined.
§Panics
Will panic if any input matrix column is not normalized when glam_assert
is enabled.
Sourcepub fn from_mat4(mat: &Mat4) -> Quat
pub fn from_mat4(mat: &Mat4) -> Quat
Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations then the resulting quaternion will be ill-defined.
§Panics
Will panic if any column of the upper 3x3 rotation matrix is not normalized when
glam_assert
is enabled.
Sourcepub fn from_rotation_arc(from: Vec3, to: Vec3) -> Quat
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?
607fn rotate_primitive_3d_meshes(
608 mut primitives_3d: Query<
609 (&mut Transform, &ViewVisibility),
610 (With<PrimitiveData>, With<MeshDim3>),
611 >,
612 time: Res<Time>,
613) {
614 let rotation_3d = Quat::from_rotation_arc(
615 Vec3::Z,
616 Vec3::new(
617 ops::sin(time.elapsed_secs()),
618 ops::cos(time.elapsed_secs()),
619 ops::sin(time.elapsed_secs()) * 0.5,
620 )
621 .try_normalize()
622 .unwrap_or(Vec3::Z),
623 );
624 primitives_3d
625 .iter_mut()
626 .filter(|(_, vis)| vis.get())
627 .for_each(|(mut transform, _)| {
628 transform.rotation = rotation_3d;
629 });
630}
631
632fn draw_gizmos_3d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time: Res<Time>) {
633 const POSITION: Vec3 = Vec3::new(LEFT_RIGHT_OFFSET_3D, 0.0, 0.0);
634 let rotation = Quat::from_rotation_arc(
635 Vec3::Z,
636 Vec3::new(
637 ops::sin(time.elapsed_secs()),
638 ops::cos(time.elapsed_secs()),
639 ops::sin(time.elapsed_secs()) * 0.5,
640 )
641 .try_normalize()
642 .unwrap_or(Vec3::Z),
643 );
644 let isometry = Isometry3d::new(POSITION, rotation);
645 let color = Color::WHITE;
646 let resolution = 10;
647
648 #[expect(
649 clippy::match_same_arms,
650 reason = "Certain primitives don't have any 3D rendering support yet."
651 )]
652 match state.get() {
653 PrimitiveSelected::RectangleAndCuboid => {
654 gizmos.primitive_3d(&CUBOID, isometry, color);
655 }
656 PrimitiveSelected::CircleAndSphere => drop(
657 gizmos
658 .primitive_3d(&SPHERE, isometry, color)
659 .resolution(resolution),
660 ),
661 PrimitiveSelected::Ellipse => {}
662 PrimitiveSelected::Triangle => gizmos.primitive_3d(&TRIANGLE_3D, isometry, color),
663 PrimitiveSelected::Plane => drop(gizmos.primitive_3d(&PLANE_3D, isometry, color)),
664 PrimitiveSelected::Line => gizmos.primitive_3d(&LINE3D, isometry, color),
665 PrimitiveSelected::Segment => gizmos.primitive_3d(&SEGMENT_3D, isometry, color),
666 PrimitiveSelected::Polyline => gizmos.primitive_3d(
667 &Polyline3d {
668 vertices: vec![
669 Vec3::new(-BIG_3D, -SMALL_3D, -SMALL_3D),
670 Vec3::new(SMALL_3D, SMALL_3D, 0.0),
671 Vec3::new(-SMALL_3D, -SMALL_3D, 0.0),
672 Vec3::new(BIG_3D, SMALL_3D, SMALL_3D),
673 ],
674 },
675 isometry,
676 color,
677 ),
678 PrimitiveSelected::Polygon => {}
679 PrimitiveSelected::RegularPolygon => {}
680 PrimitiveSelected::Capsule => drop(
681 gizmos
682 .primitive_3d(&CAPSULE_3D, isometry, color)
683 .resolution(resolution),
684 ),
685 PrimitiveSelected::Cylinder => drop(
686 gizmos
687 .primitive_3d(&CYLINDER, isometry, color)
688 .resolution(resolution),
689 ),
690 PrimitiveSelected::Cone => drop(
691 gizmos
692 .primitive_3d(&CONE, isometry, color)
693 .resolution(resolution),
694 ),
695 PrimitiveSelected::ConicalFrustum => {
696 gizmos.primitive_3d(&CONICAL_FRUSTUM, isometry, color);
697 }
698
699 PrimitiveSelected::Torus => drop(
700 gizmos
701 .primitive_3d(&TORUS, isometry, color)
702 .minor_resolution(resolution)
703 .major_resolution(resolution),
704 ),
705 PrimitiveSelected::Tetrahedron => {
706 gizmos.primitive_3d(&TETRAHEDRON, isometry, color);
707 }
708
709 PrimitiveSelected::Arc => {}
710 PrimitiveSelected::CircularSector => {}
711 PrimitiveSelected::CircularSegment => {}
712 }
713}
More examples
154fn snap_to_player_system(
155 mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,
156 player_transform: Single<&Transform, With<Player>>,
157) {
158 // Get the player translation in 2D
159 let player_translation = player_transform.translation.xy();
160
161 for mut enemy_transform in &mut query {
162 // Get the vector from the enemy ship to the player ship in 2D and normalize it.
163 let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
164
165 // Get the quaternion to rotate from the initial enemy facing direction to the direction
166 // facing the player
167 let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));
168
169 // Rotate the enemy to face the player
170 enemy_transform.rotation = rotate_to_player;
171 }
172}
13fn draw_cursor(
14 camera_query: Single<(&Camera, &GlobalTransform)>,
15 ground: Single<&GlobalTransform, With<Ground>>,
16 window: Single<&Window>,
17 mut gizmos: Gizmos,
18) {
19 let (camera, camera_transform) = *camera_query;
20
21 if let Some(cursor_position) = window.cursor_position()
22 // Calculate a ray pointing from the camera into the world based on the cursor's position.
23 && let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position)
24 // Calculate if and at what distance the ray is hitting the ground plane.
25 && let Some(distance) =
26 ray.intersect_plane(ground.translation(), InfinitePlane3d::new(ground.up()))
27 {
28 let point = ray.get_point(distance);
29
30 // Draw a circle just above the ground plane at that position.
31 gizmos.circle(
32 Isometry3d::new(
33 point + ground.up() * 0.01,
34 Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()),
35 ),
36 0.2,
37 Color::WHITE,
38 );
39 }
40}
98fn draw_example_collection(
99 mut gizmos: Gizmos,
100 mut my_gizmos: Gizmos<MyRoundGizmos>,
101 time: Res<Time>,
102) {
103 gizmos.grid(
104 Quat::from_rotation_x(PI / 2.),
105 UVec2::splat(20),
106 Vec2::new(2., 2.),
107 // Light gray
108 LinearRgba::gray(0.65),
109 );
110 gizmos.grid(
111 Isometry3d::new(Vec3::splat(10.0), Quat::from_rotation_x(PI / 3. * 2.)),
112 UVec2::splat(20),
113 Vec2::new(2., 2.),
114 PURPLE,
115 );
116 gizmos.sphere(Vec3::splat(10.0), 1.0, PURPLE);
117
118 gizmos
119 .primitive_3d(
120 &Plane3d {
121 normal: Dir3::Y,
122 half_size: Vec2::splat(1.0),
123 },
124 Isometry3d::new(
125 Vec3::splat(4.0) + Vec2::from(ops::sin_cos(time.elapsed_secs())).extend(0.0),
126 Quat::from_rotation_x(PI / 2. + time.elapsed_secs()),
127 ),
128 GREEN,
129 )
130 .cell_count(UVec2::new(5, 10))
131 .spacing(Vec2::new(0.2, 0.1));
132
133 gizmos.cuboid(
134 Transform::from_translation(Vec3::Y * 0.5).with_scale(Vec3::splat(1.25)),
135 BLACK,
136 );
137 gizmos.rect(
138 Isometry3d::new(
139 Vec3::new(ops::cos(time.elapsed_secs()) * 2.5, 1., 0.),
140 Quat::from_rotation_y(PI / 2.),
141 ),
142 Vec2::splat(2.),
143 LIME,
144 );
145
146 gizmos.cross(Vec3::new(-1., 1., 1.), 0.5, FUCHSIA);
147
148 let domain = Interval::EVERYWHERE;
149 let curve = FunctionCurve::new(domain, |t| {
150 (Vec2::from(ops::sin_cos(t * 10.0))).extend(t - 6.0)
151 });
152 let resolution = ((ops::sin(time.elapsed_secs()) + 1.0) * 100.0) as usize;
153 let times_and_colors = (0..=resolution)
154 .map(|n| n as f32 / resolution as f32)
155 .map(|t| t * 5.0)
156 .map(|t| (t, TEAL.mix(&HOT_PINK, t / 5.0)));
157 gizmos.curve_gradient_3d(curve, times_and_colors);
158
159 my_gizmos.sphere(Vec3::new(1., 0.5, 0.), 0.5, RED);
160
161 my_gizmos
162 .rounded_cuboid(Vec3::new(-2.0, 0.75, -0.75), Vec3::splat(0.9), TURQUOISE)
163 .edge_radius(0.1)
164 .arc_resolution(4);
165
166 for y in [0., 0.5, 1.] {
167 gizmos.ray(
168 Vec3::new(1., y, 0.),
169 Vec3::new(-3., ops::sin(time.elapsed_secs() * 3.), 0.),
170 BLUE,
171 );
172 }
173
174 my_gizmos
175 .arc_3d(
176 180.0_f32.to_radians(),
177 0.2,
178 Isometry3d::new(
179 Vec3::ONE,
180 Quat::from_rotation_arc(Vec3::Y, Vec3::ONE.normalize()),
181 ),
182 ORANGE,
183 )
184 .resolution(10);
185
186 // Circles have 32 line-segments by default.
187 my_gizmos.circle(Quat::from_rotation_arc(Vec3::Z, Vec3::Y), 3., BLACK);
188
189 // You may want to increase this for larger circles or spheres.
190 my_gizmos
191 .circle(Quat::from_rotation_arc(Vec3::Z, Vec3::Y), 3.1, NAVY)
192 .resolution(64);
193 my_gizmos
194 .sphere(Isometry3d::IDENTITY, 3.2, BLACK)
195 .resolution(64);
196
197 gizmos.arrow(Vec3::ZERO, Vec3::splat(1.5), YELLOW);
198
199 // You can create more complex arrows using the arrow builder.
200 gizmos
201 .arrow(Vec3::new(2., 0., 2.), Vec3::new(2., 2., 2.), ORANGE_RED)
202 .with_double_end()
203 .with_tip_length(0.5);
204}
Sourcepub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Quat
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.
Sourcepub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Quat
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.
Sourcepub fn look_to_lh(dir: Vec3, up: Vec3) -> Quat
pub fn look_to_lh(dir: Vec3, up: Vec3) -> Quat
Creates a quaterion rotation from a facing direction and an up direction.
For a left-handed view coordinate system with +X=right
, +Y=up
and +Z=forward
.
§Panics
Will panic if up
is not normalized when glam_assert
is enabled.
Sourcepub fn look_to_rh(dir: Vec3, up: Vec3) -> Quat
pub fn look_to_rh(dir: Vec3, up: Vec3) -> Quat
Creates a quaterion rotation from facing direction and an up direction.
For a right-handed view coordinate system with +X=right
, +Y=up
and +Z=back
.
§Panics
Will panic if dir
and up
are not normalized when glam_assert
is enabled.
Sourcepub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Quat
pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Quat
Creates a left-handed view matrix using a camera position, a focal point, and an up direction.
For a left-handed view coordinate system with +X=right
, +Y=up
and +Z=forward
.
§Panics
Will panic if up
is not normalized when glam_assert
is enabled.
Sourcepub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Quat
pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Quat
Creates a right-handed view matrix using a camera position, an up direction, and a focal point.
For a right-handed view coordinate system with +X=right
, +Y=up
and +Z=back
.
§Panics
Will panic if up
is not normalized when glam_assert
is enabled.
Sourcepub fn to_axis_angle(self) -> (Vec3, f32)
pub fn to_axis_angle(self) -> (Vec3, f32)
Returns the rotation axis (normalized) and angle (in radians) of self
.
Sourcepub fn to_scaled_axis(self) -> Vec3
pub fn to_scaled_axis(self) -> Vec3
Returns the rotation axis scaled by the rotation in radians.
Examples found in repository?
180fn bounding_shapes_2d(
181 shapes: Query<&Transform, With<Shape2d>>,
182 mut gizmos: Gizmos,
183 bounding_shape: Res<State<BoundingShape>>,
184) {
185 for transform in shapes.iter() {
186 // Get the rotation angle from the 3D rotation.
187 let rotation = transform.rotation.to_scaled_axis().z;
188 let rotation = Rot2::radians(rotation);
189 let isometry = Isometry2d::new(transform.translation.xy(), rotation);
190
191 match bounding_shape.get() {
192 BoundingShape::None => (),
193 BoundingShape::BoundingBox => {
194 // Get the AABB of the primitive with the rotation and translation of the mesh.
195 let aabb = HEART.aabb_2d(isometry);
196 gizmos.rect_2d(aabb.center(), aabb.half_size() * 2., WHITE);
197 }
198 BoundingShape::BoundingSphere => {
199 // Get the bounding sphere of the primitive with the rotation and translation of the mesh.
200 let bounding_circle = HEART.bounding_circle(isometry);
201 gizmos
202 .circle_2d(bounding_circle.center(), bounding_circle.radius(), WHITE)
203 .resolution(64);
204 }
205 }
206 }
207}
Sourcepub fn to_euler(self, order: EulerRot) -> (f32, f32, f32)
pub fn to_euler(self, order: EulerRot) -> (f32, f32, f32)
Returns the rotation angles for the given euler rotation sequence.
Examples found in repository?
104fn draw_bounds<Shape: Bounded2d + Send + Sync + 'static>(
105 q: Query<(&DrawBounds<Shape>, &GlobalTransform)>,
106 mut gizmos: Gizmos,
107) {
108 for (shape, transform) in &q {
109 let (_, rotation, translation) = transform.to_scale_rotation_translation();
110 let translation = translation.truncate();
111 let rotation = rotation.to_euler(EulerRot::XYZ).2;
112 let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
113
114 let aabb = shape.0.aabb_2d(isometry);
115 gizmos.rect_2d(aabb.center(), aabb.half_size() * 2.0, RED);
116
117 let bounding_circle = shape.0.bounding_circle(isometry);
118 gizmos.circle_2d(bounding_circle.center, bounding_circle.radius(), BLUE);
119 }
120}
More examples
101fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
102 let color = GRAY;
103 for (shape, transform) in query.iter() {
104 let translation = transform.translation.xy();
105 let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
106 let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
107 match shape {
108 Shape::Rectangle(r) => {
109 gizmos.primitive_2d(r, isometry, color);
110 }
111 Shape::Circle(c) => {
112 gizmos.primitive_2d(c, isometry, color);
113 }
114 Shape::Triangle(t) => {
115 gizmos.primitive_2d(t, isometry, color);
116 }
117 Shape::Line(l) => {
118 gizmos.primitive_2d(l, isometry, color);
119 }
120 Shape::Capsule(c) => {
121 gizmos.primitive_2d(c, isometry, color);
122 }
123 Shape::Polygon(p) => {
124 gizmos.primitive_2d(p, isometry, color);
125 }
126 }
127 }
128}
129
130#[derive(Component)]
131enum DesiredVolume {
132 Aabb,
133 Circle,
134}
135
136#[derive(Component, Debug)]
137enum CurrentVolume {
138 Aabb(Aabb2d),
139 Circle(BoundingCircle),
140}
141
142fn update_volumes(
143 mut commands: Commands,
144 query: Query<
145 (Entity, &DesiredVolume, &Shape, &Transform),
146 Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
147 >,
148) {
149 for (entity, desired_volume, shape, transform) in query.iter() {
150 let translation = transform.translation.xy();
151 let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
152 let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
153 match desired_volume {
154 DesiredVolume::Aabb => {
155 let aabb = match shape {
156 Shape::Rectangle(r) => r.aabb_2d(isometry),
157 Shape::Circle(c) => c.aabb_2d(isometry),
158 Shape::Triangle(t) => t.aabb_2d(isometry),
159 Shape::Line(l) => l.aabb_2d(isometry),
160 Shape::Capsule(c) => c.aabb_2d(isometry),
161 Shape::Polygon(p) => p.aabb_2d(isometry),
162 };
163 commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
164 }
165 DesiredVolume::Circle => {
166 let circle = match shape {
167 Shape::Rectangle(r) => r.bounding_circle(isometry),
168 Shape::Circle(c) => c.bounding_circle(isometry),
169 Shape::Triangle(t) => t.bounding_circle(isometry),
170 Shape::Line(l) => l.bounding_circle(isometry),
171 Shape::Capsule(c) => c.bounding_circle(isometry),
172 Shape::Polygon(p) => p.bounding_circle(isometry),
173 };
174 commands
175 .entity(entity)
176 .insert(CurrentVolume::Circle(circle));
177 }
178 }
179 }
180}
244fn rotate_camera(
245 accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
246 player: Single<(&mut Transform, &CameraSensitivity), With<Camera>>,
247) {
248 let (mut transform, camera_sensitivity) = player.into_inner();
249
250 let delta = accumulated_mouse_motion.delta;
251
252 if delta != Vec2::ZERO {
253 // Note that we are not multiplying by delta time here.
254 // The reason is that for mouse movement, we already get the full movement that happened since the last frame.
255 // This means that if we multiply by delta time, we will get a smaller rotation than intended by the user.
256 let delta_yaw = -delta.x * camera_sensitivity.x;
257 let delta_pitch = -delta.y * camera_sensitivity.y;
258
259 let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);
260 let yaw = yaw + delta_yaw;
261
262 // If the pitch was ±¹⁄₂ π, the camera would look straight up or down.
263 // When the user wants to move the camera back to the horizon, which way should the camera face?
264 // The camera has no way of knowing what direction was "forward" before landing in that extreme position,
265 // so the direction picked will for all intents and purposes be arbitrary.
266 // Another issue is that for mathematical reasons, the yaw will effectively be flipped when the pitch is at the extremes.
267 // To not run into these issues, we clamp the pitch to a safe range.
268 const PITCH_LIMIT: f32 = FRAC_PI_2 - 0.01;
269 let pitch = (pitch + delta_pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
270
271 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
272 }
273}
99fn orbit(
100 mut camera: Single<&mut Transform, With<Camera>>,
101 camera_settings: Res<CameraSettings>,
102 mouse_buttons: Res<ButtonInput<MouseButton>>,
103 mouse_motion: Res<AccumulatedMouseMotion>,
104 time: Res<Time>,
105) {
106 let delta = mouse_motion.delta;
107 let mut delta_roll = 0.0;
108
109 if mouse_buttons.pressed(MouseButton::Left) {
110 delta_roll -= 1.0;
111 }
112 if mouse_buttons.pressed(MouseButton::Right) {
113 delta_roll += 1.0;
114 }
115
116 // Mouse motion is one of the few inputs that should not be multiplied by delta time,
117 // as we are already receiving the full movement since the last frame was rendered. Multiplying
118 // by delta time here would make the movement slower that it should be.
119 let delta_pitch = delta.y * camera_settings.pitch_speed;
120 let delta_yaw = delta.x * camera_settings.yaw_speed;
121
122 // Conversely, we DO need to factor in delta time for mouse button inputs.
123 delta_roll *= camera_settings.roll_speed * time.delta_secs();
124
125 // Obtain the existing pitch, yaw, and roll values from the transform.
126 let (yaw, pitch, roll) = camera.rotation.to_euler(EulerRot::YXZ);
127
128 // Establish the new yaw and pitch, preventing the pitch value from exceeding our limits.
129 let pitch = (pitch + delta_pitch).clamp(
130 camera_settings.pitch_range.start,
131 camera_settings.pitch_range.end,
132 );
133 let roll = roll + delta_roll;
134 let yaw = yaw + delta_yaw;
135 camera.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
136
137 // Adjust the translation to maintain the correct orientation toward the orbit target.
138 // In our example it's a static target, but this could easily be customized.
139 let target = Vec3::ZERO;
140 camera.translation = target - camera.forward() * camera_settings.orbit_distance;
141}
384fn process_move_input(
385 mut selections: Query<(&mut Transform, &Selection)>,
386 mouse_buttons: Res<ButtonInput<MouseButton>>,
387 mouse_motion: Res<AccumulatedMouseMotion>,
388 app_status: Res<AppStatus>,
389) {
390 // Only process drags when movement is selected.
391 if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Move {
392 return;
393 }
394
395 for (mut transform, selection) in &mut selections {
396 if app_status.selection != *selection {
397 continue;
398 }
399
400 let position = transform.translation;
401
402 // Convert to spherical coordinates.
403 let radius = position.length();
404 let mut theta = acos(position.y / radius);
405 let mut phi = position.z.signum() * acos(position.x * position.xz().length_recip());
406
407 // Camera movement is the inverse of object movement.
408 let (phi_factor, theta_factor) = match *selection {
409 Selection::Camera => (1.0, -1.0),
410 Selection::DecalA | Selection::DecalB => (-1.0, 1.0),
411 };
412
413 // Adjust the spherical coordinates. Clamp the inclination to (0, π).
414 phi += phi_factor * mouse_motion.delta.x * MOVE_SPEED;
415 theta = f32::clamp(
416 theta + theta_factor * mouse_motion.delta.y * MOVE_SPEED,
417 0.001,
418 PI - 0.001,
419 );
420
421 // Convert spherical coordinates back to Cartesian coordinates.
422 transform.translation =
423 radius * vec3(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi));
424
425 // Look at the center, but preserve the previous roll angle.
426 let roll = transform.rotation.to_euler(EulerRot::YXZ).2;
427 transform.look_at(Vec3::ZERO, Vec3::Y);
428 let (yaw, pitch, _) = transform.rotation.to_euler(EulerRot::YXZ);
429 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
430 }
431}
432
433/// Processes a drag event that scales the selected target.
434fn process_scale_input(
435 mut selections: Query<(&mut Transform, &Selection)>,
436 mouse_buttons: Res<ButtonInput<MouseButton>>,
437 mouse_motion: Res<AccumulatedMouseMotion>,
438 app_status: Res<AppStatus>,
439) {
440 // Only process drags when the scaling operation is selected.
441 if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Scale {
442 return;
443 }
444
445 for (mut transform, selection) in &mut selections {
446 if app_status.selection == *selection {
447 transform.scale *= 1.0 + mouse_motion.delta.x * SCALE_SPEED;
448 }
449 }
450}
451
452/// Processes a drag event that rotates the selected target along its local Z
453/// axis.
454fn process_roll_input(
455 mut selections: Query<(&mut Transform, &Selection)>,
456 mouse_buttons: Res<ButtonInput<MouseButton>>,
457 mouse_motion: Res<AccumulatedMouseMotion>,
458 app_status: Res<AppStatus>,
459) {
460 // Only process drags when the rolling operation is selected.
461 if !mouse_buttons.pressed(MouseButton::Left) || app_status.drag_mode != DragMode::Roll {
462 return;
463 }
464
465 for (mut transform, selection) in &mut selections {
466 if app_status.selection != *selection {
467 continue;
468 }
469
470 let (yaw, pitch, mut roll) = transform.rotation.to_euler(EulerRot::YXZ);
471 roll += mouse_motion.delta.x * ROLL_SPEED;
472 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
473 }
474}
205fn move_player(
206 accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
207 player: Single<(&mut Transform, &CameraSensitivity), With<Player>>,
208) {
209 let (mut transform, camera_sensitivity) = player.into_inner();
210
211 let delta = accumulated_mouse_motion.delta;
212
213 if delta != Vec2::ZERO {
214 // Note that we are not multiplying by delta_time here.
215 // The reason is that for mouse movement, we already get the full movement that happened since the last frame.
216 // This means that if we multiply by delta_time, we will get a smaller rotation than intended by the user.
217 // This situation is reversed when reading e.g. analog input from a gamepad however, where the same rules
218 // as for keyboard input apply. Such an input should be multiplied by delta_time to get the intended rotation
219 // independent of the framerate.
220 let delta_yaw = -delta.x * camera_sensitivity.x;
221 let delta_pitch = -delta.y * camera_sensitivity.y;
222
223 let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);
224 let yaw = yaw + delta_yaw;
225
226 // If the pitch was ±¹⁄₂ π, the camera would look straight up or down.
227 // When the user wants to move the camera back to the horizon, which way should the camera face?
228 // The camera has no way of knowing what direction was "forward" before landing in that extreme position,
229 // so the direction picked will for all intents and purposes be arbitrary.
230 // Another issue is that for mathematical reasons, the yaw will effectively be flipped when the pitch is at the extremes.
231 // To not run into these issues, we clamp the pitch to a safe range.
232 const PITCH_LIMIT: f32 = FRAC_PI_2 - 0.01;
233 let pitch = (pitch + delta_pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
234
235 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
236 }
237}
Sourcepub fn conjugate(self) -> Quat
pub fn conjugate(self) -> Quat
Returns the quaternion conjugate of self
. For a unit quaternion the
conjugate is also the inverse.
Sourcepub fn inverse(self) -> Quat
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.
Sourcepub fn dot(self, rhs: Quat) -> f32
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.
Sourcepub fn length_squared(self) -> f32
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.
Sourcepub fn length_recip(self) -> f32
pub fn length_recip(self) -> f32
Computes 1.0 / length()
.
For valid results, self
must not be of length zero.
Sourcepub fn normalize(self) -> Quat
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.
Sourcepub fn is_finite(self) -> bool
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
.
Sourcepub fn is_normalized(self) -> bool
pub fn is_normalized(self) -> bool
Returns whether self
of length 1.0
or not.
Uses a precision threshold of 1e-6
.
pub fn is_near_identity(self) -> bool
Sourcepub fn angle_between(self, rhs: Quat) -> f32
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.
Examples found in repository?
140fn rotate_ship(ship: Single<(&mut Ship, &mut Transform)>, time: Res<Time>) {
141 let (mut ship, mut ship_transform) = ship.into_inner();
142
143 if !ship.in_motion {
144 return;
145 }
146
147 let target_rotation = ship.target_transform.rotation;
148
149 ship_transform
150 .rotation
151 .smooth_nudge(&target_rotation, 3.0, time.delta_secs());
152
153 if ship_transform.rotation.angle_between(target_rotation) <= f32::EPSILON {
154 ship.in_motion = false;
155 }
156}
Sourcepub fn rotate_towards(&self, rhs: Quat, max_angle: f32) -> Quat
pub fn rotate_towards(&self, rhs: Quat, max_angle: f32) -> Quat
Rotates towards rhs
up to max_angle
(in radians).
When max_angle
is 0.0
, the result will be equal to self
. When max_angle
is equal to
self.angle_between(rhs)
, the result will be equal to rhs
. If max_angle
is negative,
rotates towards the exact opposite of rhs
. Will not go past the target.
Both quaternions must be normalized.
§Panics
Will panic if self
or rhs
are not normalized when glam_assert
is enabled.
Sourcepub fn abs_diff_eq(self, rhs: Quat, max_abs_diff: f32) -> bool
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.
Sourcepub fn lerp(self, end: Quat, s: f32) -> Quat
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?
More examples
101fn rotate_cube(
102 mut cubes: Query<(&mut Transform, &mut CubeState), Without<Center>>,
103 center_spheres: Query<&Transform, With<Center>>,
104 timer: Res<Time>,
105) {
106 // Calculate the point to circle around. (The position of the center_sphere)
107 let mut center: Vec3 = Vec3::ZERO;
108 for sphere in ¢er_spheres {
109 center += sphere.translation;
110 }
111 // Update the rotation of the cube(s).
112 for (mut transform, cube) in &mut cubes {
113 // Calculate the rotation of the cube if it would be looking at the sphere in the center.
114 let look_at_sphere = transform.looking_at(center, *transform.local_y());
115 // Interpolate between the current rotation and the fully turned rotation
116 // when looking at the sphere, with a given turn speed to get a smooth motion.
117 // With higher speed the curvature of the orbit would be smaller.
118 let incremental_turn_weight = cube.turn_speed * timer.delta_secs();
119 let old_rotation = transform.rotation;
120 transform.rotation = old_rotation.lerp(look_at_sphere.rotation, incremental_turn_weight);
121 }
122}
Sourcepub fn slerp(self, end: Quat, s: f32) -> Quat
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?
More examples
187fn move_camera(
188 mut camera: Single<&mut Transform, With<CameraController>>,
189 mut current_view: Local<usize>,
190 button: Res<ButtonInput<MouseButton>>,
191) {
192 if button.just_pressed(MouseButton::Left) {
193 *current_view = (*current_view + 1) % CAMERA_POSITIONS.len();
194 }
195 let target = CAMERA_POSITIONS[*current_view];
196 camera.translation = camera.translation.lerp(target.translation, 0.2);
197 camera.rotation = camera.rotation.slerp(target.rotation, 0.2);
198}
Sourcepub fn mul_vec3(self, rhs: Vec3) -> Vec3
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?
More examples
192fn rotate_camera(
193 mut camera: Query<&mut Transform, With<Camera>>,
194 app_status: Res<AppStatus>,
195 time: Res<Time>,
196 mut stopwatch: Local<Stopwatch>,
197) {
198 if app_status.light_mode == LightMode::EnvironmentMap {
199 stopwatch.tick(time.delta());
200 }
201
202 let now = stopwatch.elapsed_secs();
203 for mut transform in camera.iter_mut() {
204 *transform = Transform::from_translation(
205 Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
206 )
207 .looking_at(Vec3::ZERO, Vec3::Y);
208 }
209}
Sourcepub fn mul_quat(self, rhs: Quat) -> Quat
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.
Sourcepub fn from_affine3(a: &Affine3A) -> Quat
pub fn from_affine3(a: &Affine3A) -> Quat
Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
Note if the input affine matrix contain scales, shears, or other non-rotation transformations then the resulting quaternion will be ill-defined.
§Panics
Will panic if any input affine matrix column is not normalized when glam_assert
is
enabled.
Sourcepub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A
pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A
Multiplies a quaternion and a 3D vector, returning the rotated vector.
pub fn as_dquat(self) -> DQuat
Trait Implementations§
Source§impl Add for Quat
impl Add for Quat
Source§impl AddAssign<&Quat> for Quat
impl AddAssign<&Quat> for Quat
Source§fn add_assign(&mut self, rhs: &Quat)
fn add_assign(&mut self, rhs: &Quat)
+=
operation. Read moreSource§impl AddAssign for Quat
impl AddAssign for Quat
Source§fn add_assign(&mut self, rhs: Quat)
fn add_assign(&mut self, rhs: Quat)
+=
operation. Read moreSource§impl Animatable for Quat
impl Animatable for Quat
Source§impl Curve<Quat> for CubicRotationCurve
impl Curve<Quat> for CubicRotationCurve
Source§fn sample_clamped(&self, t: f32) -> Quat
fn sample_clamped(&self, t: f32) -> Quat
t
, clamping t
to lie inside the
domain of the curve.Source§impl<'de> Deserialize<'de> for Quat
Deserialize expects a sequence of 4 values.
impl<'de> Deserialize<'de> for Quat
Deserialize expects a sequence of 4 values.
Source§fn deserialize<D>(
deserializer: D,
) -> Result<Quat, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Quat, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
Source§impl DivAssign<&f32> for Quat
impl DivAssign<&f32> for Quat
Source§fn div_assign(&mut self, rhs: &f32)
fn div_assign(&mut self, rhs: &f32)
/=
operation. Read moreSource§impl DivAssign<f32> for Quat
impl DivAssign<f32> for Quat
Source§fn div_assign(&mut self, rhs: f32)
fn div_assign(&mut self, rhs: f32)
/=
operation. Read moreSource§impl Ease for Quat
impl Ease for Quat
Source§impl From<Quat> for Isometry3d
impl From<Quat> for Isometry3d
Source§fn from(rotation: Quat) -> Isometry3d
fn from(rotation: Quat) -> Isometry3d
Source§impl FromReflect for Quat
impl FromReflect for Quat
Source§fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Quat>
fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Quat>
Self
from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read moreSource§impl GetTypeRegistration for Quat
impl GetTypeRegistration for Quat
Source§fn get_type_registration() -> TypeRegistration
fn get_type_registration() -> TypeRegistration
TypeRegistration
for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl IntoReturn for Quat
impl IntoReturn for Quat
Source§impl Mul for Quat
impl Mul for Quat
Source§fn mul(self, rhs: Quat) -> Quat
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.
Source§impl MulAssign<&Quat> for Quat
impl MulAssign<&Quat> for Quat
Source§fn mul_assign(&mut self, rhs: &Quat)
fn mul_assign(&mut self, rhs: &Quat)
*=
operation. Read moreSource§impl MulAssign<&f32> for Quat
impl MulAssign<&f32> for Quat
Source§fn mul_assign(&mut self, rhs: &f32)
fn mul_assign(&mut self, rhs: &f32)
*=
operation. Read moreSource§impl MulAssign<f32> for Quat
impl MulAssign<f32> for Quat
Source§fn mul_assign(&mut self, rhs: f32)
fn mul_assign(&mut self, rhs: f32)
*=
operation. Read moreSource§impl MulAssign for Quat
impl MulAssign for Quat
Source§fn mul_assign(&mut self, rhs: Quat)
fn mul_assign(&mut self, rhs: Quat)
*=
operation. Read moreSource§impl PartialReflect for Quat
impl PartialReflect for Quat
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn try_apply(
&mut self,
value: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<Quat>) -> ReflectOwned
fn reflect_owned(self: Box<Quat>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<Quat>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<Quat>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<Quat>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<Quat>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
Self
using reflection. Read moreSource§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
Source§fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
PartialReflect
, combines reflect_clone
and
take
in a useful fashion, automatically constructing an appropriate
ReflectCloneError
if the downcast fails. Read moreSource§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for Quat
impl Reflect for Quat
Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any
. Read moreSource§fn into_reflect(self: Box<Quat>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Quat>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl Serialize for Quat
Serialize as a sequence of 4 values.
impl Serialize for Quat
Serialize as a sequence of 4 values.
Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
Source§impl StableInterpolate for Quat
impl StableInterpolate for Quat
Source§fn interpolate_stable(&self, other: &Quat, t: f32) -> Quat
fn interpolate_stable(&self, other: &Quat, t: f32) -> Quat
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.Source§fn interpolate_stable_assign(&mut self, other: &Self, t: f32)
fn interpolate_stable_assign(&mut self, other: &Self, t: f32)
interpolate_stable
that assigns the result to self
for convenience.Source§fn smooth_nudge(&mut self, target: &Self, decay_rate: f32, delta: f32)
fn smooth_nudge(&mut self, target: &Self, decay_rate: f32, delta: f32)
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 moreSource§impl Struct for Quat
impl Struct for Quat
Source§fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>
fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>
name
as a &dyn PartialReflect
.Source§fn field_mut(
&mut self,
name: &str,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>
name
as a
&mut dyn PartialReflect
.Source§fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
index
as a
&dyn PartialReflect
.Source§fn field_at_mut(
&mut self,
index: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
index
as a &mut dyn PartialReflect
.Source§fn name_at(&self, index: usize) -> Option<&str>
fn name_at(&self, index: usize) -> Option<&str>
index
.Source§fn iter_fields(&self) -> FieldIter<'_> ⓘ
fn iter_fields(&self) -> FieldIter<'_> ⓘ
Source§fn to_dynamic_struct(&self) -> DynamicStruct
fn to_dynamic_struct(&self) -> DynamicStruct
DynamicStruct
from this struct.Source§fn get_represented_struct_info(&self) -> Option<&'static StructInfo>
fn get_represented_struct_info(&self) -> Option<&'static StructInfo>
None
if TypeInfo
is not available.Source§impl SubAssign<&Quat> for Quat
impl SubAssign<&Quat> for Quat
Source§fn sub_assign(&mut self, rhs: &Quat)
fn sub_assign(&mut self, rhs: &Quat)
-=
operation. Read moreSource§impl SubAssign for Quat
impl SubAssign for Quat
Source§fn sub_assign(&mut self, rhs: Quat)
fn sub_assign(&mut self, rhs: Quat)
-=
operation. Read moreSource§impl TypePath for Quat
impl TypePath for Quat
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
impl Copy for Quat
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, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CheckedBitPattern for Twhere
T: AnyBitPattern,
impl<T> CheckedBitPattern for Twhere
T: AnyBitPattern,
Source§type Bits = T
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
.Source§fn is_valid_bit_pattern(_bits: &T) -> bool
fn is_valid_bit_pattern(_bits: &T) -> bool
bits
as &Self
.Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
, which can then be
downcast
into Box<dyn ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
, which can then be further
downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info
.Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self
using default()
.
Source§impl<S> GetField for Swhere
S: Struct,
impl<S> GetField for Swhere
S: Struct,
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian()
.Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.