aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/strategic_roster.rs
blob: cc4741eefa87c14468a51602632111cade4b4c60 (plain) (blame)
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! The strategic warbot list assembled from installed compound controls.

use crate::{
    game_font::{load_layout_font, BitmapFont},
    mission_pager::copy_sprite,
    ui_sprite::{atlas_region, load_ui_page, load_ui_sprites},
    warbot_card::{self, CardLine},
    RgbaImage,
};
use fparkan_vfs::Vfs;

mod orders;
use orders::OrderImages;
pub use orders::{order_at, RosterOrder};

/// List origin and size in the original logical screen coordinates.
pub const ORIGIN: [u32; 2] = [51, 0];
pub const EXTENT: [u32; 2] = [319, 480];
const ROW_TOP: u32 = 118;
const ROW_PITCH: u32 = 20;
const ROW_HEIGHT: u32 = 19;
const TITLE_WIDTH: u32 = 278;
const CLOSE_LEFT: u32 = 5 + TITLE_WIDTH;
const TEXT_WIDTH: u32 = 248;
const TEXT_LEFT: u32 = 10 + 19 * 2 + 5 + 10;

/// A cockpit control button in its left-to-right card position.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CockpitControl {
    Manual,
    AutoGunner,
    Autopilot,
}

const COCKPIT_CONTROLS: [CockpitControl; 3] = [
    CockpitControl::Manual,
    CockpitControl::AutoGunner,
    CockpitControl::Autopilot,
];

/// The visible interactive area of the original list.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ListHit {
    Close,
    Cockpit(CockpitControl),
    Row(usize),
}

/// Locates a title close control or a list row, preserving the gap between rows.
pub fn hit_test([x, y]: [f32; 2], row_count: usize) -> Option<ListHit> {
    let x = x.round_ties_even() - ORIGIN[0] as f32;
    let y = y.round_ties_even();
    if !(0.0..(EXTENT[0] - 1) as f32).contains(&x) || !(0.0..480.0).contains(&y) {
        return None;
    }
    if x >= CLOSE_LEFT as f32 && y < 20.0 {
        return Some(ListHit::Close);
    }
    // iron3d+0x85c70 expands the icon rectangle by two logical pixels.
    if row_count != 0 && (89.0..108.0).contains(&y) {
        for (index, control) in COCKPIT_CONTROLS.into_iter().enumerate() {
            let left = 10.0 + 24.0 * index as f32;
            if (left..left + 19.0).contains(&x) {
                return Some(ListHit::Cockpit(control));
            }
        }
    }
    let y = (y as u32).checked_sub(ROW_TOP)?;
    let row = (y / ROW_PITCH) as usize;
    (row < row_count && y % ROW_PITCH < ROW_HEIGHT).then_some(ListHit::Row(row))
}

/// Whether the roster or its supported order panel covers the pointer.
pub fn covers_pointer([x, y]: [f32; 2], rows: usize) -> bool {
    let row_end = ROW_TOP + ROW_PITCH * rows.min(19) as u32;
    let [x, y] = [x.round_ties_even(), y.round_ties_even()];
    rows != 0
        && ((ORIGIN[0] as f32..(ORIGIN[0] + EXTENT[0] - 1) as f32).contains(&x)
            && (0.0..row_end as f32).contains(&y)
            || orders::covers_pointer([x, y], rows))
}

/// A localized row with the native icon selectors.
pub struct Row<'a> {
    pub label: &'a str,
    pub size: u32,
    pub chassis: u32,
    pub selected: bool,
    pub durability_percent: Option<i32>,
}

/// Resident art for the header, selected-unit frame, and rows.
pub struct RosterImages {
    background: RgbaImage,
    font: BitmapFont,
    cap: [RgbaImage; 2],
    icon_frame: RgbaImage,
    separator: RgbaImage,
    emitter: [RgbaImage; 2],
    ray: RgbaImage,
    end: RgbaImage,
    class_icon: RgbaImage,
    chassis_icons: [RgbaImage; 4],
    cockpit_controls: [RgbaImage; 4],
    orders: OrderImages,
}

impl RosterImages {
    /// Loads the same atlas crops used by the original compound controls.
    pub fn load(vfs: &dyn Vfs, title: &str) -> Result<Self, String> {
        let [title_cap, title_body, close, cap_off, cap_on, separator, emitter_off, emitter_on, ray, end, tl, tr, br, bl, horizontal, vertical] =
            load_ui_sprites(
                vfs,
                "ui/compaund.cfg",
                [
                    "ccres_ending_text",
                    "ccres_body_text",
                    "ccres_exit_button_pressed",
                    "ccres_lamp_text_ending_off",
                    "ccres_lamp_text_ending_normal",
                    "ccres_separator_left_text",
                    "ccres_ray_emitter_off",
                    "ccres_ray_emitter_normal",
                    "ccres_ray_body",
                    "ccres_ray_ending",
                    "ccres_frame_corner_1",
                    "ccres_frame_corner_2",
                    "ccres_frame_corner_3",
                    "ccres_frame_corner_4",
                    "ccres_frame_edge_h",
                    "ccres_frame_edge_v",
                ],
            )?;
        let [exit_icon] = load_ui_sprites(vfs, "ui/hq.cfg", ["exit_icon"])?;
        let [width, height] = EXTENT;
        let mut background = RgbaImage {
            width,
            height,
            rgba8: vec![0; (width * height * 4) as usize],
        };
        let font = load_layout_font(vfs)?;
        let caption = font.centered_line(title, TITLE_WIDTH as u16, ROW_HEIGHT as u16)?;
        stamp(&mut background, &title_cap, [0, 0, 6, 19], [255; 3]);
        stamp(
            &mut background,
            &title_body,
            [5, 0, CLOSE_LEFT + 1, 19],
            [255; 3],
        );
        stamp(&mut background, &caption, [5, 0, CLOSE_LEFT, 19], [255; 3]);
        stamp(&mut background, &close, [CLOSE_LEFT, 0, 318, 19], [255; 3]);
        stamp(
            &mut background,
            &exit_icon,
            [CLOSE_LEFT + 15, 3, CLOSE_LEFT + 28, 16],
            [255; 3],
        );

        // iron3d+0x85910 supplies the frame rectangle and its ARGB fill.
        let fill = RgbaImage {
            width: 1,
            height: 1,
            rgba8: vec![0, 128, 0, 128],
        };
        for (sprite, bounds) in [
            (&fill, [5, 25, 313, 112]),
            (&horizontal, [8, 20, 310, 25]),
            (&horizontal, [8, 112, 310, 117]),
            (&vertical, [0, 28, 5, 109]),
            (&vertical, [313, 28, 318, 109]),
            (&tl, [0, 20, 8, 28]),
            (&tr, [310, 20, 318, 28]),
            (&br, [310, 109, 318, 117]),
            (&bl, [0, 109, 8, 117]),
        ] {
            stamp(&mut background, sprite, bounds, [255; 3]);
        }
        let atlas = load_ui_page(vfs, "ui_menu")?;
        let icon =
            |x, y| atlas_region(&atlas, [x, y, 15, 15]).ok_or("warbot glyph outside ui_menu");
        Ok(Self {
            background,
            font,
            cap: [cap_off, cap_on],
            icon_frame: title_body,
            separator,
            emitter: [emitter_off, emitter_on],
            ray,
            end,
            class_icon: icon(49, 110)?,
            chassis_icons: [icon(97, 94)?, icon(49, 94)?, icon(65, 94)?, icon(81, 94)?],
            cockpit_controls: load_ui_sprites(
                vfs,
                "ui/hq.cfg",
                [
                    "short_button_frame_off",
                    "buildscreen_hq_icon",
                    "botscreen_autogunner_icon",
                    "botscreen_autodriver_icon",
                ],
            )?,
            orders: OrderImages::load(vfs)?,
        })
    }

    /// Renders the visible rows and card of the selected unit.
    pub fn paint(
        &self,
        rows: &[Row<'_>],
        card: &[Option<CardLine<'_>>],
        cockpit_controls_enabled: bool,
        orders: Option<([&str; 6], Option<RosterOrder>)>,
    ) -> Result<RgbaImage, String> {
        let mut panel = self.background.clone();
        if let Some(row) = rows.iter().find(|row| row.selected) {
            self.icons(&mut panel, row, [9, 27]);
            let width = u32::from(self.font.line_metrics(row.label)?[0]).min(263);
            let name = self.font.centered_line(row.label, width as u16, 16)?;
            stamp(&mut panel, &name, [49, 25, 49 + width, 41], [255, 255, 0]);
            warbot_card::paint(&self.font, &mut panel, card)?;
            let tint = if cockpit_controls_enabled {
                [255; 3]
            } else {
                [128; 3]
            };
            let [frame, icons @ ..] = &self.cockpit_controls;
            for (index, icon) in icons.iter().enumerate() {
                let x = 9 + 24 * index as u32;
                stamp(&mut panel, frame, [x, 88, x + 21, 109], tint);
                stamp(&mut panel, icon, [x + 3, 91, x + 18, 106], tint);
            }
        }
        for (index, row) in rows.iter().take(19).enumerate() {
            let y = ROW_TOP + index as u32 * ROW_PITCH;
            let bottom = y + ROW_HEIGHT;
            for (sprite, left, width) in [
                (&self.cap[usize::from(row.selected)], 0, 11),
                (&self.icon_frame, 10, 20),
                (&self.icon_frame, 29, 20),
                (&self.separator, 48, 6),
                (&self.emitter[usize::from(row.selected)], 53, 11),
                (&self.ray, TEXT_LEFT, TEXT_WIDTH + 1),
                (&self.end, TEXT_LEFT + TEXT_WIDTH, 7),
            ] {
                stamp(
                    &mut panel,
                    sprite,
                    [left, y, left + width, bottom],
                    [255; 3],
                );
            }
            self.icons(&mut panel, row, [12, y + 2]);
            if let Some((width, rgba)) = row
                .durability_percent
                .and_then(|percent| durability_fill(percent, TEXT_WIDTH))
            {
                let fill = RgbaImage {
                    width: 1,
                    height: 1,
                    rgba8: rgba.to_vec(),
                };
                stamp(
                    &mut panel,
                    &fill,
                    [TEXT_LEFT + 2, y + 3, TEXT_LEFT + width, bottom - 3],
                    [255; 3],
                );
            }
            let name = self
                .font
                .centered_line(row.label, TEXT_WIDTH as u16, ROW_HEIGHT as u16)?;
            let tint = if row.selected { [255; 3] } else { [128; 3] };
            stamp(
                &mut panel,
                &name,
                [TEXT_LEFT, y, TEXT_LEFT + TEXT_WIDTH, bottom],
                tint,
            );
        }
        if let Some((labels, hovered)) = orders {
            self.orders
                .paint(self, &mut panel, rows.len(), labels, hovered)?;
        }
        Ok(panel)
    }

    fn icons(&self, panel: &mut RgbaImage, row: &Row<'_>, [left, top]: [u32; 2]) {
        let tint = match row.size {
            1 => [255, 231, 255],
            2 => [255, 128, 128],
            3 => [128, 255, 128],
            4 => [128, 128, 255],
            _ => [255; 3],
        };
        stamp(
            panel,
            &self.class_icon,
            [left, top, left + 15, top + 15],
            tint,
        );
        if let Some(icon) = row
            .chassis
            .checked_sub(1)
            .and_then(|index| self.chassis_icons.get(index as usize))
        {
            stamp(panel, icon, [left + 19, top, left + 34, top + 15], tint);
        }
    }
}

fn stamp(panel: &mut RgbaImage, sprite: &RgbaImage, bounds: [u32; 4], tint: [u8; 3]) {
    copy_sprite(panel, sprite, bounds, [false; 2], tint);
}

pub(crate) fn durability_fill(percent: i32, span: u32) -> Option<(u32, [u8; 4])> {
    let width = (f64::from(percent.min(100)) * f64::from(span) * f64::from(0.01_f32))
        .round_ties_even() as u32;
    let rgba = match percent {
        ..=19 => [128, 0, 0, 128],
        20..=79 => [128, 128, 0, 128],
        _ => [0, 128, 0, 128],
    };
    (width > 2).then_some((width, rgba))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hit_testing_matches_visible_rows_and_the_close_button() {
        assert_eq!(hit_test([350.0, 7.0], 3), Some(ListHit::Close));
        assert_eq!(hit_test([200.0, 118.0], 3), Some(ListHit::Row(0)));
        assert_eq!(hit_test([200.0, 137.0], 3), None);
        assert_eq!(hit_test([200.0, 138.0], 3), Some(ListHit::Row(1)));
        assert_eq!(hit_test([200.0, 158.0], 2), None);
        assert_eq!(hit_test([200.0, 480.0], 20), None);
    }

    #[test]
    fn cockpit_buttons_use_enlarged_hit_boxes_with_gaps() {
        for (x, button) in [
            (61.0, super::CockpitControl::Manual),
            (85.0, super::CockpitControl::AutoGunner),
            (109.0, super::CockpitControl::Autopilot),
        ] {
            let hit = Some(ListHit::Cockpit(button));
            assert_eq!(hit_test([x, 89.0], 3), hit);
            assert_eq!(hit_test([x + 18.0, 107.0], 3), hit);
            assert_eq!(hit_test([x - 1.0, 89.0], 3), None);
            assert_eq!(hit_test([x + 19.0, 107.0], 3), None);
            assert_eq!(hit_test([x, 108.0], 3), None);
            assert_eq!(hit_test([x, 89.0], 0), None);
        }
    }

    #[test]
    fn original_durability_colours_follow_the_rounded_health_percentage() {
        let durability_fill = |percent| super::durability_fill(percent, TEXT_WIDTH);
        assert_eq!(durability_fill(0), None);
        assert_eq!(durability_fill(19), Some((47, [128, 0, 0, 128])));
        assert_eq!(durability_fill(20), Some((50, [128, 128, 0, 128])));
        assert_eq!(durability_fill(79), Some((196, [128, 128, 0, 128])));
        assert_eq!(durability_fill(80), Some((198, [0, 128, 0, 128])));
        assert_eq!(durability_fill(100), Some((248, [0, 128, 0, 128])));
    }
}