Skip to main content

cuqueclicker_lib/ui/
sidebar.rs

1use ratatui::{prelude::*, widgets::*};
2
3use crate::format;
4use crate::game::fingerer::{self, FINGERERS};
5use crate::game::state::{
6    GREEN_COIN_ROW_FLASH_TICKS, GameState, PURCHASE_FLASH_TICKS, UNLOCK_FLASH_TICKS,
7};
8use crate::i18n::t;
9use crate::ui::border;
10
11const ROWS_PER_FINGERER: u16 = 4;
12const FLASH_TINT: (f32, f32, f32) = (40.0, 230.0, 80.0);
13const UNAFFORDABLE_TINT: (f32, f32, f32) = (255.0, 60.0, 60.0);
14/// Brighter, more saturated green for the "now affordable!" one-shot —
15/// sits a notch above the regular purchase flash hue so the player can
16/// tell the two events apart on glance.
17const UNLOCK_TINT: (f32, f32, f32) = (120.0, 255.0, 140.0);
18/// Warm gold for the row that just received a Green Coin boost.
19/// Matches the "+10% <fingerer>" particle hue (`ParticleKind::Golden`),
20/// so the eye can track the floating label down to the sidebar row.
21const GREEN_COIN_ROW_TINT: (f32, f32, f32) = (255.0, 215.0, 0.0);
22// Resting color the flash starts from / returns to (neutral gray similar to
23// default terminal text, so the transition in and out is gentle).
24const FLASH_REST: (f32, f32, f32) = (200.0, 200.0, 210.0);
25// Active carrier: pure white so the wave pulses white<->green with maximum
26// contrast during the flash.
27const FLASH_CARRIER: (f32, f32, f32) = (255.0, 255.0, 255.0);
28const FLASH_CYCLE: f32 = 11.0;
29
30/// Returns one entry per visible fingerer row: the live `FINGERERS` index
31/// and the click-target rect on screen. Aligned 1:1 with the rendered rows
32/// so the click router can map a click coordinate to an
33/// `Action::BuyFingerer` without re-parsing the panel layout.
34pub fn draw(
35    frame: &mut Frame,
36    area: Rect,
37    state: &GameState,
38    mouse_pos: Option<(u16, u16)>,
39) -> Vec<(usize, Rect)> {
40    let lang = t();
41    let mut lines: Vec<Line> = Vec::new();
42    let visible: Vec<usize> = (0..FINGERERS.len())
43        .filter(|&i| fingerer::visible(i, state.fingerer_count_idx(i), state.lifetime_cuques))
44        .collect();
45
46    for (slot, &i) in visible.iter().enumerate() {
47        if slot >= 10 {
48            break;
49        }
50        let hotkey = if slot == 9 {
51            '0'
52        } else {
53            (b'1' + slot as u8) as char
54        };
55        let k = &FINGERERS[i];
56        let owned = state.fingerer_count_idx(i);
57        let cost = state.cost(i);
58        let affordable = state.can_buy(i);
59        let cost_style = if affordable {
60            Style::default()
61                .fg(Color::Rgb(0, 255, 80))
62                .add_modifier(Modifier::BOLD)
63        } else {
64            Style::default().fg(Color::Rgb(220, 70, 70))
65        };
66        let name = lang.fingerer_names.get(i).copied().unwrap_or("?");
67        lines.push(Line::from(vec![
68            Span::styled(format!("[{}] ", hotkey), Style::default().fg(Color::Yellow)),
69            Span::raw(k.icon),
70            Span::raw(" "),
71            Span::styled(
72                name.to_string(),
73                Style::default().add_modifier(Modifier::BOLD),
74            ),
75        ]));
76        lines.push(Line::from(vec![
77            Span::raw(format!("    {}: {}  ", lang.owned, owned)),
78            Span::styled(format!("{} {}", lang.cost, format::big(cost)), cost_style),
79        ]));
80        let mult = state.fingerer_mult(i);
81        let effective = k.fps_per_unit * mult;
82        let mult_tag = if mult > 1.0001 {
83            format!(" (x{:.1})", mult)
84        } else {
85            String::new()
86        };
87        // Permanent-modifier badge: how much the player has stacked from
88        // Green Coins (et al) on this fingerer, summed as AddPercent. Timed
89        // modifiers (Purple Coin) are intentionally excluded — they show up
90        // in the active-modifiers strip on the HUD instead. Skip the badge
91        // entirely if there's nothing to brag about.
92        let perm_pct: f64 = state
93            .fingerers_state
94            .get(k.id)
95            .map(|st| {
96                st.modifiers
97                    .iter()
98                    .filter(|m| {
99                        matches!(
100                            m.duration,
101                            crate::game::modifier::ModifierDuration::Permanent
102                        )
103                    })
104                    .flat_map(|m| m.effects.iter())
105                    .filter_map(|e| match e {
106                        crate::game::modifier::ModifierEffect::AddPercent(v) => Some(*v),
107                        _ => None,
108                    })
109                    .sum()
110            })
111            .unwrap_or(0.0);
112        let mut spans = vec![Span::raw(format!(
113            "    +{} {}{}",
114            format::rate(effective),
115            lang.fps_each,
116            mult_tag,
117        ))];
118        if perm_pct > 0.0001 {
119            spans.push(Span::styled(
120                format!(" +{:.0}%", perm_pct * 100.0),
121                Style::default()
122                    .fg(Color::Rgb(120, 230, 140))
123                    .add_modifier(Modifier::BOLD),
124            ));
125        }
126        lines.push(Line::from(spans));
127        lines.push(Line::raw(""));
128    }
129    let p = Paragraph::new(lines).block(Block::bordered().title(lang.fingerers_title));
130    frame.render_widget(p, area);
131
132    paint_flashes(frame, area, state, &visible);
133
134    // Panel-border flash on purchase: green if any fingerer's row flash is
135    // burning, red if any unaffordable click was just rejected. Mirrors the
136    // HUD title's behavior so the whole panel pulses, not just the row.
137    let any_purchase = visible
138        .iter()
139        .filter_map(|&i| state.fingerer_flash_ticks.get(i).copied())
140        .max()
141        .unwrap_or(0);
142    let any_unaff = visible
143        .iter()
144        .filter_map(|&i| state.fingerer_unaffordable_flash.get(i).copied())
145        .max()
146        .unwrap_or(0);
147    // Carrier-strength is timing-only — no bulk-buy scaling — so the
148    // panel border reaches full white on every flash. The wave amplitude
149    // booster (bulk-buy intensity) is handled inside `paint_border_flash`.
150    let purchase_strength = border::plateau_fade(any_purchase, PURCHASE_FLASH_TICKS);
151    let unaff_strength = border::plateau_fade(any_unaff, PURCHASE_FLASH_TICKS / 2);
152    // Unaffordable wins when active. The unaff flash lasts half as long
153    // as purchase (10 vs 20 ticks), so any active unaff IS the most
154    // recent action — clicking unaffordable while a previous buy's green
155    // is still decaying must immediately show red, not get suppressed.
156    // After ~0.5s the unaff fades and green resumes until it expires too.
157    if unaff_strength > 0.001 {
158        border::paint_border_flash(
159            frame,
160            area,
161            state,
162            border::PANEL_UNAFFORDABLE_TINT,
163            border::PANEL_UNAFFORDABLE_CYCLE,
164            unaff_strength,
165        );
166    } else if purchase_strength > 0.001 {
167        border::paint_border_flash(
168            frame,
169            area,
170            state,
171            border::PANEL_PURCHASE_TINT,
172            border::PANEL_PURCHASE_CYCLE,
173            purchase_strength,
174        );
175    }
176
177    if area.width < 3 || area.height < 3 {
178        return Vec::new();
179    }
180    let inner_x = area.x + 1;
181    let inner_y = area.y + 1;
182    let inner_w = area.width.saturating_sub(2);
183    let inner_h = area.height.saturating_sub(2);
184    let mut rows: Vec<(usize, Rect)> = Vec::new();
185    for (slot, &i) in visible.iter().enumerate() {
186        if slot >= 10 {
187            break;
188        }
189        let row_top = slot as u16 * ROWS_PER_FINGERER;
190        if row_top >= inner_h {
191            break;
192        }
193        // Skip the trailing blank separator (3 useful rows out of 4).
194        let height = (ROWS_PER_FINGERER - 1).min(inner_h - row_top);
195        rows.push((
196            i,
197            Rect {
198                x: inner_x,
199                y: inner_y + row_top,
200                width: inner_w,
201                height,
202            },
203        ));
204    }
205    paint_hover(frame, &rows, mouse_pos);
206    rows
207}
208
209/// Paint a subtle brightness lift on whichever row the mouse is currently
210/// over. Only the cells that already have content keep their styled
211/// foreground; this just bumps brightness, so a hovered row reads as
212/// "live" without changing the underlying color hierarchy. Cheap: at
213/// most 10 rows × ~36 cols × 3 lines = ~1k cells per hover frame.
214fn paint_hover(frame: &mut Frame, rows: &[(usize, Rect)], mouse_pos: Option<(u16, u16)>) {
215    let Some((mx, my)) = mouse_pos else { return };
216    let Some(&(_, r)) = rows
217        .iter()
218        .find(|&&(_, r)| mx >= r.x && mx < r.x + r.width && my >= r.y && my < r.y + r.height)
219    else {
220        return;
221    };
222    let buf = frame.buffer_mut();
223    for dy in 0..r.height {
224        let y = r.y + dy;
225        if y >= buf.area.y + buf.area.height {
226            break;
227        }
228        for dx in 0..r.width {
229            let x = r.x + dx;
230            if x >= buf.area.x + buf.area.width {
231                break;
232            }
233            let cell = &mut buf[(x, y)];
234            // Lift the existing fg by a fixed amount and ensure BOLD.
235            // The cell's fg may already be tinted (cost-color, flash, etc) —
236            // brightening it preserves hue but makes the row pop.
237            if let Color::Rgb(r, g, b) = cell.fg {
238                cell.set_fg(Color::Rgb(
239                    (r as u16 + 30).min(255) as u8,
240                    (g as u16 + 30).min(255) as u8,
241                    (b as u16 + 30).min(255) as u8,
242                ));
243            }
244            cell.modifier.insert(Modifier::BOLD);
245            // Subtle bg tint so even blank cells in the row signal "hover."
246            cell.set_bg(Color::Rgb(28, 28, 36));
247        }
248    }
249}
250
251fn paint_flashes(frame: &mut Frame, area: Rect, state: &GameState, visible: &[usize]) {
252    if area.width < 3 || area.height < 3 {
253        return;
254    }
255    // Steady phase clock — independent of HUD-border speed-ups so an
256    // achievement / frenzy / lucky event firing on the title border
257    // doesn't drag the sidebar's "can't-buy" or "purchase" shimmer along.
258    let phase = state.steady_phase as f32;
259    let inner_x = area.x + 1;
260    let inner_y = area.y + 1;
261    let inner_right = area.x + area.width - 1;
262    let inner_bottom = area.y + area.height - 1;
263    // Bulk-buy intensifier: 1.0..3.0 multiplier on the WAVE AMPLITUDE only
264    // (not the carrier brightness). A single buy already pulses fully white
265    // ↔ tint with maximum contrast; bulk-buy just pushes the tint peaks
266    // harder so a max-buy reads louder without dimming the white carrier.
267    let bulk_amp = state.purchase_flash_strength.clamp(1.0, 3.0);
268    let buf = frame.buffer_mut();
269
270    for (slot, &fingerer_idx) in visible.iter().enumerate() {
271        if slot >= 10 {
272            break;
273        }
274        let purchase_ticks = state
275            .fingerer_flash_ticks
276            .get(fingerer_idx)
277            .copied()
278            .unwrap_or(0);
279        let unaff_ticks = state
280            .fingerer_unaffordable_flash
281            .get(fingerer_idx)
282            .copied()
283            .unwrap_or(0);
284        let unlock_ticks = state
285            .fingerer_unlock_flash
286            .get(fingerer_idx)
287            .copied()
288            .unwrap_or(0);
289        let green_coin_ticks = state
290            .fingerer_green_coin_flash
291            .get(fingerer_idx)
292            .copied()
293            .unwrap_or(0);
294        // Per-row tint priority:
295        //   purchase     (you just bought)        — wins, longest, with bulk amp
296        //   unaffordable (you tried + failed)    — wins over unlock
297        //   green-coin   (Green Coin landed here) — gold shimmer, ~2s
298        //   unlock       (just became affordable) — quietly announces the row
299        // `strength` is the carrier blend (timing only, 0..1); `amp`
300        // boosts the wave's tint contribution for bulk buys.
301        let (strength, tint, amp) = if purchase_ticks > 0 {
302            (
303                smoothstep(purchase_ticks as f32 / PURCHASE_FLASH_TICKS as f32),
304                FLASH_TINT,
305                bulk_amp,
306            )
307        } else if unaff_ticks > 0 {
308            (
309                smoothstep(unaff_ticks as f32 / (PURCHASE_FLASH_TICKS as f32 / 2.0)),
310                UNAFFORDABLE_TINT,
311                1.0,
312            )
313        } else if green_coin_ticks > 0 {
314            (
315                smoothstep(green_coin_ticks as f32 / GREEN_COIN_ROW_FLASH_TICKS as f32),
316                GREEN_COIN_ROW_TINT,
317                1.0,
318            )
319        } else if unlock_ticks > 0 {
320            (
321                smoothstep(unlock_ticks as f32 / UNLOCK_FLASH_TICKS as f32),
322                UNLOCK_TINT,
323                1.0,
324            )
325        } else {
326            continue;
327        };
328        if strength <= 0.001 {
329            continue;
330        }
331        let row_start = inner_y + slot as u16 * ROWS_PER_FINGERER;
332        // Carrier eases from resting gray to pure WHITE on full strength —
333        // never washed out by bulk-buy. The wave below paints tint on top.
334        let carrier_r = FLASH_REST.0 + (FLASH_CARRIER.0 - FLASH_REST.0) * strength;
335        let carrier_g = FLASH_REST.1 + (FLASH_CARRIER.1 - FLASH_REST.1) * strength;
336        let carrier_b = FLASH_REST.2 + (FLASH_CARRIER.2 - FLASH_REST.2) * strength;
337        // First 3 of the 4 rows hold the fingerer's text; the 4th is the
338        // blank separator.
339        for dy in 0..3u16 {
340            let row = row_start + dy;
341            if row >= inner_bottom {
342                break;
343            }
344            for col in inner_x..inner_right {
345                let rel = (col - area.x) as f32;
346                let wave01 =
347                    (((rel + phase) * std::f32::consts::TAU / FLASH_CYCLE).sin() + 1.0) * 0.5;
348                let contribution = (wave01 * strength * amp).min(1.0);
349                let r = carrier_r + (tint.0 - carrier_r) * contribution;
350                let g = carrier_g + (tint.1 - carrier_g) * contribution;
351                let b = carrier_b + (tint.2 - carrier_b) * contribution;
352                let cell = &mut buf[(col, row)];
353                cell.set_fg(Color::Rgb(r as u8, g as u8, b as u8));
354                cell.modifier.insert(Modifier::BOLD);
355            }
356        }
357    }
358}
359
360fn smoothstep(t: f32) -> f32 {
361    let t = t.clamp(0.0, 1.0);
362    t * t * (3.0 - 2.0 * t)
363}