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
186
187
188
use bevy::{ecs::system::SystemParam, prelude::*};
use de_core::{
    gamestate::GameState, objects::ObjectTypeComponent, player::PlayerComponent,
    schedule::PostMovement,
};
use de_map::size::MapBounds;
use de_objects::SolidObjects;
use de_terrain::TerrainCollider;
use de_types::{
    objects::{ActiveObjectType, ObjectType},
    player::Player,
    projection::ToFlat,
};
use parry2d::{
    bounding_volume::Aabb,
    math::Point,
    query::{Ray, RayCast},
};

use super::draw::DrawingParam;
use crate::ray::ScreenRay;

const TERRAIN_COLOR: Color = Color::rgb(0.61, 0.46, 0.32);
const PLAYER_COLORS: [Color; Player::MAX_PLAYERS] = [
    Color::rgb(0.1, 0.1, 0.9),
    Color::rgb(0.1, 0.9, 0.1),
    Color::rgb(0.9, 0.1, 0.1),
    Color::rgb(0.9, 0.9, 0.1),
];
const MIN_ENTITY_SIZE: Vec2 = Vec2::splat(0.02);
const CAMERA_COLOR: Color = Color::rgb(0.9, 0.9, 0.9);

#[derive(Resource, Debug)]
struct PlayerColors([Color; Player::MAX_PLAYERS]);

impl PlayerColors {
    fn get_color(&self, player: Player, object_type: ActiveObjectType) -> Color {
        let player_idx: usize = (player.to_num() - 1) as usize;
        let player_color = self.0[player_idx].as_hsla();
        match object_type {
            ActiveObjectType::Building(_) => player_color,
            ActiveObjectType::Unit(_) => player_color.with_s(0.7 * player_color.s()),
        }
    }
}

impl Default for PlayerColors {
    fn default() -> Self {
        Self(PLAYER_COLORS)
    }
}

pub(super) struct FillPlugin;

impl Plugin for FillPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            PostMovement,
            (
                clear_system.in_set(FillSet::Clear),
                draw_entities_system
                    .in_set(FillSet::DrawEntities)
                    .after(FillSet::Clear),
                draw_camera_system.after(FillSet::DrawEntities),
            )
                .run_if(in_state(GameState::Playing)),
        );
    }
}

#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, SystemSet)]
enum FillSet {
    Clear,
    DrawEntities,
}

#[derive(SystemParam)]
struct UiCoords<'w> {
    bounds: Res<'w, MapBounds>,
}

impl<'w> UiCoords<'w> {
    /// Transforms 2D flat position (in meters from origin) to relative UI
    /// position (from 0 to 1 from top-right corner).
    fn flat_to_rel(&self, point: Vec2) -> Vec2 {
        Vec2::new(point.x - self.bounds.min().x, self.bounds.max().y - point.y) / self.bounds.size()
    }

    /// Transforms 2D flat position (in meters from origin) to relative UI
    /// position (from 0 to 1 from top-right corner).
    fn size_to_rel(&self, size: Vec2) -> Vec2 {
        size / self.bounds.size()
    }
}

fn clear_system(mut drawing: DrawingParam) {
    let mut drawing = drawing.drawing();
    drawing.fill(TERRAIN_COLOR);
}

fn draw_entities_system(
    mut drawing: DrawingParam,
    ui_coords: UiCoords,
    solids: SolidObjects,
    colors: Local<PlayerColors>,
    entities: Query<(&Transform, &PlayerComponent, &ObjectTypeComponent)>,
) {
    let mut drawing = drawing.drawing();

    for (transform, &player, &object_type) in entities.iter() {
        let minimap_position = ui_coords.flat_to_rel(transform.translation.to_flat());
        if let ObjectType::Active(active_object) = *object_type {
            let color = colors.get_color(*player, active_object);
            let radius = solids.get(*object_type).ichnography().radius();
            let rect_size = MIN_ENTITY_SIZE.max(ui_coords.size_to_rel(Vec2::splat(radius)));
            drawing.rect(minimap_position, rect_size, color);
        }
    }
}

#[derive(SystemParam)]
struct CameraPoint<'w, 's> {
    ray: ScreenRay<'w, 's>,
    terrain: TerrainCollider<'w, 's>,
    ui_coords: UiCoords<'w>,
}

impl<'w, 's> CameraPoint<'w, 's> {
    fn point(&self, ndc: Vec2) -> Option<Vec2> {
        let ray = self.ray.ray(ndc);
        let intersection = self.terrain.cast_ray_msl(&ray, f32::INFINITY)?;
        let point = ray.origin + ray.dir * intersection.toi;
        Some(self.ui_coords.flat_to_rel(point.to_flat()))
    }
}

fn draw_camera_system(mut drawing: DrawingParam, camera: CameraPoint) {
    let mut drawing = drawing.drawing();

    let corner_a = camera.point(Vec2::new(-1., -1.));
    let corner_b = camera.point(Vec2::new(-1., 1.));
    let corner_c = camera.point(Vec2::new(1., 1.));
    let corner_d = camera.point(Vec2::new(1., -1.));

    if let Some((start, end)) = endpoints_to_line(corner_a, corner_b) {
        drawing.line(start, end, CAMERA_COLOR);
    }
    if let Some((start, end)) = endpoints_to_line(corner_b, corner_c) {
        drawing.line(start, end, CAMERA_COLOR);
    }
    if let Some((start, end)) = endpoints_to_line(corner_c, corner_d) {
        drawing.line(start, end, CAMERA_COLOR);
    }
    if let Some((start, end)) = endpoints_to_line(corner_d, corner_a) {
        drawing.line(start, end, CAMERA_COLOR);
    }
}

/// Converts optional line endpoints to a minimap compatible line segment.
///
/// The returned line segment is the longest line segment which a) is fully
/// contained by rectangle (0, 0) -> (1, 1), b) is fully contained by the
/// original line segment.
fn endpoints_to_line(start: Option<Vec2>, end: Option<Vec2>) -> Option<(Vec2, Vec2)> {
    let start = start?;
    let end = end?;

    let mut start: Point<f32> = start.into();
    let mut end: Point<f32> = end.into();

    let aabb = Aabb::new(Point::new(0., 0.), Point::new(1., 1.));
    if !aabb.contains_local_point(&start) {
        let ray = Ray::new(start, end - start);
        let toi = aabb.cast_local_ray(&ray, 1., false)?;
        start = ray.origin + toi * ray.dir;
    }
    if !aabb.contains_local_point(&end) {
        let ray = Ray::new(end, start - end);
        let toi = aabb.cast_local_ray(&ray, 1., false)?;
        end = ray.origin + toi * ray.dir;
    }

    // Clamp to avoid rounding error issues.
    Some((
        Vec2::from(start).clamp(Vec2::ZERO, Vec2::ONE),
        Vec2::from(end).clamp(Vec2::ZERO, Vec2::ONE),
    ))
}