chore(history): squash 10 commit(s) from 2026-07-31

- feat: Фаза 1 ребрендинг combatant → lovisual + восстановление config
- refactor: Фаза 2 — выкинуть Runtime/JarReplacement, заменить на Lifecycle
- refactor: Фаза 3.5 — удалить читерские модули, ESP под легит
- refactor: Фаза 3 — разбить Renderer2D (3379→2150 фасад + 14 хелперов ≤200)
- refactor: Фаза 3 — разбить BetterChatRenderer (2870→210 фасад + 21 хелпер ≤200)
- refactor: Фаза 3 — разбить UnifiedSettingRenderer (2798→208 фасад + 24 хелпера ≤200)
- refactor: Фаза 3 — разбить ClickGuiRenderer (1887→542 фасад + 15 хелперов ≤200)
- refactor: Фаза 3 — разбить NameTags (1791→438 фасад + 11 хелперов ≤200)
- refactor: Фаза 3 — разбить TargetHud (1655→340 фасад + 11 хелперов ≤200)
- refactor: Фаза 3 — разбить ESP (1538→269 фасад + 11 хелперов ≤200)
This commit is contained in:
loki5512344 2026-07-31 23:14:14 +02:00
parent 8084ac50b3
commit 52d87368c9
1595 changed files with 35857 additions and 51145 deletions

2
.gitignore vendored
View file

@ -25,7 +25,7 @@ Thumbs.db
*/run/
# Config
config/
/config/
# Logs
*.log

264
TODO.md
View file

@ -1,248 +1,36 @@
# LoVisual — План разработки с нуля
# LoVisual — структура проекта
## Принципы (в отличие от прошлого кала)
- **Никаких пустышек** — файл без реализации не создаётся
- **Никаких this-escape** — конструктор не публикует this
- **Никакого статика** — `Minecraft.getInstance()` только лениво, никогда в поле
- **Никаких мёртвых миксинов** — миксин только если он реально нужен
- **Каждый этап компилируется** — перед переходом к следующему
- **Никаких 140 папок** — плоская структура, группировка только по смыслу
Репозиторий разбит на 3 независимых компонента. **У каждого свой TODO, корневой TODO больше не ведётся.**
| Компонент | Стек | TODO |
|-----------|------|------|
| `combatant-client-26.2/` | Java 25, Fabric (MC 26.2) | [`combatant-client-26.2/TODO.md`](combatant-client-26.2/TODO.md) |
| `backend/` | Rust 2024 + axum | [`backend/TODO.md`](backend/TODO.md) |
| `launcher/` | Rust 2024 + Slint | [`launcher/TODO.md`](launcher/TODO.md) |
---
## База: что осталось
- `ref/` — ~415 референс-модулей из 8 клиентов (не трогать)
- `.omo/` — конфиги opencode
- `.git/`, `.gitignore`, `.gitattributes`
- `SYSTEM.md` — описание архитектуры (актуализировать по ходу)
## Общие правила для Rust-компонентов (backend + launcher)
- KISS / DRY / SOLID
- Макс. 200 строк на файл
- Макс. 3 файла на папку
- Обязательно: `cargo fmt` + `cargo clippy --all-targets` + `cargo test`
- Запрещено `#[allow(dead_code)]`
- Запрещено `unsafe` в собственной логике
- Без пустышек: модуль создаётся только с рабочей реализацией
- Каждый этап компилируется
---
## Фаза 0: Project Setup
- [ ] Создать `mod/` (NeoForge 1.21.1, Gradle, Java 21)
- build.gradle.kts (userdev, checkstyle)
- settings.gradle.kts
- META-INF/neoforge.mods.toml
- access_transformer.cfg (только нужные записи)
- mixins.json (только файлы, которые реально есть)
- LoVisual.java — entry point
- LoVisualClient.java — client init
- [ ] Создать `backend/` (Go 1.24)
- go.mod
- cmd/server/main.go
- internal/config/config.go (!! существует до main.go)
- [ ] Создать `launcher/` (Rust)
- Cargo.toml
- src/main.rs
## Статус
### Проверка: `./gradlew build`, `go build ./cmd/server`, `cargo build`
### Backend
- [x] Каркас: config, /health, graceful shutdown, CORS
- [ ] Auth (argon2 + JWT), профили, конфиги, IRC — см. `backend/TODO.md`
---
## Фаза 1: Core Systems (мод)
- [ ] EventBus — свой, нестатический, с поддержкой cancellation
- Event.java (abstract), EventBus.java
- EventHandler аннотация
- post() прекращает итерацию при cancel
- [ ] Module base — без `Minecraft.getInstance()` в статике
- Module.java: lazy getMc(), рефлексия для settings, toggle/enable/disable
- ModuleInfo аннотация
- ModuleCategory enum (COMBAT, MOVEMENT, RENDER, PLAYER, MISC)
- [ ] Setting system — 6 типов:
- Setting<T>, BooleanSetting, SliderSetting, ModeSetting, ColorSetting, BindSetting, MultiSelectSetting
- [ ] ModuleManager — регистрация, получение по имени/категории
- [ ] Command system — toggle, bind, help, config
- [ ] ConfigManager — .loconf, профили, автосейв (только после полной инициализации)
- [ ] Theme / ThemeManager — без garbage (Color кэш или прямые int)
### Проверка: мод запускается, не падает, `/lovisual help` работает
---
## Фаза 2: Mixins (только нужные)
- [ ] MinecraftClientMixin — runTick() → TickEvent
- [ ] InGameHudMixin — render → Render2DEvent
- [ ] GameRendererMixin — renderLevel → Render3DEvent
- [ ] ClientConnectionMixin — send/receive → PacketEvent
- [ ] KeyboardHandlerMixin — keyPress → KeyPressEvent
- [ ] MouseHandlerMixin — click → MouseClickEvent
- [ ] ClientPlayerEntityMixin — travel → MoveEvent (если нужен)
### НИКАКИХ пустых миксинов. Никаких `cancellable=true` без cancel.
### Проверка: все события постится, можно залогировать из любого модуля
---
## Фаза 3: Первый рабочий модуль
- [ ] Sprint (MOVEMENT) — полный цикл:
- Вкл/выкл через `/lovisual toggle Sprint`
- onEnable → подписка, onDisable → отписка
- TickEvent → зажим CTRL
- Сохраняется в конфиг
- Клавиша привязывается через `/lovisual bind Sprint 29`
### Проверка: модуль работает, конфиг сохраняется/грузится
---
## Фаза 4: Modules — по одному, каждый рабочий
### Combat (4)
- [ ] AutoClicker — CPS на клик, не юзать System.currentTimeMillis()
- [ ] Trajectories — Render3DEvent, предсказание траектории
- [ ] Criticals — фолл-криты
- [ ] Velocity — анти-отбрасывание
### Movement (3)
- [ ] Sprint ↑ (готов)
- [ ] Speed — страф/вода/эйр
- [ ] AutoWalk — зажим W
### Render (12)
- [ ] FullBright — гамма
- [ ] NoHurtCam — отмена тряски
- [ ] NoWeather — отмена погоды
- [ ] NoBobbing — отмена качания
- [ ] Zoom — FOV smooth (без глитча при disable)
- [ ] Crosshair — кастомный
- [ ] Nametags — ники над игроками
- [ ] HealthTags — хп под никами
- [ ] HitParticles — частицы при ударе
- [ ] Chams — подсветка (миксин читает настройки модуля)
- [ ] Animations — свайпы/рука
- [ ] CustomGlint — кастомный глинт
### Player (8)
- [ ] AutoTool — автосмена инструмента
- [ ] ExpThrower — авто-бросок опыта
- [ ] InvManager — сортировка/мусор
- [ ] MiddleClickFriend — добавить в друзья
- [ ] InventorySort — сортировка по клику
- [ ] Refill — авто-заполнение стаков
- [ ] NoInteract — блокировка кликов по сущностям
- [ ] Friends — список друзей
### Misc (6)
- [ ] AntiAFK — анти-афк
- [ ] AutoRespawn — авто-респавн
- [ ] AutoReconnect — авто-переподключение
- [ ] IRC — WebSocket чат
- [ ] Spammer — авто-спам в чат
- [ ] NameProtect — защита ника
### Extra (из ref/: только если реально нужны)
- [ ] KillAura
- [ ] ESP
- [ ] Scaffold
- [ ] Freecam
- [ ] Blink
- [ ] ElytraFlight
- [ ] AntiBot
- [ ] HitBox
- [ ] Tracers
- [ ] ItemPhysics
- [ ] ChestStealer
- [ ] AutoFish
- [ ] AutoEat
### Проверка после каждого: модуль компилируется, включается/выключается, не крашит
---
## Фаза 5: GUI
### ClickGUI
- [ ] ClickGuiScreen — Screen
- [ ] CategoryPanel — чипсы категорий + поиск
- [ ] ModuleGrid — сетка модулей (ЛКМ toggle, ПКМ настройки, СКМ бинд)
- [ ] SettingsPanel — рендер настроек
- [ ] ThemePanel — слайдеры цветов
### HUD (10 элементов)
- [ ] Watermark
- [ ] ModuleList
- [ ] TargetHUD
- [ ] ArmorHUD
- [ ] PotionsHUD
- [ ] Keystrokes
- [ ] Scoreboard
- [ ] Coords
- [ ] ComboCounter
- [ ] Notifications
### MainMenu
- [ ] LoVisualMainMenu — кастомный экран
### Проверка: GUI рендерится, кликабельно, модули togglятся
---
## Фаза 6: Backend (Go)
### Config (существует до main.go)
- [ ] internal/config/config.go — Port, DB.Path, JWT.Secret, CORS origins
### DB
- [ ] internal/repository/db.go — SQLite, миграции
- [ ] internal/repository/users.go
- [ ] internal/repository/configs.go
- [ ] internal/repository/profiles.go
### Auth
- [ ] internal/service/auth.go — bcrypt, JWT (не SHA256)
- [ ] internal/handler/auth.go — register/login/logout
- [ ] internal/middleware/auth.go — Bearer token (не panic, возвращает 401)
### Profile
- [ ] internal/service/profile.go
- [ ] internal/handler/profile.go — get/update/playtime/search/friends
- [ ] JSON decode errors НЕ игнорировать
### Configs API
- [ ] internal/handler/config.go — upload/download (auth check, user_id из токена, не из тела)
- [ ] 16-byte share keys (минимум)
### IRC
- [ ] internal/irc/hub.go — WebSocket хаб (gorilla/websocket, не deprecated x/net)
### Middleware
- [ ] CORS — настраиваемые origins
- [ ] RateLimit — с cleanup горутиной (без утечки)
- [ ] Log — запросы
### Проверка: `go build ./cmd/server` проходит, сервер стартует, эндпоинты отвечают
---
## Фаза 7: Launcher (Rust)
### API клиент
- [ ] api.rs — reqwest, таймауты, десериализация с rename_all
- [ ] Версия читается из Cargo.toml (не хардкод)
### Экраны
- [ ] login.rs — регистрация/логин
- [ ] dashboard.rs — профиль, playtime, version check
- [ ] settings.rs — кастомная команда (ЧИТАЕТСЯ на Play, не stale)
### Launch
- [ ] launch.rs — запуск MC (команда из настроек, защита от пустой строки)
- [ ] save_session — только при логине, при logout удалять
### Проверка: `cargo run` — лаунчер открывается, логин/регистрация работают
---
## Фаза 8: Polish
- [ ] Sound system (49 звуков из ref/)
- [ ] Animation system (SpringAnimator)
- [ ] Style system (6 стилей для HUD)
- [ ] Cloud config sharing (если бэкенд готов)
- [ ] Auto-updater
- [ ] Loading screen
- [ ] AltManager
---
### Launcher
- [x] Каркас: окно логина, фоновая проверка /health
- [ ] Auth, dashboard, settings, launch — см. `launcher/TODO.md`
### Мод (combatant-client-26.2)
- [ ] Полный rewrite: ребрендинг (1464 `combatant`), разбивка 12 файлов >1500 строк, выкинуть Runtime/JarReplacement, тесты — см. `combatant-client-26.2/TODO.md`

2199
backend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

44
backend/Cargo.toml Normal file
View file

@ -0,0 +1,44 @@
[package]
name = "lovisual-backend"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"
description = "LoVisual backend: auth, profiles, friends, cloud configs, IRC"
license = "GPL-3.0"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.53", features = ["full"] }
tower-http = { version = "0.7", features = ["cors", "trace", "fs"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "sqlite", "chrono"] }
chrono = { version = "0.4", features = ["serde"] }
thiserror = "2"
anyhow = "1"
argon2 = "0.5"
jsonwebtoken = "11"
uuid = { version = "1", features = ["v4", "serde"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
[lints.rust]
unsafe_code = "forbid"
dead_code = "deny"
[lints.clippy]
correctness = "deny"
suspicious = "deny"
style = "deny"
complexity = "deny"
perf = "deny"
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = true

51
backend/TODO.md Normal file
View file

@ -0,0 +1,51 @@
# LoVisual Backend (Rust + axum)
## Правила (ОБЯЗАТЕЛЬНЫЕ, нарушение = откат)
- **KISS / DRY / SOLID** — простая структура, без оверинжиниринга
- **Макс. 200 строк на файл** — превышение = разбить на модули
- **Макс. 3 файла на папку** — больше = новая подпапка по смыслу
- **Обязательное прохождение:** `cargo fmt` + `cargo clippy --all-targets` (ноль ошибок) + `cargo test`
- **Запрещено `#[allow(dead_code)]`** — мёртвый код удаляется, не прячется
- **Запрещено `unsafe`** (в собственной логике; lints: `unsafe_code = "forbid"`)
- **Без пустышек** — модуль создаётся только с рабочей реализацией
- **Каждый этап компилируется** — перед переходом к следующему
- **Ошибки JSON-декода не игнорировать** — всегда `.context()`/`?`
- **`user_id` из токена, не из тела запроса**
---
## Сделано
- [x] Каркас: main.rs + server/{mod,config} + routes/{mod,health}
- [x] `GET /health` + graceful shutdown (SIGTERM/SIGINT)
- [x] Config из env (LOVISUAL_HOST/PORT/CORS_ORIGINS), валидация на старте
- [x] CORS (настраиваемые origins) + tower TraceLayer
- [x] Rust 2024 edition, актуальные версии пакетов
---
## Фаза 1: DB (SQLite, sqlx)
- [ ] `src/db/mod.rs` — подключение, миграции
- [ ] `src/db/users.rs` — таблица users
- [ ] `src/db/configs.rs` — облачные конфиги
- [ ] `src/db/profiles.rs` — профили, playtime, friends
## Фаза 2: Auth
- [ ] `src/auth/mod.rs` — argon2 + JWT (jsonwebtoken)
- [ ] `src/auth/handlers.rs` — register/login/logout
- [ ] `src/auth/middleware.rs` — Bearer token → 401, не panic
## Фаза 3: Profile API
- [ ] `src/profile/mod.rs` — get/update/playtime/search/friends
## Фаза 4: Configs API
- [ ] `src/config_api/mod.rs` — upload/download
- [ ] 16-byte share keys (минимум)
## Фаза 5: IRC
- [ ] `src/irc/mod.rs` — WebSocket хаб (axum + tokio-tungstenite)
## Фаза 6: Middleware
- [ ] RateLimit — с cleanup-задачей (без утечки)
- [ ] Request logging через tracing
### Проверка после каждой фазы: `cargo fmt && cargo clippy --all-targets && cargo test`

30
backend/src/main.rs Normal file
View file

@ -0,0 +1,30 @@
//! LoVisual backend server entry point.
mod routes;
mod server;
use std::net::SocketAddr;
use anyhow::Context as _;
use server::config::Config;
use server::serve;
fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "lovisual_backend=info,tower_http=info".into()),
)
.init();
let config = Config::from_env().context("failed to load config")?;
let addr: SocketAddr = config.listen_addr();
tracing::info!(%addr, "starting lovisual backend");
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("failed to build tokio runtime")?
.block_on(serve(config))
}

View file

@ -0,0 +1,47 @@
//! Health/liveness endpoints.
use axum::Router;
use axum::routing::get;
use serde::Serialize;
/// Health response body.
#[derive(Debug, Serialize)]
pub struct Health {
pub status: &'static str,
pub version: &'static str,
}
/// Build the health router.
pub fn router() -> Router {
Router::new().route("/health", get(health))
}
async fn health() -> axum::Json<Health> {
axum::Json(Health {
status: "ok",
version: env!("CARGO_PKG_VERSION"),
})
}
#[cfg(test)]
mod tests {
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt as _;
use super::*;
#[tokio::test]
async fn health_returns_ok() {
let response = router()
.oneshot(
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}

13
backend/src/routes/mod.rs Normal file
View file

@ -0,0 +1,13 @@
//! Route definitions.
//!
//! Top-level router; each domain (auth, profile, configs, irc) will add its
//! own sub-router here.
pub mod health;
use axum::Router;
/// Compose the full route tree.
pub fn router() -> Router {
Router::new().merge(health::router())
}

View file

@ -0,0 +1,120 @@
//! Runtime configuration, loaded from environment variables.
//!
//! Parsed into validated types at the boundary; invalid values fail fast
//! at startup instead of blowing up mid-request.
use std::env;
use std::net::{IpAddr, SocketAddr};
use anyhow::{Context as _, Result, bail};
use axum::http::HeaderValue;
use tower_http::cors::AllowOrigin;
/// Application configuration.
#[derive(Debug, Clone)]
pub struct Config {
pub host: IpAddr,
pub port: u16,
pub cors_origins: AllowOrigin,
}
impl Config {
/// Default host for local development.
pub const DEFAULT_HOST: &'static str = "127.0.0.1";
/// Default port for local development.
pub const DEFAULT_PORT: u16 = 8765;
/// Load configuration from the environment.
pub fn from_env() -> Result<Self> {
Self::from_vars(
env::var("LOVISUAL_HOST").ok(),
env::var("LOVISUAL_PORT").ok(),
env::var("LOVISUAL_CORS_ORIGINS").ok(),
)
}
/// Build config from raw option values (injectable for tests).
fn from_vars(host: Option<String>, port: Option<String>, cors: Option<String>) -> Result<Self> {
let host = host
.unwrap_or_else(|| Self::DEFAULT_HOST.to_owned())
.parse()
.context("LOVISUAL_HOST is not a valid IP address")?;
let port: u16 = match port {
Some(p) => p
.parse()
.context("LOVISUAL_PORT is not a valid port number")?,
None => Self::DEFAULT_PORT,
};
let origins = parse_origins(&cors)?;
Ok(Self {
host,
port,
cors_origins: origins,
})
}
/// Resolved listen address.
pub fn listen_addr(&self) -> SocketAddr {
SocketAddr::new(self.host, self.port)
}
}
fn parse_origins(raw: &Option<String>) -> Result<AllowOrigin> {
let Some(raw) = raw else {
// No origins configured: allow same-origin requests only.
return Ok(AllowOrigin::any());
};
let origins = raw
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect::<Vec<_>>();
if origins.is_empty() {
bail!("LOVISUAL_CORS_ORIGINS is set but contains no origins");
}
Ok(AllowOrigin::list(
origins
.into_iter()
.map(|o| o.parse::<HeaderValue>().context("invalid CORS origin"))
.collect::<Result<Vec<_>, _>>()?,
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_origins_allows_any() {
assert!(parse_origins(&None).is_ok());
}
#[test]
fn empty_list_origin_string_fails() {
assert!(parse_origins(&Some(String::from(",,"))).is_err());
}
#[test]
fn invalid_port_fails() {
let result = Config::from_vars(None, Some("not-a-port".into()), None);
assert!(result.is_err());
}
#[test]
fn invalid_host_fails() {
let result = Config::from_vars(Some("not-an-ip".into()), None, None);
assert!(result.is_err());
}
#[test]
fn defaults_apply_when_empty() {
let config = Config::from_vars(None, None, None).unwrap();
assert_eq!(
config.listen_addr(),
SocketAddr::from(([127, 0, 0, 1], 8765))
);
}
}

57
backend/src/server/mod.rs Normal file
View file

@ -0,0 +1,57 @@
//! Server assembly: router, listener, graceful shutdown.
use anyhow::Context as _;
use axum::Router;
use tokio::net::TcpListener;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
use super::routes;
use config::Config;
pub mod config;
/// Build the application router for a given config.
pub fn app(config: &Config) -> Router {
Router::new()
.merge(routes::router())
.layer(CorsLayer::new().allow_origin(config.cors_origins.clone()))
.layer(TraceLayer::new_for_http())
}
/// Bind and serve the application until a shutdown signal arrives.
pub async fn serve(config: Config) -> anyhow::Result<()> {
let listener = TcpListener::bind(config.listen_addr())
.await
.context("failed to bind listener")?;
axum::serve(listener, app(&config))
.with_graceful_shutdown(shutdown_signal())
.await
.context("server error")
}
/// Resolves on SIGTERM/SIGINT.
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install ctrl-c handler");
};
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}

View file

@ -0,0 +1,123 @@
# LoVisual Mod (combatant-client-26.2) — план переписи
Мод — форк Combatant Client, переписываем под LoVisual.
## Правила (ОБЯЗАТЕЛЬНЫЕ, нарушение = откат)
- **KISS / DRY / SOLID** — простая структура, без оверинжиниринга
- **Макс. 200 строк на файл** (было >1500) — превышение = разбить на модули
- **Макс. 3 файла на папку** — больше = новая подпапка по смыслу
- **Никакого статика** — `Minecraft.getInstance()` только лениво, никогда в поле
- **Никаких this-escape** — конструктор не публикует `this`
- **Никаких мёртвых миксинов** — миксин только если реально нужен; `cancellable=true` только при реальном cancel
- **Без пустышек** — файл без реализации не создаётся
- **Каждый этап компилируется** — `./gradlew build` перед переходом к следующему
- **Тесты обязательны** для новых модулей (JUnit)
---
## СТАТУС ПРОБЛЕМ (что вижу сейчас)
### 1. Ребрендинг не закончен (пункт 2)
- 288 файлов / **1464 упоминания** `combatant` в main-коде
- Классы: `CombatantRenderSystem`, `CombatantRenderEngineBootstrap`, `CombatantRenderPipelines`, `CombatantVulkanBackend`, `CombatantFrameGraph`, `CombatantTerrainVertex` и др.
- Заголовки файлов: «This file is part of the Combatant Client distribution» / `copyright (c) pivosos2007`
### 2. Файлы-гиганты (пункт 3) — 12 файлов > 1500 строк
| Файл | Строк |
|------|-------|
| render/engine/renderer/Renderer2D.java | 3379 |
| features/gui/chat/BetterChatRenderer.java | 2870 |
| features/gui/clickgui/settings/UnifiedSettingRenderer.java | 2798 |
| features/module/modules/player/Scaffold.java | 2416 |
| features/module/modules/combat/AttributeSwap.java | 1922 |
| features/gui/clickgui/ClickGuiRenderer.java | 1900 |
| features/module/modules/visuals/NameTags.java | 1791 |
| features/module/modules/combat/ElytraTarget.java | 1711 |
| features/gui/hud/draggable/impl/TargetHud.java | 1687 |
| features/module/modules/visuals/ESP.java | 1520 |
| features/module/modules/combat/AutoCrystal.java | 1516 |
| features/gui/hud/nondraggable/impl/CustomBar.java | 1496 |
### 3. Runtime / JarReplacement (пункт 4)
- `runtime/` (ClientRuntime, RuntimeGate, ClientRuntimeState, SOFT_PANIC/JAR_REPLACEMENT_PANIC, shutdown/resume-участники)
- `runtime/loader/` (JarReplacementCoordinator, LoaderBridge, PanicOnlyJarReplacementCoordinator)
- **Моё предложение: выкинуть.** Живая замена jar в памяти — источник classloader-утечек, хрупкая, для клиента не нужна (обновление делает лаунчер). Заменить на простой Lifecycle.
### 4. Security (пункт 7)
- `features/security/BackdoorProtection` — на деле защита от SSRF/translate-инъекций (порт ExploitPreventer, MIT). Полезное, но `enum`-синглтон со статикой.
- `features/relations/StaffTracker` + `StaffHeuristicsMatcher` — детект «стафа» по эвристикам TAB. Сомнительно, решить оставить/выкинуть.
### 5. Тесты (пункт 6)
- 5 тестов на ~213k строк. Добавлять по мере переписи модулей.
---
## Фаза 1: Ребрендинг (пункт 2)
- [x] **Восстановлен `config/`-пакет** (55+3 файла) из `ref/zip/combatant-client-26.2 (1).zip` — он отсутствовал в форке, без него проект не собирался. Переименован `combatant.client.config` → `dev.loki.lovisual.config`. `compileJava` ✓
- [x] Заменить `combatant` → `lovisual` в main-коде (1464 вхождения, 288 файлов)
- [x] Переименовать классы `Combatant*` → `LoVisual*` (23 шт., включая `IrisCombatantFrameHooks` → `IrisLoVisualFrameHooks`)
- [x] Заголовки файлов → LoVisual, пересобрать копирайты (GPLv3 форка)
- [x] Проверить `fabric.mod.json` / `lovisual.mixins.json` на остатки
- [x] Проверить строки/сообщения/логи на «combatant»
- [x] JNI-имена в native: `Java_combatant_client_` → `Java_dev_loki_lovisual_` (34 шт.) + FindClass-пути
### Проверка: `rg -i combatant src` → 0 ✓, `./gradlew build` ✓ (1406 файлов изменено)
## Фаза 2: Выкинуть Runtime/JarReplacement (пункт 4)
> **Вместе с рантаймом удалить и модуль Panic** (`features/module/modules/misc/Panic.java`),
> интерфейс `RuntimeControlModule`, команду `RuntimeCommand` и все ветки на них
> в `ModuleManager`/`Module`. Panic — единственная реализация `RuntimeControlModule`,
> без него они становятся мёртвым кодом.
- [x] Удалить `runtime/` и `runtime/loader/` (14 файлов)
- [x] Удалить `Panic.java` + `RuntimeControlModule.java` + `RuntimeCommand.java`
- [x] Убрать ветки `instanceof RuntimeControlModule` и `tickRuntimeControllers()` из ModuleManager/Module
- [x] Убрать `RuntimeGate` из точек входа (LoVisual.java, модули, рендер) — заменён на `Lifecycle`
- [x] Заменить на простой Lifecycle-класс (`dev.loki.lovisual.Lifecycle`: INIT → ACTIVE → SHUTDOWN, гейты `canRunRender/Hud/ShaderBridge` + `RenderResourceReadiness`)
- [x] Panic-фичи удалены; `ModuleManager.disableAll()` оставлен как простая утилита
- [x] Мёртвые cleanup-методы удалены (`shutdownForRuntime`, `clearRuntimeReferences`, `VanillaChatRuntimeCleanup`, i18n-ключи panic/runtime)
### Проверка: `./gradlew build` ✓, тесты ✓ (13), `rg runtime-подсистема` → 0
## Фаза 3: Разбивка файлов-гигантов (пункт 3) — ОТЛОЖЕНА, сначала чистка модулей
- [ ] Сначала удалены читерские модули (см. Фазу 3.5) — рефакторить удалённые файлы не нужно
- [ ] Renderer2D (3379) → renderer + пакеты (текст, примитивы, deferred-слои)
- [ ] BetterChatRenderer (2870) → рендер, парсинг, кэш
- [ ] UnifiedSettingRenderer (2798) → по типам настроек
- [ ] ClickGuiRenderer (1900), NameTags (1791), TargetHud (1687), ESP (1538), CustomBar (1495)
### Проверка: после каждого файла `./gradlew build`; цель ≤200 строк/файл
## Фаза 3.5: Удаление читерских модулей (легит-направление)
> Пользователь решил: LoVisual — легитное приложение. Все читерские модули удаляются.
- [x] combat: удалены AttributeSwap, AutoAnchor, AutoAttack, AutoBed, AutoBow, AutoCrystal, Backtrack,
Criticals, ElytraTarget, Hitbox, KillAura, KTLeave, MaceKill. **Оставлены:** ProjectilePuncher,
PvpCooldowns, Reach, RubberHand, SpearAssist, TPSSync
- [x] movement: удалены ВСЕ модули (AirJump, AutoDodge, ElytraFly, ElytraHelper, Flight, Freeze,
InventoryMove, NoFall, NoPush, NoStun, Parkour, Phase, ReverseStep, SafeWalk, Speed, Sprint,
Step, Strafe, SuperFirework, TargetStrafe, Timer, Velocity, WindJump) — 22 файла
- [x] player: удалены AirPlace, AutoArmor, AutoEat, AutoTotem, Scaffold, XCarry.
**Оставлены:** AutoTool, ClickPearl, FakeLag, NoDelay, NoInteract, ShitDropper
- [x] Осиротевшие хелпер-пакеты: удалены `combat/autocrystal/` (17), `combat/autobed/` (9),
`combat/autoanchor/` (9), `util/block/scaffold/` (10), `BlockPlacer` + тест ScaffoldPlacementGateTest
- [x] Enum-заглушки: `KillAura.RaycastMode/RotationTiming/AngleSmoothMode` → локальные enum в
ProjectilePuncher/Reach; `Criticals.SelectionMode` → удалено; `Hitbox`-зависимость убрана из ESP
- [x] ESP переписан под легит: новые настройки `only_visible` (LOS-луч от камеры), `skip_invisible`,
`only_armor` (без брони не подсвечивать) — по умолчанию `true`, только для игроков
### Проверка: `./gradlew build` ✓, тесты ✓ (13), остатки только в комментариях/строках
## Фаза 4: Security (пункт 7)
- [ ] BackdoorProtection: убрать `enum`-синглтон, сделать инстансный сервис, ленивый `Minecraft.getInstance()`
- [ ] Решить судьбу StaffTracker/StaffHeuristics — согласовать и выкинуть или переписать
- [ ] Покрыть логику фильтров тестами
## Фаза 5: Модули — нормализация под правила
- [ ] Прочесать все 131 модуль: убрать `static final Minecraft` в полях (6 шт. уже найдено)
- [ ] Проверить модули на `System.currentTimeMillis()` → заменить на игровое время
- [ ] Разнести addon/events/mixininterface по смыслу
## Фаза 6: Тесты (пункт 6)
- [ ] Юнит-тесты: EventBus, конфиг, утилиты (игровые классы — mock)
- [ ] По мере переписи модулей — тест на каждый
### Проверка: `./gradlew test` зелёный

Binary file not shown.

View file

@ -2,6 +2,8 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -15,7 +15,7 @@ import dev.loki.lovisual.render.engine.profiler.FrameStutterProfiler;
import dev.loki.lovisual.render.engine.profiler.JfrProfiler;
import dev.loki.lovisual.render.engine.profiler.ProfilerSettings;
import dev.loki.lovisual.render.engine.profiler.TracyProfiler;
import dev.loki.lovisual.runtime.RuntimeGate;
import dev.loki.lovisual.Lifecycle;
import java.nio.file.Path;
import java.time.Duration;
@ -32,13 +32,13 @@ public final class ProfilerCommand implements ClientCommand {
@Override
public boolean isAvailable() {
return RuntimeGate.canRunClientLogic();
return Lifecycle.isActive();
}
@Override
public boolean execute(CommandContext ctx) {
if (!RuntimeGate.canRunClientLogic()) {
CommandOutput.send("Profiler: disabled in Panic mode.");
if (!Lifecycle.isActive()) {
CommandOutput.send("Profiler: disabled until client is active.");
return true;
}
String target = ctx.arg(0);

View file

@ -13,7 +13,7 @@ import dev.loki.lovisual.render.engine.profiler.DevTracyProfiler;
public abstract class ProfilersMixin {
@Inject(method = "getDefaultFiller", at = @At("HEAD"), cancellable = true)
private static void combatant$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
private static void lovisual$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
if (!DevTracyProfiler.isEnabled()) {
return;
}

View file

@ -8,7 +8,6 @@ import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.runtime.RuntimeGate;
import javax.management.Notification;
import javax.management.NotificationEmitter;
@ -85,7 +84,7 @@ public enum DevFrameStutterProfiler {
RenderResourceStatsSnapshot resources) {
try {
if (!isEnabled()) return;
if (RuntimeGate.isPanic()) return;
renderThread = Thread.currentThread();
ensureSampler();
@ -258,7 +257,7 @@ public enum DevFrameStutterProfiler {
private static void ensureSampler() {
if (running || output == ProfilerSettings.OutputMode.OFF) return;
running = true;
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "Combatant-DevFrameStutterProfiler");
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "LoVisual-DevFrameStutterProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
@ -276,7 +275,7 @@ public enum DevFrameStutterProfiler {
private static void sampleLoop() {
long lastSampleNs = 0L;
while (running) {
if (output == ProfilerSettings.OutputMode.OFF || RuntimeGate.isPanic()) {
if (output == ProfilerSettings.OutputMode.OFF) {
sleepMs(20L);
continue;
}

View file

@ -32,7 +32,7 @@ public enum DevJfrProfiler {
Path file = dir.resolve(defaultFileName(preset, false));
Recording next = new Recording();
next.setName("Combatant " + preset.getId());
next.setName("LoVisual " + preset.getId());
next.setToDisk(true);
next.setDumpOnExit(false);
configure(next, preset);
@ -159,7 +159,7 @@ public enum DevJfrProfiler {
private static String defaultFileName(Preset preset, boolean snapshot) {
String timestamp = FILE_TIME.format(LocalDateTime.now(ZoneId.systemDefault()));
String suffix = snapshot ? "-snapshot" : "";
return "combatant-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
return "lovisual-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
}
private static String formatDuration(long totalSeconds) {

View file

@ -1,6 +1,6 @@
package dev.loki.lovisual.render.engine.profiler;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import java.util.*;
@ -19,11 +19,11 @@ public enum DevRenderCostProfiler {
private static final int DEFAULT_LOG_TOP = 20;
private static final double DEFAULT_LOG_MIN_MS = 0.02;
private static final String PROP_ENABLED = "combatant.profiler.renderCost";
private static final String PROP_LOG = "combatant.profiler.renderCost.log";
private static final String PROP_INTERVAL = "combatant.profiler.renderCost.interval";
private static final String PROP_TOP = "combatant.profiler.renderCost.top";
private static final String PROP_MIN_MS = "combatant.profiler.renderCost.minMs";
private static final String PROP_ENABLED = "lovisual.profiler.renderCost";
private static final String PROP_LOG = "lovisual.profiler.renderCost.log";
private static final String PROP_INTERVAL = "lovisual.profiler.renderCost.interval";
private static final String PROP_TOP = "lovisual.profiler.renderCost.top";
private static final String PROP_MIN_MS = "lovisual.profiler.renderCost.minMs";
private static final LinkedHashMap<String, Bucket> buckets = new LinkedHashMap<>();
private static final HashMap<String, String> labelCache = new HashMap<>(256);
@ -351,17 +351,17 @@ public enum DevRenderCostProfiler {
static Counters capture() {
try {
long uploaded = CombatantRenderSystem.rhi().stats().uploadedVertexBytes()
+ CombatantRenderSystem.rhi().stats().uploadedIndexBytes();
long uploaded = LoVisualRenderSystem.rhi().stats().uploadedVertexBytes()
+ LoVisualRenderSystem.rhi().stats().uploadedIndexBytes();
return new Counters(
CombatantRenderSystem.rhi().stats().drawCalls(),
CombatantRenderSystem.rhi().stats().meshUploads(),
CombatantRenderSystem.rhi().stats().fullscreenPasses(),
CombatantRenderSystem.rhi().stats().textureFastCopies(),
CombatantRenderSystem.rhi().stats().textureShaderCopies(),
LoVisualRenderSystem.rhi().stats().drawCalls(),
LoVisualRenderSystem.rhi().stats().meshUploads(),
LoVisualRenderSystem.rhi().stats().fullscreenPasses(),
LoVisualRenderSystem.rhi().stats().textureFastCopies(),
LoVisualRenderSystem.rhi().stats().textureShaderCopies(),
uploaded,
CombatantRenderSystem.uniforms().stats().writes(),
CombatantRenderSystem.uniforms().stats().uploadedBytes()
LoVisualRenderSystem.uniforms().stats().writes(),
LoVisualRenderSystem.uniforms().stats().uploadedBytes()
);
} catch (Throwable ignored) {
return ZERO;

View file

@ -3,7 +3,7 @@ package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.command.UiStatsSnapshot;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.ui.runtime.script.CachedUiScriptRuntime;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
@ -12,7 +12,6 @@ import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot
import dev.loki.lovisual.render.engine.text.TextCommandStatsSnapshot;
import dev.loki.lovisual.render.engine.text.TextRenderSystem;
import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.*;
@ -168,7 +167,7 @@ public enum DevRenderProfiler2D {
));
}
TextCommandStatsSnapshot textStats = CombatantRenderSystem.textStatsSnapshot();
TextCommandStatsSnapshot textStats = LoVisualRenderSystem.textStatsSnapshot();
if (textStats.recorded() > 0 || textStats.meshUploads() > 0 || textStats.glyphs() > 0) {
lines.add(String.format(
"text: rec/sub %d/%d, backend vanilla/bitmap/msdf/world %d/%d/%d/%d, effect/clip %d/%d, glyphs %d, meshUploads %d, router hit/miss/fallback %d/%d/%d, adjacent %d, uploaded v/i %s/%s",
@ -256,7 +255,7 @@ public enum DevRenderProfiler2D {
}
appendRhiCounters(lines);
var immediatelyFast = CombatantRenderSystem.immediatelyFastSnapshot();
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
@ -290,8 +289,8 @@ public enum DevRenderProfiler2D {
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.uniformStatsSnapshot();
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
@ -331,7 +330,7 @@ public enum DevRenderProfiler2D {
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = CombatantRenderSystem.resourceStatsSnapshot();
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
@ -383,7 +382,7 @@ public enum DevRenderProfiler2D {
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (RuntimeGate.isPanic()) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;

View file

@ -2,7 +2,7 @@ package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
@ -10,7 +10,6 @@ import dev.loki.lovisual.render.engine.world.WorldRenderStatsSnapshot;
import dev.loki.lovisual.render.iris.IrisRuntimeSnapshot;
import dev.loki.lovisual.render.sodium.SodiumTerrainInteropStatsSnapshot;
import dev.loki.lovisual.render.sodium.SodiumVisibilityStatsSnapshot;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.*;
@ -160,8 +159,8 @@ public enum DevRenderProfiler3D {
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.uniformStatsSnapshot();
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
@ -177,7 +176,7 @@ public enum DevRenderProfiler3D {
formatBytes(rhi.uploadedIndexBytes())
));
}
WorldRenderStatsSnapshot world = CombatantRenderSystem.worldRenderStatsSnapshot();
WorldRenderStatsSnapshot world = LoVisualRenderSystem.worldRenderStatsSnapshot();
if (world.recordedCommands() > 0 || world.submittedCommands() > 0 || world.skippedEmptyCommands() > 0) {
lines.add(String.format(
"world3d: commands rec/sub/skip %d/%d/%d, vertices/indices %d/%d, fog %d, depth pre/main/none %d/%d/%d",
@ -217,7 +216,7 @@ public enum DevRenderProfiler3D {
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = CombatantRenderSystem.resourceStatsSnapshot();
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
@ -233,17 +232,17 @@ public enum DevRenderProfiler3D {
));
}
IrisRuntimeSnapshot iris = CombatantRenderSystem.irisSnapshot();
IrisRuntimeSnapshot iris = LoVisualRenderSystem.irisSnapshot();
if (iris.modLoaded() || iris.shaderpackInUse()) {
lines.add(iris.shortLine());
}
var immediatelyFast = CombatantRenderSystem.immediatelyFastSnapshot();
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
SodiumVisibilityStatsSnapshot sodiumVisibility = CombatantRenderSystem.sodiumVisibilityStatsSnapshot();
SodiumVisibilityStatsSnapshot sodiumVisibility = LoVisualRenderSystem.sodiumVisibilityStatsSnapshot();
if (sodiumVisibility.queries() > 0 || sodiumVisibility.errors() > 0) {
lines.add(String.format(
"sodium vis: queries %d, accepts/rejects %d/%d, bypass %d (unavail %d, optout %d), errors %d",
@ -257,7 +256,7 @@ public enum DevRenderProfiler3D {
));
}
SodiumTerrainInteropStatsSnapshot sodiumTerrain = CombatantRenderSystem.sodiumTerrainStatsSnapshot();
SodiumTerrainInteropStatsSnapshot sodiumTerrain = LoVisualRenderSystem.sodiumTerrainStatsSnapshot();
if (sodiumTerrain.terrainUpdatesScheduled() > 0
|| sodiumTerrain.rebuildsScheduled() > 0
|| sodiumTerrain.interopErrors() > 0) {
@ -305,7 +304,7 @@ public enum DevRenderProfiler3D {
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (RuntimeGate.isPanic()) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;

View file

@ -2,7 +2,6 @@ package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.ArrayList;
import java.util.HashMap;
@ -37,7 +36,7 @@ public enum DevSamplingProfiler {
stopIfRunning();
return;
}
if (RuntimeGate.isPanic()) return;
lastSource = source;
flushPendingChat();
if (!matchesTarget(source)) return;
@ -56,7 +55,7 @@ public enum DevSamplingProfiler {
private static void ensureRunning() {
if (running) return;
running = true;
samplerThread = new Thread(DevSamplingProfiler::runLoop, "Combatant-DevSamplingProfiler");
samplerThread = new Thread(DevSamplingProfiler::runLoop, "LoVisual-DevSamplingProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
@ -88,10 +87,6 @@ public enum DevSamplingProfiler {
pendingChatLines = null;
break;
}
if (RuntimeGate.isPanic()) {
sleepMs(20);
continue;
}
Thread t = targetThread;
if (t == null) {
sleepMs(10);

View file

@ -40,7 +40,7 @@ public enum DevTracyProfiler {
boolean active = isAvailable();
if (active) {
ProfilerLog.info("Tracy enabled; data is streamed to the external Tracy viewer, not latest.log");
TracyClient.message("Combatant Tracy enabled");
TracyClient.message("LoVisual Tracy enabled");
}
return active;
}
@ -105,7 +105,7 @@ public enum DevTracyProfiler {
loadAttempted = true;
try {
TracyClient.load();
TracyClient.reportAppInfo("Combatant render profiler");
TracyClient.reportAppInfo("LoVisual render profiler");
available = TracyClient.isAvailable();
if (available) {
ProfilerLog.info("Tracy client loaded");

View file

@ -0,0 +1,60 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual;
import dev.loki.lovisual.util.logging.DebugLog;
import dev.loki.lovisual.util.resources.RenderResourceReadiness;
import java.util.concurrent.atomic.AtomicReference;
/**
* Minimal client lifecycle: INIT until explicitly activated, then ACTIVE.
* Replaces the former Runtime/JarReplacement state machine.
*/
public enum Lifecycle {
;
private enum State {
INIT,
ACTIVE,
SHUTDOWN
}
private static final AtomicReference<State> STATE = new AtomicReference<>(State.INIT);
private Lifecycle() {
}
public static void activate() {
if (STATE.compareAndSet(State.INIT, State.ACTIVE)) {
DebugLog.info("Lifecycle: INIT -> ACTIVE");
}
}
public static void shutdown() {
if (STATE.getAndSet(State.SHUTDOWN) != State.SHUTDOWN) {
DebugLog.info("Lifecycle: -> SHUTDOWN");
}
}
public static boolean isActive() {
return STATE.get() == State.ACTIVE;
}
public static boolean canRunRender() {
return isActive() && RenderResourceReadiness.isReady();
}
public static boolean canRunHud() {
return canRunRender();
}
public static boolean canRunShaderBridge() {
return canRunRender();
}
}

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -8,7 +8,6 @@
package dev.loki.lovisual;
import dev.loki.lovisual.events.impl.GameTickEvent;
import dev.loki.lovisual.runtime.*;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
@ -25,7 +24,6 @@ import dev.loki.lovisual.config.MainConfig;
import dev.loki.lovisual.events.Events;
import dev.loki.lovisual.features.account.AccountConfig;
import dev.loki.lovisual.features.command.CommandManager;
import dev.loki.lovisual.features.command.VanillaChatRuntimeCleanup;
import dev.loki.lovisual.features.gui.clickgui.ClickGuiRenderer;
import dev.loki.lovisual.features.gui.clickgui.settings.I18nPreflightContributors;
import dev.loki.lovisual.features.gui.hud.HudElements;
@ -41,8 +39,8 @@ import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.mixininterface.IGuiGraphics;
import dev.loki.lovisual.render.effects.NetherPortalRiftPass;
import dev.loki.lovisual.render.effects.SleepOverlayPass;
import dev.loki.lovisual.render.engine.CombatantRenderEngineBootstrap;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.LoVisualRenderEngineBootstrap;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import dev.loki.lovisual.render.engine.core.RenderPhase;
import dev.loki.lovisual.render.engine.core.RenderPhaseScope;
import dev.loki.lovisual.render.engine.core.ViewportContext;
@ -78,90 +76,10 @@ import dev.loki.lovisual.util.time.TimerController;
public class LoVisual implements ClientModInitializer {
private static void registerRuntimeLifecycle() {
AddonManager.registerRuntimeLifecycle();
ClientRuntime.setCallbackCounter(Events.BUS::listenerCount);
ClientRuntime.setModuleCounter(ModuleManager::registeredCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ModuleManager.shutdownForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void resume(String reason) {
ModuleManager.restoreAfterSoftPanic(reason);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "clickgui";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ClickGuiRenderer.shutdownForRuntime();
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "vanilla_chat";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
VanillaChatRuntimeCleanup.clearVanillaChatCache();
context.increment("vanillaChatCleared", 1);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "hud";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
DraggableHudElementRegistry.clearRuntimeReferences();
StaticHudElementRegistry.clearRuntimeReferences();
}
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "render";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
PostProcessManager.shutdownForRuntime();
CombatantRenderSystem.shutdown();
}
}
});
}
private static void renderWorldPhase(WorldPhase phase,
com.mojang.blaze3d.vertex.PoseStack matrices,
net.minecraft.client.renderer.SubmitNodeCollector consumers) {
if (!RuntimeGate.canRunRender()) return;
if (!Lifecycle.canRunRender()) return;
ModuleManager.renderWorld(
phase,
@ -172,7 +90,7 @@ public class LoVisual implements ClientModInitializer {
}
private static void refreshHudFrameTiming(DeltaTracker tickCounter) {
CombatantRenderSystem.updateFrameTiming(
LoVisualRenderSystem.updateFrameTiming(
TickDelta.tickProgress(tickCounter, false),
TickDelta.frameDeltaTicks(tickCounter),
TickDelta.fixedDeltaTicks(tickCounter)
@ -180,7 +98,7 @@ public class LoVisual implements ClientModInitializer {
}
private static void renderHudPhase(HudPhase phase, GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
if (!RuntimeGate.canRunHud()) return;
if (!Lifecycle.canRunHud()) return;
float tickProgress = TickDelta.tickProgress(tickCounter, false);
ModuleManager.renderHud(phase, ctx, tickProgress);
Renderer2D.Deferred2DLayer layer = deferredLayerForHudPhase(phase);
@ -218,7 +136,7 @@ public class LoVisual implements ClientModInitializer {
Renderer2D.withDeferredLayer(layer, () -> {
SystemCursor.beginFrame(ctx);
try (RenderPhaseScope hudPhase = CombatantRenderSystem.phase(RenderPhase.HUD_MAIN, "2d:phase:" + phase.name())) {
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_MAIN, "2d:phase:" + phase.name())) {
// Raw HUD pass
if (rawMain) {
Renderer2D.COLOR.begin();
@ -284,7 +202,7 @@ public class LoVisual implements ClientModInitializer {
}
private static void renderHudAfterHotbar(GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
if (!RuntimeGate.canRunHud()) return;
if (!Lifecycle.canRunHud()) return;
boolean swapTooltipWork = SwapTooltip.hasWork();
boolean targetHudWork = DraggableHudElementRegistry.hasEngineWidgetWork("target_hud");
if (!swapTooltipWork && !targetHudWork) return;
@ -299,7 +217,7 @@ public class LoVisual implements ClientModInitializer {
Renderer2D.withDeferredLayer(layer, () -> {
SystemCursor.beginFrame(ctx);
try (RenderPhaseScope hudPhase = CombatantRenderSystem.phase(RenderPhase.HUD_EFFECTS, "2d:after_hotbar")) {
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_EFFECTS, "2d:after_hotbar")) {
// Raw pass
if (swapTooltipWork) {
try (ProfilerPhase.Scope tooltipsScope = ProfilerPhase.scope("2d:after_hotbar:swap_tooltip");
@ -337,7 +255,7 @@ public class LoVisual implements ClientModInitializer {
private static void appendHudDeferredMarker(Renderer2D.Deferred2DLayer layer, GuiGraphicsExtractor ctx) {
if (!(ctx instanceof IGuiGraphics graphics)) return;
ctx.nextStratum();
graphics.combatant$addDeferredHudMarker(layer);
graphics.lovisual$addDeferredHudMarker(layer);
ctx.nextStratum();
}
@ -372,7 +290,7 @@ public class LoVisual implements ClientModInitializer {
@Override
public void onInitializeClient() {
CombatantRenderEngineBootstrap.init();
LoVisualRenderEngineBootstrap.init();
PostProcessManager.register(new NetherPortalRiftPass());
PostProcessManager.register(new SleepOverlayPass());
MainConfig.get(); // Load global settings (debug flag)
@ -419,13 +337,12 @@ public class LoVisual implements ClientModInitializer {
ClientTickEvents.START_CLIENT_TICK.register(client -> {
if (client.player == null) return;
if (!RuntimeGate.canRunClientLogic()) return;
if (!Lifecycle.isActive()) return;
Events.BUS.post(new GameTickEvent());
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
ModuleManager.tickRuntimeControllers();
if (!RuntimeGate.canRunClientLogic()) return;
if (!Lifecycle.isActive()) return;
if (!ClickGuiRenderer.isBlockingModuleKeybinds()) {
ModuleManager.handleModuleKeybinds();
@ -518,8 +435,7 @@ public class LoVisual implements ClientModInitializer {
(ctx, tc) -> renderHudAfterHotbar(ctx, tc)
);
registerRuntimeLifecycle();
ClientRuntime.markActive("client initialized");
Lifecycle.activate();
RenderPrewarmManager.prewarm("client initialized");
}
}

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -15,10 +15,6 @@ import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.runtime.ClientRuntime;
import dev.loki.lovisual.runtime.RuntimeResumeParticipant;
import dev.loki.lovisual.runtime.RuntimeShutdownContext;
import dev.loki.lovisual.runtime.RuntimeShutdownParticipant;
import dev.loki.lovisual.util.logging.DebugLog;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.metadata.CustomValue;
@ -34,7 +30,7 @@ import java.util.Map;
public enum AddonManager {
;
public static final String ADDON_METADATA_KEY = "combatant:addon";
public static final String ADDON_METADATA_KEY = "lovisual:addon";
private static final Map<String, AddonRegistration> ADDONS = new LinkedHashMap<>();
private static final Map<String, Boolean> ENABLED_OVERRIDES = new LinkedHashMap<>();
@ -88,32 +84,6 @@ public enum AddonManager {
discoverEntrypoints();
}
public static void registerRuntimeLifecycle() {
ClientRuntime.setAddonCounter(AddonManager::activeCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
suspendForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void resume(String reason) {
resumeAfterRuntime(reason);
}
});
}
public static List<AddonSnapshot> snapshots() {
init();
return ADDONS.values().stream()
@ -142,7 +112,7 @@ public enum AddonManager {
out.addAll(registration.issues);
}
if (out.isEmpty()) {
out.add(new AddonIssue("combatant", AddonIssue.Severity.INFO, "No addon errors found", ""));
out.add(new AddonIssue("lovisual", AddonIssue.Severity.INFO, "No addon errors found", ""));
}
return List.copyOf(out);
}
@ -349,42 +319,6 @@ public enum AddonManager {
return addon;
}
private static void suspendForRuntime(RuntimeShutdownContext context) {
int suspended = 0;
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.ACTIVE) continue;
try {
if (context.jarReplacement()) {
shutdownAddon(registration, context.reason());
registration.status = AddonStatus.SHUTDOWN;
} else {
registration.addon.onRuntimeSuspended(
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
);
registration.status = AddonStatus.SUSPENDED;
}
suspended++;
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Runtime suspend failed", t.toString());
DebugLog.error("Addon runtime suspend failed: %s", t, registration.descriptor.id());
}
}
context.increment("addons_suspended", suspended);
}
private static void resumeAfterRuntime(String reason) {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.SUSPENDED || !registration.enabled) {
continue;
}
resumeAddon(registration, reason);
if (registration.status != AddonStatus.ERROR) {
registration.status = AddonStatus.ACTIVE;
}
}
}
private static void suspendAddon(AddonRegistration registration, String reason) {
if (registration.addon == null) return;
try {

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -53,7 +53,7 @@ final class AddonStateStore {
private static Path stateFile() {
return FabricLoader.getInstance().getConfigDir()
.resolve("combatant")
.resolve("lovisual")
.resolve("addons.json");
}

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -22,7 +22,7 @@ import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.render.engine.pipeline.CombatantRenderPipelines;
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import dev.loki.lovisual.render.iris.patch.ShaderPatchEngine;
import net.fabricmc.loader.api.FabricLoader;
@ -149,7 +149,7 @@ final class LoVisualAddonContextImpl implements LoVisualAddonContext {
@Override
public RenderPipeline registerRenderPipeline(RenderPipeline pipeline) {
if (pipeline == null) return null;
RenderPipeline registered = CombatantRenderPipelines.registerAddonPipeline(pipeline);
RenderPipeline registered = LoVisualRenderPipelines.registerAddonPipeline(pipeline);
registration.renderCallbacks.add("pipeline:" + pipeline.getLocation());
return registered;
}

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -8,12 +8,12 @@
package dev.loki.lovisual.api.v0.addon;
/**
* Fabric entrypoint contract for Combatant addons.
* Fabric entrypoint contract for LoVisual addons.
*
* <p>Declare it in fabric.mod.json under the {@value #ENTRYPOINT_KEY} entrypoint.
*/
public interface LoVisualAddon {
String ENTRYPOINT_KEY = "combatant:addon";
String ENTRYPOINT_KEY = "lovisual:addon";
int API_VERSION = 0;
/**

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -11,7 +11,7 @@ import dev.loki.lovisual.events.UsedImplicitly;
import dev.loki.lovisual.features.module.Module;
/**
* Early addon context used before Combatant's built-in modules are instantiated.
* Early addon context used before LoVisual's built-in modules are instantiated.
*
* <p>Only enabled addons receive this callback. Exclusions are startup-only: changing
* an addon's enabled state after module discovery requires a client restart for the

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -12,7 +12,7 @@ import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.shaders.UniformType;
import com.mojang.blaze3d.vertex.VertexFormat;
import dev.loki.lovisual.render.engine.pipeline.CombatantRenderPipelines;
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
import dev.loki.lovisual.render.engine.pipeline.DepthTestFunction;
import dev.loki.lovisual.render.engine.pipeline.ExtendedRenderPipelineBuilder;
import dev.loki.lovisual.render.engine.rhi.clip.ShapeClipRenderPassContract;
@ -31,7 +31,7 @@ public final class LoVisualRenderPipelineBuilder {
}
public static RenderPipeline.Snippet meshUniforms() {
return CombatantRenderPipelines.meshUniforms();
return LoVisualRenderPipelines.meshUniforms();
}
public LoVisualRenderPipelineBuilder location(Identifier id) {
@ -104,6 +104,6 @@ public final class LoVisualRenderPipelineBuilder {
}
public RenderPipeline buildAndRegister() {
return CombatantRenderPipelines.registerAddonPipeline(build());
return LoVisualRenderPipelines.registerAddonPipeline(build());
}
}

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -8,7 +8,7 @@
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.buffers.GpuBufferSlice;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import java.nio.ByteBuffer;
@ -29,7 +29,7 @@ public enum LoVisualUniforms {
if (writer == null) {
throw new IllegalArgumentException("Uniform writer cannot be null");
}
return CombatantRenderSystem.uniforms().write(name, std140Size, expectedWritesPerFrame, writer::write);
return LoVisualRenderSystem.uniforms().write(name, std140Size, expectedWritesPerFrame, writer::write);
}
public static GpuBufferSlice writeCached(String name,
@ -47,7 +47,7 @@ public enum LoVisualUniforms {
if (writer == null) {
throw new IllegalArgumentException("Uniform writer cannot be null");
}
return CombatantRenderSystem.uniforms().writeCached(
return LoVisualRenderSystem.uniforms().writeCached(
name,
std140Size,
expectedWritesPerFrame,
@ -59,12 +59,12 @@ public enum LoVisualUniforms {
public static GpuBufferSlice current(String name) {
if (name == null || name.isBlank()) return null;
return CombatantRenderSystem.uniforms().current(name);
return LoVisualRenderSystem.uniforms().current(name);
}
public static void invalidate(String name) {
if (name == null || name.isBlank()) return;
CombatantRenderSystem.uniforms().invalidate(name);
LoVisualRenderSystem.uniforms().invalidate(name);
}
@FunctionalInterface

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -19,7 +19,7 @@ public enum TriangulatorXaeroState {
;
public static final String NAME = "Stronghold";
public static final String SYMBOL = "S";
public static final String SET = "combatant";
public static final String SET = "lovisual";
public static final int DEFAULT_Y = 64;
@Nullable

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.

View file

@ -1,5 +1,5 @@
/*
* This file is part of the Combatant Client distribution.
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
@ -21,7 +21,7 @@ import java.util.concurrent.atomic.AtomicLong;
public enum XaeroWaypointStore {
;
public static final String SET = "combatant";
public static final String SET = "lovisual";
public static final String DEFAULT_NAME = "LoVisual";
public static final String DEFAULT_SYMBOL = "C";

View file

@ -0,0 +1,30 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import net.minecraft.client.resources.language.I18n;
import dev.loki.lovisual.config.values.ConfigValue;
public enum ConfigLang {
;
public static String getName(ConfigValue<?> v) {
String key = "config." + v.getName() + ".name";
return translateOrFallback(key, v.getName());
}
public static String getDesc(ConfigValue<?> v) {
String key = "config." + v.getName() + ".desc";
return translateOrFallback(key, "");
}
private static String translateOrFallback(String key, String fallback) {
String translated = I18n.get(key);
return translated.equals(key) ? fallback : translated;
}
}

View file

@ -0,0 +1,15 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
/**
* Optional stable config name override (used for file names).
*/
public interface ConfigNameProvider {
String getConfigName();
}

View file

@ -0,0 +1,16 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import dev.loki.lovisual.config.values.ConfigValue;
import java.util.List;
public interface ConfigObject {
List<ConfigValue<?>> getConfigValues();
}

View file

@ -0,0 +1,29 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import java.nio.file.Path;
import java.nio.file.Paths;
public enum ConfigPaths {
;
// TODO: make the user config root configurable, including base directory and visible folder name.
// Keep config/lovisual as the default for compatibility with existing installs.
public static Path root() {
return Paths.get("config", legacyNamespaceName());
}
public static Path profilesRoot() {
return root().resolve("profiles");
}
public static String legacyNamespaceName() {
return new String(new char[]{'l', 'o', 'v', 'i', 's', 'u', 'a', 'l'});
}
}

View file

@ -0,0 +1,664 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import com.google.gson.*;
import de.marhali.json5.*;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.HudGlobalConfig;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.relations.EntityFilters;
import dev.loki.lovisual.util.logging.DebugLog;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public enum ConfigSerializer {
;
private static final Path CONFIG_DIR = ConfigPaths.root();
private static final long SAVE_DEBOUNCE_MS = 220L;
private static final ScheduledExecutorService SAVE_EXECUTOR =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "LoVisual-ConfigSaver");
t.setDaemon(true);
return t;
});
private static final Object SAVE_LOCK = new Object();
private static final Map<Path, String> PENDING_TEXT = new HashMap<>();
private static final Map<Path, ScheduledFuture<?>> PENDING_TASKS = new HashMap<>();
private static final Map<Path, Long> PENDING_TOKENS = new HashMap<>();
// One Json5 instance for utilities (player relations, filters, debug config, etc.)
private static final Json5 JSON5 = Json5.builder(builder -> builder
.trailingComma() // allow trailing commas
.indentFactor(2) // pretty output
.quoteSingle() // use " quotes
.build()
);
// Gson serializer for modules (strict JSON)
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
private static long SAVE_TOKEN_SEQ = 0L;
// =============================================================
// Bulk load / save helpers
// =============================================================
@SuppressWarnings("unused") // kept for bulk-loading singletons via ClassGraph
public static void loadAll() {
try (ScanResult sc = new ClassGraph()
.enableClassInfo()
.acceptPackages("dev.loki.lovisual")
.scan()) {
for (ClassInfo ci : sc.getClassesImplementing(ConfigObject.class)) {
Class<?> cls = ci.loadClass();
ConfigObject inst = singletonConfigObjectFor(cls);
if (inst != null) {
load(inst);
}
}
} catch (Exception e) {
DebugLog.error("ConfigSerializer.loadAll failed", e);
}
}
public static void saveAll() {
try (ScanResult sc = new ClassGraph()
.enableClassInfo()
.acceptPackages("dev.loki.lovisual")
.scan()) {
for (ClassInfo ci : sc.getClassesImplementing(ConfigObject.class)) {
Class<?> cls = ci.loadClass();
ConfigObject inst = singletonConfigObjectFor(cls);
if (inst != null) {
save(inst);
}
}
} catch (Exception e) {
DebugLog.error("ConfigSerializer.saveAll failed", e);
}
}
private static ConfigObject singletonConfigObjectFor(Class<?> cls) throws IllegalAccessException {
if (cls == null) return null;
for (Field field : cls.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) continue;
if (!ConfigObject.class.isAssignableFrom(field.getType())) continue;
field.setAccessible(true);
Object value = field.get(null);
if (value instanceof ConfigObject configObject) {
return configObject;
}
}
return null;
}
// =============================================================
// Dispatch
// =============================================================
public static void save(ConfigObject obj) {
if (obj instanceof HudGlobalConfig) return;
saveNow(obj);
}
public static void requestSave(ConfigObject obj) {
if (obj == null || obj instanceof HudGlobalConfig) return;
PendingWrite write;
try {
write = buildWrite(obj);
} catch (Exception e) {
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
return;
}
if (write == null) return;
long token;
synchronized (SAVE_LOCK) {
token = ++SAVE_TOKEN_SEQ;
PENDING_TEXT.put(write.path, write.text);
PENDING_TOKENS.put(write.path, token);
ScheduledFuture<?> prev = PENDING_TASKS.get(write.path);
if (prev != null) prev.cancel(false);
ScheduledFuture<?> task = SAVE_EXECUTOR.schedule(
() -> flushPending(write.path, token),
SAVE_DEBOUNCE_MS,
TimeUnit.MILLISECONDS
);
PENDING_TASKS.put(write.path, task);
}
}
public static void load(ConfigObject obj) {
if (obj instanceof HudGlobalConfig) return;
if (isModule(obj)) {
loadModule(obj);
} else if (isJsonConfig(obj)) {
loadJson(obj);
} else {
loadJson5(obj);
}
}
private static boolean isModule(ConfigObject obj) {
return obj instanceof Module;
}
private static boolean isJsonConfig(ConfigObject obj) {
return obj instanceof JsonConfigObject;
}
private static String configNameOf(ConfigObject obj) {
String name = null;
if (obj instanceof ConfigNameProvider provider) {
name = provider.getConfigName();
}
if (name == null || name.isBlank()) {
name = obj.getClass().getSimpleName();
}
return sanitizeConfigName(name);
}
private static String sanitizeConfigName(String name) {
if (name == null) return "config";
String base = name.trim().toLowerCase(Locale.ROOT);
if (base.isEmpty()) return "config";
StringBuilder out = new StringBuilder(base.length());
for (int i = 0; i < base.length(); i++) {
char c = base.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
out.append(c);
} else {
out.append('_');
}
}
return out.toString();
}
private static Path namedJsonFile(String configName) {
return CONFIG_DIR.resolve(sanitizeConfigName(configName) + ".json");
}
private static Path namedJson5File(String configName) {
return CONFIG_DIR.resolve(sanitizeConfigName(configName) + ".json5");
}
private static Path moduleFile(ConfigObject obj) {
String category = "uncategorized";
if (obj instanceof Module module && module.getCategory() != null) {
category = sanitizeConfigName(module.getCategory().name());
}
return CONFIG_DIR.resolve("modules")
.resolve(category)
.resolve(configNameOf(obj) + ".json");
}
private static Path jsonFile(ConfigObject obj) {
if (obj instanceof DraggableHudElement) {
return CONFIG_DIR.resolve("hud")
.resolve("draggable")
.resolve(configNameOf(obj) + ".json");
}
if (obj instanceof AbstractHudElement) {
return CONFIG_DIR.resolve("hud")
.resolve("nondraggable")
.resolve(configNameOf(obj) + ".json");
}
return namedJsonFile(configNameOf(obj));
}
private static Path utilFile(ConfigObject obj) {
return isJsonConfig(obj)
? jsonFile(obj)
: namedJson5File(configNameOf(obj));
}
private static Path fileOf(ConfigObject obj) {
return isModule(obj) ? moduleFile(obj) : utilFile(obj);
}
// =============================================================
// Module (Gson JSON)
// =============================================================
private static PendingWrite buildModuleWrite(ConfigObject obj) {
try {
JsonObject root = new JsonObject();
for (ConfigValue<?> v : obj.getConfigValues()) {
root.add(v.getName(), toJsonElement(v.toJson()));
}
String text = GSON.toJson(root) + "\n";
Path out = moduleFile(obj);
return new PendingWrite(out, text);
} catch (Exception e) {
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
return null;
}
}
private static void loadModule(ConfigObject obj) {
try {
Path path = moduleFile(obj);
if (!Files.exists(path)) {
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
save(obj);
return;
}
DebugLog.config("Config loading: %s", path.toAbsolutePath());
String txt = Files.readString(path);
JsonElement parsed = GSON.fromJson(txt, JsonElement.class);
if (!(parsed instanceof JsonObject root)) return;
Module module = (Module) obj;
JsonElement legacySettings = root.get("settings");
if (legacySettings != null) {
module.applyLegacySettings(unwrapJsonElement(legacySettings));
}
boolean usedLegacyAlias = false;
for (ConfigValue<?> v : obj.getConfigValues()) {
JsonLookup lookup = findJsonElement(obj, root, v.getName());
if (lookup.element() != null) {
v.fromJson(unwrapJsonElement(lookup.element()));
usedLegacyAlias |= lookup.alias();
}
}
module.syncSettingsAfterLoad();
if (usedLegacyAlias) {
requestSave(obj);
}
} catch (Exception e) {
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
}
}
// =============================================================
// JSON (Gson) for non-Module configs
// =============================================================
private static PendingWrite buildJsonWrite(ConfigObject obj) {
try {
JsonObject root = new JsonObject();
for (ConfigValue<?> v : obj.getConfigValues()) {
root.add(v.getName(), toJsonElement(v.toJson()));
}
String text = GSON.toJson(root) + "\n";
Path out = jsonFile(obj);
return new PendingWrite(out, text);
} catch (Exception e) {
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
return null;
}
}
private static void loadJson(ConfigObject obj) {
try {
Path path = jsonFile(obj);
if (!Files.exists(path)) {
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
save(obj);
return;
}
DebugLog.config("Config loading: %s", path.toAbsolutePath());
String txt = Files.readString(path);
JsonElement parsed = GSON.fromJson(txt, JsonElement.class);
if (!(parsed instanceof JsonObject root)) return;
boolean missing = false;
boolean usedLegacyAlias = false;
for (ConfigValue<?> v : obj.getConfigValues()) {
JsonLookup lookup = findJsonElement(obj, root, v.getName());
if (lookup.element() != null) {
v.fromJson(unwrapJsonElement(lookup.element()));
usedLegacyAlias |= lookup.alias();
} else {
missing = true;
}
}
if (missing || usedLegacyAlias) {
requestSave(obj);
}
} catch (Exception e) {
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
}
}
// =============================================================
// Utilities (Json5)
// =============================================================
private static PendingWrite buildJson5Write(ConfigObject obj) {
try {
Json5Object root = new Json5Object();
for (ConfigValue<?> v : obj.getConfigValues()) {
Object raw = v.toJson();
root.add(v.getName(), toJson5Element(raw));
}
String text = JSON5.serialize(root);
String sb = text + "\n";
Path out = utilFile(obj);
if (obj instanceof EntityFilters) {
DebugLog.config("[EntityFilters][SAVE] to=%s data=%s", out.toAbsolutePath(), text);
}
return new PendingWrite(out, sb);
} catch (Exception e) {
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
return null;
}
}
private static void loadJson5(ConfigObject obj) {
try {
Path path = utilFile(obj);
if (!Files.exists(path)) {
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
save(obj);
return;
}
DebugLog.config("Config loading: %s", path.toAbsolutePath());
String txt = Files.readString(path);
Json5Element parsed = JSON5.parse(txt);
if (!(parsed instanceof Json5Object root)) {
return;
}
Map<String, Json5Element> map = root.asMap();
boolean missing = false;
boolean usedLegacyAlias = false;
for (ConfigValue<?> v : obj.getConfigValues()) {
Json5Lookup lookup = findJson5Element(obj, map, v.getName());
if (lookup.element() != null) {
v.fromJson(unwrapJson5(lookup.element()));
usedLegacyAlias |= lookup.alias();
} else {
missing = true;
}
}
if (obj instanceof Module module) {
module.syncSettingsAfterLoad();
}
if (missing || usedLegacyAlias) {
requestSave(obj);
}
} catch (Exception e) {
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
}
}
private static JsonLookup findJsonElement(ConfigObject obj, JsonObject root, String valueName) {
if (root == null || valueName == null) return JsonLookup.missing();
JsonElement direct = root.get(valueName);
if (direct != null && !direct.isJsonNull()) {
return new JsonLookup(direct, false);
}
if (obj instanceof ConfigValueAliasProvider provider) {
List<String> aliases = provider.getLegacyValueNames(valueName);
if (aliases != null) {
for (String alias : aliases) {
if (alias == null || alias.isBlank()) continue;
JsonElement legacy = root.get(alias);
if (legacy != null && !legacy.isJsonNull()) {
return new JsonLookup(legacy, true);
}
}
}
}
return JsonLookup.missing();
}
private static Json5Lookup findJson5Element(ConfigObject obj, Map<String, Json5Element> map, String valueName) {
if (map == null || valueName == null) return Json5Lookup.missing();
Json5Element direct = map.get(valueName);
if (direct != null) {
return new Json5Lookup(direct, false);
}
if (obj instanceof ConfigValueAliasProvider provider) {
List<String> aliases = provider.getLegacyValueNames(valueName);
if (aliases != null) {
for (String alias : aliases) {
if (alias == null || alias.isBlank()) continue;
Json5Element legacy = map.get(alias);
if (legacy != null) {
return new Json5Lookup(legacy, true);
}
}
}
}
return Json5Lookup.missing();
}
private static JsonElement toJsonElement(Object v) {
if (v == null) return JsonNull.INSTANCE;
if (v instanceof JsonElement el) return el;
if (v instanceof Boolean b) return new JsonPrimitive(b);
if (v instanceof Number n) return new JsonPrimitive(n);
if (v instanceof CharSequence s) return new JsonPrimitive(s.toString());
if (v instanceof Map<?, ?> map) {
JsonObject obj = new JsonObject();
for (var e : map.entrySet()) {
obj.add(String.valueOf(e.getKey()), toJsonElement(e.getValue()));
}
return obj;
}
if (v instanceof Iterable<?> it) {
JsonArray arr = new JsonArray();
for (Object el : it) arr.add(toJsonElement(el));
return arr;
}
return new JsonPrimitive(String.valueOf(v));
}
private static Json5Element toJson5Element(Object v) {
if (v == null) {
return Json5Primitive.fromNull();
}
if (v instanceof Json5Element el) {
return el;
}
if (v instanceof Boolean b) {
return Json5Primitive.fromBoolean(b);
}
if (v instanceof Number n) {
return Json5Primitive.fromNumber(n);
}
if (v instanceof CharSequence s) {
return Json5Primitive.fromString(s.toString());
}
if (v instanceof Map<?, ?> map) {
Json5Object obj = new Json5Object();
for (var e : map.entrySet()) {
String key = String.valueOf(e.getKey());
obj.add(key, toJson5Element(e.getValue()));
}
return obj;
}
if (v instanceof Iterable<?> it) {
Json5Array arr = new Json5Array();
for (Object el : it) {
arr.add(toJson5Element(el));
}
return arr;
}
return Json5Primitive.fromString(String.valueOf(v));
}
// =============================================================
// Helpers
// =============================================================
private static Object unwrapJsonElement(JsonElement el) {
if (el == null || el.isJsonNull()) return null;
if (el.isJsonPrimitive()) {
JsonPrimitive p = el.getAsJsonPrimitive();
if (p.isBoolean()) return p.getAsBoolean();
if (p.isNumber()) return p.getAsNumber();
return p.getAsString();
}
if (el.isJsonArray()) {
List<Object> out = new ArrayList<>();
for (JsonElement child : el.getAsJsonArray()) {
out.add(unwrapJsonElement(child));
}
return out;
}
if (el.isJsonObject()) {
Map<String, Object> out = new LinkedHashMap<>();
for (var e : el.getAsJsonObject().entrySet()) {
out.put(e.getKey(), unwrapJsonElement(e.getValue()));
}
return out;
}
return null;
}
private static Object unwrapJson5(Json5Element el) {
if (el == null || el.isJson5Null()) return null;
if (el.isJson5Primitive()) {
Json5Primitive p = el.getAsJson5Primitive();
if (p.isBoolean()) return p.getAsBoolean();
if (p.isNumber()) return p.getAsNumber();
return p.getAsString();
}
if (el.isJson5Array()) {
List<Object> out = new ArrayList<>();
for (Json5Element child : el.getAsJson5Array()) {
out.add(unwrapJson5(child));
}
return out;
}
if (el.isJson5Object()) {
Map<String, Object> out = new LinkedHashMap<>();
for (var e : el.getAsJson5Object().asMap().entrySet()) {
out.put(e.getKey(), unwrapJson5(e.getValue()));
}
return out;
}
return null;
}
private static PendingWrite buildWrite(ConfigObject obj) {
if (obj == null) return null;
if (isModule(obj)) return buildModuleWrite(obj);
if (isJsonConfig(obj)) return buildJsonWrite(obj);
return buildJson5Write(obj);
}
private static void saveNow(ConfigObject obj) {
PendingWrite write;
try {
write = buildWrite(obj);
} catch (Exception e) {
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
return;
}
if (write == null) return;
clearPending(write.path);
writeConfig(write.path, write.text);
}
// =============================================================
// Async write helpers
// =============================================================
private static void flushPending(Path path, long token) {
String text;
synchronized (SAVE_LOCK) {
Long current = PENDING_TOKENS.get(path);
if (current == null || current != token) return;
text = PENDING_TEXT.remove(path);
PENDING_TOKENS.remove(path);
PENDING_TASKS.remove(path);
}
if (text != null) {
writeConfig(path, text);
}
}
private static void clearPending(Path path) {
synchronized (SAVE_LOCK) {
ScheduledFuture<?> prev = PENDING_TASKS.remove(path);
if (prev != null) prev.cancel(false);
PENDING_TEXT.remove(path);
PENDING_TOKENS.remove(path);
}
}
private static void writeConfig(Path out, String text) {
try {
Path parent = out.getParent();
Files.createDirectories(parent != null ? parent : CONFIG_DIR);
Files.writeString(out, text);
DebugLog.config("Config saved: %s", out.toAbsolutePath());
} catch (IOException e) {
DebugLog.error("Failed to save config %s", e, out.toAbsolutePath());
}
}
private record JsonLookup(JsonElement element, boolean alias) {
static JsonLookup missing() {
return new JsonLookup(null, false);
}
}
private record Json5Lookup(Json5Element element, boolean alias) {
static Json5Lookup missing() {
return new Json5Lookup(null, false);
}
}
private record PendingWrite(Path path, String text) {
}
}

View file

@ -0,0 +1,14 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import java.util.List;
public interface ConfigValueAliasProvider {
List<String> getLegacyValueNames(String currentValueName);
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Opts a setting out of i18n lookup. Use this for user/content values where raw ids
* are the intended labels, for example selectable sound ids.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DisableSettingI18n {
boolean name() default true;
boolean options() default true;
}

View file

@ -0,0 +1,14 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
/**
* Marker for config objects that must be stored as JSON (not JSON5).
*/
public interface JsonConfigObject extends ConfigObject {
}

View file

@ -0,0 +1,477 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import dev.loki.lovisual.config.values.*;
import dev.loki.lovisual.config.values.*;
import dev.loki.lovisual.render.iris.IrisRuntime;
import dev.loki.lovisual.util.logging.DebugLog;
import dev.loki.lovisual.util.logging.DebugMode;
import dev.loki.lovisual.util.player.inventory.InventorySearchScope;
import dev.loki.lovisual.util.player.inventory.InventorySwap;
import dev.loki.lovisual.util.player.inventory.InventorySwapPolicy;
import dev.loki.lovisual.util.player.inventory.InventorySwapVisibility;
import net.minecraft.client.resources.language.I18n;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public final class MainConfig implements ConfigObject, ConfigNameProvider, SettingOwner {
public static final MainConfig INSTANCE = new MainConfig();
private static final String IRIS_MSAA_REASON_KEY = "setting.main_config.msaa3d.iris_blocked";
private static final String IRIS_MSAA_REASON_FALLBACK = "Iris shaderpack pipeline is active.";
//@CFGComment("Debug logging mode: off / error_only / error_and_warnings / info / config / render_thread / stencil / serverdebug / all")
private final ModeValue debug =
new ModeValue("debug", "off", "off", "error_only", "error_and_warnings", "info", "config", "render_thread", "stencil", "serverdebug", "all");
//@CFGComment("Force PvP mode ON everywhere (dev/testing only)")
private final BooleanValue forcePvp =
new BooleanValue("forcePvp", false);
//@CFGComment("Menu background shader: off / waves / aurora")
private final ModeValue menuBg =
new ModeValue("menuBg", "off", "off", "waves", "aurora");
//@CFGComment("Use ClickGUI theme colors for menu background shader")
private final BooleanValue menuBgUseTheme =
new BooleanValue("menuBgUseTheme", false);
//@CFGComment("Show seconds in the custom main menu clock")
private final BooleanValue menuClockShowSeconds =
new BooleanValue("menuClockShowSeconds", false);
//@CFGComment("MSAA for world render: off / 2x / 4x")
private final ModeValue msaa3d =
new ModeValue("msaa3d", "off", "off", "2x", "4x");
//@CFGComment("Show ClickGUI modules hotkey hints")
private final BooleanValue clickGuiModulesHints =
new BooleanValue("clickGuiModulesHints", true);
//@CFGComment("Show ClickGUI HUD editor hotkey hints")
private final BooleanValue clickGuiHudEditorHints =
new BooleanValue("clickGuiHudEditorHints", true);
//@CFGComment("Default inventory swap safety policy: none / grim_strict / legit")
private final EnumValue<InventorySwapPolicy> inventorySwapPolicy =
new EnumValue<>("inventorySwapPolicy", InventorySwapPolicy.NONE, InventorySwapPolicy.class);
//@CFGComment("Default inventory swap search scope: hotbar / inventory / full")
private final EnumValue<InventorySearchScope> inventorySwapScope =
new EnumValue<>("inventorySwapScope", InventorySearchScope.FULL, InventorySearchScope.class);
//@CFGComment("Default inventory swap visibility: normal / silent")
private final EnumValue<InventorySwapVisibility> inventorySwapVisibility =
new EnumValue<>("inventorySwapVisibility", InventorySwapVisibility.SILENT, InventorySwapVisibility.class);
//@CFGComment("Restore the original hotbar slot after default swap requests")
private final BooleanValue inventorySwapRestore =
new BooleanValue("inventorySwapRestore", true);
//@CFGComment("Prefer hotbar matches before inventory matches for full-scope swap requests")
private final BooleanValue inventorySwapPreferHotbar =
new BooleanValue("inventorySwapPreferHotbar", true);
//@CFGComment("Extra delay before queued legit inventory swap actions")
private final NumberValue<Integer> inventorySwapLegitWaitTicks =
new NumberValue<>("inventorySwapLegitWaitTicks", 2, 0, 20);
// @CFGComment("Extra delay before queued Grim-strict inventory click/close actions")
private final NumberValue<Integer> inventorySwapStrictInventoryWaitTicks =
new NumberValue<>("inventorySwapStrictInventoryWaitTicks", 1, 0, 20);
//@CFGComment("Movement input lock duration while waiting for Grim-strict inventory actions")
private final NumberValue<Integer> inventorySwapStrictMovementLockTicks =
new NumberValue<>("inventorySwapStrictMovementLockTicks", 2, 0, 20);
//@CFGComment("Hard-disable narrator and narrator hotkey")
private final BooleanValue disableNarrator =
new BooleanValue("disableNarrator", true);
//@CFGComment("Always-on backdoor protection master switch")
private final BooleanValue backdoorProtection =
new BooleanValue("backdoorProtection", true);
//@CFGComment("Filter non-whitelisted translation keys in server-controlled sign/anvil text")
private final BooleanValue backdoorTranslationFilter =
new BooleanValue("backdoorTranslationFilter", true);
//@CFGComment("Filter non-vanilla keybind text keys in server-controlled text")
private final BooleanValue backdoorKeybindFilter =
new BooleanValue("backdoorKeybindFilter", true);
//@CFGComment("Block remote servers from redirecting resource-pack downloads into local/private network addresses")
private final BooleanValue backdoorLocalHttpGuard =
new BooleanValue("backdoorLocalHttpGuard", true);
//@CFGComment("Isolate downloaded server-pack cache by account UUID to reduce pack-cache fingerprinting")
private final BooleanValue backdoorPackCacheIsolation =
new BooleanValue("backdoorPackCacheIsolation", true);
//@CFGComment("Allow local/private HTTP requests when connected to local/integrated server")
private final BooleanValue backdoorAllowLocalHttpWhenServerLocal =
new BooleanValue("backdoorAllowLocalHttpWhenServerLocal", true);
//@CFGComment("Extra allowed translation resource-pack ids for server-controlled text")
private final SetValue backdoorAllowedTranslationPacks =
new SetValue("backdoorAllowedTranslationPacks", defaultAllowedTranslationPacks());
//@CFGComment("Extra allowed keybind ids for server-controlled text")
private final SetValue backdoorAllowedKeybinds =
new SetValue("backdoorAllowedKeybinds");
private MainConfig() {
ConfigSerializer.load(this);
applyDebugMode();
applyInventorySwapSettings();
}
public static MainConfig get() {
return INSTANCE;
}
private static Set<String> defaultAllowedTranslationPacks() {
LinkedHashSet<String> out = new LinkedHashSet<>();
out.add("vanilla");
return out;
}
@Override
public String getConfigName() {
return "mainconfig";
}
@Override
public String name() {
return "main_config";
}
// ================= DEBUG =================
@Override
public void saveConfig() {
applyDebugMode();
applyInventorySwapSettings();
ConfigSerializer.requestSave(this);
}
public DebugMode getDebugMode() {
try {
return DebugMode.valueOf(debug.get().toUpperCase());
} catch (IllegalArgumentException e) {
return DebugMode.OFF;
}
}
public void setDebugMode(DebugMode mode) {
if (mode == null) mode = DebugMode.OFF;
debug.set(mode.name().toLowerCase());
applyDebugMode();
ConfigSerializer.requestSave(this);
}
private void applyDebugMode() {
DebugLog.setMode(getDebugMode());
}
public boolean isForcePvp() {
return forcePvp.get();
}
public String getMenuBackgroundMode() {
return menuBg.get();
}
public boolean isMenuBackgroundUseTheme() {
return menuBgUseTheme.get();
}
public boolean isMenuClockShowSeconds() {
return menuClockShowSeconds.get();
}
public int getMsaa3dSamples() {
if (IrisRuntime.isShaderpackRendererActive()) return 0;
String v = msaa3d.get();
if (v == null) return 0;
if (v.equalsIgnoreCase("2x")) return 2;
if (v.equalsIgnoreCase("4x")) return 4;
return 0;
}
public boolean isClickGuiModulesHintsEnabled() {
return clickGuiModulesHints.get();
}
public boolean isClickGuiHintsEnabled() {
return clickGuiModulesHints.get();
}
public void setClickGuiModulesHintsEnabled(boolean enabled) {
clickGuiModulesHints.set(enabled);
ConfigSerializer.requestSave(this);
}
public void setClickGuiHintsEnabled(boolean enabled) {
setClickGuiModulesHintsEnabled(enabled);
}
public boolean isClickGuiHudEditorHintsEnabled() {
return clickGuiHudEditorHints.get();
}
public void setClickGuiHudEditorHintsEnabled(boolean enabled) {
clickGuiHudEditorHints.set(enabled);
ConfigSerializer.requestSave(this);
}
public InventorySwapPolicy getInventorySwapPolicy() {
return inventorySwapPolicy.get();
}
public void setInventorySwapPolicy(InventorySwapPolicy policy) {
inventorySwapPolicy.set(policy != null ? policy : InventorySwapPolicy.NONE);
saveAndApplyInventorySwapSettings();
}
public InventorySearchScope getInventorySwapScope() {
return inventorySwapScope.get();
}
public void setInventorySwapScope(InventorySearchScope scope) {
inventorySwapScope.set(scope != null ? scope : InventorySearchScope.FULL);
saveAndApplyInventorySwapSettings();
}
public InventorySwapVisibility getInventorySwapVisibility() {
return inventorySwapVisibility.get();
}
public void setInventorySwapVisibility(InventorySwapVisibility visibility) {
inventorySwapVisibility.set(visibility != null ? visibility : InventorySwapVisibility.SILENT);
saveAndApplyInventorySwapSettings();
}
public boolean isInventorySwapRestore() {
return inventorySwapRestore.get();
}
public void setInventorySwapRestore(boolean restore) {
inventorySwapRestore.set(restore);
saveAndApplyInventorySwapSettings();
}
public boolean isInventorySwapPreferHotbar() {
return inventorySwapPreferHotbar.get();
}
public void setInventorySwapPreferHotbar(boolean preferHotbar) {
inventorySwapPreferHotbar.set(preferHotbar);
saveAndApplyInventorySwapSettings();
}
public int getInventorySwapLegitWaitTicks() {
return inventorySwapLegitWaitTicks.get();
}
public void setInventorySwapLegitWaitTicks(int ticks) {
inventorySwapLegitWaitTicks.fromJson(ticks);
saveAndApplyInventorySwapSettings();
}
public int getInventorySwapStrictInventoryWaitTicks() {
return inventorySwapStrictInventoryWaitTicks.get();
}
public void setInventorySwapStrictInventoryWaitTicks(int ticks) {
inventorySwapStrictInventoryWaitTicks.fromJson(ticks);
saveAndApplyInventorySwapSettings();
}
public int getInventorySwapStrictMovementLockTicks() {
return inventorySwapStrictMovementLockTicks.get();
}
public void setInventorySwapStrictMovementLockTicks(int ticks) {
inventorySwapStrictMovementLockTicks.fromJson(ticks);
saveAndApplyInventorySwapSettings();
}
public EnumValue<InventorySwapPolicy> inventorySwapPolicyValue() {
return inventorySwapPolicy;
}
public EnumValue<InventorySearchScope> inventorySwapScopeValue() {
return inventorySwapScope;
}
public EnumValue<InventorySwapVisibility> inventorySwapVisibilityValue() {
return inventorySwapVisibility;
}
public BooleanValue inventorySwapRestoreValue() {
return inventorySwapRestore;
}
public BooleanValue inventorySwapPreferHotbarValue() {
return inventorySwapPreferHotbar;
}
public NumberValue<Integer> inventorySwapLegitWaitTicksValue() {
return inventorySwapLegitWaitTicks;
}
public NumberValue<Integer> inventorySwapStrictInventoryWaitTicksValue() {
return inventorySwapStrictInventoryWaitTicks;
}
public NumberValue<Integer> inventorySwapStrictMovementLockTicksValue() {
return inventorySwapStrictMovementLockTicks;
}
public List<SettingDef> getImageSettingDefs() {
List<SettingDef> list = new ArrayList<>();
list.add(SettingDef.mode(msaa3d)
.unavailableWhen(IrisRuntime::isShaderpackRendererActive, MainConfig::irisMsaaReason));
list.add(SettingDef.mode(menuBg));
list.add(SettingDef.bool(menuClockShowSeconds));
list.add(SettingDef.bool(menuBgUseTheme));
return list;
}
private static String irisMsaaReason() {
String translated = I18n.get(IRIS_MSAA_REASON_KEY);
return IRIS_MSAA_REASON_KEY.equals(translated) ? IRIS_MSAA_REASON_FALLBACK : translated;
}
public List<SettingDef> getMiscellaneousSettingDefs() {
List<SettingDef> list = new ArrayList<>();
list.add(SettingDef.mode(debug));
list.add(SettingDef.bool(forcePvp));
list.add(SettingDef.bool(disableNarrator));
return list;
}
public List<SettingDef> getSecuritySettingDefs() {
List<SettingDef> list = new ArrayList<>();
list.add(SettingDef.bool(backdoorProtection));
list.add(SettingDef.bool(backdoorTranslationFilter).visibleWhen(backdoorProtection::get));
list.add(SettingDef.bool(backdoorKeybindFilter).visibleWhen(backdoorProtection::get));
list.add(SettingDef.bool(backdoorLocalHttpGuard).visibleWhen(backdoorProtection::get));
list.add(SettingDef.bool(backdoorPackCacheIsolation).visibleWhen(backdoorProtection::get));
list.add(SettingDef.bool(backdoorAllowLocalHttpWhenServerLocal).visibleWhen(backdoorProtection::get));
list.add(SettingDef.textList(backdoorAllowedTranslationPacks)
.visibleWhen(() -> backdoorProtection.get() && backdoorTranslationFilter.get()));
list.add(SettingDef.textList(backdoorAllowedKeybinds)
.visibleWhen(() -> backdoorProtection.get() && backdoorKeybindFilter.get()));
return list;
}
public List<SettingDef> getUtilitySettingDefs() {
List<SettingDef> list = new ArrayList<>();
list.add(SettingDef.mode(inventorySwapPolicy).common("inventory.swap_policy"));
list.add(SettingDef.mode(inventorySwapScope).common("inventory.search_scope"));
list.add(SettingDef.mode(inventorySwapVisibility).common("inventory.swap_visibility"));
list.add(SettingDef.bool(inventorySwapRestore).common("inventory.restore_item"));
list.add(SettingDef.bool(inventorySwapPreferHotbar).common("inventory.prefer_hotbar"));
list.add(SettingDef.number(inventorySwapLegitWaitTicks).common("inventory.legit_wait_ticks"));
list.add(SettingDef.number(inventorySwapStrictInventoryWaitTicks).common("inventory.strict_inventory_wait_ticks"));
list.add(SettingDef.number(inventorySwapStrictMovementLockTicks).common("inventory.strict_movement_lock_ticks"));
return list;
}
public boolean isNarratorDisabled() {
return disableNarrator.get();
}
public boolean isBackdoorProtectionEnabled() {
return backdoorProtection.get();
}
public boolean isBackdoorTranslationFilterEnabled() {
return backdoorProtection.get() && backdoorTranslationFilter.get();
}
public boolean isBackdoorKeybindFilterEnabled() {
return backdoorProtection.get() && backdoorKeybindFilter.get();
}
public boolean isBackdoorLocalHttpGuardEnabled() {
return backdoorProtection.get() && backdoorLocalHttpGuard.get();
}
public boolean isBackdoorPackCacheIsolationEnabled() {
return backdoorProtection.get() && backdoorPackCacheIsolation.get();
}
public boolean isBackdoorAllowLocalHttpWhenServerLocal() {
return backdoorAllowLocalHttpWhenServerLocal.get();
}
public Set<String> getBackdoorAllowedTranslationPacks() {
return new LinkedHashSet<>(backdoorAllowedTranslationPacks.get());
}
// ================= CONFIG =================
public Set<String> getBackdoorAllowedKeybinds() {
return new LinkedHashSet<>(backdoorAllowedKeybinds.get());
}
@Override
public List<ConfigValue<?>> getConfigValues() {
List<ConfigValue<?>> list = new ArrayList<>();
list.add(debug);
list.add(forcePvp);
list.add(menuBg);
list.add(menuClockShowSeconds);
list.add(menuBgUseTheme);
list.add(msaa3d);
list.add(clickGuiModulesHints);
list.add(clickGuiHudEditorHints);
list.add(inventorySwapPolicy);
list.add(inventorySwapScope);
list.add(inventorySwapVisibility);
list.add(inventorySwapRestore);
list.add(inventorySwapPreferHotbar);
list.add(inventorySwapLegitWaitTicks);
list.add(inventorySwapStrictInventoryWaitTicks);
list.add(inventorySwapStrictMovementLockTicks);
list.add(disableNarrator);
list.add(backdoorProtection);
list.add(backdoorTranslationFilter);
list.add(backdoorKeybindFilter);
list.add(backdoorLocalHttpGuard);
list.add(backdoorPackCacheIsolation);
list.add(backdoorAllowLocalHttpWhenServerLocal);
list.add(backdoorAllowedTranslationPacks);
list.add(backdoorAllowedKeybinds);
return list;
}
private void saveAndApplyInventorySwapSettings() {
applyInventorySwapSettings();
ConfigSerializer.requestSave(this);
}
private void applyInventorySwapSettings() {
InventorySwap swap = InventorySwap.INSTANCE;
swap.setDefaultPolicy(inventorySwapPolicy.get());
swap.setDefaultScope(inventorySwapScope.get());
swap.setDefaultVisibility(inventorySwapVisibility.get());
swap.setRestoreByDefault(inventorySwapRestore.get());
swap.setPreferHotbar(inventorySwapPreferHotbar.get());
swap.setLegitWaitTicks(inventorySwapLegitWaitTicks.get());
swap.setStrictInventoryWaitTicks(inventorySwapStrictInventoryWaitTicks.get());
swap.setStrictMovementLockTicks(inventorySwapStrictMovementLockTicks.get());
}
}

View file

@ -0,0 +1,371 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import dev.loki.lovisual.config.common.CommonSettingSchema;
import dev.loki.lovisual.config.values.*;
import dev.loki.lovisual.features.gui.clickgui.settings.TextListSetting;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/**
* GUI-neutral setting descriptor. UI layer can build actual widgets from these.
*/
public final class SettingDef {
private final Kind kind;
private final String id;
private final ConfigValue<?> value;
private final BindMode bindMode;
private final TextListSetting.PickerMode pickerMode;
private Supplier<Boolean> visibility;
private Supplier<String> unavailableReason;
private final List<String> commonI18nKeys = new ArrayList<>();
private boolean i18nNameEnabled = true;
private boolean i18nOptionsEnabled = true;
private SettingDef(Kind kind, String id, ConfigValue<?> value) {
this(kind, id, value, null, null);
}
private SettingDef(Kind kind, String id, ConfigValue<?> value, BindMode bindMode) {
this(kind, id, value, bindMode, null);
}
private SettingDef(Kind kind,
String id,
ConfigValue<?> value,
BindMode bindMode,
TextListSetting.PickerMode pickerMode) {
this.kind = kind;
this.id = id;
this.value = value;
this.bindMode = bindMode;
this.pickerMode = pickerMode;
}
public static SettingDef bool(String id, BooleanValue value) {
return new SettingDef(Kind.BOOLEAN, id, value);
}
public static SettingDef bool(BooleanValue value) {
return new SettingDef(Kind.BOOLEAN, value.getName(), value);
}
public static SettingDef number(String id, NumberValue<?> value) {
return new SettingDef(Kind.NUMBER, id, value);
}
public static SettingDef number(NumberValue<?> value) {
return new SettingDef(Kind.NUMBER, value.getName(), value);
}
public static SettingDef mode(String id, ModeValue value) {
return new SettingDef(Kind.MODE, id, value);
}
public static SettingDef mode(String id, EnumValue<?> value) {
return new SettingDef(Kind.MODE, id, value);
}
public static SettingDef mode(ModeValue value) {
return new SettingDef(Kind.MODE, value.getName(), value);
}
public static SettingDef mode(EnumValue<?> value) {
return new SettingDef(Kind.MODE, value.getName(), value);
}
public static SettingDef color(String id, RGBAColorValue value) {
return new SettingDef(Kind.COLOR, id, value);
}
public static SettingDef color(RGBAColorValue value) {
return new SettingDef(Kind.COLOR, value.getName(), value);
}
public static SettingDef colorNoAlpha(String id, RGBColorValue value) {
return new SettingDef(Kind.COLOR_NO_ALPHA, id, value);
}
public static SettingDef colorNoAlpha(RGBColorValue value) {
return new SettingDef(Kind.COLOR_NO_ALPHA, value.getName(), value);
}
public static SettingDef text(String id, StringValue value) {
return new SettingDef(Kind.TEXT, id, value);
}
public static SettingDef text(StringValue value) {
return new SettingDef(Kind.TEXT, value.getName(), value);
}
public static SettingDef textList(String id, SetValue value) {
return new SettingDef(Kind.TEXT_LIST, id, value);
}
public static SettingDef textList(String id,
SetValue value,
TextListSetting.PickerMode pickerMode) {
return new SettingDef(Kind.TEXT_LIST, id, value, null, pickerMode);
}
public static SettingDef textList(SetValue value) {
return new SettingDef(Kind.TEXT_LIST, value.getName(), value);
}
public static SettingDef textList(SetValue value,
TextListSetting.PickerMode pickerMode) {
return new SettingDef(Kind.TEXT_LIST, value.getName(), value, null, pickerMode);
}
public static SettingDef textList(String id, ItemIdSetValue value) {
return new SettingDef(Kind.TEXT_LIST, id, value);
}
public static SettingDef textList(String id,
ItemIdSetValue value,
TextListSetting.PickerMode pickerMode) {
return new SettingDef(Kind.TEXT_LIST, id, value, null, pickerMode);
}
public static SettingDef textList(ItemIdSetValue value) {
return new SettingDef(Kind.TEXT_LIST, value.getName(), value);
}
public static SettingDef textList(ItemIdSetValue value,
TextListSetting.PickerMode pickerMode) {
return new SettingDef(Kind.TEXT_LIST, value.getName(), value, null, pickerMode);
}
public static SettingDef cooldownRules(String id, ItemCooldownRulesValue value) {
return new SettingDef(Kind.COOLDOWN_RULES, id, value);
}
public static SettingDef cooldownRules(ItemCooldownRulesValue value) {
return new SettingDef(Kind.COOLDOWN_RULES, value.getName(), value);
}
public static SettingDef protocolHeuristics(String id, BooleanMapValue value) {
return new SettingDef(Kind.PROTOCOL_HEURISTICS, id, value);
}
public static SettingDef protocolHeuristics(BooleanMapValue value) {
return new SettingDef(Kind.PROTOCOL_HEURISTICS, value.getName(), value);
}
public static SettingDef group(String id, BooleanMapValue value) {
return new SettingDef(Kind.GROUP, id, value);
}
public static SettingDef group(BooleanMapValue value) {
return new SettingDef(Kind.GROUP, value.getName(), value);
}
public static SettingDef bind(String id, KeyBindValue value, BindMode mode) {
return new SettingDef(Kind.BIND, id, value, mode);
}
public static SettingDef bind(KeyBindValue value, BindMode mode) {
return new SettingDef(Kind.BIND, value.getName(), value, mode);
}
public static SettingDef bind(String id, KeyBindValue value) {
return new SettingDef(Kind.BIND, id, value, BindMode.PRESS);
}
public static SettingDef bind(KeyBindValue value) {
return new SettingDef(Kind.BIND, value.getName(), value, BindMode.PRESS);
}
public static void applyI18nAnnotations(Object owner, Iterable<SettingDef> defs) {
if (owner == null || defs == null) return;
Map<ConfigValue<?>, SettingDef> defsByValue = new IdentityHashMap<>();
for (SettingDef def : defs) {
if (def != null && def.value() != null) {
defsByValue.put(def.value(), def);
}
}
if (defsByValue.isEmpty()) return;
Class<?> type = owner.getClass();
while (type != null && type != Object.class) {
for (Field field : type.getDeclaredFields()) {
DisableSettingI18n annotation = field.getAnnotation(DisableSettingI18n.class);
if (annotation == null) continue;
if (!ConfigValue.class.isAssignableFrom(field.getType())) continue;
boolean accessible = field.canAccess(owner);
try {
if (!accessible) {
field.setAccessible(true);
}
if (field.get(owner) instanceof ConfigValue<?> value) {
SettingDef def = defsByValue.get(value);
if (def != null) {
def.disableI18n(annotation.name(), annotation.options());
}
}
} catch (Throwable ignored) {
} finally {
if (!accessible) {
try {
field.setAccessible(false);
} catch (Throwable ignored) {
}
}
}
}
type = type.getSuperclass();
}
}
public Kind kind() {
return kind;
}
public String id() {
return id;
}
public String getId() {
return id;
}
public ConfigValue<?> value() {
return value;
}
public BindMode bindMode() {
return bindMode;
}
public TextListSetting.PickerMode pickerMode() {
return pickerMode;
}
public Supplier<Boolean> visibility() {
return visibility;
}
public Supplier<String> unavailableReason() {
return unavailableReason;
}
public String commonI18nKey() {
return commonI18nKeys.isEmpty() ? null : commonI18nKeys.get(0);
}
public List<String> commonI18nKeys() {
return List.copyOf(commonI18nKeys);
}
public boolean i18nNameEnabled() {
return i18nNameEnabled;
}
public boolean i18nOptionsEnabled() {
return i18nOptionsEnabled;
}
public SettingDef visibleWhen(Supplier<Boolean> supplier) {
this.visibility = supplier;
return this;
}
public SettingDef unavailableWhen(Supplier<Boolean> supplier, String reason) {
return unavailableWhen(supplier, () -> reason);
}
public SettingDef unavailableWhen(Supplier<Boolean> supplier, Supplier<String> reason) {
if (supplier == null) {
this.unavailableReason = null;
return this;
}
this.unavailableReason = () -> {
boolean unavailable;
try {
unavailable = supplier.get();
} catch (Exception ignored) {
unavailable = false;
}
if (!unavailable) {
return null;
}
try {
return reason == null ? "" : reason.get();
} catch (Exception ignored) {
return "";
}
};
return this;
}
public SettingDef availableWhen(Supplier<Boolean> supplier, String reasonWhenUnavailable) {
return availableWhen(supplier, () -> reasonWhenUnavailable);
}
public SettingDef availableWhen(Supplier<Boolean> supplier, Supplier<String> reasonWhenUnavailable) {
if (supplier == null) {
this.unavailableReason = null;
return this;
}
return unavailableWhen(() -> !supplier.get(), reasonWhenUnavailable);
}
public SettingDef common(String key) {
addCommonKey(key);
return this;
}
public SettingDef common(CommonSettingSchema schema) {
if (schema != null) {
for (String key : schema.commonI18nKeys()) {
addCommonKey(key);
}
}
return this;
}
private void addCommonKey(String key) {
if (key == null) return;
String normalized = key.trim();
if (!normalized.isBlank() && !commonI18nKeys.contains(normalized)) {
commonI18nKeys.add(normalized);
}
}
public SettingDef disableI18n(boolean name, boolean options) {
if (name) {
this.i18nNameEnabled = false;
}
if (options) {
this.i18nOptionsEnabled = false;
}
return this;
}
public enum Kind {
BOOLEAN,
NUMBER,
MODE,
COLOR,
COLOR_NO_ALPHA,
TEXT,
TEXT_LIST,
COOLDOWN_RULES,
PROTOCOL_HEURISTICS,
GROUP,
BIND
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
import java.util.List;
/**
* Provides GUI-neutral setting definitions.
*/
public interface SettingDefProvider {
List<SettingDef> getSettingDefs();
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config;
/**
* Owner of GUI settings. Allows settings to save config and build i18n keys
* without tying them to Module.
*/
public interface SettingOwner {
String name();
void saveConfig();
default String getTranslationKeyPrefix() {
String name = name();
if (name == null || name.isBlank()) return null;
return "setting." + name;
}
}

View file

@ -0,0 +1,14 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common;
import java.util.Map;
public interface CommonBooleanGroupSchema extends CommonSettingSchema {
Map<String, Boolean> defaults();
}

View file

@ -0,0 +1,19 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common;
import java.util.List;
public interface CommonSettingSchema {
String commonI18nKey();
default List<String> commonI18nKeys() {
String key = commonI18nKey();
return key == null || key.isBlank() ? List.of() : List.of(key);
}
}

View file

@ -0,0 +1,200 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common;
import dev.loki.lovisual.config.common.impl.*;
public enum CommonSettingSchemas {
;
public static final TargetFilters TARGET_FILTERS = new TargetFilters();
public static final CombatPriority COMBAT_PRIORITY = new CombatPriority();
public static final RotationMovementCorrection ROTATION_MOVEMENT_CORRECTION = new RotationMovementCorrection();
public static final RotationResetTicks ROTATION_RESET_TICKS = new RotationResetTicks();
public static final RotationResetThreshold ROTATION_RESET_THRESHOLD = new RotationResetThreshold();
public static final RotationTiming ROTATION_TIMING = new RotationTiming();
public static final RotationMode ROTATION_MODE = new RotationMode();
public static final RotationThroughWalls ROTATION_THROUGH_WALLS = new RotationThroughWalls();
// Generic repeated combat/action labels.
public static final CommonSettingSchema PLACE = key("place");
public static final CommonSettingSchema EXPLODE = key("explode");
public static final CommonSettingSchema BREAK = key("break");
public static final CommonSettingSchema TIMING = key("timing");
public static final CommonSettingSchema CALC_DELAY = key("calc_delay");
public static final CommonSettingSchema LOW_PLACE_DELAY = key("low_place_delay");
public static final CommonSettingSchema LOW_EXPLODE_DELAY = key("low_explode_delay");
public static final CommonSettingSchema AIR_PLACE = key("air_place");
public static final CommonSettingSchema MIN_DAMAGE = key("min_damage");
public static final CommonSettingSchema FACEPLACE_HEALTH = key("faceplace_health");
public static final CommonSettingSchema MAX_SELF_DAMAGE = key("max_self_damage");
public static final CommonSettingSchema SELF_PREDICT_TICKS = key("self_predict_ticks");
public static final CommonSettingSchema UNSAFE_DIMENSION_ONLY = key("unsafe_dimension_only");
public static final CommonSettingSchema PAUSE_MINING = key("pause_mining");
public static final CommonSettingSchema PAUSE_EATING = key("pause_eating");
public static final CommonSettingSchema RENDER_SELF_DAMAGE = key("render_self_damage");
public static final CommonSettingSchema RENDER_DAMAGE = key("render_damage");
public static final CommonSettingSchema FILL_COLOR = key("fill_color");
public static final CommonSettingSchema LINE_COLOR = key("line_color");
public static final CommonSettingSchema LINE_WIDTH = key("line_width");
public static final CommonSettingSchema TEXT_COLOR = key("text_color");
public static final CommonSettingSchema SLIDE_DELAY = key("slide_delay");
public static final CommonSettingSchema FADE_TIME = key("fade_time");
public static final CommonSettingSchema MODE = key("mode");
// Sprint Reset
public static final CommonSettingSchema COMBAT_CRITICALS = key("combat.criticals");
public static final CommonSettingSchema COMBAT_SPRINT_RESET = key("combat.sprint_reset");
public static final CommonSettingSchema COMBAT_WHEN_SPRINTING = key("combat.when_sprinting");
public static final CommonSettingSchema COMBAT_STOP_SPRINTING = key("combat.stop_sprinting");
public static final CommonSettingSchema COMBAT_ATTACK_MODE = key("combat.attack_mode");
public static final CommonSettingSchema COMBAT_CPS_MIN = key("combat.cps_min");
public static final CommonSettingSchema COMBAT_CPS_MAX = key("combat.cps_max");
public static final CommonSettingSchema COMBAT_PROTOCOL = key("combat.protocol");
public static final CombatProtocolHeuristicSources COMBAT_PROTOCOL_HEURISTICS = new CombatProtocolHeuristicSources();
public static final CommonSettingSchema COMBAT_RANGE = key("combat.range", "target_range", "range");
public static final CommonSettingSchema COMBAT_REACH_MODE = key("combat.reach_mode");
public static final CommonSettingSchema COMBAT_RANGE_INCREMENT = key("combat.range_increment");
public static final CommonSettingSchema COMBAT_WALL_RANGE = key("combat.wall_range");
public static final CommonSettingSchema COMBAT_FOV = key("combat.fov", "target_fov", "fov");
public static final CommonSettingSchema COMBAT_CORRECTION_TYPE = key("combat.correction_type");
public static final CommonSettingSchema COMBAT_RAYCAST = key("combat.raycast");
public static final CommonSettingSchema COMBAT_BACKTRACK_TARGET_MODE = key("combat.backtrack.target_mode", "target_mode");
public static final CommonSettingSchema COMBAT_BACKTRACK_RANGE_MIN = key("combat.backtrack.range_min", "range_min");
public static final CommonSettingSchema COMBAT_BACKTRACK_RANGE_MAX = key("combat.backtrack.range_max", "range_max");
public static final CommonSettingSchema COMBAT_BACKTRACK_DELAY_MIN = key("combat.backtrack.delay_min", "delay_min");
public static final CommonSettingSchema COMBAT_BACKTRACK_DELAY_MAX = key("combat.backtrack.delay_max", "delay_max");
public static final CommonSettingSchema COMBAT_BACKTRACK_NEXT_DELAY_MIN = key("combat.backtrack.next_delay_min", "next_delay_min");
public static final CommonSettingSchema COMBAT_BACKTRACK_NEXT_DELAY_MAX = key("combat.backtrack.next_delay_max", "next_delay_max");
public static final CommonSettingSchema COMBAT_BACKTRACK_TRACKING_BUFFER = key("combat.backtrack.tracking_buffer", "tracking_buffer");
public static final CommonSettingSchema COMBAT_BACKTRACK_CHANCE = key("combat.backtrack.chance", "chance");
public static final CommonSettingSchema COMBAT_BACKTRACK_PAUSE_ON_HURT_TIME = key("combat.backtrack.pause_on_hurt_time", "pause_on_hurt_time");
public static final CommonSettingSchema COMBAT_BACKTRACK_HURT_TIME = key("combat.backtrack.hurt_time", "hurt_time");
public static final CommonSettingSchema COMBAT_BACKTRACK_LAST_ATTACK_TIME = key("combat.backtrack.last_attack_time", "last_attack_time");
public static final CommonSettingSchema COMBAT_BACKTRACK_RENDER = key("combat.backtrack.render", "render");
public static final CommonSettingSchema COMBAT_BACKTRACK_LINE_WIDTH = key("combat.backtrack.line_width", "line_width");
public static final CommonSettingSchema COMBAT_WEAPON = key("combat.weapon");
public static final CommonSettingSchema COMBAT_OBJECTIVE = key("combat.objective");
public static final CommonSettingSchema COMBAT_ON_ITEM_USE = key("combat.on_item_use");
public static final CommonSettingSchema COMBAT_CRYSTAL_DISTANCE = key("combat.crystal_distance");
public static final CommonSettingSchema COMBAT_BREAK_SHIELDS = key("combat.break_shields");
public static final CommonSettingSchema INVENTORY_SEARCH_SCOPE = key("inventory.search_scope", "swap_scope");
public static final CommonSettingSchema INVENTORY_SWAP_VISIBILITY = key("inventory.swap_visibility", "swap_visibility");
public static final CommonSettingSchema INVENTORY_RESTORE_ITEM = key("inventory.restore_item", "restore_item");
public static final CommonSettingSchema INVENTORY_PREFER_HOTBAR = key("inventory.prefer_hotbar", "prefer_hotbar");
public static final CommonSettingSchema INTERACTION_IGNORE_OPEN_INVENTORY = key("interaction.ignore_open_inventory", "ignore_open_inventory");
public static final CommonSettingSchema COMBAT_ONLY_PLAYERS = key("combat.only_players");
public static final CommonSettingSchema COMBAT_ONLY_BLOCKING = key("combat.only_blocking");
public static final CommonSettingSchema COMBAT_MIN_FALL_DISTANCE = key("combat.min_fall_distance", "min_fall_distance");
public static final CommonSettingSchema COMBAT_RESPECT_COOLDOWN = key("combat.respect_cooldown");
public static final CommonSettingSchema ITEMS_PROJECTILES = key("items.projectiles");
public static final CommonSettingSchema ITEMS_SAVE_UNENCHANTED = key("items.save_unenchanted");
//Placement
public static final CommonSettingSchema PLACEMENT_RANGE = key("placement.range", "place_range");
public static final CommonSettingSchema PLACEMENT_WALL_RANGE = key("placement.wall_range", "wall_range");
public static final CommonSettingSchema PLACEMENT_BREAK_RANGE = key("placement.break_range", "break_range");
public static final CommonSettingSchema PLACEMENT_BREAK_WALL_RANGE = key("placement.break_wall_range", "break_wall_range");
public static final CommonSettingSchema PLACEMENT_MODE = key("placement.mode", "placement_mode");
public static final CommonSettingSchema PLACEMENT_SPEED = key("placement.speed", "placement_speed");
public static final CommonSettingSchema PLACEMENT_DELAY = key("placement.delay", "place_delay");
public static final CommonSettingSchema PLACEMENT_BREAK_DELAY = key("placement.break_delay", "break_delay", "explode_delay");
public static final CommonSettingSchema PLACEMENT_PREDICTION = key("placement.prediction", "predict_ticks");
public static final CommonSettingSchema PLACEMENT_RENDER = key("placement.render", "render");
public static final CommonSettingSchema PLACEMENT_RENDER_MODE = key("placement.render_mode", "render_mode");
public static final CommonSettingSchema PLACEMENT_ROTATION_TIMING = key("placement.rotation_timing", "rotation.rotation_timing", "rotation_timing");
public static final CommonSettingSchema PLACEMENT_MOVEMENT_CORRECTION = key("placement.movement_correction", "rotation.movement_correction", "movement_correction");
public static final CommonSettingSchema PLACEMENT_ROTATION_RESET_TICKS = key("placement.rotation_reset_ticks", "rotation.rotation_reset_ticks", "rotation_reset_ticks");
public static final CommonSettingSchema PLACEMENT_ROTATION_RESET_THRESHOLD = key("placement.rotation_reset_threshold", "rotation.rotation_reset_threshold", "rotation_reset_threshold");
public static final CommonSettingSchema INVENTORY_SWAP_MODE = key("inventory.swap_mode", "swap_mode");
public static final CommonSettingSchema PLAYER_HEALTH_THRESHOLD = key("player.health_threshold", "pause_health", "health_threshold");
public static final CommonSettingSchema PLAYER_ELYTRA_HEALTH = key("player.elytra_health");
public static final CommonSettingSchema PLAYER_FALL_CHECK = key("player.fall_check");
public static final CommonSettingSchema PLAYER_USE_RELATIONS = key("player.use_relations");
public static final CommonSettingSchema TOTEM_POP_COUNTER = key("totem_pop.counter", "totem_pop_counter");
public static final CommonSettingSchema TOTEM_POP_RESET_SECONDS = key("totem_pop.reset_seconds", "totem_pop_reset_seconds");
public static final CommonSettingSchema PLAYER_FAKELAG_MODE = key("player.fakelag.mode");
public static final CommonSettingSchema PLAYER_FAKELAG_RANGE_MIN = key("player.fakelag.range_min", "min_range", "range_min");
public static final CommonSettingSchema PLAYER_FAKELAG_RANGE_MAX = key("player.fakelag.range_max", "max_range", "range_max");
public static final CommonSettingSchema PLAYER_FAKELAG_DELAY_MIN = key("player.fakelag.delay_min", "delay_min");
public static final CommonSettingSchema PLAYER_FAKELAG_DELAY_MAX = key("player.fakelag.delay_max", "delay_max");
public static final CommonSettingSchema PLAYER_FAKELAG_RECOIL_TIME = key("player.fakelag.recoil_time", "recoil_time");
public static final FakeLagFlushOn PLAYER_FAKELAG_FLUSH_ON = new FakeLagFlushOn();
// Elytra target / fireworks
public static final CommonSettingSchema ELYTRA_HITBOX_EXPAND = key("elytra.hitbox_expand");
public static final CommonSettingSchema ELYTRA_EXPAND_WHEN_READY = key("elytra.expand_when_ready");
public static final CommonSettingSchema ELYTRA_FIREWORK_SPEED = key("elytra.firework_speed", "firework_speed");
public static final CommonSettingSchema ELYTRA_TARGET_MUST_FLY = key("elytra.target_must_fly");
public static final CommonSettingSchema ELYTRA_PREPARE_ROTATIONS = key("elytra.prepare_rotations", "prepare_rotations");
public static final CommonSettingSchema ELYTRA_VELOCITY_TUNE = key("elytra.velocity_tune");
public static final CommonSettingSchema ELYTRA_CUSTOM_VELOCITY_TABLE = key("elytra.custom_velocity_table");
public static final CommonSettingSchema ELYTRA_FIREWORK_SILENT_SWAP = key("elytra.firework_silent_swap", "silent_swap", "firework_silent_swap");
// ESP / world scan
public static final CommonSettingSchema ESP_SCAN_MODE = key("esp.scan_mode");
public static final CommonSettingSchema ESP_LIMIT_DISTANCE = key("esp.limit_distance");
public static final CommonSettingSchema ESP_MAX_DISTANCE = key("esp.max_distance", "max_distance");
public static final CommonSettingSchema ESP_SCAN_DELAY = key("esp.scan_delay", "scan_delay");
public static final CommonSettingSchema ESP_MAX_TARGETS = key("esp.max_targets", "max_targets");
public static final CommonSettingSchema ESP_USE_TRACERS = key("esp.use_tracers");
public static final CommonSettingSchema ESP_LINE_WIDTH = key("esp.line_width", "line_width");
public static final CommonSettingSchema ESP_OUTLINE_SHAPE = key("esp.outline_shape", "outline_shape");
public static final CommonSettingSchema ESP_BOX_MODE = key("esp.box_mode");
public static final CommonSettingSchema ESP_HEALTH_BAR = key("esp.health_bar");
public static final CommonSettingSchema ESP_HEALTH_BAR_GRADIENT = key("esp.health_bar_gradient");
public static final CommonSettingSchema ESP_HEALTH_BAR_DISTANCE = key("esp.health_bar_distance", "health_bar_distance");
// AngleSmooth generic
public static final CommonSettingSchema ANGLESMOOTH_HORIZONTAL_MIN = key("rotation.anglesmooth.horizontal_min");
public static final CommonSettingSchema ANGLESMOOTH_HORIZONTAL_MAX = key("rotation.anglesmooth.horizontal_max");
public static final CommonSettingSchema ANGLESMOOTH_VERTICAL_MIN = key("rotation.anglesmooth.vertical_min");
public static final CommonSettingSchema ANGLESMOOTH_VERTICAL_MAX = key("rotation.anglesmooth.vertical_max");
// Sigmoid
public static final CommonSettingSchema ANGLESMOOTH_STEEPNESS = key("rotation.anglesmooth.steepness");
public static final CommonSettingSchema ANGLESMOOTH_MIDPOINT = key("rotation.anglesmooth.midpoint");
// Smart
public static final CommonSettingSchema ANGLESMOOTH_YAW_MIN = key("rotation.anglesmooth.yaw_min");
public static final CommonSettingSchema ANGLESMOOTH_YAW_MAX = key("rotation.anglesmooth.yaw_max");
public static final CommonSettingSchema ANGLESMOOTH_PITCH_MIN = key("rotation.anglesmooth.pitch_min");
public static final CommonSettingSchema ANGLESMOOTH_PITCH_MAX = key("rotation.anglesmooth.pitch_max");
public static final CommonSettingSchema ANGLESMOOTH_SNAP_THRESHOLD = key("rotation.anglesmooth.snap_threshold");
public static final CommonSettingSchema ANGLESMOOTH_JITTER_YAW = key("rotation.anglesmooth.jitter_yaw");
public static final CommonSettingSchema ANGLESMOOTH_JITTER_PITCH = key("rotation.anglesmooth.jitter_pitch");
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_ENABLED = key("rotation.anglesmooth.decelerate_enabled");
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_ANGLE = key("rotation.anglesmooth.decelerate_angle");
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_MIN_FACTOR = key("rotation.anglesmooth.decelerate_min_factor");
// Lazy aim
public static final CommonSettingSchema LAZY_AIM_ENABLED = key("rotation.lazy_aim.enabled");
public static final CommonSettingSchema LAZY_AIM_THRESHOLD = key("rotation.lazy_aim.threshold");
public static final CommonSettingSchema LAZY_AIM_FOLLOW_FACTOR = key("rotation.lazy_aim.follow_factor");
// Shake aim
public static final CommonSettingSchema SHAKE_AIM_ENABLED = key("rotation.shake_aim.enabled");
public static final CommonSettingSchema SHAKE_AIM_YAW_AMPLITUDE = key("rotation.shake_aim.yaw_amplitude");
public static final CommonSettingSchema SHAKE_AIM_PITCH_AMPLITUDE = key("rotation.shake_aim.pitch_amplitude");
public static final CommonSettingSchema SHAKE_AIM_SPEED = key("rotation.shake_aim.speed");
// Fail
public static final CommonSettingSchema FAIL_ENABLED = key("rotation.fail.enabled");
public static final CommonSettingSchema FAIL_RATE = key("rotation.fail.rate");
public static final CommonSettingSchema FAIL_FACTOR = key("rotation.fail.factor");
public static final CommonSettingSchema FAIL_STRENGTH_HORIZONTAL_MIN = key("rotation.fail.strength_horizontal_min");
public static final CommonSettingSchema FAIL_STRENGTH_HORIZONTAL_MAX = key("rotation.fail.strength_horizontal_max");
public static final CommonSettingSchema FAIL_STRENGTH_VERTICAL_MIN = key("rotation.fail.strength_vertical_min");
public static final CommonSettingSchema FAIL_STRENGTH_VERTICAL_MAX = key("rotation.fail.strength_vertical_max");
public static final CommonSettingSchema FAIL_TRANSITION_MIN = key("rotation.fail.transition_min");
public static final CommonSettingSchema FAIL_TRANSITION_MAX = key("rotation.fail.transition_max");
public static final CommonSettingSchema ANTICHEAT_MODE = key("anticheat.mode");
public static final CommonSettingSchema RENDER_COLOR_MODE = key("render.color_mode", "color_mode");
public static final CommonSettingSchema RENDER_COLOR_SPEED = key("render.color_speed", "color_speed");
public static final CommonSettingSchema RENDER_PRIMARY_COLOR = key("render.primary_color", "primary_color");
public static final CommonSettingSchema RENDER_SECONDARY_COLOR = key("render.secondary_color", "secondary_color");
public static final CommonSettingSchema RENDER_DEPTH_TEST = key("render.depth_test", "depth_test");
public static final CommonSettingSchema RENDER_SCALE = key("render.scale", "scale");
private static CommonSettingSchema key(String key, String... aliases) {
return new CommonKey(key, aliases);
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class CombatPriority implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "combat.priority";
}
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
import dev.loki.lovisual.util.combat.protocol.CombatProtocolHeuristics;
import java.util.Map;
public final class CombatProtocolHeuristicSources implements CommonBooleanGroupSchema {
@Override
public String commonI18nKey() {
return "combat.protocol_heuristics";
}
@Override
public Map<String, Boolean> defaults() {
return CombatProtocolHeuristics.defaultSourceToggles();
}
}

View file

@ -0,0 +1,46 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
import java.util.ArrayList;
import java.util.List;
public final class CommonKey implements CommonSettingSchema {
private final List<String> keys;
public CommonKey(String key, String... aliases) {
ArrayList<String> out = new ArrayList<>();
add(out, key);
if (aliases != null) {
for (String alias : aliases) {
add(out, alias);
}
}
this.keys = List.copyOf(out);
}
@Override
public String commonI18nKey() {
return keys.isEmpty() ? null : keys.get(0);
}
@Override
public List<String> commonI18nKeys() {
return keys;
}
private static void add(ArrayList<String> out, String key) {
if (key == null) return;
String normalized = key.trim();
if (!normalized.isBlank() && !out.contains(normalized)) {
out.add(normalized);
}
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
import java.util.LinkedHashMap;
import java.util.Map;
public final class FakeLagFlushOn implements CommonBooleanGroupSchema {
public static final String ENTITY_INTERACT = "entity_interact";
public static final String BLOCK_INTERACT = "block_interact";
public static final String ACTION = "action";
@Override
public String commonI18nKey() {
return "fakelag.flush_on";
}
@Override
public Map<String, Boolean> defaults() {
Map<String, Boolean> defaults = new LinkedHashMap<>();
defaults.put(ENTITY_INTERACT, false);
defaults.put(BLOCK_INTERACT, false);
defaults.put(ACTION, false);
return defaults;
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationMode implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.rotation_mode";
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationMovementCorrection implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.movement_correction";
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationResetThreshold implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.rotation_reset_threshold";
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationResetTicks implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.rotation_reset_ticks";
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationThroughWalls implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.rotation_through_walls";
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonSettingSchema;
public final class RotationTiming implements CommonSettingSchema {
@Override
public String commonI18nKey() {
return "rotation.rotation_timing";
}
}

View file

@ -0,0 +1,42 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.common.impl;
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
import java.util.LinkedHashMap;
import java.util.Map;
public final class TargetFilters implements CommonBooleanGroupSchema {
public static final String PLAYERS_ONLY = "players_only";
public static final String IGNORE_FRIENDS = "ignore_friends";
public static final String IGNORE_STAFF = "ignore_staff";
public static final String IGNORE_ENEMIES = "ignore_enemies";
public static final String IGNORE_NAKED = "ignore_naked";
public static final String IGNORE_ENTITIES = "ignore_entities";
public static final String VISIBLE_ONLY = "visible_only";
@Override
public String commonI18nKey() {
return "target";
}
@Override
public Map<String, Boolean> defaults() {
Map<String, Boolean> defaults = new LinkedHashMap<>();
defaults.put(PLAYERS_ONLY, true);
defaults.put(IGNORE_FRIENDS, true);
defaults.put(IGNORE_STAFF, true);
defaults.put(IGNORE_ENEMIES, false);
defaults.put(IGNORE_NAKED, false);
defaults.put(IGNORE_ENTITIES, false);
defaults.put(VISIBLE_ONLY, false);
return defaults;
}
}

View file

@ -0,0 +1,157 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import dev.loki.lovisual.features.theme.Theme;
import dev.loki.lovisual.config.ConfigObject;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.addon.AddonManager;
import dev.loki.lovisual.features.gui.hud.BaseHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.theme.Themes;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.util.logging.DebugLog;
import java.util.HashMap;
import java.util.Map;
public final class ConfigProfileApplier {
public ApplyResult apply(ConfigProfileSnapshot snapshot) {
if (snapshot == null) return new ApplyResult(0, 0, 0);
ApplyCounter counter = new ApplyCounter();
if (snapshot.meta().type() == ConfigProfileType.MODULES) {
ModuleManager.runSilentConfigApply(() -> applyEntries(snapshot, counter));
} else {
applyEntries(snapshot, counter);
}
return new ApplyResult(counter.appliedOwners, counter.missingOwners, counter.missingValues);
}
private void applyEntries(ConfigProfileSnapshot snapshot, ApplyCounter counter) {
if (snapshot.meta().type() == ConfigProfileType.THEMES) {
applyThemeEntries(snapshot, counter);
return;
}
for (ConfigProfileEntry entry : snapshot.entries()) {
ConfigObject owner = resolveOwner(entry.ownerId());
if (owner == null) {
counter.missingOwners++;
DebugLog.config("Config profile missing owner: %s", entry.ownerId());
continue;
}
applyValues(owner, entry, counter);
counter.appliedOwners++;
afterOwnerApplied(owner);
}
}
private void applyThemeEntries(ConfigProfileSnapshot snapshot, ApplyCounter counter) {
String currentId = null;
for (ConfigProfileEntry entry : snapshot.entries()) {
String ownerId = entry.ownerId();
if (ownerId == null) {
counter.missingOwners++;
continue;
}
if (ownerId.equals("theme-state:current")) {
Object current = entry.values().get("current");
if (current instanceof CharSequence s && !s.toString().isBlank()) {
currentId = s.toString();
}
counter.appliedOwners++;
continue;
}
if (!ownerId.startsWith("theme:")) {
counter.missingOwners++;
continue;
}
String id = ownerId.substring("theme:".length());
try {
Themes.importProfileValues(id, entry.displayName(), entry.values());
counter.appliedOwners++;
} catch (Throwable t) {
counter.missingValues++;
DebugLog.error("Failed to apply theme profile entry %s", t, ownerId);
}
}
if (currentId != null) {
String selectedId = currentId.toLowerCase(java.util.Locale.ROOT);
if (Theme.themes().stream().anyMatch(theme -> theme.getId().equals(selectedId))) {
Theme.setTheme(selectedId);
}
}
}
private void applyValues(ConfigObject owner, ConfigProfileEntry entry, ApplyCounter counter) {
Map<String, ConfigValue<?>> byName = new HashMap<>();
for (ConfigValue<?> value : owner.getConfigValues()) {
if (value != null && value.getName() != null) byName.put(value.getName(), value);
}
for (Map.Entry<String, Object> saved : entry.values().entrySet()) {
ConfigValue<?> value = byName.get(saved.getKey());
if (value == null) {
counter.missingValues++;
continue;
}
try {
value.fromJson(saved.getValue());
} catch (Throwable t) {
counter.missingValues++;
DebugLog.error("Failed to apply profile value %s.%s", t, entry.ownerId(), saved.getKey());
}
}
}
private ConfigObject resolveOwner(String ownerId) {
if (ownerId == null) return null;
if (ownerId.startsWith("addon:")) {
return resolveOwner(stripAddonPrefix(ownerId));
}
if (ownerId.startsWith("module:")) return ModuleManager.get(ownerId.substring("module:".length()));
if (ownerId.startsWith("hud.draggable:")) {
return DraggableHudElementRegistry.getById(ownerId.substring("hud.draggable:".length()));
}
if (ownerId.startsWith("hud.static:")) {
return StaticHudElementRegistry.getById(ownerId.substring("hud.static:".length()));
}
return null;
}
private String stripAddonPrefix(String ownerId) {
String addonId = AddonManager.addonIdFromProfileOwner(ownerId);
if (addonId == null) return "";
String prefix = "addon:" + addonId + ":";
if (!ownerId.startsWith(prefix)) return "";
return ownerId.substring(prefix.length());
}
private void afterOwnerApplied(ConfigObject owner) {
if (owner instanceof Module module) {
module.applyConfiguredEnabledState();
module.syncSettingsAfterLoad();
module.saveConfig();
return;
}
if (owner instanceof BaseHudElement hud) {
hud.saveConfig();
return;
}
}
private static final class ApplyCounter {
int appliedOwners;
int missingOwners;
int missingValues;
}
public record ApplyResult(int appliedOwners, int missingOwners, int missingValues) {
}
}

View file

@ -0,0 +1,152 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public final class ConfigProfileBinaryCodec {
public static final int VERSION = 1;
static final int MAGIC = 0x43424346; // CBCF
private static final int FLAG_COMPRESSED = 1;
public ConfigProfileBinaryCodec() {
}
public byte[] write(ConfigProfileSnapshot snapshot) throws IOException {
if (snapshot == null) throw new IllegalArgumentException("snapshot is null");
ByteArrayOutputStream payloadRaw = new ByteArrayOutputStream();
try (DataOutputStream payload = new DataOutputStream(payloadRaw)) {
writePayload(payload, snapshot.entries());
}
byte[] payloadBytes = compress(payloadRaw.toByteArray());
CRC32 crc = new CRC32();
crc.update(payloadBytes);
ByteArrayOutputStream fileRaw = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(fileRaw)) {
ConfigProfileMeta meta = snapshot.meta();
out.writeInt(MAGIC);
out.writeByte(VERSION);
out.writeByte(meta.type().wireId());
out.writeShort(FLAG_COMPRESSED);
out.writeLong(meta.createdAt());
out.writeLong(meta.updatedAt());
ConfigProfileValueCodec.writeString(out, meta.author());
ConfigProfileValueCodec.writeString(out, meta.name());
ConfigProfileValueCodec.writeString(out, meta.getId());
ConfigProfileValueCodec.writeVarInt(out, payloadBytes.length);
out.write(payloadBytes);
out.writeInt((int) crc.getValue());
}
return fileRaw.toByteArray();
}
public ConfigProfileMeta readMeta(byte[] bytes) throws IOException {
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
Header header = readHeader(in);
return header.meta();
}
}
public ConfigProfileSnapshot read(byte[] bytes) throws IOException {
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
Header header = readHeader(in);
byte[] payload = new byte[header.payloadLength()];
in.readFully(payload);
int expectedCrc = in.readInt();
CRC32 crc = new CRC32();
crc.update(payload);
if ((int) crc.getValue() != expectedCrc) {
throw new IOException("Config profile checksum mismatch: " + header.meta().name());
}
byte[] rawPayload = (header.flags() & FLAG_COMPRESSED) != 0 ? decompress(payload) : payload;
List<ConfigProfileEntry> entries;
try (DataInputStream payloadIn = new DataInputStream(new ByteArrayInputStream(rawPayload))) {
entries = readPayload(payloadIn);
}
return new ConfigProfileSnapshot(header.meta(), entries);
}
}
private Header readHeader(DataInputStream in) throws IOException {
int magic = in.readInt();
if (magic != MAGIC) throw new IOException("Invalid profile magic");
int version = in.readUnsignedByte();
if (version != VERSION) throw new IOException("Unsupported profile version: " + version);
ConfigProfileType type = ConfigProfileType.fromWireId(in.readUnsignedByte());
int flags = in.readUnsignedShort();
long createdAt = in.readLong();
long updatedAt = in.readLong();
String author = ConfigProfileValueCodec.readString(in);
String name = ConfigProfileValueCodec.readString(in);
String id = ConfigProfileValueCodec.readString(in);
int payloadLength = ConfigProfileValueCodec.readVarInt(in);
if (payloadLength < 0) throw new IOException("Negative payload length");
ConfigProfileMeta meta = new ConfigProfileMeta(id, name, type, author, createdAt, updatedAt, version);
return new Header(meta, flags, payloadLength);
}
private void writePayload(DataOutputStream out, List<ConfigProfileEntry> entries) throws IOException {
ConfigProfileValueCodec.writeVarInt(out, entries.size());
for (ConfigProfileEntry entry : entries) {
ConfigProfileValueCodec.writeString(out, entry.ownerId());
ConfigProfileValueCodec.writeString(out, entry.displayName());
ConfigProfileValueCodec.writeVarInt(out, entry.values().size());
for (Map.Entry<String, Object> value : entry.values().entrySet()) {
ConfigProfileValueCodec.writeString(out, value.getKey());
ConfigProfileValueCodec.writeValue(out, value.getValue());
}
}
}
private List<ConfigProfileEntry> readPayload(DataInputStream in) throws IOException {
int entryCount = ConfigProfileValueCodec.readVarInt(in);
List<ConfigProfileEntry> entries = new ArrayList<>(Math.max(0, entryCount));
for (int i = 0; i < entryCount; i++) {
String ownerId = ConfigProfileValueCodec.readString(in);
String displayName = ConfigProfileValueCodec.readString(in);
int valueCount = ConfigProfileValueCodec.readVarInt(in);
java.util.Map<String, Object> values = new java.util.LinkedHashMap<>();
for (int j = 0; j < valueCount; j++) {
values.put(ConfigProfileValueCodec.readString(in), ConfigProfileValueCodec.readValue(in));
}
entries.add(new ConfigProfileEntry(ownerId, displayName, values));
}
return entries;
}
private byte[] compress(byte[] bytes) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.BEST_SPEED);
try (DeflaterOutputStream zip = new DeflaterOutputStream(out, deflater)) {
zip.write(bytes);
} finally {
deflater.end();
}
return out.toByteArray();
}
private byte[] decompress(byte[] bytes) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (InflaterInputStream zip = new InflaterInputStream(new ByteArrayInputStream(bytes))) {
zip.transferTo(out);
}
return out.toByteArray();
}
private record Header(ConfigProfileMeta meta, int flags, int payloadLength) {
}
}

View file

@ -0,0 +1,106 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import dev.loki.lovisual.features.theme.Theme;
import net.minecraft.client.Minecraft;
import dev.loki.lovisual.config.ConfigObject;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.addon.AddonManager;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.theme.Themes;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleManager;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class ConfigProfileCollector {
public ConfigProfileSnapshot collect(ConfigProfileType type, String name) {
long now = System.currentTimeMillis();
String safeName = (name == null || name.isBlank()) ? defaultName(type) : name.trim();
String id = ConfigProfileStorage.sanitizeFileName(safeName);
ConfigProfileMeta meta = new ConfigProfileMeta(
id,
safeName,
type,
currentAuthorName(),
now,
now,
ConfigProfileBinaryCodec.VERSION
);
return new ConfigProfileSnapshot(meta, collectEntries(type));
}
public ConfigProfileSnapshot collectWithMeta(ConfigProfileMeta meta) {
if (meta == null) throw new IllegalArgumentException("profile meta is null");
return new ConfigProfileSnapshot(meta, collectEntries(meta.type()));
}
public List<ConfigProfileEntry> collectEntries(ConfigProfileType type) {
List<ConfigProfileEntry> entries = new ArrayList<>();
if (type == ConfigProfileType.HUD) {
for (DraggableHudElement widget : DraggableHudElementRegistry.getWidgets()) {
String ownerId = AddonManager.draggableHudProfileOwnerId(widget.getId());
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, widget.getTitle()), widget));
}
for (AbstractHudElement element : StaticHudElementRegistry.getAll()) {
String ownerId = AddonManager.staticHudProfileOwnerId(element.getId());
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, element.getTitle()), element));
}
} else if (type == ConfigProfileType.THEMES) {
Map<String, Object> state = new LinkedHashMap<>();
state.put("current", Theme.currentId());
entries.add(new ConfigProfileEntry("theme-state:current", "Current Theme", state));
for (Themes.ThemeEntry theme : Theme.customThemes()) {
entries.add(new ConfigProfileEntry("theme:" + theme.getId(), theme.name(), Themes.toProfileValues(theme)));
}
} else {
for (Module module : ModuleManager.getModules()) {
String ownerId = AddonManager.moduleProfileOwnerId(module.name());
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, module.getDisplayName()), module));
}
}
return entries;
}
private ConfigProfileEntry entry(String ownerId, String displayName, ConfigObject owner) {
Map<String, Object> values = new LinkedHashMap<>();
if (owner != null) {
for (ConfigValue<?> value : owner.getConfigValues()) {
if (value != null && value.getName() != null) {
values.put(value.getName(), value.toJson());
}
}
}
return new ConfigProfileEntry(ownerId, displayName, values);
}
private String currentAuthorName() {
try {
Minecraft mc = Minecraft.getInstance();
if (mc != null && mc.getUser() != null) {
String username = mc.getUser().getName();
if (username != null && !username.isBlank()) return username;
}
} catch (Throwable ignored) {
}
// TODO: use Discord RPC nickname/avatar when Discord integration is ready.
return "Unknown";
}
private String defaultName(ConfigProfileType type) {
return type == ConfigProfileType.HUD ? "Hud Config" : type == ConfigProfileType.THEMES ? "Themes Config" : "Modules Config";
}
}

View file

@ -0,0 +1,37 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public enum ConfigProfileDateFormatter {
;
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("dd.MM.yyyy");
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm");
public static String created(ConfigProfileMeta meta) {
return DATE.format(toDate(meta.createdAt()));
}
public static String updated(ConfigProfileMeta meta) {
LocalDate created = toDate(meta.createdAt());
LocalDate updated = toDate(meta.updatedAt());
String text = DATE.format(updated);
if (created.equals(updated)) {
text += " (" + TIME.format(Instant.ofEpochMilli(meta.updatedAt()).atZone(ZoneId.systemDefault())) + ")";
}
return text;
}
private static LocalDate toDate(long epochMillis) {
return Instant.ofEpochMilli(epochMillis).atZone(ZoneId.systemDefault()).toLocalDate();
}
}

View file

@ -0,0 +1,57 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public record ConfigProfileDiff(
ConfigProfileType type,
List<Entry> entries
) {
public ConfigProfileDiff {
if (type == null) type = ConfigProfileType.MODULES;
List<Entry> copy = new ArrayList<>();
if (entries != null) copy.addAll(entries);
entries = Collections.unmodifiableList(copy);
}
public boolean isEmpty() {
return entries.isEmpty();
}
public int valueChangeCount() {
int count = 0;
for (Entry entry : entries) count += entry.values().size();
return count;
}
public enum Kind {
ADDED,
REMOVED,
CHANGED
}
public record Entry(String ownerId, String displayName, List<Value> values) {
public Entry {
if (ownerId == null) ownerId = "";
if (displayName == null || displayName.isBlank()) displayName = ownerId;
List<Value> copy = new ArrayList<>();
if (values != null) copy.addAll(values);
values = Collections.unmodifiableList(copy);
}
}
public record Value(String key, Object currentValue, Object selectedValue, Kind kind) {
public Value {
if (key == null) key = "";
if (kind == null) kind = Kind.CHANGED;
}
}
}

View file

@ -0,0 +1,64 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.util.*;
public final class ConfigProfileDiffEngine {
public ConfigProfileDiff compare(ConfigProfileSnapshot current, ConfigProfileSnapshot selected) {
if (current == null || selected == null) {
return new ConfigProfileDiff(ConfigProfileType.MODULES, List.of());
}
ConfigProfileType type = selected.meta().type();
Map<String, ConfigProfileEntry> currentMap = mapByOwner(current);
Map<String, ConfigProfileEntry> selectedMap = mapByOwner(selected);
Set<String> owners = new LinkedHashSet<>();
owners.addAll(currentMap.keySet());
owners.addAll(selectedMap.keySet());
List<ConfigProfileDiff.Entry> entries = new ArrayList<>();
for (String ownerId : owners) {
ConfigProfileEntry c = currentMap.get(ownerId);
ConfigProfileEntry s = selectedMap.get(ownerId);
String displayName = s != null ? s.displayName() : c != null ? c.displayName() : ownerId;
Map<String, Object> cv = c != null ? c.values() : Map.of();
Map<String, Object> sv = s != null ? s.values() : Map.of();
Set<String> keys = new LinkedHashSet<>();
keys.addAll(cv.keySet());
keys.addAll(sv.keySet());
List<ConfigProfileDiff.Value> values = new ArrayList<>();
for (String key : keys) {
boolean hasCurrent = cv.containsKey(key);
boolean hasSelected = sv.containsKey(key);
Object currentValue = cv.get(key);
Object selectedValue = sv.get(key);
if (hasCurrent && hasSelected && Objects.equals(currentValue, selectedValue)) continue;
ConfigProfileDiff.Kind kind;
if (!hasCurrent) kind = ConfigProfileDiff.Kind.ADDED;
else if (!hasSelected) kind = ConfigProfileDiff.Kind.REMOVED;
else kind = ConfigProfileDiff.Kind.CHANGED;
values.add(new ConfigProfileDiff.Value(key, currentValue, selectedValue, kind));
}
if (!values.isEmpty()) {
entries.add(new ConfigProfileDiff.Entry(ownerId, displayName, values));
}
}
return new ConfigProfileDiff(type, entries);
}
private Map<String, ConfigProfileEntry> mapByOwner(ConfigProfileSnapshot snapshot) {
Map<String, ConfigProfileEntry> map = new LinkedHashMap<>();
for (ConfigProfileEntry entry : snapshot.entries()) {
map.put(entry.ownerId(), entry);
}
return map;
}
}

View file

@ -0,0 +1,26 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public record ConfigProfileEntry(
String ownerId,
String displayName,
Map<String, Object> values
) {
public ConfigProfileEntry {
if (ownerId == null) ownerId = "";
if (displayName == null || displayName.isBlank()) displayName = ownerId;
Map<String, Object> copy = new LinkedHashMap<>();
if (values != null) copy.putAll(values);
values = Collections.unmodifiableMap(copy);
}
}

View file

@ -0,0 +1,39 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
public record ConfigProfileMeta(
String id,
String name,
ConfigProfileType type,
String author,
long createdAt,
long updatedAt,
int version
) {
public ConfigProfileMeta {
if (id == null || id.isBlank()) id = ConfigProfileStorage.sanitizeFileName(name);
if (name == null || name.isBlank()) name = id;
if (type == null) type = ConfigProfileType.MODULES;
if (author == null || author.isBlank()) author = "Unknown";
if (version <= 0) version = ConfigProfileBinaryCodec.VERSION;
}
public ConfigProfileMeta withUpdatedAt(long timestamp) {
return new ConfigProfileMeta(id, name, type, author, createdAt, timestamp, version);
}
public String getId() {
return id;
}
public ConfigProfileMeta withName(String nextName, long timestamp) {
String nextId = ConfigProfileStorage.sanitizeFileName(nextName);
return new ConfigProfileMeta(nextId, nextName, type, author, createdAt, timestamp, version);
}
}

View file

@ -0,0 +1,101 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
public final class ConfigProfileService {
public static final ConfigProfileService INSTANCE = new ConfigProfileService();
private final ConfigProfileStorage storage = new ConfigProfileStorage();
private final ConfigProfileCollector collector = new ConfigProfileCollector();
private final ConfigProfileApplier applier = new ConfigProfileApplier();
private final ConfigProfileDiffEngine diffEngine = new ConfigProfileDiffEngine();
private ConfigProfileService() {
}
public ConfigProfileStorage storage() {
return storage;
}
public List<ConfigProfileMeta> list(ConfigProfileType type) {
return storage.list(type);
}
public ConfigProfileSnapshot saveCurrent(ConfigProfileType type, String name) throws IOException {
ConfigProfileMeta old = find(type, name);
ConfigProfileSnapshot snapshot = collector.collect(type, name);
if (old != null) {
ConfigProfileMeta meta = new ConfigProfileMeta(
old.getId(),
old.name(),
old.type(),
old.author(),
old.createdAt(),
System.currentTimeMillis(),
ConfigProfileBinaryCodec.VERSION
);
snapshot = collector.collectWithMeta(meta);
}
storage.save(snapshot);
return snapshot;
}
public ConfigProfileSnapshot overwriteCurrent(ConfigProfileMeta target) throws IOException {
if (target == null) throw new IllegalArgumentException("profile meta is null");
ConfigProfileMeta meta = target.withUpdatedAt(System.currentTimeMillis());
ConfigProfileSnapshot snapshot = collector.collectWithMeta(meta);
storage.save(snapshot);
return snapshot;
}
public ConfigProfileSnapshot read(ConfigProfileType type, String idOrName) throws IOException {
return storage.read(type, idOrName);
}
public ConfigProfileApplier.ApplyResult apply(ConfigProfileType type, String idOrName) throws IOException {
return applier.apply(storage.read(type, idOrName));
}
public ConfigProfileDiff diffWithCurrent(ConfigProfileType type, String idOrName) throws IOException {
ConfigProfileSnapshot selected = storage.read(type, idOrName);
ConfigProfileSnapshot current = collector.collectWithMeta(new ConfigProfileMeta(
"__current__",
"Current",
type,
"Runtime",
System.currentTimeMillis(),
System.currentTimeMillis(),
ConfigProfileBinaryCodec.VERSION
));
return diffEngine.compare(current, selected);
}
public ConfigProfileSnapshot rename(ConfigProfileType type, String idOrName, String newName) throws IOException {
return storage.rename(type, idOrName, newName);
}
public boolean delete(ConfigProfileType type, String idOrName) throws IOException {
return storage.delete(type, idOrName);
}
public ConfigProfileStorage.ImportResult importProfileFile(Path source, boolean moveSource) throws IOException {
return storage.importProfileFile(source, moveSource);
}
private ConfigProfileMeta find(ConfigProfileType type, String name) {
String id = ConfigProfileStorage.sanitizeFileName(name);
for (ConfigProfileMeta meta : storage.list(type)) {
if (meta.getId().equals(id)) return meta;
}
return null;
}
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public record ConfigProfileSnapshot(
ConfigProfileMeta meta,
List<ConfigProfileEntry> entries
) {
public ConfigProfileSnapshot {
if (meta == null) throw new IllegalArgumentException("profile meta is null");
List<ConfigProfileEntry> copy = new ArrayList<>();
if (entries != null) copy.addAll(entries);
entries = Collections.unmodifiableList(copy);
}
}

View file

@ -0,0 +1,179 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import dev.loki.lovisual.config.ConfigPaths;
import dev.loki.lovisual.util.logging.DebugLog;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public final class ConfigProfileStorage {
public static final String EXTENSION = ".cbcfg";
private static final Path ROOT = ConfigPaths.profilesRoot();
private final ConfigProfileBinaryCodec codec = new ConfigProfileBinaryCodec();
public static String sanitizeFileName(String name) {
if (name == null) return "config";
String base = name.trim().toLowerCase(Locale.ROOT);
if (base.endsWith(EXTENSION)) base = base.substring(0, base.length() - EXTENSION.length());
if (base.isEmpty()) return "config";
StringBuilder out = new StringBuilder(base.length());
for (int i = 0; i < base.length(); i++) {
char c = base.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
out.append(c);
} else {
out.append('_');
}
}
return out.length() == 0 ? "config" : out.toString();
}
public Path root() {
return ROOT;
}
public Path directory(ConfigProfileType type) {
return ROOT.resolve(type.folderName());
}
public List<ConfigProfileMeta> list(ConfigProfileType type) {
normalizeLooseProfiles();
List<ConfigProfileMeta> out = new ArrayList<>();
Path dir = directory(type);
if (!Files.isDirectory(dir)) return out;
try (var stream = Files.list(dir)) {
stream.filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(EXTENSION))
.forEach(path -> {
try {
ConfigProfileMeta meta = codec.readMeta(Files.readAllBytes(path));
out.add(meta);
} catch (Exception e) {
DebugLog.error("Failed to read profile meta %s", e, path.toAbsolutePath());
}
});
} catch (IOException e) {
DebugLog.error("Failed to list profiles %s", e, dir.toAbsolutePath());
}
out.sort(Comparator.comparingLong(ConfigProfileMeta::updatedAt).reversed());
return out;
}
public ImportResult importProfileFile(Path source, boolean moveSource) throws IOException {
if (source == null) throw new IllegalArgumentException("profile path is null");
if (!Files.isRegularFile(source)) throw new IOException("profile is not a regular file: " + source);
String fileName = source.getFileName() == null ? "" : source.getFileName().toString();
if (!fileName.toLowerCase(Locale.ROOT).endsWith(EXTENSION)) {
throw new IOException("not a " + EXTENSION + " profile: " + source);
}
byte[] bytes = Files.readAllBytes(source);
ConfigProfileMeta meta = codec.read(bytes).meta();
Path dest = file(meta.type(), meta.getId());
Files.createDirectories(dest.getParent());
Path sourceAbs = source.toAbsolutePath().normalize();
Path destAbs = dest.toAbsolutePath().normalize();
if (!sourceAbs.equals(destAbs)) {
if (moveSource) {
Files.move(source, dest, StandardCopyOption.REPLACE_EXISTING);
} else {
Files.write(dest, bytes);
}
}
return new ImportResult(meta, dest);
}
public ConfigProfileSnapshot read(ConfigProfileType type, String idOrName) throws IOException {
Path path = file(type, idOrName);
return codec.read(Files.readAllBytes(path));
}
public ConfigProfileSnapshot read(ConfigProfileMeta meta) throws IOException {
if (meta == null) throw new IllegalArgumentException("profile meta is null");
return read(meta.type(), meta.getId());
}
public void save(ConfigProfileSnapshot snapshot) throws IOException {
if (snapshot == null) throw new IllegalArgumentException("snapshot is null");
Files.createDirectories(directory(snapshot.meta().type()));
Path path = file(snapshot.meta().type(), snapshot.meta().getId());
Files.write(path, codec.write(snapshot));
DebugLog.config("Config profile saved: %s", path.toAbsolutePath());
}
public boolean delete(ConfigProfileType type, String idOrName) throws IOException {
Path path = file(type, idOrName);
return Files.deleteIfExists(path);
}
public ConfigProfileSnapshot rename(ConfigProfileType type, String idOrName, String newName) throws IOException {
if (newName == null || newName.isBlank()) throw new IllegalArgumentException("profile name is blank");
ConfigProfileSnapshot old = read(type, idOrName);
ConfigProfileMeta oldMeta = old.meta();
ConfigProfileMeta newMeta = oldMeta.withName(newName.trim(), System.currentTimeMillis());
Path oldPath = file(type, oldMeta.getId());
Path newPath = file(type, newMeta.getId());
if (!oldMeta.getId().equals(newMeta.getId()) && Files.exists(newPath)) {
throw new IOException("profile already exists: " + newMeta.name());
}
ConfigProfileSnapshot renamed = new ConfigProfileSnapshot(newMeta, old.entries());
save(renamed);
if (!oldPath.equals(newPath)) Files.deleteIfExists(oldPath);
return renamed;
}
public boolean exists(ConfigProfileType type, String idOrName) {
return Files.exists(file(type, idOrName));
}
public Path file(ConfigProfileType type, String idOrName) {
String id = sanitizeFileName(idOrName);
if (!id.endsWith(EXTENSION)) id += EXTENSION;
return directory(type).resolve(id);
}
private void normalizeLooseProfiles() {
if (!Files.isDirectory(ROOT)) return;
List<Path> candidates = new ArrayList<>();
try (var stream = Files.walk(ROOT)) {
stream.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(EXTENSION))
.forEach(candidates::add);
} catch (IOException e) {
DebugLog.error("Failed to scan loose config profiles %s", e, ROOT.toAbsolutePath());
return;
}
for (Path candidate : candidates) {
try {
ConfigProfileMeta meta = codec.read(Files.readAllBytes(candidate)).meta();
Path dest = file(meta.type(), meta.getId());
Path candidateAbs = candidate.toAbsolutePath().normalize();
Path destAbs = dest.toAbsolutePath().normalize();
if (candidateAbs.equals(destAbs)) continue;
Files.createDirectories(dest.getParent());
Files.move(candidate, dest, StandardCopyOption.REPLACE_EXISTING);
DebugLog.config("Moved config profile %s -> %s", candidateAbs, destAbs);
} catch (Exception e) {
DebugLog.error("Failed to normalize config profile %s", e, candidate.toAbsolutePath());
}
}
}
public record ImportResult(ConfigProfileMeta meta, Path path) {
}
}

View file

@ -0,0 +1,50 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.util.Locale;
public enum ConfigProfileType {
MODULES((byte) 0, "modules"),
HUD((byte) 1, "hud"),
THEMES((byte) 2, "themes");
private final byte wireId;
private final String folderName;
ConfigProfileType(byte wireId, String folderName) {
this.wireId = wireId;
this.folderName = folderName;
}
public static ConfigProfileType fromWireId(int id) {
for (ConfigProfileType type : values()) {
if ((type.wireId & 0xFF) == id) return type;
}
throw new IllegalArgumentException("Unknown profile type id: " + id);
}
public static ConfigProfileType fromName(String name) {
if (name == null) return MODULES;
String normalized = name.trim().toLowerCase(Locale.ROOT);
for (ConfigProfileType type : values()) {
if (type.name().toLowerCase(Locale.ROOT).equals(normalized) || type.folderName.equals(normalized)) {
return type;
}
}
return MODULES;
}
public byte wireId() {
return wireId;
}
public String folderName() {
return folderName;
}
}

View file

@ -0,0 +1,136 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.profile;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
enum ConfigProfileValueCodec {
;
private static final byte NULL = 0;
private static final byte BOOLEAN = 1;
private static final byte INT = 2;
private static final byte LONG = 3;
private static final byte FLOAT = 4;
private static final byte DOUBLE = 5;
private static final byte STRING = 6;
private static final byte LIST = 7;
private static final byte MAP = 8;
static void writeValue(DataOutputStream out, Object value) throws IOException {
if (value == null) {
out.writeByte(NULL);
} else if (value instanceof Boolean b) {
out.writeByte(BOOLEAN);
out.writeBoolean(b);
} else if (value instanceof Integer i) {
out.writeByte(INT);
writeVarInt(out, i);
} else if (value instanceof Long l) {
out.writeByte(LONG);
out.writeLong(l);
} else if (value instanceof Float f) {
out.writeByte(FLOAT);
out.writeFloat(f);
} else if (value instanceof Number n) {
out.writeByte(DOUBLE);
out.writeDouble(n.doubleValue());
} else if (value instanceof CharSequence s) {
out.writeByte(STRING);
writeString(out, s.toString());
} else if (value instanceof Iterable<?> iterable) {
out.writeByte(LIST);
List<Object> list = new ArrayList<>();
for (Object item : iterable) list.add(item);
writeVarInt(out, list.size());
for (Object item : list) writeValue(out, item);
} else if (value instanceof Map<?, ?> map) {
out.writeByte(MAP);
writeVarInt(out, map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
writeString(out, String.valueOf(entry.getKey()));
writeValue(out, entry.getValue());
}
} else {
out.writeByte(STRING);
writeString(out, String.valueOf(value));
}
}
static Object readValue(DataInputStream in) throws IOException {
int type = in.readUnsignedByte();
return switch (type) {
case NULL -> null;
case BOOLEAN -> in.readBoolean();
case INT -> readVarInt(in);
case LONG -> in.readLong();
case FLOAT -> in.readFloat();
case DOUBLE -> in.readDouble();
case STRING -> readString(in);
case LIST -> {
int size = readVarInt(in);
List<Object> list = new ArrayList<>(Math.max(0, size));
for (int i = 0; i < size; i++) list.add(readValue(in));
yield list;
}
case MAP -> {
int size = readVarInt(in);
Map<String, Object> map = new LinkedHashMap<>();
for (int i = 0; i < size; i++) {
map.put(readString(in), readValue(in));
}
yield map;
}
default -> throw new IOException("Unknown profile value type: " + type);
};
}
static void writeString(DataOutputStream out, String value) throws IOException {
if (value == null) value = "";
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
writeVarInt(out, bytes.length);
out.write(bytes);
}
static String readString(DataInputStream in) throws IOException {
int length = readVarInt(in);
if (length < 0) throw new IOException("Negative string length: " + length);
byte[] bytes = new byte[length];
in.readFully(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
static void writeVarInt(DataOutputStream out, int value) throws IOException {
int v = value;
while ((v & 0xFFFFFF80) != 0L) {
out.writeByte((v & 0x7F) | 0x80);
v >>>= 7;
}
out.writeByte(v & 0x7F);
}
static int readVarInt(DataInputStream in) throws IOException {
int numRead = 0;
int result = 0;
byte read;
do {
read = in.readByte();
int value = (read & 0x7F);
result |= (value << (7 * numRead));
numRead++;
if (numRead > 5) throw new IOException("VarInt is too big");
} while ((read & 0x80) != 0);
return result;
}
}

View file

@ -0,0 +1,13 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.config.values;
public enum BindMode {
PRESS,
HOLD
}

Some files were not shown because too many files have changed in this diff Show more