1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use bevy::{
    pbr::ExtendedMaterial,
    prelude::*,
    render::{
        primitives::{Aabb as BevyAabb, Frustum},
        view::VisibilitySystems,
    },
    utils::FloatOrd,
};
use de_core::{
    frustum, gamestate::GameState, objects::ObjectTypeComponent, visibility::VisibilityFlags,
};
use de_objects::SolidObjects;
use de_types::projection::ToFlat;
use glam::Vec3A;
use parry2d::bounding_volume::Aabb;

use crate::shader::{Circle, Rectangle, TerrainMaterial, CIRCLE_CAPACITY, RECTANGLE_CAPACITY};

const RECTANGLE_MARKER_MARGIN: f32 = 1.;

pub(crate) struct MarkerPlugin;

impl Plugin for MarkerPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            PostUpdate,
            (
                update_markers::<CircleMarker>,
                update_markers::<RectangleMarker>,
            )
                .run_if(in_state(GameState::Playing))
                .after(VisibilitySystems::CheckVisibility),
        );
    }
}

/// A component representing the visibility of a terrain marker.
#[derive(Component, Default)]
pub struct MarkerVisibility(pub VisibilityFlags);

trait Marker {
    type Shape: Clone + Copy;
    const UNIFORM_CAPACITY: usize;

    fn as_shape(&self, position: Vec2) -> Self::Shape;
    fn apply_to_material(material: &mut TerrainMaterial, shapes: Vec<Self::Shape>);
}

/// This component configures a semi-transparent circle drawn on the terrain
/// surface below the entity.
#[derive(Component)]
pub struct CircleMarker {
    radius: f32,
}

impl CircleMarker {
    /// Crates a new circle marker.
    pub fn new(radius: f32) -> Self {
        Self { radius }
    }
}

impl Marker for CircleMarker {
    type Shape = Circle;
    const UNIFORM_CAPACITY: usize = CIRCLE_CAPACITY;

    fn as_shape(&self, position: Vec2) -> Self::Shape {
        Circle::new(position, self.radius)
    }

    fn apply_to_material(material: &mut TerrainMaterial, shapes: Vec<Self::Shape>) {
        material.set_circle_markers(shapes);
    }
}

/// This component configures a semi-transparent rectangle drawn on the terrain
/// surface below the entity.
#[derive(Component)]
pub struct RectangleMarker {
    inverse_transform: Mat3,
    half_size: Vec2,
}

impl RectangleMarker {
    /// Creates a new rectangle marker.
    pub fn new(transform: &Transform, half_size: Vec2) -> Self {
        Self {
            inverse_transform: transform.compute_matrix().inverse().to_flat(),
            half_size,
        }
    }

    /// Creates a new rectangle marker with the size of the AABB plus a margin.
    pub fn from_aabb_transform(local_aabb: Aabb, transform: &Transform) -> Self {
        let half_extents: Vec2 = local_aabb.half_extents().into();
        Self::new(
            transform,
            half_extents + Vec2::ONE * RECTANGLE_MARKER_MARGIN,
        )
    }
}

impl Marker for RectangleMarker {
    type Shape = Rectangle;
    const UNIFORM_CAPACITY: usize = RECTANGLE_CAPACITY;

    fn as_shape(&self, _position: Vec2) -> Self::Shape {
        Rectangle::new(self.inverse_transform, self.half_size)
    }

    fn apply_to_material(material: &mut TerrainMaterial, shapes: Vec<Self::Shape>) {
        material.set_rectangle_markers(shapes);
    }
}

fn update_markers<M>(
    mut materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, TerrainMaterial>>>,
    solids: SolidObjects,
    camera: Query<(&Transform, &Frustum), With<Camera3d>>,
    terrains: Query<(
        &ViewVisibility,
        &Handle<ExtendedMaterial<StandardMaterial, TerrainMaterial>>,
    )>,
    markers: Query<(
        &ObjectTypeComponent,
        &ViewVisibility,
        &GlobalTransform,
        &M,
        &MarkerVisibility,
    )>,
) where
    M: Marker + Component,
{
    let (eye, cam_frustum) = match camera.get_single() {
        Ok((transform, frustum)) => (transform.translation, frustum),
        Err(_) => return,
    };

    struct ShapeWithDist<S> {
        shape: S,
        distance_sq: FloatOrd,
    }

    let mut candidates = Vec::new();
    for (&object_type, circle_visibility, transform, marker, marker_visibility) in markers.iter() {
        if !circle_visibility.get() {
            continue;
        }

        if !marker_visibility.0.visible() {
            continue;
        }

        let aabb = solids.get(*object_type).collider().aabb();
        let aabb = BevyAabb {
            center: Vec3A::from(aabb.center()),
            half_extents: Vec3A::from(aabb.half_extents()),
        };

        if frustum::intersects_bevy(cam_frustum, transform, &aabb) {
            let translation = transform.translation();
            candidates.push(ShapeWithDist {
                shape: marker.as_shape(translation.to_flat()),
                distance_sq: FloatOrd(eye.distance_squared(translation)),
            });
        }
    }
    candidates.sort_unstable_by_key(|c| c.distance_sq);

    let shapes: Vec<M::Shape> = candidates
        .iter()
        .take(M::UNIFORM_CAPACITY)
        .map(|s| s.shape)
        .collect();

    for (terrain_visibility, material) in terrains.iter() {
        if !terrain_visibility.get() {
            continue;
        }

        let material = materials.get_mut(material).unwrap();
        M::apply_to_material(&mut material.extension, shapes.clone());
    }
}