Launcher : mods et pack HD des decors

- carte « Mods et decors HD » : mods actifs, decors HD, un interrupteur par mod
  (nom, auteur, description de mod.ini ; nombre de decors HD et de fichiers)
- creation d'un pack HD avec Upscayl (choix du modele, tools/hd_export.py)
- apercu « Bienvenue a Barryville » et banniere avec les decors HD
  (pas avec le filtre CRT, comme en jeu)
- settings.ini : cles lues et ecrites dans leur section ([display], [audio], [mods])
- compilation via build.bat DOSSIER / build.bat nogen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
linkatplugandClaude Opus 5.5 committed 2026-12-05 03:37:33 +01:00
1 parent 37acf64362
commit 50e0c507f0
7 files changed
+626 -85

No files matched your search

+1
View File
@@ -399,6 +399,7 @@ name = "dtr-launcher"
version = "0.1.0"
dependencies = [
"eframe",
"png",
]
[[package]]
+1
View File
@@ -10,6 +10,7 @@ name = "DoubleTroubleLauncher"
path = "src/main.rs"
[dependencies]
png = "0.18"
eframe = { version = "0.38", default-features = false, features = ["glow", "default_fonts", "clipboard", "links"] }
[profile.release]
+14 -4
View File
@@ -304,17 +304,27 @@ fn read(dir: &Path, rel: &str) -> Option<Vec<u8>> {
/// décors utilisés en fond de bannière (partie jeu 320×140, sans le panneau)
const BACKDROPS: &[&str] = &["LOC01", "LOC20", "LOC10", "LOC50", "DICKDIGS", "LOC40A", "CLIO1"];
pub fn backdrops(dir: &Path) -> Vec<Rgba> {
/// (nom du PCX, image) des décors trouvés
pub fn backdrops(dir: &Path) -> Vec<(&'static str, Rgba)> {
BACKDROPS
.iter()
.filter_map(|n| decode_pcx(&read(dir, &format!("{n}.PCX"))?))
.map(|p| {
.filter_map(|n| {
let p = decode_pcx(&read(dir, &format!("{n}.PCX"))?)?;
let h = p.h.min(140);
p.to_rgba(0, 0, p.w, h, |_, _| 255)
Some((*n, p.to_rgba(0, 0, p.w, h, |_, _| 255)))
})
.collect()
}
impl Rgba {
/// garde les `num`/`den` premières lignes (partie jeu d'un décor HD plein écran)
pub fn top(mut self, num: usize, den: usize) -> Self {
self.h = self.h * num / den;
self.px.truncate(self.w * self.h * 4);
self
}
}
/// logo « Bud Tucker in Double Trouble » : dernière image de l'écran-titre, le noir devient transparent
pub fn logo(dir: &Path) -> Option<Rgba> {
let img = decode_flc_last(&read(dir, "GRAPHICS/BUDTTLE2.FLC")?)?;
+231 -21
View File
@@ -10,6 +10,7 @@
#![windows_subsystem = "windows"]
mod art;
mod mods;
mod preview;
mod saves;
mod settings;
@@ -491,10 +492,15 @@ struct Art {
backdrops: Vec<egui::TextureHandle>,
/// mêmes décors en RGBA, pour l'aperçu des filtres
raw: Vec<art::Rgba>,
names: Vec<&'static str>,
/// décors HD des mods actifs (même ordre que `raw`), et leur clé de chargement
hd_raw: Vec<Option<art::Rgba>>,
hd_tex: Vec<Option<egui::TextureHandle>>,
hd_key: String,
logo: Option<egui::TextureHandle>,
/// miniatures des lieux des sauvegardes, par n° de lieu
thumbs: std::collections::HashMap<u32, Option<egui::TextureHandle>>,
preview_key: Option<(usize, usize, bool, usize, usize)>,
preview_key: Option<(usize, usize, bool, usize, usize, bool)>,
preview: Option<egui::TextureHandle>,
}
@@ -564,6 +570,10 @@ struct App {
save_confirm: Option<u32>,
restore_confirm: Option<PathBuf>,
save_msg: Option<(bool, String)>,
mods: Vec<mods::Mod>,
upscayl: Option<PathBuf>,
upscayl_models: Vec<String>,
upscayl_model: String,
art: Art,
tx: Sender<Msg>,
rx: Receiver<Msg>,
@@ -609,6 +619,10 @@ impl App {
save_confirm: None,
restore_confirm: None,
save_msg: None,
mods: Vec::new(),
upscayl: None,
upscayl_models: Vec::new(),
upscayl_model: mods::DEFAULT_MODEL.to_string(),
art: Art::default(),
tx,
rx,
@@ -624,6 +638,7 @@ impl App {
}
}
app.reload_saves();
app.reload_mods();
app.recheck();
app
}
@@ -653,7 +668,9 @@ impl App {
self.art = Art { dir: self.checks.game_dir.clone(), ..Default::default() };
let Some(dir) = self.art.dir.clone() else { return };
let opts = egui::TextureOptions::LINEAR;
self.art.raw = art::backdrops(&dir);
let found = art::backdrops(&dir);
self.art.names = found.iter().map(|(n, _)| *n).collect();
self.art.raw = found.into_iter().map(|(_, img)| img).collect();
self.art.backdrops = self
.art
.raw
@@ -668,6 +685,189 @@ impl App {
}
}
fn mods_dir(&self) -> Option<PathBuf> {
self.root.as_ref().map(|r| mods::dir(r, &self.gs.mods_dir))
}
fn reload_mods(&mut self) {
self.mods = self.mods_dir().map(|d| mods::list(&d)).unwrap_or_default();
self.upscayl = mods::find_upscayl();
self.upscayl_models = self.upscayl.as_ref().map(|b| mods::upscayl_models(b)).unwrap_or_default();
if !self.upscayl_models.is_empty() && !self.upscayl_models.contains(&self.upscayl_model) {
self.upscayl_model = self.upscayl_models[0].clone();
}
self.art.hd_key.clear();
}
/// décors HD à charger : mods actifs et décors HD activés
fn hd_active(&self) -> bool {
self.gs.mods_enabled && self.gs.hd_pack
}
/// visibles en jeu : le filtre CRT affiche toujours les décors d'origine
fn hd_shown(&self) -> bool {
self.hd_active() && self.gs.filter != 3
}
/// (re)charge les décors HD de la bannière et de l'aperçu quand les mods ou les réglages changent
fn refresh_hd(&mut self) {
let key = format!(
"{:?}|{}|{:?}|{}",
self.art.dir,
self.hd_active(),
self.gs.mods_disabled,
self.mods.iter().map(|m| format!("{}:{}", m.id, m.hd_images)).collect::<Vec<_>>().join(",")
);
if key == self.art.hd_key {
return;
}
self.art.hd_key = key;
self.art.preview_key = None;
let active = self.hd_active();
let disabled = self.gs.mods_disabled.clone();
self.art.hd_raw = self
.art
.names
.iter()
.map(|n| {
active
.then(|| mods::hd_image(&self.mods, &disabled, n))
.flatten()
.and_then(|p| mods::load_png(&p))
.map(|img| img.top(140, 200))
})
.collect();
self.art.hd_tex = self
.art
.hd_raw
.iter()
.enumerate()
.map(|(i, img)| {
img.as_ref().map(|img| self.ctx.load_texture(format!("hd{i}"), to_image(img), egui::TextureOptions::LINEAR))
})
.collect();
}
fn create_hd_pack(&mut self) {
let (Some(game), Some(mdir)) = (self.checks.game_dir.clone(), self.mods_dir()) else { return };
let id = mods::pack_id(&self.upscayl_model);
let target = mdir.join(&id);
mods::write_mod_ini(&target, &self.upscayl_model);
let mut cmd = format!(
"python -I tools\\hd_export.py \"{}\" \"{}\" --upscayl {}",
game.display(),
target.join("hd").display(),
self.upscayl_model
);
if let Some(bin) = &self.upscayl {
cmd.push_str(&format!(" --upscayl-bin \"{}\"", bin.display()));
}
self.start_task("hd", vec![cmd]);
}
fn mods_card(&mut self, ui: &mut egui::Ui) {
let en = self.cfg.lang == Lang::En;
let tr = |fr: &'static str, e: &'static str| if en { e } else { fr };
let running = self.game_running;
let busy = self.busy != Busy::No;
let can_create = !busy && self.checks.game_dir.is_some() && self.checks.python.is_some();
let mut open_dir = false;
let mut refresh = false;
let mut create = false;
card(ui, |ui| {
title(ui, tr("Mods et décors HD", "Mods & HD backgrounds"));
ui.add_enabled_ui(!running, |ui| {
ui.horizontal_wrapped(|ui| {
ui.checkbox(&mut self.gs.mods_enabled, tr("Activer les mods", "Enable mods"));
ui.add_enabled_ui(self.gs.mods_enabled, |ui| {
ui.checkbox(&mut self.gs.hd_pack, tr("Décors HD", "HD backgrounds"));
});
});
if self.gs.filter == 3 && self.gs.hd_pack {
ui.label(RichText::new(tr("Le filtre CRT affiche les décors d'origine.", "The CRT filter shows the original backgrounds.")).weak());
}
if self.mods.is_empty() {
ui.label(RichText::new(tr("Aucun mod installé.", "No mod installed.")).weak());
}
ui.add_enabled_ui(self.gs.mods_enabled, |ui| {
for m in &self.mods {
let mut on = !self.gs.mods_disabled.contains(&m.id);
ui.horizontal(|ui| {
if ui.checkbox(&mut on, RichText::new(&m.name).strong()).changed() {
if on {
self.gs.mods_disabled.retain(|d| d != &m.id);
} else {
self.gs.mods_disabled.push(m.id.clone());
}
}
if m.hd_images > 0 {
ui.label(RichText::new(format!("HD · {} {}", m.hd_images, tr("décors", "backgrounds"))).color(ACCENT).small());
}
if m.files > 0 {
ui.label(RichText::new(format!("{} {}", m.files, tr("fichiers", "files"))).color(OK).small());
}
});
let mut sub = m.description.clone();
if !m.author.is_empty() {
sub = if sub.is_empty() { m.author.clone() } else { format!("{sub} · {}", m.author) };
}
if !sub.is_empty() {
ui.label(RichText::new(sub).weak().small());
}
}
});
ui.horizontal_wrapped(|ui| {
if ui.button(tr("Ouvrir le dossier des mods", "Open mods folder")).clicked() {
open_dir = true;
}
if ui.button(tr("Actualiser", "Refresh")).clicked() {
refresh = true;
}
});
ui.separator();
if self.upscayl.is_some() {
ui.label(RichText::new(tr("Créer un pack HD avec Upscayl", "Create an HD pack with Upscayl")).strong());
ui.horizontal_wrapped(|ui| {
egui::ComboBox::from_id_salt("upscayl_model")
.selected_text(self.upscayl_model.clone())
.show_ui(ui, |ui| {
for m in &self.upscayl_models {
ui.selectable_value(&mut self.upscayl_model, m.clone(), m);
}
});
if ui.add_enabled(can_create, egui::Button::new(tr("Créer le pack", "Create pack"))).clicked() {
create = true;
}
});
ui.label(RichText::new(format!(
"{} mods\\{}",
tr("122 décors agrandis ×4, quelques secondes à quelques minutes. Dossier :", "122 backgrounds upscaled ×4, seconds to minutes. Folder:"),
mods::pack_id(&self.upscayl_model)
)).weak().small());
} else {
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(tr("Pour créer un pack HD, installez", "To create an HD pack, install")).weak());
ui.hyperlink_to("Upscayl", "https://upscayl.org");
});
}
});
if running {
ui.label(RichText::new(tr("En jeu : « Décors HD » se change aussi avec F12.", "In game: toggle « HD backgrounds » with F12.")).weak());
}
});
if open_dir {
if let Some(d) = self.mods_dir() {
saves::open_folder(&d);
}
}
if refresh {
self.reload_mods();
}
if create {
self.create_hd_pack();
}
}
fn saves_dir(&self) -> Option<PathBuf> {
self.root.as_ref().map(|r| r.join("saves"))
}
@@ -759,7 +959,8 @@ impl App {
let ppp = ui.ctx().pixels_per_point();
let (ow, oh) = ((w * ppp) as usize, (h * ppp) as usize);
let k = ((ui.input(|i| i.time) / 7.0) as usize + n / 2) % n;
let key = (k, self.gs.filter, self.gs.aspect_43, ow, oh);
let hd = self.hd_shown() && self.art.hd_raw.get(k).is_some_and(Option::is_some);
let key = (k, self.gs.filter, self.gs.aspect_43, ow, oh, hd);
if self.art.preview_key != Some(key) && ow > 8 && oh > 8 {
// ×4 comme une fenêtre de 1280 pixels de large ; pixels 1,2 fois plus hauts en 4:3
let img = &self.art.raw[k];
@@ -767,8 +968,10 @@ impl App {
let cw = ((ow as f32 / 4.0).round() as usize).clamp(8, img.w);
let ch = ((oh as f32 / (4.0 * ay)).round() as usize).clamp(8, img.h);
let (x0, y0) = ((img.w - cw) / 2, (img.h - ch) / 2);
let src = preview::Src::crop(&img.px, img.w, x0, y0, cw, ch);
let px = preview::render(&src, self.gs.filter, ow, oh);
let px = match self.art.hd_raw.get(k).and_then(Option::as_ref).filter(|_| hd) {
Some(h) => preview::render_hd(h, x0 as f32, y0 as f32, cw as f32, ch as f32, ow, oh),
None => preview::render(&preview::Src::crop(&img.px, img.w, x0, y0, cw, ch), self.gs.filter, ow, oh),
};
let ci = egui::ColorImage::from_rgba_unmultiplied([ow, oh], &px);
self.art.preview = Some(ui.ctx().load_texture("preview", ci, egui::TextureOptions::NEAREST));
self.art.preview_key = Some(key);
@@ -778,6 +981,11 @@ impl App {
ui.painter().image(tex.id(), rect, full, Color32::WHITE);
}
ui.painter().rect_stroke(rect, CornerRadius::ZERO, Stroke::new(2.0, Color32::BLACK), egui::StrokeKind::Inside);
if hd {
let r = Rect::from_min_size(rect.min + egui::vec2(8.0, 8.0), egui::vec2(44.0, 24.0));
ui.painter().rect_filled(r, CornerRadius::same(6), ACCENT);
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "HD", cartoon(18.0), Color32::BLACK);
}
ui.label(RichText::new(if en {
"Zoom ×4, as in a 1280-pixel-wide window. Same filters as the game."
} else {
@@ -925,19 +1133,9 @@ impl App {
fn build(&mut self, regenerate: bool) {
let (Some(dir), Some(vc)) = (self.checks.game_dir.clone(), self.checks.vcvars.clone()) else { return };
let mut steps = Vec::new();
if regenerate {
// mêmes arguments que build.bat
steps.push(format!(
"python -I tools\\recomp.py \"{}\" build\\gen_tucker tucker F",
dir.join("TUCKER.EXE").display()
));
steps.push(format!(
"python -I tools\\recomp.py \"{}\" build\\gen_intro intro I",
dir.join("INTRO.EXE").display()
));
}
steps.push(format!("call \"{}\" >nul && build.bat nogen", vc.display()));
// build.bat DOSSIER régénère le C depuis le jeu choisi, build.bat nogen recompile seulement
let arg = if regenerate { format!("\"{}\"", dir.display()) } else { "nogen".to_string() };
let steps = vec![format!("call \"{}\" >nul && build.bat {arg}", vc.display())];
self.start_task(if regenerate { "build" } else { "build-nogen" }, steps);
}
@@ -1037,11 +1235,13 @@ impl App {
Msg::TaskDone { ok } => {
self.last_ok = Some(ok);
self.busy = Busy::No;
self.reload_mods();
self.recheck();
}
Msg::GameExited(code) => {
self.game_running = false;
self.reload_saves();
self.reload_mods();
// le joueur a pu changer ses réglages avec F12 : on relit le fichier
self.gs = settings::GameSettings::load();
self.gs_saved = self.gs.clone();
@@ -1063,6 +1263,14 @@ impl App {
let p = ui.painter_at(rect);
p.rect_filled(rect, 0.0, CARD_DARK);
let t = ui.input(|i| i.time) as f32;
self.refresh_hd();
let shown = self.hd_shown();
let tex = |i: usize| -> &egui::TextureHandle {
match self.art.hd_tex.get(i) {
Some(Some(h)) if shown => h,
_ => &self.art.backdrops[i],
}
};
let n = self.art.backdrops.len();
if n > 0 {
// diaporama des décors, fondu enchaîné et lent glissement vertical
@@ -1071,9 +1279,9 @@ impl App {
let phase = t % per;
let fade = ((phase - (per - 1.5)) / 1.5).clamp(0.0, 1.0);
let drift = |kk: usize, ph: f32| ((ph / per) * 2.0 - 1.0) * if kk % 2 == 0 { 1.0 } else { -1.0 };
paint_cover(&p, rect, &self.art.backdrops[k % n], 1.0, drift(k, phase));
paint_cover(&p, rect, tex(k % n), 1.0, drift(k, phase));
if fade > 0.0 {
paint_cover(&p, rect, &self.art.backdrops[(k + 1) % n], fade, drift(k + 1, phase - per));
paint_cover(&p, rect, tex((k + 1) % n), fade, drift(k + 1, phase - per));
}
ui.ctx().request_repaint();
}
@@ -1427,12 +1635,14 @@ impl eframe::App for App {
ui.columns(2, |cols| {
self.setup_column(&mut cols[0], &root);
self.play_column(&mut cols[1]);
cols[1].add_space(10.0);
self.mods_card(&mut cols[1]);
});
});
});
if self.gs != self.gs_saved && !self.game_running {
if let Err(e) = self.gs.save() {
if let Err(e) = self.gs.save(&self.gs_saved) {
self.log.push(format!("!! settings.ini : {e}"));
}
self.gs_saved = self.gs.clone();
+204
View File
@@ -0,0 +1,204 @@
//! Mods et pack HD, côté launcher : voir docs/MODS.md.
//! - un mod = un sous-dossier de mods/ (ignoré s'il commence par « _ » ou « . ») ;
//! - mod.ini [mod] name / author / description, lu seulement par le launcher ;
//! - hd/*.png : décors HD ; files/** : fichiers remplacés.
//! Les mods s'appliquent dans l'ordre alphabétique : pour un même fichier, le dernier l'emporte.
use std::path::{Path, PathBuf};
pub struct Mod {
pub id: String,
pub path: PathBuf,
pub name: String,
pub author: String,
pub description: String,
pub hd_images: usize,
pub files: usize,
}
/// dossier des mods : clé [mods] dir, sinon mods/ à la racine du projet (comme le jeu lancé depuis build\)
pub fn dir(root: &Path, configured: &str) -> PathBuf {
let c = configured.trim();
if c.is_empty() {
return root.join("mods");
}
let p = PathBuf::from(c);
if p.is_absolute() { p } else { root.join(p) }
}
fn count_files(d: &Path) -> usize {
std::fs::read_dir(d)
.map(|rd| {
rd.flatten()
.map(|e| if e.path().is_dir() { count_files(&e.path()) } else { 1 })
.sum()
})
.unwrap_or(0)
}
fn count_png(d: &Path) -> usize {
std::fs::read_dir(d)
.map(|rd| {
rd.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("png")))
.count()
})
.unwrap_or(0)
}
fn read_ini(path: &Path) -> (String, String, String) {
let (mut name, mut author, mut desc) = (String::new(), String::new(), String::new());
if let Ok(text) = std::fs::read_to_string(path) {
let mut in_mod = false;
for line in text.lines() {
let l = line.trim();
if l.starts_with('[') {
in_mod = l.eq_ignore_ascii_case("[mod]");
continue;
}
if !in_mod {
continue;
}
if let Some((k, v)) = l.split_once('=') {
match k.trim() {
"name" => name = v.trim().to_string(),
"author" => author = v.trim().to_string(),
"description" => desc = v.trim().to_string(),
_ => {}
}
}
}
}
(name, author, desc)
}
pub fn list(mods_dir: &Path) -> Vec<Mod> {
let mut v: Vec<Mod> = std::fs::read_dir(mods_dir)
.map(|rd| {
rd.flatten()
.filter(|e| e.path().is_dir())
.filter_map(|e| {
let id = e.file_name().to_string_lossy().to_string();
if id.starts_with('_') || id.starts_with('.') {
return None;
}
let path = e.path();
let (name, author, description) = read_ini(&path.join("mod.ini"));
Some(Mod {
name: if name.is_empty() { id.clone() } else { name },
author,
description,
hd_images: count_png(&path.join("hd")),
files: count_files(&path.join("files")),
id,
path,
})
})
.collect()
})
.unwrap_or_default();
v.sort_by(|a, b| a.id.cmp(&b.id));
v
}
/// image HD d'un PCX (nom sans extension) fournie par le dernier mod actif qui l'a
pub fn hd_image(mods: &[Mod], disabled: &[String], pcx: &str) -> Option<PathBuf> {
mods.iter()
.rev()
.filter(|m| !disabled.contains(&m.id))
.find_map(|m| {
let hd = m.path.join("hd");
std::fs::read_dir(&hd).ok()?.flatten().map(|e| e.path()).find(|p| {
p.extension().is_some_and(|x| x.eq_ignore_ascii_case("png"))
&& p.file_stem().is_some_and(|s| s.to_string_lossy().eq_ignore_ascii_case(pcx))
})
})
}
/// PNG → RGBA 8 bits
pub fn load_png(path: &Path) -> Option<crate::art::Rgba> {
let f = std::io::BufReader::new(std::fs::File::open(path).ok()?);
let mut dec = png::Decoder::new(f);
dec.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = dec.read_info().ok()?;
let mut buf = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut buf).ok()?;
let (w, h) = (info.width as usize, info.height as usize);
let src = &buf[..info.buffer_size()];
let px: Vec<u8> = match info.color_type {
png::ColorType::Rgba => src.to_vec(),
png::ColorType::Rgb => src.chunks(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect(),
png::ColorType::Grayscale => src.iter().flat_map(|&g| [g, g, g, 255]).collect(),
png::ColorType::GrayscaleAlpha => src.chunks(2).flat_map(|c| [c[0], c[0], c[0], 255]).collect(),
png::ColorType::Indexed => return None,
};
(px.len() == w * h * 4).then_some(crate::art::Rgba { w, h, px })
}
// ------------------------------------------------------------------ Upscayl
/// upscayl-bin.exe, aux mêmes endroits que tools/hd_export.py
pub fn find_upscayl() -> Option<PathBuf> {
let mut bases = Vec::new();
if let Some(v) = std::env::var_os("UPSCAYL_BIN") {
let p = PathBuf::from(v);
if p.is_file() {
return Some(p);
}
}
for var in ["ProgramFiles", "ProgramFiles(x86)"] {
if let Some(v) = std::env::var_os(var) {
bases.push(PathBuf::from(v));
}
}
if let Some(v) = std::env::var_os("LOCALAPPDATA") {
bases.push(PathBuf::from(v).join("Programs"));
}
bases
.into_iter()
.map(|b| b.join("Upscayl").join("resources").join("bin").join("upscayl-bin.exe"))
.find(|p| p.is_file())
}
/// modèles disponibles (fichiers .param du dossier models d'Upscayl)
pub fn upscayl_models(bin: &Path) -> Vec<String> {
let Some(models) = bin.parent().and_then(Path::parent).map(|p| p.join("models")) else { return Vec::new() };
let mut v: Vec<String> = std::fs::read_dir(models)
.map(|rd| {
rd.flatten()
.filter_map(|e| {
let p = e.path();
if p.extension()? != "param" {
return None;
}
Some(p.file_stem()?.to_string_lossy().to_string())
})
.collect()
})
.unwrap_or_default();
v.sort();
v
}
pub const DEFAULT_MODEL: &str = "digital-art-4x";
/// dossier du mod créé pour un modèle : hd_upscayl pour le modèle par défaut, hd_upscayl_<modèle> sinon
pub fn pack_id(model: &str) -> String {
if model == DEFAULT_MODEL { "hd_upscayl".into() } else { format!("hd_upscayl_{model}") }
}
/// écrit mod.ini s'il n'existe pas encore
pub fn write_mod_ini(mod_dir: &Path, model: &str) {
let p = mod_dir.join("mod.ini");
if p.exists() {
return;
}
let _ = std::fs::create_dir_all(mod_dir);
let _ = std::fs::write(
p,
format!(
"[mod]\nname=Décors HD (Upscayl, {model})\nauthor=créé par le launcher\n\
description=Décors du jeu agrandis ×4 avec Upscayl (Real-ESRGAN, modèle {model})\n"
),
);
}
+33 -1
View File
@@ -189,6 +189,23 @@ fn crt(s: &Src, u: f32, v: f32, px_x: usize, ow: usize) -> [f32; 3] {
col.map(|x| (x * 1.35 * edge).clamp(0.0, 1.0).sqrt())
}
/// zone (x0, y0, cw, ch), en coordonnées 320×200, d'un décor HD de n'importe quelle taille, rééchantillonnée
/// en `ow`×`oh` (interpolation bilinéaire, comme le rendu du jeu pour la couche HD)
pub fn render_hd(hd: &crate::art::Rgba, x0: f32, y0: f32, cw: f32, ch: f32, ow: usize, oh: usize) -> Vec<u8> {
let s = hd.w as f32 / 320.0;
let src = Src::crop(&hd.px, hd.w, 0, 0, hd.w, hd.h);
let mut out = Vec::with_capacity(ow * oh * 4);
for py in 0..oh {
let v = ((y0 + ch * (py as f32 + 0.5) / oh as f32) * s) / hd.h as f32;
for px in 0..ow {
let u = ((x0 + cw * (px as f32 + 0.5) / ow as f32) * s) / hd.w as f32;
let c = src.bilinear(u, v);
out.extend_from_slice(&[(c[0] * 255.0 + 0.5) as u8, (c[1] * 255.0 + 0.5) as u8, (c[2] * 255.0 + 0.5) as u8, 255]);
}
}
out
}
/// rend `src` en `ow`×`oh` pixels avec le filtre `filter` (0 net, 1 lissé, 2 xBR, 3 CRT) ; RGBA 8 bits
pub fn render(src: &Src, filter: usize, ow: usize, oh: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(ow * oh * 4);
@@ -222,7 +239,7 @@ mod tests {
fn dump_filters() {
let (Ok(game), Ok(out)) = (std::env::var("DTR_GAME"), std::env::var("DTR_OUT")) else { return };
let imgs = crate::art::backdrops(std::path::Path::new(&game));
let img = &imgs[0];
let img = &imgs[0].1;
let (ow, oh) = (480usize, 252usize);
let (cw, ch) = (ow / 4, (oh as f32 / 4.8) as usize);
let src = super::Src::crop(&img.px, img.w, (img.w - cw) / 2, (img.h - ch) / 2, cw, ch);
@@ -237,4 +254,19 @@ mod tests {
std::fs::write(format!("{out}/preview_{f}.ppm"), ppm).unwrap();
}
}
/// DTR_HD=décor HD (png) DTR_OUT=dossier : écrit preview_hd.ppm (même cadrage que dump_filters)
#[test]
fn dump_hd() {
let (Ok(hd), Ok(out)) = (std::env::var("DTR_HD"), std::env::var("DTR_OUT")) else { return };
let img = crate::mods::load_png(std::path::Path::new(&hd)).expect("png").top(140, 200);
let (ow, oh) = (480usize, 252usize);
let (cw, ch) = (ow / 4, (oh as f32 / 4.8) as usize);
let px = super::render_hd(&img, ((320 - cw) / 2) as f32, ((140 - ch) / 2) as f32, cw as f32, ch as f32, ow, oh);
let mut ppm = format!("P6 {ow} {oh} 255\n").into_bytes();
for p in px.chunks(4) {
ppm.extend_from_slice(&p[..3]);
}
std::fs::write(format!("{out}/preview_hd.ppm"), ppm).unwrap();
}
}
+142 -59
View File
@@ -1,4 +1,5 @@
//! settings.ini, partagé avec le jeu (menu F12) : voir docs/SETTINGS.md.
//! Une clé n'est reconnue que dans sa section ([display], [audio], [mods]).
//! Le launcher ne réécrit que les valeurs de ses clés : ordre, commentaires et clés inconnues restent intacts.
use std::path::PathBuf;
@@ -13,13 +14,30 @@ pub struct GameSettings {
pub filter: usize,
pub aspect_43: bool,
pub vsync: bool,
pub hd_pack: bool,
pub vol: [u32; 4],
pub mods_enabled: bool,
/// dossier des mods ; vide = détection automatique par le jeu
pub mods_dir: String,
/// noms de dossiers de mods désactivés
pub mods_disabled: Vec<String>,
}
impl Default for GameSettings {
fn default() -> Self {
// mêmes défauts que le jeu (settings_defaults)
Self { fullscreen: false, window_scale: 3, filter: 0, aspect_43: true, vsync: false, vol: [100; 4] }
Self {
fullscreen: false,
window_scale: 3,
filter: 0,
aspect_43: true,
vsync: false,
hd_pack: true,
vol: [100; 4],
mods_enabled: true,
mods_dir: String::new(),
mods_disabled: Vec::new(),
}
}
}
@@ -35,33 +53,62 @@ fn parse_bool(v: &str) -> Option<bool> {
}
}
/// (clé, valeur) d'une ligne `cle=valeur`, hors commentaires et sections
fn key_value(line: &str) -> Option<(&str, &str)> {
enum Line<'a> {
Section(String),
Pair(&'a str, &'a str),
Other,
}
fn classify(line: &str) -> Line<'_> {
let l = line.trim();
if l.is_empty() || l.starts_with('#') || l.starts_with(';') || l.starts_with('[') {
return None;
if l.starts_with('[') && l.ends_with(']') {
return Line::Section(l[1..l.len() - 1].trim().to_ascii_lowercase());
}
if l.is_empty() || l.starts_with('#') || l.starts_with(';') {
return Line::Other;
}
match l.split_once('=') {
Some((k, v)) => Line::Pair(k.trim(), v.trim()),
None => Line::Other,
}
let (k, v) = l.split_once('=')?;
Some((k.trim(), v.trim()))
}
impl GameSettings {
pub fn load() -> Self {
let mut s = Self::default();
let Some(text) = path().and_then(|p| std::fs::read_to_string(p).ok()) else { return s };
let mut section = String::new();
for line in text.lines() {
let Some((k, v)) = key_value(line) else { continue };
match k {
"fullscreen" => s.fullscreen = parse_bool(v).unwrap_or(s.fullscreen),
"window_scale" => s.window_scale = v.parse().map(|n: u32| n.clamp(1, 16)).unwrap_or(s.window_scale),
"filter" => s.filter = FILTERS.iter().position(|f| f.eq_ignore_ascii_case(v)).unwrap_or(s.filter),
"aspect_43" => s.aspect_43 = parse_bool(v).unwrap_or(s.aspect_43),
"vsync" => s.vsync = parse_bool(v).unwrap_or(s.vsync),
_ => {
let (k, v) = match classify(line) {
Line::Section(n) => {
section = n;
continue;
}
Line::Pair(k, v) => (k, v),
Line::Other => continue,
};
match (section.as_str(), k) {
("display", "fullscreen") => s.fullscreen = parse_bool(v).unwrap_or(s.fullscreen),
("display", "window_scale") => {
s.window_scale = v.parse().map(|n: u32| n.clamp(1, 16)).unwrap_or(s.window_scale)
}
("display", "filter") => {
s.filter = FILTERS.iter().position(|f| f.eq_ignore_ascii_case(v)).unwrap_or(s.filter)
}
("display", "aspect_43") => s.aspect_43 = parse_bool(v).unwrap_or(s.aspect_43),
("display", "vsync") => s.vsync = parse_bool(v).unwrap_or(s.vsync),
("display", "hd_pack") => s.hd_pack = parse_bool(v).unwrap_or(s.hd_pack),
("mods", "enabled") => s.mods_enabled = parse_bool(v).unwrap_or(s.mods_enabled),
("mods", "dir") => s.mods_dir = v.to_string(),
("mods", "disabled") => {
s.mods_disabled = v.split(',').map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).collect()
}
("audio", _) => {
if let Some(i) = VOLUMES.iter().position(|&n| n == k) {
s.vol[i] = v.parse().map(|n: u32| n.min(100)).unwrap_or(s.vol[i]);
}
}
_ => {}
}
}
s
@@ -75,51 +122,78 @@ impl GameSettings {
("display", "filter", FILTERS[self.filter].to_string()),
("display", "aspect_43", b(self.aspect_43)),
("display", "vsync", b(self.vsync)),
("display", "hd_pack", b(self.hd_pack)),
];
for (i, k) in VOLUMES.iter().enumerate() {
e.push(("audio", k, self.vol[i].to_string()));
}
e.push(("mods", "enabled", b(self.mods_enabled)));
e.push(("mods", "dir", self.mods_dir.clone()));
e.push(("mods", "disabled", self.mods_disabled.join(",")));
e
}
pub fn save(&self) -> std::io::Result<()> {
/// écrit seulement les clés qui diffèrent de `old` (pour ne pas écraser un changement fait en jeu)
pub fn save(&self, old: &GameSettings) -> std::io::Result<()> {
let Some(p) = path() else { return Ok(()) };
let old = std::fs::read_to_string(&p).unwrap_or_default();
let mut lines: Vec<String> = old.lines().map(str::to_string).collect();
for (section, key, value) in self.entries() {
// 1. la clé existe : on remplace sa valeur sur place
if let Some(l) = lines.iter_mut().find(|l| key_value(l).is_some_and(|(k, _)| k == key)) {
*l = format!("{key}={value}");
continue;
}
// 2. sinon : à la fin de sa section, créée au besoin
let header = format!("[{section}]");
match lines.iter().position(|l| l.trim().eq_ignore_ascii_case(&header)) {
Some(h) => {
let mut end = h + 1;
while end < lines.len() && !lines[end].trim().starts_with('[') {
end += 1;
}
while end > h + 1 && lines[end - 1].trim().is_empty() {
end -= 1;
}
lines.insert(end, format!("{key}={value}"));
}
None => {
if lines.last().is_some_and(|l| !l.trim().is_empty()) {
lines.push(String::new());
}
lines.push(header);
lines.push(format!("{key}={value}"));
}
}
let before = old.entries();
let changes: Vec<_> = self.entries().into_iter().filter(|e| !before.contains(e)).collect();
if changes.is_empty() {
return Ok(());
}
let text = std::fs::read_to_string(&p).unwrap_or_default();
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
for (section, key, value) in changes {
set(&mut lines, section, key, &value);
}
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let mut text = lines.join("\n");
text.push('\n');
std::fs::write(p, text)
let mut out = lines.join("\n");
out.push('\n');
std::fs::write(p, out)
}
}
/// remplace `key` dans `[section]`, ou l'ajoute à la fin de la section (créée au besoin)
fn set(lines: &mut Vec<String>, section: &str, key: &str, value: &str) {
let mut cur = String::new();
let mut sec_start: Option<usize> = None;
let mut sec_end = lines.len();
for i in 0..lines.len() {
match classify(&lines[i]) {
Line::Section(n) => {
if sec_start.is_some() && cur == section {
sec_end = i;
break;
}
cur = n;
if cur == section {
sec_start = Some(i);
}
}
Line::Pair(k, _) if cur == section && k == key => {
lines[i] = format!("{key}={value}");
return;
}
_ => {}
}
}
match sec_start {
Some(h) => {
let mut end = sec_end;
while end > h + 1 && lines[end - 1].trim().is_empty() {
end -= 1;
}
lines.insert(end, format!("{key}={value}"));
}
None => {
if lines.last().is_some_and(|l| !l.trim().is_empty()) {
lines.push(String::new());
}
lines.push(format!("[{section}]"));
lines.push(format!("{key}={value}"));
}
}
}
@@ -128,25 +202,34 @@ mod tests {
use super::*;
#[test]
fn save_keeps_unknown_lines() {
fn sections_are_respected() {
let dir = std::env::temp_dir().join(format!("dtr-settings-{}", std::process::id()));
std::fs::create_dir_all(dir.join("DoubleTroubleRecomp")).unwrap();
// SAFETY : test isolé, aucun autre fil ne lit APPDATA ici
unsafe { std::env::set_var("APPDATA", &dir) };
let file = dir.join("DoubleTroubleRecomp").join("settings.ini");
std::fs::write(&file, "# commentaire\n[display]\nfilter=CRT\nhd_pack=perso\n\n[mods]\nfoo=1\n").unwrap();
let mut s = GameSettings::load();
assert_eq!(s.filter, 3);
std::fs::write(
&file,
"# commentaire\n[display]\nfilter=CRT\nhd_pack=0\nperso=1\n\n[mods]\nenabled=1\ndisabled=a, b\n\n[autre]\nfilter=nearest\n",
)
.unwrap();
let old = GameSettings::load();
assert_eq!(old.filter, 3);
assert!(!old.hd_pack);
assert_eq!(old.mods_disabled, vec!["a", "b"]);
let mut s = old.clone();
s.window_scale = 5;
s.vol[1] = 40;
s.save().unwrap();
s.mods_disabled = vec!["b".into()];
s.hd_pack = true;
s.save(&old).unwrap();
let text = std::fs::read_to_string(&file).unwrap();
assert!(text.starts_with("# commentaire\n[display]\nfilter=crt\nhd_pack=perso\n"), "{text}");
assert!(text.contains("window_scale=5"), "{text}");
assert!(text.contains("[mods]\nfoo=1"), "{text}");
assert!(text.contains("[audio]\nmaster_volume=100\nmusic_volume=40"), "{text}");
let again = GameSettings::load();
assert!(again == s);
assert!(text.starts_with("# commentaire\n[display]\nfilter=CRT\nhd_pack=1\nperso=1\nwindow_scale=5\n"), "{text}");
assert!(text.contains("[mods]\nenabled=1\ndisabled=b\n"), "{text}");
assert!(text.contains("[autre]\nfilter=nearest\n"), "{text}");
assert!(text.contains("[audio]\nmusic_volume=40"), "{text}");
assert!(!text.contains("master_volume"), "seules les clés changées sont écrites : {text}");
assert!(GameSettings::load() == s);
let _ = std::fs::remove_dir_all(dir);
}
}