Something went wrong. Try again.
a better speedrun timer
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329/* Copyright 2025 periwinkle
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.*/
use super::{BuiltinPlugin, PAD};
use hail_config::plugins::{Precision, SegmentStat, SegmentTimerConfig};use hail_core::{ HailState, types::{Comparison, SplitStatus, StateChange, TimeType, TimingMethod},};use hail_pdk::{ InputState, font_kit::source::SystemSource, utils::{TextRenderer, format_millis, format_tenths},};
use std::{ cmp::{max, min}, collections::HashMap, mem::replace,};
use anyhow::Result;use sdl2::{ pixels::{Color, PixelFormatEnum}, rect::Rect, render::{ScaleMode, Texture, TextureCreator, TextureQuery, WindowCanvas}, video::WindowContext,};
struct StatTextures { stat: SegmentStat, name: Texture, nwidth: u32, value: Texture,}
impl StatTextures { fn replace_value(&mut self, val: Texture) { // safe as long as the window still exists, which it better. unsafe { replace(&mut self.value, val).destroy(); } }}
pub struct SegmentTimer { stats_renderer: TextRenderer, creator: TextureCreator<WindowContext>, stat_texes: Vec<StatTextures>, bg_color: Color, base_color: Color, none: HashMap<char, Texture>, behind: HashMap<char, Texture>, gaining: HashMap<char, Texture>, losing: HashMap<char, Texture>, ahead: HashMap<char, Texture>, advance: i32, decimal_advance: i32, decimal_scale: f32, decimal_chars: usize, asc_adj: i32, timer_pad: i32, canv_height: u32, timing: TimingMethod,}
impl SegmentTimer { pub fn new( config: SegmentTimerConfig, canvas: &WindowCanvas, source: &SystemSource, ) -> Result<Self> { let mut timer_renderer = TextRenderer::new(source, config.timer_font)?; let mut stats_renderer = TextRenderer::new(source, config.stats_font)?; let creator = canvas.texture_creator();
let mut none = HashMap::new(); let mut behind = HashMap::new(); let mut gaining = HashMap::new(); let mut losing = HashMap::new(); let mut ahead = HashMap::new(); let mut advance = 0; for ch in "0123456789:.".chars() { { let s = String::from(ch); let mut tex = timer_renderer.render_text_line(&s, config.base_color.into(), &creator)?; // safe because it's a valid texture and a valid enum value tex.set_scale_mode(ScaleMode::Best); advance = max(advance, tex.query().width as i32); none.insert(ch, tex); behind.insert( ch, timer_renderer.render_text_line(&s, config.behind_color.into(), &creator)?, ); gaining.insert( ch, timer_renderer.render_text_line(&s, config.gaining_color.into(), &creator)?, ); losing.insert( ch, timer_renderer.render_text_line(&s, config.losing_color.into(), &creator)?, ); ahead.insert( ch, timer_renderer.render_text_line(&s, config.ahead_color.into(), &creator)?, ); } }
let decimal_chars = match config.precision { Precision::Millis => 4, Precision::Hundredths => 3, Precision::Tenths => 2, Precision::Seconds => 0, };
let sdesc = stats_renderer.line_height as i32 - stats_renderer.asc; let spad = PAD - min(sdesc, PAD);
let canv_height = max( stats_renderer.line_height * config.stats.len() as u32 + spad as u32, timer_renderer.line_height, ) + PAD as u32;
let timer_desc = timer_renderer.line_height as i32 - timer_renderer.asc; let timer_pad = PAD - min(timer_desc, PAD);
let mut stat_texes = vec![]; for stat in config.stats { let name = match stat { SegmentStat::Pb => "PB: ", SegmentStat::Gold => "Gold: ", SegmentStat::Avg => "Avg: ", }; let name = stats_renderer.render_text_line(name, config.base_color.into(), &creator)?; let value = creator.create_texture_static(PixelFormatEnum::RGBA32, 1, 1)?; let nwidth = name.query().width; stat_texes.push(StatTextures { stat, name, nwidth, value, }); }
Ok(Self { stats_renderer, creator, stat_texes, none, behind, gaining, losing, ahead, advance, decimal_advance: (config.decimal_scale * advance as f32) as i32, decimal_scale: config.decimal_scale, decimal_chars, asc_adj: timer_desc - (timer_desc as f32 * config.decimal_scale).round() as i32, timer_pad, bg_color: config.bg_color.into(), base_color: config.base_color.into(), canv_height, timing: config.timing, }) }}
impl BuiltinPlugin for SegmentTimer { fn update(&mut self, s: &HailState, _: &InputState) { for &c in &s.changes { match c { StateChange::Reset | StateChange::ChangeSeg { .. } => { for stat in &mut self.stat_texes { let val = match stat.stat { SegmentStat::Pb => s.run.pb_segments(self.timing)[s.current_seg], SegmentStat::Gold => { (if self.timing == TimingMethod::Rta { &s.run.rta_gold_segments } else { &s.run.igt_gold_segments })[s.current_seg] } SegmentStat::Avg => s.run.avg_segments(self.timing)[s.current_seg], }; let text = if val.is_time() { &format_tenths(val.val()) } else { " -" }; let val = self .stats_renderer .render_text_line(text, self.base_color, &self.creator) .unwrap(); stat.replace_value(val); } } _ => {} } } } fn min_dims(&self) -> Option<(u32, u32)> { Some((1, self.canv_height)) } fn max_height(&self) -> u32 { self.canv_height } fn draw(&mut self, s: &HailState, c: &mut WindowCanvas) { let vp = c.viewport(); let c_width = vp.width() as i32; let c_height = vp.height() as i32; c.set_draw_color(self.bg_color); c.clear();
let mut y = PAD; for stat in &self.stat_texes { c.copy( &stat.name, None, Rect::new(PAD, y, stat.nwidth, self.stats_renderer.line_height), ) .unwrap(); let TextureQuery { width, height, .. } = stat.value.query(); c.copy( &stat.value, None, Rect::new(PAD + stat.nwidth as i32, y, width, height), ) .unwrap(); y += self.stats_renderer.line_height as i32; }
let timer = if self.timing == TimingMethod::Rta { &s.rta } else { &s.igt };
let time = if timer.active_time <= 0 { 0 } else { timer.active_time - timer.run_split_times.last().map_or(0, TimeType::val) };
let charmap = if !s.is_running(self.timing) { &self.none } else { let stat = match s.comparison { Comparison::PersonalBest => timer.active_pb_status, Comparison::Golds => timer.active_gold_status, Comparison::Average => timer.active_avg_status, Comparison::None => SplitStatus::None, }; match stat { SplitStatus::None | SplitStatus::Gold => &self.none, SplitStatus::Behind => &self.behind, SplitStatus::Gaining => &self.gaining, SplitStatus::Losing => &self.losing, SplitStatus::Ahead => &self.ahead, } }; let time_str = format_millis(time); let mut x = c_width - PAD;
for (i, ch) in time_str .chars() .rev() .skip(4 - self.decimal_chars) .enumerate() { // should always occur if let Some(tex) = charmap.get(&ch) { let query = tex.query(); let (width, height) = if i < self.decimal_chars { ( (query.width as f32 * self.decimal_scale) as u32, (query.height as f32 * self.decimal_scale) as u32, ) } else { (query.width, query.height) }; let mut y = c_height - height as i32 - self.timer_pad; if ch == ':' || ch == '.' { x -= width as i32; } else if i < self.decimal_chars { x -= self.decimal_advance; } else { x -= self.advance; }
if i < self.decimal_chars { y -= self.asc_adj; } c.copy(tex, None, Rect::new(x, y, width, height)).unwrap(); } } } fn shutdown(&mut self) { for (_, tex) in self.none.drain() { unsafe { tex.destroy() } } for (_, tex) in self.behind.drain() { unsafe { tex.destroy() } } for (_, tex) in self.gaining.drain() { unsafe { tex.destroy() } } for (_, tex) in self.losing.drain() { unsafe { tex.destroy() } } for (_, tex) in self.ahead.drain() { unsafe { tex.destroy() } } for stat in self.stat_texes.drain(..) { unsafe { stat.name.destroy(); stat.value.destroy(); } } }}