Skip to main content

mesh2d_arcs/
mesh2d_arcs.rs

1//! Demonstrates UV mappings of the [`CircularSector`] and [`CircularSegment`] primitives.
2//!
3//! Also draws the bounding boxes and circles of the primitives.
4
5use std::f32::consts::FRAC_PI_2;
6
7use bevy::{
8    color::palettes::css::{BLUE, GRAY, RED},
9    math::Isometry2d,
10    mesh::{CircularMeshUvMode, CircularSectorMeshBuilder, CircularSegmentMeshBuilder},
11    prelude::*,
12};
13
14fn main() {
15    App::new()
16        .add_plugins(DefaultPlugins)
17        .add_systems(Startup, setup)
18        .add_systems(
19            Update,
20            (
21                draw_bounds::<CircularSector>,
22                draw_bounds::<CircularSegment>,
23            ),
24        )
25        .run();
26}
27
28#[derive(Component, Debug)]
29struct DrawBounds<Shape: Bounded2d + Send + Sync + 'static>(Shape);
30
31fn setup(
32    mut commands: Commands,
33    asset_server: Res<AssetServer>,
34    mut meshes: ResMut<Assets<Mesh>>,
35    mut materials: ResMut<Assets<ColorMaterial>>,
36) {
37    let material = materials.add(asset_server.load("branding/icon.png"));
38
39    commands.spawn((
40        Camera2d,
41        Camera {
42            clear_color: ClearColorConfig::Custom(GRAY.into()),
43            ..default()
44        },
45    ));
46
47    const NUM_SLICES: i32 = 8;
48    const SPACING_X: f32 = 100.0;
49    const OFFSET_X: f32 = SPACING_X * (NUM_SLICES - 1) as f32 / 2.0;
50
51    // This draws NUM_SLICES copies of the Bevy logo as circular sectors and segments,
52    // with successively larger angles up to a complete circle.
53    for i in 0..NUM_SLICES {
54        let fraction = (i + 1) as f32 / NUM_SLICES as f32;
55
56        let sector = CircularSector::from_turns(40.0, fraction);
57        // We want to rotate the circular sector so that the sectors appear clockwise from north.
58        // We must rotate it both in the Transform and in the mesh's UV mappings.
59        let sector_angle = -sector.half_angle();
60        let sector_mesh =
61            CircularSectorMeshBuilder::new(sector).uv_mode(CircularMeshUvMode::Mask {
62                angle: sector_angle,
63            });
64        commands.spawn((
65            Mesh2d(meshes.add(sector_mesh)),
66            MeshMaterial2d(material.clone()),
67            Transform {
68                translation: Vec3::new(SPACING_X * i as f32 - OFFSET_X, 50.0, 0.0),
69                rotation: Quat::from_rotation_z(sector_angle),
70                ..default()
71            },
72            DrawBounds(sector),
73        ));
74
75        let segment = CircularSegment::from_turns(40.0, fraction);
76        // For the circular segment, we will draw Bevy charging forward, which requires rotating the
77        // shape and texture by 90 degrees.
78        //
79        // Note that this may be unintuitive; it may feel like we should rotate the texture by the
80        // opposite angle to preserve the orientation of Bevy. But the angle is not the angle of the
81        // texture itself, rather it is the angle at which the vertices are mapped onto the texture.
82        // so it is the negative of what you might otherwise expect.
83        let segment_angle = -FRAC_PI_2;
84        let segment_mesh =
85            CircularSegmentMeshBuilder::new(segment).uv_mode(CircularMeshUvMode::Mask {
86                angle: -segment_angle,
87            });
88        commands.spawn((
89            Mesh2d(meshes.add(segment_mesh)),
90            MeshMaterial2d(material.clone()),
91            Transform {
92                translation: Vec3::new(SPACING_X * i as f32 - OFFSET_X, -50.0, 0.0),
93                rotation: Quat::from_rotation_z(segment_angle),
94                ..default()
95            },
96            DrawBounds(segment),
97        ));
98    }
99}
100
101fn draw_bounds<Shape: Bounded2d + Send + Sync + 'static>(
102    q: Query<(&DrawBounds<Shape>, &GlobalTransform)>,
103    mut gizmos: Gizmos,
104) {
105    for (shape, transform) in &q {
106        let (_, rotation, translation) = transform.to_scale_rotation_translation();
107        let translation = translation.truncate();
108        let rotation = rotation.to_euler(EulerRot::XYZ).2;
109        let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
110
111        let aabb = shape.0.aabb_2d(isometry);
112        gizmos.rect_2d(aabb.center(), aabb.half_size() * 2.0, RED);
113
114        let bounding_circle = shape.0.bounding_circle(isometry);
115        gizmos.circle_2d(bounding_circle.center, bounding_circle.radius(), BLUE);
116    }
117}