Compare commits
10 commits
4e3ccfd736
...
b6712391fd
| Author | SHA1 | Date | |
|---|---|---|---|
| b6712391fd | |||
| 8ff02cff18 | |||
| 02e2947f47 | |||
| c120309663 | |||
| 4263df50a2 | |||
| e8b6569ccf | |||
| 4d999c89a8 | |||
| b771cc1c98 | |||
| 7e227e39a4 | |||
| cc521dc284 |
207 changed files with 3842 additions and 2355 deletions
15
.github/workflows/build.yml
vendored
15
.github/workflows/build.yml
vendored
|
|
@ -15,7 +15,7 @@ jobs:
|
|||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# 1.19.2 / 1.20.1 — Java 21 (plugin requires Java 21+; lolib jar is 21 bytecode)
|
||||
# 1.19.2 / 1.20.1 — Java 21 (plugin requires Java 21+)
|
||||
- { mc: "1.19.2", coordinate: "io.papermc.paper:paper-api:1.19.2-R0.1-SNAPSHOT", java: 21, release: 21, api: "1.19" }
|
||||
- { mc: "1.20.1", coordinate: "io.papermc.paper:paper-api:1.20.1-R0.1-SNAPSHOT", java: 21, release: 21, api: "1.20" }
|
||||
# 1.21 — Java 21
|
||||
|
|
@ -55,8 +55,19 @@ jobs:
|
|||
with:
|
||||
distribution: temurin
|
||||
java-version: 21
|
||||
- name: Full build
|
||||
- name: Full build (checkstyle, PMD, spotless, spotbugs, forbidden-apis, CPD, tests, coverage)
|
||||
run: ./gradlew --no-daemon build
|
||||
- name: Upload quality reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: quality-reports
|
||||
path: |
|
||||
build/reports/spotbugs
|
||||
build/reports/cpd
|
||||
build/reports/jacoco
|
||||
build/reports/checkstyle
|
||||
build/reports/pmd
|
||||
- name: Upload default jar
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
|
|
|
|||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -12,7 +12,6 @@
|
|||
|
||||
# Package Files
|
||||
*.jar
|
||||
!libs/*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
|
|
@ -64,9 +63,6 @@ test-output/
|
|||
# Modrinth files (local only)
|
||||
modrinth/
|
||||
|
||||
# LoLib API Documentation (не нужно в репозитории)
|
||||
api_docs/
|
||||
|
||||
# Project documentation (local only)
|
||||
TODO.md
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@
|
|||
|
||||
### Новое
|
||||
|
||||
- **Ghost: личные реплеи забегов.** Серверный тумблер записи (`ghost-mode.enabled`) + персональный переключатель в меню настроек. Запоминаются последние 5 забегов игрока (`ghost-mode.max-runs`). Просмотр через `/lp replay [номер]`: вас телепортирует на старт записанного забега, и моделька игрока с вашим скином повторяет движение по блокам.
|
||||
- **Coop-режим теперь работает.** `/lp join coop` создаёт общую сессию, друзья заходят через `/lp join <ник>`, общий счёт и статистика вклада.
|
||||
- **Ghost: личные реплеи забегов.** Серверный тумблер записи (`ghost-mode.enabled`) + персональный переключатель в меню настроек. Запоминаются последние 5 забегов игрока (`ghost-mode.max-runs`). Просмотр через `/lpk replay [номер]`: вас телепортирует на старт записанного забега, и моделька игрока с вашим скином повторяет движение по блокам.
|
||||
- **Coop-режим теперь работает.** `/lpk join coop` создаёт общую сессию, друзья заходят через `/lpk join <ник>`, общий счёт и статистика вклада.
|
||||
- **Мультиверсия в CI.** Сборка под Minecraft 1.19.2, 1.20.1, 1.20.4, 1.21, 1.21.11, 26.1.2, 26.2 (Java 21+).
|
||||
|
||||
### Исправления
|
||||
|
|
@ -26,8 +26,8 @@
|
|||
|
||||
### New
|
||||
|
||||
- **Ghost: personal run replays.** Server-wide recording toggle (`ghost-mode.enabled`) plus a per-player toggle in the settings menu. The last 5 runs per player are kept (`ghost-mode.max-runs`). Watch via `/lp replay [number]`: you are teleported to the start of the recorded run and a figure with your skin replays the movement block by block.
|
||||
- **Coop mode now works.** `/lp join coop` creates a shared session, friends join via `/lp join <name>`, shared score and contribution stats.
|
||||
- **Ghost: personal run replays.** Server-wide recording toggle (`ghost-mode.enabled`) plus a per-player toggle in the settings menu. The last 5 runs per player are kept (`ghost-mode.max-runs`). Watch via `/lpk replay [number]`: you are teleported to the start of the recorded run and a figure with your skin replays the movement block by block.
|
||||
- **Coop mode now works.** `/lpk join coop` creates a shared session, friends join via `/lpk join <name>`, shared score and contribution stats.
|
||||
- **Multi-version CI.** Builds for Minecraft 1.19.2, 1.20.1, 1.20.4, 1.21, 1.21.11, 26.1.2, 26.2 (Java 21+).
|
||||
|
||||
### Fixes
|
||||
|
|
|
|||
31
README.md
31
README.md
|
|
@ -6,7 +6,6 @@ Advanced infinitely generating parkour plugin with ghost system, leaderboards an
|
|||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
|
|
@ -53,14 +52,14 @@ LoParkour is an advanced parkour plugin with infinite world generation. The cour
|
|||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `/lp join` | Join parkour |
|
||||
| `/lp leave` | Leave parkour |
|
||||
| `/lp spectate <player>` | Spectate another player |
|
||||
| `/lp schematic save <name>` | Save a schematic |
|
||||
| `/lp schematic reload` | Reload schematics |
|
||||
| `/lp schematic convert` | Convert old vilib format |
|
||||
| `/lp forcejoin <player>` | Force player to join (admin) |
|
||||
| `/lp reset` | Reset leaderboards (admin) |
|
||||
| `/lpk join` | Join parkour |
|
||||
| `/lpk leave` | Leave parkour |
|
||||
| `/lpk spectate <player>` | Spectate another player |
|
||||
| `/lpk schematic save <name>` | Save a schematic |
|
||||
| `/lpk schematic reload` | Reload schematics |
|
||||
| `/lpk schematic convert` | Convert old vilib format |
|
||||
| `/lpk forcejoin <player>` | Force player to join (admin) |
|
||||
| `/lpk reset` | Reset leaderboards (admin) |
|
||||
|
||||
### Dependencies
|
||||
|
||||
|
|
@ -103,13 +102,13 @@ LoParkour - продвинутый паркур-плагин с бесконеч
|
|||
|
||||
| Команда | Описание |
|
||||
|---------|----------|
|
||||
| `/lp join` | Начать паркур |
|
||||
| `/lp leave` | Выйти из паркура |
|
||||
| `/lp spectate <игрок>` | Наблюдать за игроком |
|
||||
| `/lp schematic save <имя>` | Сохранить схематику |
|
||||
| `/lp schematic reload` | Перезагрузить схематики |
|
||||
| `/lp forcejoin <игрок>` | Заставить игрока начать (админ) |
|
||||
| `/lp reset` | Сбросить лидерборды (админ) |
|
||||
| `/lpk join` | Начать паркур |
|
||||
| `/lpk leave` | Выйти из паркура |
|
||||
| `/lpk spectate <игрок>` | Наблюдать за игроком |
|
||||
| `/lpk schematic save <имя>` | Сохранить схематику |
|
||||
| `/lpk schematic reload` | Перезагрузить схематики |
|
||||
| `/lpk forcejoin <игрок>` | Заставить игрока начать (админ) |
|
||||
| `/lpk reset` | Сбросить лидерборды (админ) |
|
||||
|
||||
### Зависимости
|
||||
|
||||
|
|
|
|||
371
TODO.md
371
TODO.md
|
|
@ -46,19 +46,32 @@
|
|||
|
||||
### Функциональность, которая не работает
|
||||
|
||||
- **21. Folia-поддержка — фикция.** Нет `folia-plugin.yml` (Folia не загрузит плагин). `MetricsCollector` использует удалённое API `BukkitRunnable.runTaskTimerAsynchronously` (MetricsCollector.java:73). `SessionStateManager.runTimer` → GlobalRegionScheduler, но тик мутирует блоки/entities (SessionStateManager.java:76, LifecycleTickManager.java:75, BlockPlacer.java:158, teleport в ParkourUser.java:93-95). → Либо выпилить бейдж Folia из README, либо: добавить folia-plugin.yml, перевести тик на runTimerAtLocation/runAtEntity, заменить BukkitRunnable.
|
||||
- **21. Folia-поддержка — фикция.** ✅ **ЧАСТИЧНО (2026-10-10):** все вызовы планировщика идут через фасад `scheduler/`
|
||||
(добавлен `runTimerAsync`: Bukkit → `runTaskTimerAsynchronously`, Folia → `AsyncScheduler.runAtFixedRate` рефлексией);
|
||||
`MetricsCacheStore` переведён с `BukkitRunnable` на фасад, прямые `Bukkit.getScheduler()` из `DuelsCountdown`/`DuelsGenerator`
|
||||
убраны — вне `scheduler/` их больше нет. Бейдж Folia из README убран (поддержка не проверена на Folia-сервере).
|
||||
❌ Осталось: тик идёт через global scheduler, но мутирует блоки/entities (`SessionStateManager`, `LifecycleTickManager`,
|
||||
`BlockPlacer`, teleport) → нужен region/entity-tick + `folia-plugin.yml`; без Folia-стенда не верифицируется (см. п.143).
|
||||
- **22. Ghost-система — 100% мёртвый код.** `GhostManager`/`GhostRecorder`/`GhostPlayer` нигде не инстанцируются (grep: только само-ссылки). Конфиг `ghost-mode.*` не потребляется. → Подключить к lifecycle (запись в saveGhost/спавн в spawnGhosts) ИЛИ удалить подсистему и конфиг.
|
||||
- **23. Coop-режим нерабочий.** Ни одно `Session.create` не строит `CoopGenerator` (CoopMode.java:134). `/parkour join <игрок>` ведёт в спектаторы. → Реализовать создание coop-сессии (лобби/инвайты) или выпилить режим из меню и регистрации.
|
||||
- **24. Coop: латентный StackOverflow.** `ParkourPlayer.unregister()` → `CoopMode.leave()` → `ParkourUser.leave()` → `UserRegistry.unregister()` → `user.unregister()` — бесконечная рекурсия (ParkourPlayer.java:102-107, CoopMode.java:115-121, UserRegistry.java:58-67). Нет guard-флага. → Добавить in-flight guard в unregister (например, reentrancy flag в ParkourUser).
|
||||
- **25. Лидерборд: тайминги сломаны.** `Score.getTimeMillis()` ждёт ровно 3 части через `:` (Score.java:36-55), но генератор пишет `mm:ss.SSS` (2 части) и `HH:mm:ss.SSS` (третья `02.123` → NFE). Итог: TIME-сортировка и тай-брейк мёртвые, Race-лидерборд не обновляется. Плюс переполнение `int` в m*60*1000+... (Score.java:51). → Унифицировать формат времени; парсить `mm:ss.SSS` и `HH:mm:ss.SSS`; перейти на `long`.
|
||||
- **26. ConfigUpdater уничтожает пользовательские данные.** `merge()` перегенерирует весь файл из шаблона при каждом старте (ConfigUpdater.java:85-127): теряются листы (`options.leads.amount`, стили), кастомные ключи, комментарии; алгоритм отступов (`prevIndent -= 2`) ошибочен; `ignoredSections` не защищают. → Точечный merge только отсутствующих ключей, сохранять листы/комментарии, либо заменить на библиотеку (e.g. `me.mattstudios` / SimpleConfig) или `Bukkit's config addDefaults`.
|
||||
- **27. SQL: утечка Hikari-пулов.** `StorageSQL.init(mode)` вызывается на каждый режим (6 лидербордов), каждый раз пересоздаёт `connectionManager` (StorageSQL.java:66-77, LeaderboardStorage.java:35) → до ~10 соединений висят навсегда. → Один пул на плагин, инициализация один раз.
|
||||
- **28. SQL: блокирующий connect на main thread** (SQLConnectionManager.java:34-56) — при лежащей БД включение висит до 5с×режимы. → `setInitializationFailTimeout(-1)` + асинхронный connect.
|
||||
- **29. SQL: адаптив не стартует.** `AdaptiveServices.init` вызывается до создания лидербордов, а `StorageSQL.runWhenConnected` выбрасывает колбэк при не-подключении (StorageSQL.java:45-51). → Очередь колбэков в SQLConnectionManager.onConnectCallbacks; порядок init: лидерборды → storage → adaptive.
|
||||
- **30. SQL: настройки игрока не сохраняются.** `SQLDataMapper.serializeSettings` всегда `"{}"`, десериализация no-op (SQLDataMapper.java:105-115) → при входе `schematicDifficulty`/`blockLead` и др. = null → NPE в `ParkourPlayer.updateGeneratorSettings:157-164` и `PAPIHook.java:140`. → Реализовать сериализацию/десериализацию всех настроек (JSON-колонка) + fallback на defaults.
|
||||
- **26. ConfigUpdater уничтожает пользовательские данные.** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
точечный merge (`ConfigMergeProcessor` + `ConfigMergeParser`): block-sequence листы и `ignoredSections` сохраняются,
|
||||
есть `ConfigMergeProcessorTest` (249 строк). `performUpdate` ловит только `IOException`, runtime уходит на границу `ConfigLoader`.
|
||||
- **27. SQL: утечка Hikari-пулов.** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
`StorageSQL.init(mode)` создаёт пул один раз (`if (connectionManager == null)`).
|
||||
- **28. SQL: блокирующий connect на main thread** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
`setInitializationFailTimeout(-1)` — пул стартует, не дожидаясь БД.
|
||||
- **29. SQL: адаптив не стартует.** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
`SQLConnectionManager.runWhenConnected` складывает колбэки в `onConnectCallbacks` вместо выбрасывания.
|
||||
- **30. SQL: настройки игрока не сохраняются.** ✅ **СДЕЛАНО**: `SQLDataMapper.serializeSettings` пишет `PlayerSettingsManager.toSettingsMap(player)` (12 ключей) в JSON-колонку, `deserializeSettings` читает её тем же словарём (`normalizeNumericSettings` + `applySettings`) и падает на `applyDefaults` при пустоте/битости → `schematicDifficulty`/`blockLead` больше не null при входе (NPE в `updateGeneratorSettings`/`PAPIHook` не стало). Диск и SQL теперь используют **один и тот же** набор ключей.
|
||||
- **31. Схематики: креш на main thread от битых файлов.** `LPSchematicLegacy`/`SchemLoader` парсят без валидации; NPE/AIOOBE мимо `catch(IOException)` (SchematicManager.java:109-133, LpschemConverter.java:44-54). Битый файл = отказ включения плагина. → Валидация dimensions/palette/frameCount + `catch(RuntimeException)` + лимиты размера файла/блоков.
|
||||
- **32. JumpCalculator: возврат невалидного прыжка.** После 10 неудач валидация сдаётся и возвращает заведомо невалидный блок (JumpCalculator.java:125-136). → Пере-роллить offset/направление, а не только уменьшать distance/height; при исчерпании — safety-fallback (простой допустимый шаг).
|
||||
- **33. JumpCalculator: диагональный heading залипает.** `JumpDirector.getRecommendedHeading` в безопасной зоне возвращает current без изменений (JumpDirector.java:105-107), а `calculateJumpOffset` при `offset.getX()!=0` перезаписывает Z (JumpCalculator.java:110-115) → курс зигзагом и не выпрямляется. → При диагонали аппендикс не перезаписывать случайным; корректный поворот-домножитель.
|
||||
- **32. JumpCalculator: возврат невалидного прыжка.** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
`validateAndRetryJump` + `safetyFallback` (3 ре-ролла шага 1/0, затем прямой шаг без джиттера, в крайнем случае `current`);
|
||||
покрыто `JumpCalculatorTest` (`safetyFallbackReturnsValidStepForUnitHeading`, `...ReturnsCurrentWhenStraightStepImpossible`).
|
||||
- **33. JumpCalculator: диагональный heading залипает.** ✅ **СДЕЛАНО (ещё в fea15e6, подтверждено 2026-10-10):**
|
||||
`offsetFor` считает перпендикулярный джиттер без перезаписи Z; покрыто `JumpCalculatorTest`.
|
||||
|
||||
### Генерация / lifecycle
|
||||
|
||||
|
|
@ -86,12 +99,22 @@
|
|||
- **47. `UserRegistry.getUsers()` строит полный Set на каждый BlockBreak/Place/Drop/Damage** (UserRegistry.java:94-98) → O(n) аллокаций на горячем пути. → Кэш `Map<UUID, ParkourUser>` + привязка через PersistentDataContainer или entity.
|
||||
- **48. `sendTranslated(...).formatted()` бросает IllegalFormatException при `%` в нике/сообщении** (ParkourUser.java:102, Locales.java:76-82). → Обернуть в try или использовать replace-based формат.
|
||||
- **49. `getJoinCount` — int между main и async (bStats)** (UserRegistry.java:100-104). → AtomicInteger.
|
||||
- **168. ✅ ИСПРАВЛЕНО (2026-10-06, см. ПРОГРЕСС-8): `ParkourUser.chatType` — состояние без записи.** Поле инициализировано
|
||||
`PUBLIC`, читалось в `ParkourRestrictionListener.onChat` (switch `chatType()`), но сеттера не было нигде → ветки
|
||||
`LOBBY_ONLY`/`PLAYERS_ONLY` были недостижимы. Оказалось, фича спроектирована, но не подключена: в `en.yml`/`ru.yml`
|
||||
уже лежал готовый блок `settings.chat` (material/name/lore/values + formats), а `ParkourOption.CHAT("settings.chat", …)`
|
||||
уже был в реестре опций. → Кнопка-цикл в `SettingsMenu` (слот 15) + `ParkourUser.setChatType(...)` + `ChatType.next()`.
|
||||
|
||||
### Modes
|
||||
|
||||
- **50. `GravityShiftMode` не снимает эффекты при выходе игрока** (только в reset для присутствующих, GravityShiftMode.java:149-163). → Снимать в unregister.
|
||||
- **51. `RaceMode.finishRace` — `reset(false)` оставляет игрока в воздухе** (RaceMode.java:142-147; GeneratorCleanup.reset чистит курс без регенерации/телепорта). → Телепорт в лобби + регенерация старта.
|
||||
- **52. `SpeedrunMode` оставляет удалённые блоки в `history`** → ломает координатные поиски. → Удалять координату из history при снятии блока.
|
||||
- **167. ✅ ИСПРАВЛЕНО (2026-10-06, см. ПРОГРЕСС-8): Elytra-под-режимы не отличались от базового.**
|
||||
`ElytraGenerator.getMode()` возвращал `Modes.elytra()`, а 5 под-генераторов (`Close/MinSpeed/TimeTrial/SpeedDemon/ObstacleGenerator`)
|
||||
его не переопределяли → guard `getMode() instanceof CloseMode` в `create()` **никогда не был истинен**: повторная команда
|
||||
в том же режиме не делала early-return, а пересоздавала сессию. Геттеры `Modes.speedDemon()/minSpeed()/timeTrial()/close()/obstacle()`
|
||||
не вызывались нигде. → режим передаётся в конструктор `ElytraGenerator`, `getMode()` отдаёт его.
|
||||
|
||||
### Схематики (жизнь в игре)
|
||||
|
||||
|
|
@ -112,10 +135,10 @@
|
|||
|
||||
- **60. `SQLDataMapper` UUID.fromString кидает unchecked IllegalArgumentException** (SQLDataMapper.java:65,31) мимо catch(SQLException) → битые строки роняют чтение. → Ловить и логировать/скипать строку.
|
||||
- **61. `SQLQueryExecutor.prepareStatement`** (без callers) никогда не закрывает connection → утечка пула при будущем использовании. → try-with-resources / borrow-tracking.
|
||||
- **62. `SQLMigrationManager` мёртв; `migration_adaptive.sql` ссылается на несуществующую `loparkour_scores` и нигде не исполняется**; та же DDL в 3 копиях; префикс `SQL_PREFIX` применён непоследовательно. → Единый мигратор с версионированием; починить/удалить SQL-файл.
|
||||
- **62. `SQLMigrationManager` мёртв; `migration_adaptive.sql` ссылается на несуществующую `loparkour_scores` и нигде не исполняется**; та же DDL в 3 копиях; префикс `OptionSQL.prefix()` применён непоследовательно. → Единый мигратор с версионированием; починить/удалить SQL-файл.
|
||||
- **63. `writeScores` гоняет всю таблицу туда-сюда** без дельт (StorageSQL.java:105-128). → Инкрементальные upsert'ы только изменённых записей.
|
||||
- **64. `Score.fromString` — CSV по запятой: ник с `,` ломает все поля** (Score.java:19-31). → Экранирование или JSON.
|
||||
- **65. `validateConnection` мутирует `Option.SQL=false` при транзиентном сбое** (SQLConnectionManager.java:81-86) — SQL отключается навсегда. → Отдельный флаг/ретрай.
|
||||
- **65. `validateConnection` мутирует `OptionSQL.disable()` при транзиентном сбое** (SQLConnectionManager.java:87-92) — SQL отключается навсегда. → Отдельный флаг/ретрай.
|
||||
|
||||
### Adaptive
|
||||
|
||||
|
|
@ -126,11 +149,14 @@
|
|||
|
||||
### Config / reload
|
||||
|
||||
- **70. `/lp reload` не атомарен**: дублирует `Registry.STYLES` (никогда не чистится), оставляет старые `Rewards` при `enabled:false`, `BORDER_SIZE` устаревший, миры/генераторы не обновляются (ConfigUpdater, OptionStyles.java:23-43, Rewards.java:41-52, OptionGeneral.java:38-40). → Полный reset registry + пересоздание зависимых подсистем.
|
||||
- **70. `/lp reload` не атомарен**: дублирует `Registry.STYLES` (никогда не чистится), оставляет старые `Rewards` при `enabled:false`, `OptionGeneral.borderSize()` устаревший (перечитывается только при `firstLoad`), миры/генераторы не обновляются (ConfigUpdater, OptionStyles.java:23-43, Rewards.java:41-52, OptionGeneral.java:44-50). → Полный reset registry + пересоздание зависимых подсистем.
|
||||
- **71. `LocaleLoader` при ошибке подменяет кэш на emptyMap** → все сообщения пустые (LocaleCache.java:22-25). → Сохранять старый кэш при сбое.
|
||||
- **72. Нет fallback на en** для пропущенных ключей/неизвестных локалей (Locales.java:69-71). → Fallback-цепочка locale → en.
|
||||
- **73. `Rewards.init()` при `enabled:false` не чистит статические мапы** → старые награды продолжают выдаваться после reload. → Очистка.
|
||||
- **74. `ConfigAccessor` типо-опечатка тихо даёт false/0** (ConfigAccessor.java:45-48). → Строгая валидация ключей при старте.
|
||||
- **164. Секция `generation.*` в generation.yml игнорируется.** Живые веса берутся из `advanced.distance|height|type|special` (`GeneratorProfileManager`, `GenerationProfileLoader`), а `generation.type|normal|special` читал только мёртвый `OptionGeneration.initGenerationProbabilities()` — удалён на шаге инкапсуляции `config/options`. В shipped `generation.yml` обе секции дублируют друг друга (значения разные: 85/10/5 против 80/15/5) → пользователь правит то, что не работает. → Либо удалить `generation.type|normal|special` из generation.yml, либо сделать их источником для профилей; `generation.settings.min-y/max-y` остаются живыми. `ConfigLoader.validateConfigs` уже проверяет живые пути `advanced.*`.
|
||||
- **165. Мёртвый конфиг частиц/звуков.** `particles.sound-type|sound-pitch|sound-volume|particle-type|particle-shape` читаются в `OptionParticles`, все 6 геттеров (`shape()`, `soundType()`, `particleData()`…) не вызываются нигде → настройки не влияют на игру (используются per-player `ParkourPlayer.particles/sound` из меню). → Подключить в рендере частиц/звуков (`util/particle/`, `HookSound`) или убрать секцию из config.yml.
|
||||
- **166. Ещё два читаемых, но не потребляемых ключа.** `options.leads.amount` → `OptionGeneral.possibleLeads()` (валидация 1–128 и лог работают, список не читает никто — lead берётся из `default-values.leads.default`), `memory.block-cleanup-distance` → `OptionGeneration.blockCleanupDistance()` (дистанция чистки захардкожена в `GeneratorCleanup`). → Подключить или удалить.
|
||||
|
||||
### Session
|
||||
|
||||
|
|
@ -169,7 +195,7 @@
|
|||
- **95. `SchematicIdGenerator` хеширует только byte-координаты → коллизии id** (SchematicIdGenerator.java:23-28).
|
||||
- **96. `parseDifficulty` принимает NaN/Infinity** (SchematicCreator.java:64-70) → схема навсегда невыбираема.
|
||||
- **97. `stem()` регистрирует файл `.nbt` под пустым id**; `.NBT` игнорируется, `.schematic` — case-insensitive (SchematicManager.java:147-150,88).
|
||||
- **98. `Locales.getPlayerLocale`/`ParkourUser.locale` deref `OPTIONS_DEFAULTS.get(LANG)` без null-check** (Locales.java:170-184, ParkourUser.java:64).
|
||||
- **98. `Locales.getPlayerLocale`/`ParkourUser.locale` deref `OptionGeneral.optionsDefaults().get(LANG)` без null-check** (Locales.java:170-184, ParkourUser.java:64).
|
||||
- **99. Магические числа**: fall-threshold -30 (LifecycleTickManager.java:72), render 24.0/0.1/%4 (InvisibleBarrierMode.java:67-68,98), 10/30 (GravityShiftMode.java:82,108), 100 тиков (RaceMode.java:147), hotbar delay 5 (ParkourPlayer.java:192), `TICKS_PER_SECOND=20` переопределён (SpeedrunMode.java:82). → В конфиг/константы.
|
||||
- **100. Deprecated API**: `Material.STONE_SLAB` (MaterialUtil.java:20), `registerNewObjective(String,String,String)` (ScoreboardManager.java:75), `getOfflinePlayer(name)` (AdminCommandHandler.java:186-199), legacy ACTION_BAR (ParkourSpectator.java:73, RaceMode.java:103).
|
||||
- **101. `ParkourSpectator.java:96` — бессмысленный double-set spectator target** (no-op).
|
||||
|
|
@ -178,7 +204,7 @@
|
|||
- **104. `ProfileValue.asDouble/asInt` бросают NFE на нечисловых строках** (Profile.java:54,64) — только empty-guard.
|
||||
- **105. Дубликат логики `create()` во всех режимах** с несогласованными проверками дублей (instanceof DefaultMode vs instanceof SpeedrunGenerator).
|
||||
- **106. Мёртвый код**: `EffectManager` целиком, `SessionUserManager`, `SQLMigrationManager`, `SQLQueryExecutor`, `SkullSetter`, `Locations.max/min`, `ParkourBlockGenerateEvent`, `onPlayerJoin` (CoopMode.java:169), `PLAYER_COLUMNS`/`OptionContainer` (ParkourPlayer.java:38,205), `acceptingPlayers`-механизм, `Muted` в двух местах.
|
||||
- **107. Публичные mutable поля-государство**: `GeneratorState` — 15 публичных полей, `ParkourGenerator.session/island/profile/state/generatorOptions` публичные final, `Score` времени в строке. → Инкапсуляция.
|
||||
- **107. Публичные mutable поля-государство**: ✅ **ЧАСТИЧНО** — `GeneratorState` (15 полей) и весь кластер `player/*` (`ParkourUser`, `ParkourPlayer`, `PlayerSettings`) инкапсулированы в ПРОГРЕСС-6, `VisibilityModifier` переведён в `error`. Остались `ParkourGenerator.session/island/profile/state/generatorOptions` (публичные final — правило их разрешает, но состояние чужое мутируется) и `Score` времени в строке. → Инкапсуляция.
|
||||
|
||||
## 🧪 Тесты
|
||||
|
||||
|
|
@ -303,12 +329,329 @@ Checkstyle отработал `0 errors` (error-уровневые legacy-нар
|
|||
- **135. [M] Починить `NPathComplexity` (legacy, 29 / 25 файлов).** Решается декомпозицией методов (файлы и так в списке на рефакторинг).
|
||||
- **136. [M] Починить `IllegalCatch` (legacy, 22 / 19 файлов).** catch(Exception/Throwable/RuntimeException)→сужение до конкретных исключений либо переименовать в `expected|ignore`.
|
||||
- **137. [M] Починить все нарушения PMD (45):** `CognitiveComplexity(17)` + `CyclomaticComplexity(7)` — декомпозиция; `GodClass(4)` + `TooManyMethods(8)` — декомпозиция; `AvoidReassigningParameters(7)` — переименование параметров; `EmptyCatchBlock(2)` — комментарий/конкретный тип.
|
||||
- **138. [S] Перевести PMD из report-only в жёсткий гейт.** После зачистки убрать `isIgnoreFailures=true` в `build.gradle.kts` (pmd-блок).
|
||||
- **138. [S] Перевести PMD из report-only в жёсткий гейт.** После зачистки убрать `isIgnoreFailures=true` в `build.gradle.kts` (pmd-блок). ✅ сделано в `b771cc1`.
|
||||
- **169. [M] Починить `ReturnCount` (69 warning / 52 файла) — ПЕРЕСТРУКТУРИРОВАНИЕМ, не порогом.** ✅ **ВЫПОЛНЕНО (2026-10-10):** все 69 void-методов переструктурированы (guard-`return` → `if`-блок или helper: `placePlayer`/`tickPlayer`/`boostIfValid`/`applyCommand`/`firstNonNull`), порог не поднимался, `NestedIfDepth` ≤ 2 соблюдён; правило переведено в `error`. Попутно `NPathComplexity` 12 → 9. Checkstyle: **0 errors / 61 warning**, тесты 96/0 fail.
|
||||
- **170. [M] Починить `IllegalCatch` (23 warning / 18 файлов).** ✅ **ЧАСТИЧНО (2026-10-10, остаток 18 — осознанные границы, правило остаётся в warning):**
|
||||
3× `catch (Throwable)` → `catch (RuntimeException)` (диспетчер команд, session-tick, shutdown — `Error` больше не глотается);
|
||||
сужено 5: `HoloHook` → `ClassNotFoundException | LinkageError`, `OptionGeneral` → `NumberFormatException` и
|
||||
`IllegalArgumentException | IndexOutOfBoundsException`, `GeneratorProfileManager` → `IllegalArgumentException`,
|
||||
`ConfigUpdater` → `IOException` (runtime уходит на границу `ConfigLoader`).
|
||||
Не сужено осознанно (у каждого — комментарий «почему»): границы enable/reload/shutdown (`PluginBootstrap`,
|
||||
`ConfigLoader`, `LocaleLoader`, `LoParkour:106`, `SQLConnectionManager:59` — таксономия ошибок HikariCP не публична),
|
||||
порча данных (`InventoryData`, `PreviousData`, `SchematicManager` ×2), внешние API (`ScoreboardManager`/PAPI),
|
||||
leave-путь (`UserRegistry`), изоляция колбэков (`SQLConnectionManager:106`), хот-путь генерации
|
||||
(`JumpValidator`, `BlockSelector`), кэш сообщений (`LocaleCache`).
|
||||
|
||||
После зачистки п.132–137 — удалить соответствующие записи из `config/checkstyle/suppressions.xml` (супрессии остаются только для ещё незачищенных legacy-файлов).
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Порядок работ: Задача 1 → Задача 2 → остальное
|
||||
|
||||
> Задано владельцем 2026-10-06. Всё остальное в этом файле (версии 1.19.2–26.3, смена команды, пункты аудита) делается **после** задач 1 и 2,
|
||||
> потому что и lolib-слой, и структура пакетов затрагивают почти все файлы.
|
||||
|
||||
### Задача 1. Отказаться от `lolib` (`libs/lolib-3.0.0.jar`)
|
||||
|
||||
Почему: исходников и репозитория lolib нет (архив/утерян), jar лежит в `libs/` как бинарник, байткод 21 (мешает п.139 про Java 17), внутри — fat-jar с чужими зависимостями.
|
||||
Мы тащим его целиком (`implementation(files("libs/lolib-3.0.0.jar"))` + релокация `dev.lolib`), а используем **5 классов в 28 файлах**:
|
||||
|
||||
| Что берём из lolib | Где (файлов) | Замена своим кодом |
|
||||
|---|---|---|
|
||||
| `dev.lolib.gui.InventoryGUI` | ~12 (все `menu/*`: `Menu`, `LPMenu`, `MainMenu`, `LobbyMenu`, `SettingsMenu`, `LangMenu`, `SpectatorMenu`, `DuelsMenu`, лидерборд-меню, `PlayerManagementMenu`, `ParkourSettingsMenu`) | собственный `menu/gui/` (инвентарь + `InventoryClickEvent`-листенер, слоты/страницы; per-player состояние — заодно закрывает п.78, п.81) |
|
||||
| `dev.lolib.scheduler.Scheduler` / `ScheduledTask` | ~16 (`SessionStateManager`, `GhostPlayer/GhostReplay`, `RaceMode`, `SpeedrunMode`, `ParkourSpectator`, `PlayerSpawnSetup`, `InventoryData`, `Schematics`, `StorageSQL`, `LeaderboardStorage`, `World`…) | тонкая обёртка `scheduler/` над Bukkit + Folia-схедулерами (global/region/entity/async) — фундамент для п.21/143; без неё Folia не починить |
|
||||
| `dev.lolib.worlds.VoidGenerator` | `World.java` | свой `ChunkGenerator` (void) в `world/` — это п.112/145 |
|
||||
| `dev.lolib.core.LoPlugin` | `LoParkour.java` (+`PluginBootstrap`) | перейти на обычный `JavaPlugin` (что именно давал `LoPlugin` — проверить декомпиляцией: порядок enable/disable, автосервисы) |
|
||||
|
||||
Шаги:
|
||||
1. **Выяснить фактическую поверхность API:** `javap`/декомпилятор по 5 классам, список методов, реально вызываемых из нашего кода (`grep` по `dev.lolib` — всё остальное внутри jar нам не нужно).
|
||||
2. **Транзитивные библиотеки:** lolib — fat-jar (gson, HikariCP, caffeine, snakeyaml, slf4j, checkerframework). Сейчас gson/Hikari у нас и так объявлены явно (`FileStatsStorage`, `StorageDisk`, `SQLDataMapper`, `SQLConnectionManager`, `ParkourPlayer`); **caffeine/snakeyaml/slf4j напрямую не импортируются** — убедиться, что без jar сборка и тесты проходят, не добавлять лишнего.
|
||||
3. Написать замены (scheduler → void-gen → gui → `JavaPlugin`), по одной, с тестами; после каждой — `./gradlew build`.
|
||||
4. Удалить `libs/lolib-3.0.0.jar`, `implementation(files(...))`, релокацию `dev.lolib` и закомментированный `exclude` в `shadowJar`; убрать `softdepend: VoidGen` из `plugin.yml`.
|
||||
5. Проверка: jar без `dev/loki/loparkour/lib/lolib/**` (`unzip -l`), плагин стартует на 1.21.x/26.x (см. п.141), размер jar заметно меньше.
|
||||
6. Папка `libs/` остаётся пустой → удалить, если больше ничего не лежит.
|
||||
|
||||
Критерий готовности: `grep -r "dev.lolib" src build.gradle.kts` пусто, `build` зелёный, меню/таймеры/мир работают.
|
||||
|
||||
> ## ✅ ПРОГРЕСС — Задача 1 ВЫПОЛНЕНА (2026-10-06)
|
||||
> Поверхность API уточнена декомпиляцией (`javap`): реально использовались `InventoryGUI` (create/title/rows/fill/setItem/open + GUIManager-листенер),
|
||||
> `Scheduler.get().run/runAsync/runLater/runTimer` + `ScheduledTask.cancel()`, `VoidGenerator.getGenerator()`, `LoPlugin.enable/disable` + `loLogger()`
|
||||
> (`AutoRegister`/`dependencies`/`load` — no-op, в коде аннотаций нет). Замены (по шагам, `build` зелёный после каждого):
|
||||
> - **`scheduler/`** — `Scheduler` (фасад, кэш по плагину, `Backend`), `ScheduledTask` (functional interface, только `cancel()` — `isCancelled()` нигде не вызывался),
|
||||
> `BukkitBackend` (Bukkit-планировщик), `FoliaBackend` (global/async-рефлексия: `RegionizedServer`-детект, fallback с warning — Folia API нет в Spigot/Paper артефактах матрицы).
|
||||
> Entity/region-варианты (`runAt*`) не реализовывались — их никто не вызывает; добавить при п.143.
|
||||
> - **`world/core/VoidGenerator`** — `ChunkGenerator` без генерации (`shouldGenerate*` = false; `shouldGenerateBedrock()` не переопределяется — deprecated в 1.19.2/1.20.4, default и так false).
|
||||
> - **`menu/gui/inventory/`** — `InventoryGui` (тот же флюентный API, что и у lolib: call-site'ы меняли только import) + `GuiManager`
|
||||
> (UUID→GUI, dispatch по raw slot, отмена кликов, чистка при close/quit). Удалён мёртвый `menu/gui/Menu.java` (legacy-стаб с javadoc на LoLib).
|
||||
> - **`LoParkour extends JavaPlugin`** — `enable/disable` → `onEnable/onDisable`, `loLogger()` → `getLogger()` (+`log(Level, …)` в `PluginBootstrap`).
|
||||
> - **Удалено:** `libs/lolib-3.0.0.jar` (+папка `libs/`), `implementation(files(...))`, релокация `dev.lolib`, закомментированный `minimize/exclude`,
|
||||
> `softdepend: VoidGen`, строка `!libs/*.jar` в `.gitignore`, запись `api_docs/`, упоминания LoLib в комментариях/javadoc/CI.
|
||||
> - **Проверки:** `grep -r "dev.lolib" src build.gradle.kts` пусто; `unzip -l` — нет ни `dev/lolib`, ни `dev/loki/loparkour/lib/lolib`;
|
||||
> **jar 9 770 813 → 7 816 441 байт (−20%)**; `build` зелёный: checkstyle **0 errors / 0 warnings**, PMD **0**, **87 тестов / 0 fail**;
|
||||
> матрица собирается: 1.19.2, 1.20.1, 1.21, 1.21.11 (JDK 21) и 26.1.2, 26.2 (JDK 25).
|
||||
> - **Новые тесты:** `scheduler/SchedulerTest` (нет Folia-детекта на обычном JVM, кэш по плагину), `menu/gui/inventory/InventoryGuiTest`
|
||||
> (границы rows, fill не затрагивает поставленное, dispatch+cancel клика), `world/core/VoidGeneratorTest` (синглтон, ничего не генерирует).
|
||||
> - **Smoke-тест ПРОЙДЕН** (`./gradlew runServer`, Paper 1.21.4): `Loading` → `Enabling LoParkour` → конфиги синхронизированы,
|
||||
> PAPI-хук зарегистрирован, паркур-мир создан → `Done (27.831s)`, `Disabling` без единого ERROR/Exception/WARN в логе.
|
||||
> - **Остаток:** Folia-путь `FoliaBackend` не проверялся на Folia-сервере (п.143).
|
||||
|
||||
### Задача 2. Жёсткий рефакторинг под KISS / DRY / SOLID (сразу после задачи 1)
|
||||
|
||||
Правила (становятся **жёсткими гейтами**, не рекомендациями; расширяют `docs/ARCHITECTURE.md` п.5 и п.8):
|
||||
- **≤ 4 файла в папке** (было «ориентир 3–5»). Больше → делим на подпапки по смыслу. Сейчас: 89 пакетов, **6 превышают 4**: `elytra/generator` (7), `elytra/mode` (6), `command/schematic` (6), `player/core` (5), `generator/jump/placement` (5), `generator/jump/calculation` (5).
|
||||
- **≤ 200 строк на файл** — гейт уже есть (`FileLength` 200, error); проверить, что супрессий на FileLength не осталось; снизить `MethodLength` 80 → ~40.
|
||||
- **KISS:** убрать абстракции с одной реализацией, пустые интерфейсы, неиспользуемые слои; метод делает одно (cyclomatic ≤ 10 вместо 20, `NPath` ≤ 50 → ≤ 30, вложенность if ≤ 2).
|
||||
- **DRY:** убрать дубли (`create()` во всех режимах — п.105, дубликаты в SQL DDL — п.62, `SessionUserManager` ≈ `SessionPlayerManager` — п.76, дубли `canJump` и т.п.). Гейт — PMD CPD (минимум ~60 токенов).
|
||||
- **SOLID:** SRP (god-классы уже порезаны, закрепить `TooManyMethods` ≤ 10, `TooManyFields`, `GodClass` вернуть), DIP (домен не импортирует `org.bukkit` там, где можно через порт), ISP (узкие интерфейсы), OCP (новые режимы без правок ядра).
|
||||
- **Правило слоёв** (`api → core → subsystems → platform`) проверять автоматически (см. ниже), а не только в документе.
|
||||
|
||||
Настройка линтеров (усилить «сильно»):
|
||||
- **Checkstyle:** `FinalLocalVariable`, `MagicNumber`, `ClassFanOutComplexity` (сейчас 20 → 12), `ClassDataAbstractionCoupling` (20 → 10), `ParameterNumber` 7 → 5, `ReturnCount`, `NestedIfDepth` 2 → 1–2, `IllegalCatch`, `IllegalThrows`, `HiddenField`, `VisibilityModifier` (закрывает п.77/107 — публичные mutable-поля), `DesignForExtension`/`FinalClass`, `JavadocMethod` для публичного API; **все warning → error**, `suppressions.xml` обнулить (сейчас 87 строк).
|
||||
- **PMD 7:** включить категории `bestpractices`, `errorprone`, `design`, `multithreading`, `performance`, `security` целиком (а не выборочные правила); вернуть `GodClass`, добавить `CouplingBetweenObjects`, `LawOfDemeter` (по месту), `AvoidSynchronizedAtMethodLevel`, `DoNotUseThreads`, `AvoidUsingVolatile`; запустить и на `src/test`; `isIgnoreFailures=false` уже стоит — оставить.
|
||||
- **Новые проверки (предложение, выбрать):**
|
||||
1. **ArchUnit** (тест в JUnit): слои, отсутствие циклов между пакетами, «в папке ≤ 4 файла» и «≤ 200 строк» как тест, запрет `BukkitRunnable`/`Bukkit.getScheduler()` вне `scheduler/` (п.109 — Folia-инварианты), запрет `org.bukkit` в `api`/`core`.
|
||||
2. **SpotBugs** (+ `find-sec-bugs`) — NPE/гонки/SQL-инъекции, закрывает целый класс пунктов P2 по потокобезопасности.
|
||||
3. **Error Prone + NullAway** (compile-time) — null-safety на всём коде, `@Nullable` на границах.
|
||||
4. **PMD CPD** — гейт на дубли (DRY).
|
||||
5. **JaCoCo** — минимальное покрытие (старт 50% строк, ядро — 70%), отчёт в CI; п.108 (тесты) становится обязательным.
|
||||
6. **Spotless** (google-java-format/palantir) — единый формат, `spotlessCheck` в CI; убирает `WhitespaceAround`/`EmptyLineSeparator` шум.
|
||||
7. **OWASP dependency-check** или `gradle-versions`/`dependabot` — уязвимости/устаревшие зависимости (HikariCP 5.1.0, mysql-connector 8.3.0, bstats).
|
||||
8. **forbidden-apis** — запрет deprecated/запрещённых вызовов (`String.format` без Locale, `Thread.sleep`, `System.out`).
|
||||
9. **Gradle `dependency-analysis`** — лишние/недостающие зависимости (поймает остатки lolib).
|
||||
10. **Проверка дат/версий:** тест, что `plugin.yml`/`build.gradle.kts`/README/CHANGELOG версии совпадают.
|
||||
- **CI:** `quality`-job запускает всё выше (`checkstyleMain checkstyleTest pmdMain pmdTest spotbugsMain test jacocoTestCoverageVerification archTest`) и валит PR; на `main` — ещё и матрица версий.
|
||||
|
||||
Порядок: (a) настроить линтеры и **получить красный отчёт** (честный baseline) → (b) зафиксировать список нарушений по пакетам → (c) рефакторить пакет за пакетом (папка ≤ 4, файл ≤ 200) → (d) вычищать супрессии → (e) включить гейты в CI. Нельзя добавлять новые файлы в `suppressions.xml` (уже правило п.7 ARCHITECTURE.md).
|
||||
Сложность: **L** — трогает ~285 файлов; делать малыми PR по пакетам, `build` зелёный на каждом шаге.
|
||||
|
||||
> ## ✅ ПРОГРЕСС — Задача 2, шаги (a) + (b) ВЫПОЛНЕНЫ, (c) НАЧАТ (2026-10-06)
|
||||
>
|
||||
> **(a) Линтеры усилены.** Новый `config/checkstyle/checkstyle.xml` — двухуровневый гейт (ratchet):
|
||||
> - `severity="error"` (build падает): все прежние error-правила **плюс пороги подтянуты** — `MethodLength` 80→40,
|
||||
> `CyclomaticComplexity` 20→15, `NestedIfDepth` 3→2, `ParameterNumber` 7→5, `ClassDataAbstractionCoupling` 25→10,
|
||||
> `ClassFanOutComplexity` 30→12, `MagicNumber` и `FinalLocalVariable` **warning→error** (оба чистые!).
|
||||
> Добавлены: `ReturnCount` (max 5), `FinalClass`, `HiddenField`, `VisibilityModifier`, `NPathComplexity` (секция вернулась в явном виде).
|
||||
> - `severity="warning"` (build зелёный, но каждое нарушение видно в отчёте) — **бэклог дизайна**, правило:
|
||||
> **счётчик обнулился → сразу переводить в error**. Актуальный список — в ПРОГРЕСС-6 ниже
|
||||
> (на шаге 0.5: `VisibilityModifier` 163, `ReturnCount` 69, `HiddenField` 30, `IllegalCatch` 23,
|
||||
> `ClassFanOutComplexity` 17, `NPathComplexity` 12, `ParameterNumber` 8, `MethodLength` 5, `CDAC` 2).
|
||||
> - **`suppressions.xml` ОБНУЛЁН** (45 записей удалено, включая FileLength/NPath/WhitespaceAround/IllegalCatch).
|
||||
>
|
||||
> **Красный baseline (честный, до фиксов): 431 нарушение в 129 файлах.** Замеры порогов перед выбором:
|
||||
> `ReturnCount` max 3→5 (88→69), `NPathComplexity` max 30→50 (36→12) — пороги 3/30 дают мусор на легаси-кодах,
|
||||
> реальная работа начинается с 5/50.
|
||||
>
|
||||
> **(b) Список по пакетам (после фиксов, 329 нарушений / 103 файла / 60 пакетов):**
|
||||
>
|
||||
> | Пакет | ↑ | | Файл | ↑ |
|
||||
> |---|---|---|---|---|
|
||||
> | `config/options` | 53 | | `config/options/Option.java` | 45 |
|
||||
> | `config/options/section` | 38 | | `config/options/section/OptionGeneration.java` | 25 |
|
||||
> | `player/core` | 19 | | `generator/core/model/GeneratorState.java` | 15 |
|
||||
> | `generator/core/model` | 17 | | `menu/core/Menus.java` | 15 |
|
||||
> | `config/core` | 15 | | `mode/base/Modes.java` | 15 |
|
||||
> | `menu/core` | 15 | | `config/core/Config.java` | 14 |
|
||||
> | `mode/base` | 15 | | `player/core/ParkourPlayer.java` | 13 |
|
||||
> | `elytra/generator` | 12 | | `config/options/OptionGeneral.java` | 8 |
|
||||
>
|
||||
> Остальные 52 пакета — ≤ 7 нарушений; размазаны по `ReturnCount` (52 файла, ≤ 5 каждая) и `VisibilityModifier` (20 файлов).
|
||||
>
|
||||
> **(c) Исправлено 102 нарушения (431 → 329):**
|
||||
> - `FinalClass` **37** — во всех классах с единственным private-конструктором добавлен `final` (безопасно: такой класс всё равно не наследуется).
|
||||
> - `WhitespaceAround` **22** — 11 пустых блоков `{}` → `{ }` (пустые конструкторы, `new TypeToken<…>(){}`, пустой record-body, `default -> {}`).
|
||||
>
|
||||
> **Состояние на конец шага:** `./gradlew build` — **BUILD SUCCESSFUL**, checkstyle **0 error / 329 warning**, PMD **0**,
|
||||
> тесты **94 / 0 fail (1 skipped)**, jar собирается (матрица версий не перепроверялась после правок — только локальная сборка).
|
||||
> Изменено 45 файлов (TODO.md, 2 конфига линтеров, 46 исходников).
|
||||
>
|
||||
> **Осталось (порядок):**
|
||||
> 1. ✅ Тест-гейт «**в папке ≤ 4 файлов**» (JUnit, без новых зависимостей) + разбивка 6 переполненных пакетов —
|
||||
> сделано в `4263df5`, `FOLDER_DEBT = Set.of()`, ни одна папка `src/main/java` не содержит >4 файлов.
|
||||
> 2. ✅ Бэклог `config/options` обнулён (см. ПРОГРЕСС-5 ниже) → **`VisibilityModifier` ещё НЕ в error**: в пакете остались
|
||||
> только 2 `IllegalCatch` (общий бэклог п.3), а правило висит на 75 нарушениях в других пакетах.
|
||||
> 3. `IllegalCatch` 23: 3 сайта намеренные (команда/конфиг с откатом/скетчи — boundary-catch), остальные 20 — выловить конкретные типы;
|
||||
> **нужно решение владельца** по трём.
|
||||
> 4. Дальше по плану (a): PMD-категории целиком, CPD, SpotBugs, ArchUnit-слои, JaCoCo, Spotless, quality-job в CI — ✅ сделано в `b771cc1`.
|
||||
>
|
||||
> ## ✅ ПРОГРЕСС-5 (Задача 2, шаг (c): `config/options` инкапсулирован, 2026-10-06)
|
||||
> Был анти-паттерн: `Option` — фасад-зеркало на **45 `public static` полей**, которые `syncFields()` копировал
|
||||
> из 4 секций (`OptionSQL`, `OptionParticles`, `OptionGeneration`, `OptionGeneral`), и в самих секциях поля тоже
|
||||
> были `public static` (мутабельное состояние чужих пакетов = п.77/107 в миниатюре).
|
||||
> - **`Option` сокращён до `init(boolean)`** — единственная точка перезагрузки конфигов (её зовёт `ConfigLoader`);
|
||||
> зеркало, `syncFields()` и мёртвый `@Deprecated initStyles` (0 вызовов) удалены. Класс больше не дублирует секции.
|
||||
> - **Секции: `private static` поля + fluent-аксессоры** (`OptionSQL.enabled()`, `OptionGeneration.cleanupInterval()`,
|
||||
> `OptionGeneral.goBackLocation()`…), без префикса `get` — как у соседних статик-холдеров (`Materials.parse`, `Probs.random`).
|
||||
> Две точки записи `Option.SQL = false` → `OptionSQL.disable()`.
|
||||
> - **Защита от протечки состояния:** `possibleLeads()/optionsEnabled()/optionsDefaults()` отдают unmodifiable-представления
|
||||
> (null сохраняется как раньше), `goBackLocation()` — копию (`Location` мутируется при reload через `setPitch/setYaw`).
|
||||
> - `ParticleShape` вынесен из вложенного enum'а в `config/options/ParticleShape.java` (в `section/` леж бы 5-й файл — гейт «≤4»).
|
||||
> - **Удалены мёртвые данные:** 17 полей вероятностей генерации + `initGenerationProbabilities()` — не читались нигде,
|
||||
> живые веса берутся из `advanced.*` (`GeneratorProfileManager`/`GenerationProfileLoader`). Границы `min-y/max-y`
|
||||
> с проверкой `minY >= maxY` перенесены 1-в-1 в `initBounds()`. Найденное оформлено пунктами **164–166**.
|
||||
> - **63 обращения `Option.<ПОЛЕ>`** (не 127 — счёт предыдущей сессии был завышен из-за подстроки в `ParkourOption.*`)
|
||||
> переписаны в **19 файлах**; `Option`-импорт остался только в `ConfigLoader`.
|
||||
> - Попутно (предложения `CodeReview`): `ConfigLoader.validateConfigs()` проверяет **живые** пути
|
||||
> `advanced.distance.chances|height.chances|height.min|max|type` (раньше проверялась мёртвая секция `generation.normal.height.*`);
|
||||
> в `ParkourRestrictionListener.onChat` unboxing `Boolean` → `getOrDefault(CHAT, true)` как в `ParkourOption.mayPerform`.
|
||||
> - **Счётчики:** checkstyle **0 error / 329 → 240 warning**; `VisibilityModifier` **163 → 75**, `MethodLength` 5 → 4.
|
||||
> В `config/options` — **0 нарушений VisibilityModifier** (было 88), остаются 2 `IllegalCatch`.
|
||||
> `./gradlew check` зелёный: PMD 0, тесты 94/0 fail, JaCoCo/ArchUnit/Spotless ок, NullAway 48 (как в baseline;
|
||||
> ⚠️ как выяснилось на шаге 6 — это было артефактом обрезки javac на 100 предупреждениях, честные числа там же).
|
||||
> Пороги правил не снижались, `suppressions.xml` пустая. Реальных прогонов на сервере после правок не было (только `check`).
|
||||
>
|
||||
> ## ✅ ПРОГРЕСС-6 (Задача 2, шаг (c): инкапсуляция игрового состояния — `player/*` + `GeneratorState`, 2026-10-06)
|
||||
> **Checkstyle 329 → 165 warning; `VisibilityModifier` 75 → 0 и переведён в `error`.**
|
||||
> - **Кластер `player` закрыт:** `ParkourUser` (5 полей) и `ParkourPlayer` (12) → `private` + аксессоры без `get` (та же идиома,
|
||||
> что в ПРОГРЕСС-5 для `config/options`). ~46 обращений в 19 файлах переписаны.
|
||||
> - **Выключен баг тенимого `locale`:** `@Expose String locale` был объявлен и в `ParkourUser`, и в `ParkourPlayer` —
|
||||
> запись в поле и в аксессор расходилась. Осталось одно поле в родителе; на gson-2.11.0 проверено, что `@Expose`
|
||||
> наследуемого поля сериализуется, поэтому набор ключей на диске не изменился.
|
||||
> - **П.107 для `GeneratorState`:** 15 публичных полей → `private` + аксессоры/сеттеры; инкременты и сбросы оформлены
|
||||
> методами (`addGeneratedBlocks(int)`, `resetScore()`, `setScore(int)`), ~90 обращений в 25 файлах.
|
||||
> Публичные `ParkourGenerator.session/island/profile/state` — как были (остаток п.107).
|
||||
> - **SRP: настройки игрока вынесены в `player/data/PlayerSettings`** (11 полей + аксессоры). `ParkourPlayer` —
|
||||
> 194 → 93 строки, засчитываемых методов 20 → 9. Это и починило свежесломанное нарушение PMD `TooManyMethods` (гейт 0 нарушений
|
||||
> был испорчен моим же рефакторингом) — декомпозицией, а НЕ ослаблением порога и НЕ переименованием под name-based
|
||||
> освобождение правила (`getX()` в проекте не используется: 0 объявлений в `src/main`).
|
||||
> - **DRY по настройкам:** троекратное повторение санитизации «legacy-locale» → `PlayerSettingsManager.sanitizeLocale()`
|
||||
> (фолбэк берётся из конфига, а не захардкожен `"en"`); байт-в-байт одинаковая сборка 12-ключевого map в
|
||||
> `StorageDisk.readPlayer` и `SQLDataMapper.serializeSettings` → `toSettingsMap()`; удалены мёртвый `getColumnMappings()`,
|
||||
> `PLAYER_COLUMNS` и дубль `OptionContainer` (п.106); реестр-фасады `ParkourPlayer.isPlayer/getPlayer/getPlayers`
|
||||
> переехали в `UserRegistry` (22 файла);
|
||||
> дубли `parseIntSafe`/`parseDoubleSafe` схлопнуты в `numericOrFallback`.
|
||||
> - **Закрыт п.30** (SQL не сохранял настройки) и **формат disk-файла игрока пересобран сознательно:** раньше Gson писал
|
||||
> `ParkourPlayer` по `@Expose`-полям, а читал его через Unsafe-аллокацию «полупустого» объекта, чей map потом переливали
|
||||
> в живого игрока. Теперь `StorageDisk` пишет и читает тот же канонический `Map<String,Object>`, что и JSON-колонка SQL —
|
||||
> один словарь на оба бэкенда, `@Expose` из доменных классов убран совсем. Старые файлы остаются читаемыми: 3 ключа,
|
||||
> которые совпадали с именами полей (`particles`/`useSpecialBlocks`/`showFallMessage`), нормализует
|
||||
> `StorageDisk.normalizeLegacyKeys()`. ⚠️ Живых файлов игроков в `run/plugins/LoParkour/players/` нет — миграция
|
||||
> проверена кодом и тестами, не реальным апгрейдом.
|
||||
> - **Артефакт замера предупреждений:** в `build.gradle.kts` (JavaCompile) добавлен `-Xmaxwarns 100000`, потому что javac по умолчанию
|
||||
> обрывает список предупреждений на 100 — отсюда «NullAway 48» в ПРОГРЕСС-5. Честные замеры через `git stash`:
|
||||
> baseline HEAD **NullAway 165 / Error Prone 289**, сейчас **NullAway 164 / EP 265** — регресса нет.
|
||||
> - **Счётчики:** checkstyle **0 error / 165 warning** (бэклог: `ReturnCount` 69, `HiddenField` 30, `IllegalCatch` 23,
|
||||
> `ClassFanOutComplexity` 17, `NPathComplexity` 12, `ParameterNumber` 8, `MethodLength` 4, `CDAC` 2).
|
||||
> В ноль обнулены и переведены в `error`: `VisibilityModifier`, `EmptyLineSeparator`, `MissingDeprecated`.
|
||||
> PMD **0** (жёсткий гейт), `./gradlew check` зелёный, тесты **94 / 0 fail (1 skipped)**. Пороги правил не снижались,
|
||||
> `suppressions.xml` пустая. Реальных прогонов на сервере не было (только `check`).
|
||||
> - **Найдено по пути и оформлено отдельными пунктами (молча не чинилось):** **167** (elytra-под-режимы недостижимы —
|
||||
> `getMode()` не переопределён) и **168** (`ParkourUser.chatType` не записывается нигде).
|
||||
>
|
||||
> ## ✅ ПРОГРЕСС-7 (Задача 2, шаг (c): `HiddenField` обнулён + директива владельца про линтеры, 2026-10-06)
|
||||
> **Checkstyle 165 → 135 warning; `HiddenField` 30 → 0 и переведён в `error`.**
|
||||
> - **Директива владельца (зафиксирована, действует дальше):** нарушения линтеров **чинить**, а не **глушить** —
|
||||
> пороги правил не поднимать, `suppressions.xml` не наполнять, под name-based освобождения не подстраиваться.
|
||||
> В `error` правило переводится только после того, как счётчик реально обнулён правками.
|
||||
> - **`HiddenField` 30 → 0** — тенящие параметры/локалы переименованы (поля не трогали): `Config` (12 методов-делегата,
|
||||
> параметр `path` → `key`), `ObstacleGenerator` (внешнее поле `radius` → `obstacleRadius` — одним переименованием сняли
|
||||
> 7 теней в enum-реализациях `getPoints(center, radius)`), `GhostService.setReplaying(uuid, active)`,
|
||||
> `Leaderboard.sort(order)`, `PagedMenu.addToDisplay(menuItems)`, `Reward` (локал `string` → `command`),
|
||||
> `ParticleData` (fluent-сеттеры принимают `value`), `World.create()` (локал `world` → `existingWorld`, а
|
||||
> `World.world = world` превратился в обычное присваивание поля).
|
||||
> - **`ReturnCount` 69 — решено оформить отдельным пунктом 169:** все 69 нарушений приходятся на половину правила
|
||||
> про void (`maxForVoid` по умолчанию = 1, то есть запрещена любая guard-клауза `if (x) { return; }`);
|
||||
> для value-методов при `max=5` нарушений **0**. Поднимать `maxForVoid` я предлагал, владелец отказал — значит
|
||||
> 69 void-методов переструктурируются по-настоящему (early-return → `if`-блок или выделение helper'а),
|
||||
> с оглядкой на `NestedIfDepth` (error, max=2) и `NPathComplexity`.
|
||||
> - **`IllegalCatch` 23** — сузить типы там, где конкретика реальна (IO/NumberFormat/SQL/ClassNotFound),
|
||||
> а на истинных границах заменить `catch (Throwable)` → `catch (RuntimeException)` (это не «приглушение», а починка:
|
||||
> `Throwable` глотает `Error`-ы — OOM, StackOverflow). Диспетчер команд, `onEnable/onDisable`, загрузчики конфигов
|
||||
> и схематчей, session-state — пограничные точки, их фиксируем отдельно (п.170).
|
||||
> - **Авария и восстановление:** после частичного отката правок в IDE (отклонённые diffs) рабочий код был сломан:
|
||||
> `player/data/PlayerSettings.java` удалился целиком, `ParkourPlayer` вернулся к 11 `@Expose`-полям при уже
|
||||
> переписанных вызовах (`settings()` ссылался на несуществующее поле, `updateGeneratorSettings` пропал),
|
||||
> в `GeneratorCleanup` потерялся импорт `@Nullable` (2 ошибки компиляции), `checkstyle.xml` откатился к
|
||||
> HEAD-версии и **потерял все четыре флипа** (`VisibilityModifier`, `EmptyLineSeparator`, `MissingDeprecated`,
|
||||
> `HiddenField`), `PagedMenu`/`GhostService` вернулись к тенящим параметрам, а с `ParkourUser` слез лишний `@Expose`
|
||||
> (после перехода диска на map он мёртвый). Всё восстановлено и перепроверено:
|
||||
> `./gradlew check` — **BUILD SUCCESSFUL**, checkstyle **0 error / 135 warning** (test-отчёт пуст), PMD **0**,
|
||||
> тесты **94 / 0 fail (1 skipped)**, `suppressions.xml` пустая. Реальных прогонов на сервере по-прежнему не было.
|
||||
> Урок на будущее: после любой отменённой пачки правок сверять `git status` + полный `check`, а не только счётчики.
|
||||
> - **Остаток бэклога (135):** `ReturnCount` 69, `IllegalCatch` 23, `ClassFanOutComplexity` 17, `NPathComplexity` 12,
|
||||
> `ParameterNumber` 8, `MethodLength` 4, `ClassDataAbstractionCoupling` 2.
|
||||
>
|
||||
> ## ✅ ПРОГРЕСС-8 (Задача 2: починены реальные баги 167 и 168, 2026-10-06)
|
||||
> По решению владельца вместо механической зачистки варнингов взяты два мёртвых куска логики.
|
||||
> - **167 — elytra-под-режимы научились представляться.** `ElytraGenerator` больше не возвращает хардкод
|
||||
> `Modes.elytra()`: режим передаётся в конструктор (`private final Mode mode`, канонический конструктор
|
||||
> `(session, pointType, mode)` + two convenience-перегрузки), `getMode()` отдаёт его. Под-генераторы
|
||||
> объявляют свою идентичность одной строкой `super(session, Modes.speedDemon())` — вместо пяти копий `getMode()`
|
||||
> (у `ObstacleGenerator` не хватило бы строк: лимит FileLength = 200, а файл — 199).
|
||||
> Попутно удалено дублирование: `ObstacleGenerator` заново читал `elytra.radius` и держал свой `DEFAULT_RADIUS = 3` —
|
||||
> теперь общий `radius()` из родителя (199 → 194 строки).
|
||||
> - **Что реально поменялось для игрока (следствие, а не побочка):**
|
||||
> 1) guard в `create()` стал достижим → повторная `/parkour speeddemon` в том же режиме больше не пересоздаёт сессию;
|
||||
> 2) обратная сторона — `/parkour elytra` внутри под-режима раньше **не работал** (под-генератор выдавал себя за
|
||||
> `ElytraMode`, `instanceof ElytraMode` был истинен и делал early-return), теперь переключает;
|
||||
> 3) очки, rewards (`%mode:`-префикс в `rewards-v2.yml`), голограммы и PAPI теперь попадают в **свой** лидерборд
|
||||
> под-режима, а не в общий `elytra`. ⚠️ Старые записи в `leaderboards/elytra.json`/SQL не теряются, но
|
||||
> пер-режимные доски начинаются с нуля; реальных прогонов на сервере не было (только `check`).
|
||||
> - **168 — переключатель области чата подключён к меню.** Фича была спроектирована, но не собрана: блоки
|
||||
> `settings.chat` (material/name/lore/values + formats) есть и в `en.yml`, и в `ru.yml`, `ParkourOption.CHAT` зарегистрирован,
|
||||
> `ParkourRestrictionListener.onChat` уже умеет маршрутизировать `LOBBY_ONLY`/`PLAYERS_ONLY`, но кнопка не
|
||||
> создавалась, сеттера не было, и `chatType` навечно оставался `PUBLIC`.
|
||||
> Сделано: `Session.ChatType.next()` (цикл по порядку объявления = порядку `settings.chat.values`),
|
||||
> `ParkourUser.setChatType(...)`, кнопка в `SettingsMenu` (слот 15, gate `ParkourOption.CHAT.mayPerform`) по образцу
|
||||
> `LobbyMenu.visibilityItem` — клик меняет область и перерисовывает меню. Новатье — `ChatTypeTest` (2 теста).
|
||||
> - **Счётчики:** checkstyle **0 error / 135 warning** (тот же бэклог, что в ПРОГРЕСС-7 — баги чинились без
|
||||
> новых варнингов), PMD **0**, тесты **96 / 0 fail (1 skipped)**, `./gradlew check` зелёный.
|
||||
|
||||
---
|
||||
|
||||
## 🗺 План: поддержка версий 1.19.2 → 26.3 (Java 21 + Java 25), смена команды
|
||||
|
||||
> Задано владельцем 2026-10-06. Сейчас: `build.gradle.kts` параметризован (`-PmcVersion/-PapiCoordinate/-PjavaRelease/-PapiVersion`),
|
||||
> CI-матрица собирает 1.19.2 / 1.20.1 / 1.21 / 1.21.11 (Java 21) и 26.1.2 / 26.2 (Java 25, `release: 25`). **Только сборка — запуск на серверах не проверяется.**
|
||||
|
||||
- **139. [P1] Целевой диапазон: Paper/Spigot 1.19.2 … 26.3 и Java 21 + Java 25.** MC 26.x требует Java 25 на сервере, поэтому плагин должен работать на JDK 21 *и* 25.
|
||||
Ориентир — IP-Reborn: один jar с байткодом Java 21 (`release 21`), собранный на JDK 25, запускается на Java 21 и 25 (`ref/IP-Reborn/README.md`, раздел Building).
|
||||
→ Не выпускать отдельные jar под `release 25` (сломают 1.21.x на Java 21); оставить `release 21` для всех. Проверить, что `lolib-3.0.0.jar` (байткод 21) и shadow-релокации (ASM) читают class-version 65 на JDK 25.
|
||||
→ Если нужен запуск 1.19.2–1.20.4 на Java 17 — отдельное решение: lolib и наш код пересобрать на `release 17` (иначе нижняя граница фактически Java 21).
|
||||
- **140. [P1] Добавить 26.3 в CI-матрицу и в README.** IP-Reborn проверяет `26.3.build.142-beta`; у нас только 26.1.2/26.2. Обновить бейджи/раздел «Supported servers» (сейчас «Paper 1.19.2+»).
|
||||
- **141. [P1] Запуск, а не только сборка.** CI собирает jar, но не стартует сервер. → smoke-тест: поднять Paper на каждой версии (`run-paper` уже подключён), проверить, что плагин включается без исключений. Начать с 1.19.2, 1.21.11, 26.3.
|
||||
- **142. [P1] Убрать API, которых нет в старых/новых версиях.** Известно: `GameRule.*` и `Particle.*` разные (см. п.129: `Particle.FIREWORK` нет в 1.20.4), `Material.STONE_SLAB` (п.100), `BukkitRunnable.runTaskTimerAsynchronously` (п.21), `registerNewObjective(String,String,String)`. В 5.4.0-paper26 IP-Reborn заменял «removed Paper and Adventure API calls» — просмотреть их список как чек-лист.
|
||||
→ Вынести версионно-зависимое в один слой `compat/` (определение версии по `Bukkit.getVersion()` — как `ref/ajParkour/.../utils/VersionSupport.java`; для 26+ учесть смену схемы версий: major ≥ 26).
|
||||
- **143. [P1] Folia (п.21, issue #1).** `World.create()` уже не вызывает `createWorld` для загруженного мира (коммит «reuse already loaded world…»). Остаётся: `folia-plugin.yml`/`folia-supported: true`, region-scheduler вместо BukkitRunnable, настройки мира из global region. IP-Reborn сознательно *не* поддерживает Folia — честнее убрать бейдж, если не успеваем.
|
||||
- **144. [P1] Заменить команду `/lp` — конфликт с LuckPerms.** ✅ **ВЫПОЛНЕНО (2026-10-10, решение владельца: `lp`→`lpk`, `parkour` оставить).** `plugin.yml`: `aliases: [parkour, lpk]`; `/lp` → `/lpk` в `README.md`, `docs/SCHEMATICS.md`, `src/main/resources/docs/SCHEMATICS.md`, `schematics.yml`, `CHANGELOG.md`, javadoc `ReplayCommandExecutor`. Права (`loparkour.*`) не менялись.
|
||||
→ Убрать `lp` (и, вероятно, `parkour`) из `aliases`; оставить `loparkour` + короткий алиас без конфликтов (предложение: **`lpk`**; *имя ждёт решения владельца*).
|
||||
→ Править: `src/main/resources/plugin.yml`; все `/lp …` в `README.md` (15), `docs/SCHEMATICS.md` (16), `src/main/resources/docs/SCHEMATICS.md`, `schematics/schematics.yml`, `docs/ARCHITECTURE.md`, локали, тексты сообщений/usage; `ReplayCommandExecutor` (javadoc `/lp replay`).
|
||||
→ Права (`loparkour.*`) не менять. Добавить в CHANGELOG пометку о breaking-изменении алиаса; рассмотреть deprecation-сообщение при вызове старого алиаса, если он останется.
|
||||
|
||||
## 📥 Что взять из `ref/` (IP-Reborn, ajParkour, A5H73Y Parkour)
|
||||
|
||||
> Берём только **идеи**: всё реализуем своим кодом, чужой код в репозиторий не копируем (поэтому атрибуции/NOTICE не нужны).
|
||||
> Список — кандидаты по структуре и README; каждый пункт перед реализацией проверить по коду.
|
||||
|
||||
### IP-Reborn (`ref/IP-Reborn`)
|
||||
|
||||
- **145. Native void-генератор** (`world/`, в 6.0 убрали зависимость от VoidGen/PaperLib/vilib). У нас внешний `dev.lolib.worlds.VoidGenerator` и `softdepend: VoidGen` — закрывает п.112.
|
||||
- **146. Паритет режимов** (`ipp/mode/single`, `ipp/mode/multi`, `ipp/mode/lobby`): Practice, Hourglass, SuperJump, TimeTrial, WaveTrial, Speed, TeamSurvival, Lobby/LobbySelection — основа для п.110/111 (invite-лобби).
|
||||
- **147. `HologramManager`/`TrackedHologram`/`HologramConfig`** (`hologram/`) — заменить хрупкий `HoloHook` (п.87).
|
||||
- **148. `LegacyDataMigrator` + `MIGRATION.md`** — шаблон безопасной миграции данных старых версий без удаления старых папок; полезно для смены команды/структуры конфигов.
|
||||
- **149. Жизненный цикл интеграций** (`integration/IntegrationLoader`): снятие PAPI-expansion и хуков при reload/disable; по одному `HandlerList` на каждое кастомное событие — проверить наши `api/event/*`.
|
||||
- **150. Документация-сайт** (`docs/guide`, `docs/index.md`, zh-перевод) — шаблон для п.114.
|
||||
- **151. Правила сборки/CI под 26.x** (`pom.xml`, `CHANGES.md` 5.4.0-paper26/6.0.x) — как держат один jar на 1.21.11…26.3.
|
||||
|
||||
### A5H73Y Parkour (`ref/Parkour`, MIT)
|
||||
|
||||
- **152. Versioned upgrade системы** (`upgrade/major/*`) — пошаговые миграции конфигов/данных по версиям; решение для п.26 (ConfigUpdater) и п.62 (SQL-мигратор).
|
||||
- **153. `PluginBackupUtil`** — автобэкап конфигов/данных перед апгрейдом.
|
||||
- **154. Реестр команд** (`commands/CommandUsage`, `ParkourAutoTabCompleter`, `utility/parkourCommands.json`): описание команд в данных → одновременно help, tab-complete и права; убрало бы ручной `CommandTabCompleter`.
|
||||
- **155. Чекпоинты / киты / челленджи / звуки** (`type/checkpoint`, `type/kit`, `type/challenge`, `type/sounds`) — идеи фич для карт; `TaskCooldowns`, `SignUtils` (таблички) — мелкие утилиты.
|
||||
- **156. Conversation-API для настройки через чат** (`conversation/*`) — альтернатива меню для ввода значений (приз, режим).
|
||||
- **157. Плагин-обёртки** (`plugin/PluginWrapper`, `EconomyApi`, `PermissionVault`, `BountifulApi`, `PlaceholderApi`) — единый паттерн ленивого подключения soft-зависимостей; решает п.89 (VaultHook кэширует навсегда).
|
||||
- **158. `parkourPlaceholders.json`** — список плейсхолдеров данными; идея для п.120.
|
||||
|
||||
### ajParkour (`ref/ajParkour`, GPL-3.0)
|
||||
|
||||
- **159. `VersionSupport`** (версия по `Bukkit.getVersion()`, учёт major ≥ 26, action bar через spigot API) — готовая основа для п.142.
|
||||
- **160. Портал/зона** (`Portal`, `AreaStorage`, `game/PkArea`, `WorldeditSelector`) — вход в паркур через зону/портал в мире, выбор области WorldEdit.
|
||||
- **161. `TopManager`/`TopEntry`** — компактный top-10 для голограмм/PAPI.
|
||||
- **162. `Updater`** — проверка новой версии (opt-in, без блокировки main thread).
|
||||
- **163. `jumps.yml` + `Difficulty`** — выносить параметры прыжков в данные (закрывает мёртвый `jump-validation`/`jump-types`, п.38).
|
||||
|
||||
---
|
||||
|
||||
## Итог по аудиту
|
||||
|
||||
- Найдено: **~125 новых пунктов** (P1: 18, P2: 21, P3: 28, P4: 14, тесты: 2, конкуренты: 13, наследие форка: 5, новые режимы: 10, зачистка варнингов: 7).
|
||||
|
|
|
|||
129
build.gradle.kts
129
build.gradle.kts
|
|
@ -1,3 +1,4 @@
|
|||
import net.ltgt.gradle.errorprone.errorprone
|
||||
import java.io.File
|
||||
import java.net.URI
|
||||
import java.util.zip.ZipFile
|
||||
|
|
@ -15,11 +16,18 @@ buildscript {
|
|||
}
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("java-library")
|
||||
id("com.gradleup.shadow") version("9.6.1")
|
||||
id("xyz.jpenilla.run-paper") version("3.0.2")
|
||||
checkstyle
|
||||
pmd
|
||||
jacoco
|
||||
id("net.ltgt.errorprone") version("4.3.0")
|
||||
id("com.diffplug.spotless") version("7.0.4")
|
||||
id("com.github.spotbugs") version("6.1.13")
|
||||
id("de.thetaphi.forbiddenapis") version("3.9")
|
||||
id("com.autonomousapps.dependency-analysis") version("2.19.0")
|
||||
id("org.owasp.dependencycheck") version("12.1.3")
|
||||
}
|
||||
|
||||
group = "dev.loki"
|
||||
|
|
@ -144,6 +152,8 @@ val remapNms by tasks.registering {
|
|||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach { dependsOn(remapNms) }
|
||||
// Analysis tasks (dependency-analysis, spotbugs, ...) read the remapped NMS jars too.
|
||||
tasks.matching { it.name != "remapNms" && it.name != "clean" }.configureEach { mustRunAfter(remapNms) }
|
||||
|
||||
// Resolve the org.bukkit:bukkit capability conflict that newer paper-api artifacts
|
||||
// introduce (they both bundle the bukkit classes and declare the capability).
|
||||
|
|
@ -182,9 +192,6 @@ dependencies {
|
|||
compileOnly("net.kyori:adventure-api:4.14.0")
|
||||
compileOnly("net.kyori:adventure-text-minimessage:4.14.0")
|
||||
|
||||
// LoLib Core
|
||||
implementation(files("libs/lolib-3.0.0.jar"))
|
||||
|
||||
// Shaded dependencies
|
||||
implementation("io.papermc:paperlib:1.0.7")
|
||||
implementation("com.google.code.gson:gson:2.11.0")
|
||||
|
|
@ -204,11 +211,16 @@ dependencies {
|
|||
compileOnly("me.filoghost.holographicdisplays:holographicdisplays-api:3.0.0-SNAPSHOT")
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
|
||||
// Error Prone + NullAway (compile-time bug/null-safety checks)
|
||||
errorprone("com.google.errorprone:error_prone_core:2.41.0")
|
||||
errorprone("com.uber.nullaway:nullaway:0.12.10")
|
||||
|
||||
// Annotations
|
||||
compileOnly("org.jetbrains:annotations:24.1.0")
|
||||
|
||||
// Testing
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.0-M1")
|
||||
testImplementation("com.tngtech.archunit:archunit-junit5:1.4.1")
|
||||
testImplementation("org.mockito:mockito-core:5.10.0")
|
||||
testImplementation("org.mockito:mockito-junit-jupiter:5.10.0")
|
||||
testImplementation("org.spigotmc:spigot-api:1.20.4-R0.1-SNAPSHOT")
|
||||
|
|
@ -222,18 +234,10 @@ tasks.shadowJar {
|
|||
archiveFileName.set("LoParkour-${project.version}-mc${mcVersion}.jar")
|
||||
|
||||
// Relocate shaded dependencies
|
||||
relocate("dev.lolib", "dev.loki.loparkour.lib.lolib")
|
||||
relocate("io.papermc.lib", "dev.loki.loparkour.lib.paperlib")
|
||||
relocate("com.google.gson", "dev.loki.loparkour.lib.gson")
|
||||
relocate("org.bstats", "dev.loki.loparkour.lib.bstats")
|
||||
relocate("org.apache.commons.math3", "dev.loki.loparkour.lib.commonsmath3")
|
||||
|
||||
// Don't minimize - causes issues with Caffeine's dynamically generated classes
|
||||
// minimize {
|
||||
// exclude(dependency("com.zaxxer:HikariCP:.*"))
|
||||
// exclude(dependency("com.mysql:mysql-connector-j:.*"))
|
||||
// exclude(dependency(files("libs/lolib-3.0.0.jar")))
|
||||
// }
|
||||
}
|
||||
|
||||
tasks.named("build") {
|
||||
|
|
@ -257,6 +261,18 @@ tasks.withType<Test> {
|
|||
tasks.withType<JavaCompile> {
|
||||
options.encoding = "UTF-8"
|
||||
options.release = javaRelease
|
||||
options.compilerArgs.addAll(listOf("-Xmaxwarns", "100000"))
|
||||
options.errorprone {
|
||||
disableWarningsInGeneratedCode = true
|
||||
// NullAway: only code annotated @NullMarked-style packages is checked once adopted;
|
||||
// start as warnings so the baseline is visible but does not block.
|
||||
check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.WARN)
|
||||
option("NullAway:AnnotatedPackages", "dev.loki.loparkour")
|
||||
option("NullAway:ExcludedFieldAnnotations", "org.jetbrains.annotations.Nullable")
|
||||
}
|
||||
if (name == "compileTestJava") {
|
||||
options.errorprone.isEnabled.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Javadoc> {
|
||||
|
|
@ -310,5 +326,94 @@ tasks.withType<Pmd>().configureEach {
|
|||
exclude("**/build/generated/**")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extra quality gates (see TODO.md, task 2). Existing debt is recorded, new
|
||||
// violations fail the build; tighten thresholds as the refactor progresses.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
jacoco {
|
||||
toolVersion = "0.8.13"
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
finalizedBy(tasks.jacocoTestReport)
|
||||
}
|
||||
|
||||
tasks.jacocoTestReport {
|
||||
dependsOn(tasks.test)
|
||||
reports {
|
||||
xml.required.set(true)
|
||||
html.required.set(true)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.jacocoTestCoverageVerification {
|
||||
violationRules {
|
||||
rule {
|
||||
limit {
|
||||
counter = "LINE"
|
||||
minimum = "0.05".toBigDecimal() // baseline; raise toward 0.5 (core 0.7)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.check {
|
||||
dependsOn(tasks.jacocoTestCoverageVerification, "cpdCheck")
|
||||
}
|
||||
|
||||
spotless {
|
||||
java {
|
||||
target("src/**/*.java")
|
||||
removeUnusedImports()
|
||||
trimTrailingWhitespace()
|
||||
endWithNewline()
|
||||
}
|
||||
}
|
||||
|
||||
spotbugs {
|
||||
toolVersion = "4.9.3"
|
||||
effort = com.github.spotbugs.snom.Effort.MAX
|
||||
reportLevel = com.github.spotbugs.snom.Confidence.MEDIUM
|
||||
ignoreFailures = true // report-only until the baseline is triaged
|
||||
}
|
||||
|
||||
tasks.withType<com.github.spotbugs.snom.SpotBugsTask>().configureEach {
|
||||
reports.create("html") { required = true }
|
||||
}
|
||||
|
||||
forbiddenApis {
|
||||
bundledSignatures = setOf("jdk-unsafe-21", "jdk-deprecated-21", "jdk-system-out", "jdk-non-portable")
|
||||
ignoreFailures = true // report-only until the baseline is triaged
|
||||
}
|
||||
|
||||
// Copy/paste detector (DRY). The de.aaschmid.cpd plugin does not support PMD 7, so run PMD's CPD directly.
|
||||
val cpdTool: Configuration by configurations.creating
|
||||
dependencies {
|
||||
cpdTool("net.sourceforge.pmd:pmd-cli:7.0.0")
|
||||
cpdTool("net.sourceforge.pmd:pmd-java:7.0.0")
|
||||
}
|
||||
|
||||
val cpdCheck by tasks.registering(JavaExec::class) {
|
||||
group = "verification"
|
||||
description = "Finds duplicated code (min 100 tokens). Report-only until duplicates are triaged."
|
||||
classpath = cpdTool
|
||||
mainClass.set("net.sourceforge.pmd.cli.PmdCli")
|
||||
args("cpd", "--minimum-tokens", "100", "--language", "java", "--dir", "src/main/java",
|
||||
"--format", "text")
|
||||
isIgnoreExitValue = true // exit code 4 = duplicates found
|
||||
doFirst {
|
||||
val dir = layout.buildDirectory.dir("reports/cpd").get().asFile
|
||||
dir.mkdirs()
|
||||
standardOutput = File(dir, "cpd.txt").outputStream()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyCheck {
|
||||
// Run explicitly: ./gradlew dependencyCheckAnalyze (set NVD_API_KEY for speed).
|
||||
failBuildOnCVSS = 7.0f
|
||||
nvd.apiKey = System.getenv("NVD_API_KEY")
|
||||
}
|
||||
|
||||
// Default task
|
||||
defaultTasks("clean", "build")
|
||||
|
|
|
|||
|
|
@ -3,6 +3,24 @@
|
|||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!--
|
||||
Two-tier gate (ratchet):
|
||||
|
||||
* severity="error" — rules that are at ZERO violations right now. The build
|
||||
fails if any of them fires. Strict thresholds live here; they were raised
|
||||
from the pre-Task-2 values (MethodLength 80->40, CyclomaticComplexity
|
||||
20->15, NestedIfDepth 3->2, ParameterNumber 7->5, MagicNumber and
|
||||
FinalLocalVariable promoted from warning to error).
|
||||
|
||||
* severity="warning" — the design-debt backlog: rules that are ON and report
|
||||
every violation in build/reports/checkstyle, but do not fail the build
|
||||
while their backlog is non-zero. Counts are tracked in TODO.md
|
||||
(Задача 2, блок «красный baseline»). When a rule reaches zero violations
|
||||
it MUST be flipped to severity="error" in this file.
|
||||
|
||||
suppressions.xml is intentionally empty — never add entries back; fix the
|
||||
code or, for a documented intentional pattern, agree on it with the owner.
|
||||
-->
|
||||
<module name="Checker">
|
||||
<property name="charset" value="UTF-8"/>
|
||||
<property name="severity" value="error"/>
|
||||
|
|
@ -17,11 +35,8 @@
|
|||
<property name="max" value="200"/>
|
||||
</module>
|
||||
|
||||
<!-- Legacy files that still exceed 200 lines. Remove entries as they get
|
||||
decomposed; new files must already comply and must NOT be added here. -->
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file"
|
||||
value="${config_loc}/suppressions.xml"/>
|
||||
<property name="file" value="${config_loc}/suppressions.xml"/>
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
|
|
@ -37,16 +52,23 @@
|
|||
<module name="SuppressWarningsHolder"/>
|
||||
|
||||
<module name="MethodLength">
|
||||
<property name="max" value="80"/>
|
||||
<property name="max" value="40"/>
|
||||
<property name="countEmpty" value="false"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
|
||||
<module name="CyclomaticComplexity">
|
||||
<property name="max" value="20"/>
|
||||
<property name="max" value="15"/>
|
||||
</module>
|
||||
|
||||
<module name="ParameterNumber">
|
||||
<property name="max" value="7"/>
|
||||
<property name="max" value="5"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
|
||||
<module name="ReturnCount">
|
||||
<property name="max" value="5"/>
|
||||
<property name="severity" value="error"/>
|
||||
</module>
|
||||
|
||||
<module name="AvoidStarImport"/>
|
||||
|
|
@ -86,6 +108,18 @@
|
|||
<module name="ArrayTypeStyle"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="OuterTypeFilename"/>
|
||||
<module name="FinalClass"/>
|
||||
|
||||
<module name="HiddenField">
|
||||
<property name="ignoreConstructorParameter" value="true"/>
|
||||
<property name="ignoreSetter" value="true"/>
|
||||
<property name="severity" value="error"/>
|
||||
</module>
|
||||
|
||||
<module name="VisibilityModifier">
|
||||
<property name="allowPublicFinalFields" value="true"/>
|
||||
<property name="severity" value="error"/>
|
||||
</module>
|
||||
|
||||
<module name="EmptyBlock">
|
||||
<property name="option" value="text"/>
|
||||
|
|
@ -102,9 +136,10 @@
|
|||
<!-- ============ Complexity and size ============ -->
|
||||
<module name="NPathComplexity">
|
||||
<property name="max" value="50"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="NestedIfDepth">
|
||||
<property name="max" value="3"/>
|
||||
<property name="max" value="2"/>
|
||||
</module>
|
||||
<module name="NestedForDepth">
|
||||
<property name="max" value="2"/>
|
||||
|
|
@ -113,11 +148,11 @@
|
|||
<property name="max" value="2"/>
|
||||
</module>
|
||||
<module name="ClassDataAbstractionCoupling">
|
||||
<property name="max" value="25"/>
|
||||
<property name="max" value="10"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="ClassFanOutComplexity">
|
||||
<property name="max" value="30"/>
|
||||
<property name="max" value="12"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
|
||||
|
|
@ -126,7 +161,6 @@
|
|||
<property name="ignoreNumbers" value="-1, 0, 1, 2"/>
|
||||
<property name="ignoreHashCodeMethod" value="true"/>
|
||||
<property name="ignoreAnnotation" value="true"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="Regexp">
|
||||
<property name="format" value="System\.(out|err)\.print"/>
|
||||
|
|
@ -142,23 +176,20 @@
|
|||
<module name="IllegalCatch">
|
||||
<property name="illegalClassNames"
|
||||
value="java.lang.Exception, java.lang.Throwable, java.lang.RuntimeException"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
|
||||
<!-- ============ Style and maintainability ============ -->
|
||||
<module name="EmptyLineSeparator">
|
||||
<property name="allowNoEmptyLineBetweenFields" value="true"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="WhitespaceAround"/>
|
||||
<module name="WhitespaceAfter"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="MissingOverride"/>
|
||||
<module name="MissingDeprecated">
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
<module name="MissingDeprecated"/>
|
||||
<module name="FinalLocalVariable">
|
||||
<property name="validateEnhancedForLoopVariable" value="true"/>
|
||||
<property name="severity" value="warning"/>
|
||||
</module>
|
||||
</module>
|
||||
</module>
|
||||
|
|
|
|||
|
|
@ -1,88 +1,3 @@
|
|||
<?xml version="1.0"?>
|
||||
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||
|
||||
<!--
|
||||
Suppressions for legacy files that violate the stricter rules:
|
||||
- FileLength (200-line limit),
|
||||
- IllegalCatch (no catch of Exception/Throwable/RuntimeException),
|
||||
- NPathComplexity (<= 50) and WhitespaceAround.
|
||||
|
||||
Legacy files are scheduled for decomposition / cleanup (see docs/ARCHITECTURE.md).
|
||||
Remove each entry once the file complies on its own.
|
||||
|
||||
New files must already comply with ALL rules and must NOT be added here —
|
||||
EXCEPT two documented defensive boundary catches (see below).
|
||||
|
||||
NOTE: the noisy MagicNumber/FinalLocalVariable rules are kept at
|
||||
severity="warning", so they do not need suppressions.
|
||||
-->
|
||||
|
||||
<suppressions>
|
||||
<!-- ===== FileLength (200 lines) ===== -->
|
||||
|
||||
<!--
|
||||
===== Intentional defensive boundary catches =====
|
||||
These are NOT swallowing exceptions:
|
||||
- LoParkourCommand.onCommand: catches Throwable at the command entry point,
|
||||
logs the full stack trace and notifies the player (never silent).
|
||||
- ConfigUpdater: catches Exception to roll back to the backup copy and
|
||||
rethrows — transactional semantics, the exception is not swallowed.
|
||||
Do not remove without a review of the intended behavior.
|
||||
-->
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]command[\\/]core[\\/]LoParkourCommand\.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]config[\\/]core[\\/]merge[\\/]ConfigUpdater\.java"/>
|
||||
|
||||
<!--
|
||||
SchematicManager: catches RuntimeException so a corrupted/truncated schematic
|
||||
(WorldEdit/Bukkit throw unchecked exceptions) is skipped instead of breaking
|
||||
plugin enable. Not swallowing — the failure is logged at SEVERE with the cause.
|
||||
-->
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]schematic[\\/]core[\\/]SchematicManager\.java"/>
|
||||
|
||||
<!-- ===== IllegalCatch / NPathComplexity / WhitespaceAround (legacy debt) ===== -->
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]LoParkour.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]adaptive[\\/]bootstrap[\\/]AdaptiveServices.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]bootstrap[\\/]PluginBootstrap.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]command[\\/]player[\\/]PlayerCommandHandler.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]config[\\/]core[\\/]ConfigLoader.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]config[\\/]locale[\\/]LocaleCache.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]config[\\/]locale[\\/]LocaleLoader.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]config[\\/]options[\\/]OptionGeneral.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]generator[\\/]core[\\/]coordinator[\\/]GeneratorProfileManager.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]generator[\\/]core[\\/]model[\\/]GeneratorState.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]generator[\\/]effect[\\/]EffectManager.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]generator[\\/]jump[\\/]calculation[\\/]JumpDirector.java"/>
|
||||
<suppress checks="IllegalCatch|NPathComplexity" files=".*[\\/]generator[\\/]jump[\\/]calculation[\\/]JumpValidator.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]generator[\\/]jump[\\/]placement[\\/]BlockSelector.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]generator[\\/]lifecycle[\\/]loop[\\/]LifecycleEventManager.java"/>
|
||||
<suppress checks="NPathComplexity|WhitespaceAround" files=".*[\\/]generator[\\/]lifecycle[\\/]player[\\/]GeneratorCleanup.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]hook[\\/]floodgate[\\/]FloodgateHook.java"/>
|
||||
<suppress checks="IllegalCatch|NPathComplexity|WhitespaceAround" files=".*[\\/]hook[\\/]holo[\\/]HoloHook.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]hook[\\/]vault[\\/]VaultHook.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]leaderboard[\\/]core[\\/]LeaderboardSorter.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]listener[\\/]gameplay[\\/]ParkourRestrictionListener.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]listener[\\/]schematic[\\/]SchematicWandListener.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]community[\\/]LeaderboardsMenu.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]community[\\/]SingleLeaderboardMenu.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]menu[\\/]core[\\/]screen[\\/]DynamicMenu\.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]core[\\/]screen[\\/]MainMenu\.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]menu[\\/]core[\\/]MenuStub.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]lobby[\\/]LobbyMenu.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]lobby[\\/]PlayerManagementMenu.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]play[\\/]SingleMenu.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]menu[\\/]play[\\/]SpectatorMenu.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]mode[\\/]impl[\\/]solo[\\/]GravityShiftMode\.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]player[\\/]data[\\/]InventoryData.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]player[\\/]data[\\/]PreviousData.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]player[\\/]service[\\/]ui[\\/]ScoreboardManager\.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]player[\\/]service[\\/]UserRegistry.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]reward[\\/]core[\\/]Reward.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]session[\\/]manager[\\/]SessionStateManager.java"/>
|
||||
<suppress checks="IllegalCatch" files=".*[\\/]storage[\\/]sql[\\/]SQLConnectionManager.java"/>
|
||||
<suppress checks="WhitespaceAround" files=".*[\\/]storage[\\/]sql[\\/]SQLDataMapper.java"/>
|
||||
<suppress checks="NPathComplexity|WhitespaceAround" files=".*[\\/]util[\\/]item[\\/]Materials.java"/>
|
||||
<suppress checks="NPathComplexity" files=".*[\\/]world[\\/]core[\\/]World.java"/>
|
||||
</suppressions>
|
||||
<!DOCTYPE suppressions PUBLIC "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||
<suppressions/>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ Jump structures are loaded from `plugins/LoParkour/schematics/` and matched to a
|
|||
|-----------|--------|--------|
|
||||
| `.nbt` | Vanilla structure block, `/structure save` | Pasted with Bukkit `StructureManager` |
|
||||
| `.schem`, `.schematic` | WorldEdit (`//copy`, `//schem save`) | Read via embedded WorldEdit clipboard IO |
|
||||
| `.lpschem` | **Legacy LoParkour format** | Not used in-game; convert with `/lp schematic convert` |
|
||||
| `.lpschem` | **Legacy LoParkour format** | Not used in-game; convert with `/lpk schematic convert` |
|
||||
|
||||
During parkour generation, when the profile rolls **schematic** type, the plugin picks a random file whose `difficulty` in YAML is **≤** the player's schematic setting (0.0–1.0).
|
||||
|
||||
|
|
@ -26,23 +26,23 @@ Player setting **0.25 (easy)** → only structures with difficulty ≤ 0.25.
|
|||
|
||||
## Creating schematics in-game (admin)
|
||||
|
||||
1. Get the wand: `/lp schematic wand`
|
||||
2. **Left-click** = position 1, **right-click** = position 2 (or use `/lp schematic pos1` / `pos2`)
|
||||
1. Get the wand: `/lpk schematic wand`
|
||||
2. **Left-click** = position 1, **right-click** = position 2 (or use `/lpk schematic pos1` / `pos2`)
|
||||
3. Save and register:
|
||||
- `/lp create <difficulty>` — auto name `parkour-<hash>.schem` + YAML entry
|
||||
- `/lp schematic create <difficulty>` — same
|
||||
- `/lp schematic create <name> <difficulty>` — custom name (letters, numbers, `-`, `_`)
|
||||
- `/lpk create <difficulty>` — auto name `parkour-<hash>.schem` + YAML entry
|
||||
- `/lpk schematic create <difficulty>` — same
|
||||
- `/lpk schematic create <name> <difficulty>` — custom name (letters, numbers, `-`, `_`)
|
||||
|
||||
Difficulty examples: `0.25`, `0.5`, `0.75`, `1.0` (must be between 0 and 1).
|
||||
|
||||
4. `/lp schematic reload` — reload files without restart
|
||||
4. `/lpk schematic reload` — reload files without restart
|
||||
|
||||
## Converting old `.lpschem` files
|
||||
|
||||
Place `.lpschem` files in `plugins/LoParkour/schematics/` or legacy `schematics-new/`, then:
|
||||
|
||||
```
|
||||
/lp schematic convert
|
||||
/lpk schematic convert
|
||||
```
|
||||
|
||||
Each file becomes `parkour-<id>.schem` in `schematics/` and gets a `difficulty:` entry (from the old metadata, or `0.5` if missing). Original `.lpschem` files are kept; delete them manually after checking.
|
||||
|
|
@ -51,14 +51,14 @@ Each file becomes `parkour-<id>.schem` in `schematics/` and gets a `difficulty:`
|
|||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `/lp schematic wand` | Selection wand |
|
||||
| `/lp schematic pos1` / `pos2` | Set corners at your feet |
|
||||
| `/lp create <difficulty>` | Save selection → `.schem` + YAML |
|
||||
| `/lp schematic create <name> <difficulty>` | Save with custom name |
|
||||
| `/lp schematic convert` | Convert all `.lpschem` in schematics folders |
|
||||
| `/lp schematic list` | List loaded structures |
|
||||
| `/lp schematic paste <name>` | Test-paste at your location |
|
||||
| `/lp schematic reload` | Reload disk files |
|
||||
| `/lpk schematic wand` | Selection wand |
|
||||
| `/lpk schematic pos1` / `pos2` | Set corners at your feet |
|
||||
| `/lpk create <difficulty>` | Save selection → `.schem` + YAML |
|
||||
| `/lpk schematic create <name> <difficulty>` | Save with custom name |
|
||||
| `/lpk schematic convert` | Convert all `.lpschem` in schematics folders |
|
||||
| `/lpk schematic list` | List loaded structures |
|
||||
| `/lpk schematic paste <name>` | Test-paste at your location |
|
||||
| `/lpk schematic reload` | Reload disk files |
|
||||
|
||||
## Flow (runtime)
|
||||
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -11,9 +11,9 @@ import dev.loki.loparkour.schematic.core.SchematicManager;
|
|||
import dev.loki.loparkour.storage.Storage;
|
||||
import dev.loki.loparkour.world.core.Divider;
|
||||
import dev.loki.loparkour.world.core.World;
|
||||
import dev.lolib.core.LoPlugin;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
|
|
@ -26,7 +26,7 @@ import java.util.logging.Level;
|
|||
*
|
||||
* @author loki
|
||||
*/
|
||||
public final class LoParkour extends LoPlugin {
|
||||
public final class LoParkour extends JavaPlugin {
|
||||
|
||||
public static final String NAME = "&#FF6464&lLoParkour&r";
|
||||
public static final String PREFIX = NAME + " 񢩈» &#A0A0A0";
|
||||
|
|
@ -87,13 +87,13 @@ public final class LoParkour extends LoPlugin {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
PluginBootstrap.enable(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
public void onDisable() {
|
||||
PluginBootstrap.disable(this);
|
||||
}
|
||||
|
||||
|
|
@ -104,6 +104,7 @@ public final class LoParkour extends LoPlugin {
|
|||
try {
|
||||
session.onAllPlayersLeft();
|
||||
} catch (Exception e) {
|
||||
// Boundary: one failing session must not abort server shutdown.
|
||||
getLogger().warning("Error cleaning up session: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
|
|
@ -114,8 +115,8 @@ public final class LoParkour extends LoPlugin {
|
|||
ParkourUser.leave(user);
|
||||
}
|
||||
|
||||
if (Modes.DEFAULT != null && Modes.DEFAULT.getLeaderboard() != null) {
|
||||
Modes.DEFAULT.getLeaderboard().write(false);
|
||||
if (Modes.defaultMode() != null && Modes.defaultMode().getLeaderboard() != null) {
|
||||
Modes.defaultMode().getLeaderboard().write(false);
|
||||
}
|
||||
|
||||
Rewards.clear();
|
||||
|
|
@ -125,7 +126,7 @@ public final class LoParkour extends LoPlugin {
|
|||
}
|
||||
Storage.close();
|
||||
World.delete();
|
||||
} catch (Throwable t) {
|
||||
} catch (RuntimeException t) {
|
||||
getLogger().log(Level.SEVERE, "Error during plugin shutdown: " + t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import dev.loki.loparkour.adaptive.model.SkillRating;
|
|||
import dev.loki.loparkour.adaptive.storage.FileStatsStorage;
|
||||
import dev.loki.loparkour.adaptive.storage.SQLStatsStorage;
|
||||
import dev.loki.loparkour.adaptive.storage.StatsRepository;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.section.OptionSQL;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.generator.core.model.Profile;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
|
|
@ -42,7 +42,7 @@ public final class AdaptiveServices {
|
|||
}
|
||||
|
||||
final Runnable setup = () -> startCollector(createRepository());
|
||||
if (Option.SQL) {
|
||||
if (OptionSQL.enabled()) {
|
||||
Storage.runWhenReady(setup);
|
||||
} else {
|
||||
setup.run();
|
||||
|
|
@ -54,7 +54,7 @@ public final class AdaptiveServices {
|
|||
AdaptiveConfig.reload();
|
||||
if (plugin != null && AdaptiveConfig.isEnabled()) {
|
||||
final Runnable setup = () -> startCollector(createRepository());
|
||||
if (Option.SQL) {
|
||||
if (OptionSQL.enabled()) {
|
||||
Storage.runWhenReady(setup);
|
||||
} else {
|
||||
setup.run();
|
||||
|
|
@ -147,7 +147,7 @@ public final class AdaptiveServices {
|
|||
|
||||
@NotNull
|
||||
private static StatsRepository createRepository() {
|
||||
if (Option.SQL && StorageSQL.isConnected()) {
|
||||
if (OptionSQL.enabled() && StorageSQL.isConnected()) {
|
||||
return new SQLStatsStorage(StorageSQL.getConnectionManager());
|
||||
}
|
||||
return new FileStatsStorage();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.loparkour.adaptive.core;
|
|||
import dev.loki.loparkour.adaptive.model.PlayerMetrics;
|
||||
import dev.loki.loparkour.adaptive.storage.StatsRepository;
|
||||
import dev.loki.loparkour.generator.core.coordinator.GeneratorEventListener;
|
||||
import dev.loki.loparkour.generator.jump.calculation.JumpType;
|
||||
import dev.loki.loparkour.generator.jump.model.JumpType;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
|
|
|||
|
|
@ -45,4 +45,4 @@ public class JumpTimingTracker {
|
|||
lastBlockCache.remove(playerUuid);
|
||||
lastLandTimeCache.remove(playerUuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package dev.loki.loparkour.adaptive.core.metrics;
|
||||
|
||||
import dev.loki.loparkour.adaptive.model.PlayerMetrics;
|
||||
import dev.loki.loparkour.generator.jump.calculation.JumpType;
|
||||
import dev.loki.loparkour.generator.jump.model.JumpType;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
|
@ -71,4 +71,4 @@ public class MetricEventCollector {
|
|||
public void unload(@NotNull UUID playerUuid) {
|
||||
timingTracker.unload(playerUuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ package dev.loki.loparkour.adaptive.core.metrics;
|
|||
|
||||
import dev.loki.loparkour.adaptive.model.PlayerMetrics;
|
||||
import dev.loki.loparkour.adaptive.storage.StatsRepository;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
|
@ -29,7 +30,7 @@ public class MetricsCacheStore {
|
|||
private final StatsRepository repository;
|
||||
private final Map<UUID, PlayerMetrics> metricsCache;
|
||||
|
||||
private BukkitRunnable autoSaveTask;
|
||||
private ScheduledTask autoSaveTask;
|
||||
|
||||
public MetricsCacheStore(@NotNull Plugin plugin, @NotNull StatsRepository repository) {
|
||||
this.plugin = plugin;
|
||||
|
|
@ -81,14 +82,8 @@ public class MetricsCacheStore {
|
|||
autoSaveTask.cancel();
|
||||
}
|
||||
|
||||
autoSaveTask = new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
saveAll();
|
||||
}
|
||||
};
|
||||
|
||||
autoSaveTask.runTaskTimerAsynchronously(plugin, AUTO_SAVE_INTERVAL_TICKS, AUTO_SAVE_INTERVAL_TICKS);
|
||||
autoSaveTask = Scheduler.get(plugin).runTimerAsync(this::saveAll,
|
||||
AUTO_SAVE_INTERVAL_TICKS, AUTO_SAVE_INTERVAL_TICKS);
|
||||
}
|
||||
|
||||
public void stopAutoSave() {
|
||||
|
|
@ -97,4 +92,4 @@ public class MetricsCacheStore {
|
|||
autoSaveTask = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ package dev.loki.loparkour.adaptive.core.model;
|
|||
*
|
||||
* Thread-safe: Stateless, all methods are pure functions.
|
||||
*/
|
||||
public class DifficultyWeights {
|
||||
public final class DifficultyWeights {
|
||||
|
||||
private static final double[] LEVEL_THRESHOLDS = {0.3, 0.6, 0.8};
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
* Cached configuration for the adaptive difficulty system.
|
||||
* Loads settings from config.yml and caches them for performance.
|
||||
*/
|
||||
public class AdaptiveConfig {
|
||||
public final class AdaptiveConfig {
|
||||
|
||||
private AdaptiveConfig() {
|
||||
}
|
||||
|
|
|
|||
|
|
@ -171,9 +171,9 @@ public class SQLStatsStorage implements StatsRepository {
|
|||
flushBatch();
|
||||
}
|
||||
|
||||
private static class PendingUpdate {
|
||||
int jumps = 0;
|
||||
int falls = 0;
|
||||
int longestStreak = 0;
|
||||
private static final class PendingUpdate {
|
||||
private int jumps = 0;
|
||||
private int falls = 0;
|
||||
private int longestStreak = 0;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package dev.loki.loparkour.api.core;
|
|||
import dev.loki.loparkour.api.event.generation.ParkourBlockGenerateEvent;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
|
|
@ -17,7 +18,7 @@ import org.jetbrains.annotations.Nullable;
|
|||
* <li>For jump structures, see {@link dev.loki.loparkour.schematic.core.ParkourSchematic}</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class ParkourAPI {
|
||||
public final class ParkourAPI {
|
||||
|
||||
private ParkourAPI() throws IllegalAccessException {
|
||||
throw new IllegalAccessException("Initializing API class");
|
||||
|
|
@ -28,7 +29,7 @@ public class ParkourAPI {
|
|||
* @return The {@link ParkourPlayer}. Null if not found.
|
||||
*/
|
||||
public static @Nullable ParkourPlayer getPlayer(Player player) {
|
||||
return ParkourPlayer.getPlayer(player);
|
||||
return UserRegistry.getPlayer(player);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import dev.loki.loparkour.api.core.Registry;
|
|||
import dev.loki.loparkour.command.core.LoParkourCommand;
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.section.OptionSQL;
|
||||
import dev.loki.loparkour.duels.DuelsMode;
|
||||
import dev.loki.loparkour.ghost.service.GhostService;
|
||||
import dev.loki.loparkour.hook.holo.HoloHook;
|
||||
|
|
@ -14,12 +14,12 @@ import dev.loki.loparkour.hook.papi.PAPIHook;
|
|||
import dev.loki.loparkour.listener.gameplay.ParkourRestrictionListener;
|
||||
import dev.loki.loparkour.listener.schematic.SchematicWandListener;
|
||||
import dev.loki.loparkour.listener.player.PlayerConnectionListener;
|
||||
import dev.loki.loparkour.elytra.mode.CloseMode;
|
||||
import dev.loki.loparkour.elytra.mode.ElytraMode;
|
||||
import dev.loki.loparkour.elytra.mode.MinSpeedMode;
|
||||
import dev.loki.loparkour.elytra.mode.ObstacleMode;
|
||||
import dev.loki.loparkour.elytra.mode.SpeedDemonMode;
|
||||
import dev.loki.loparkour.elytra.mode.TimeTrialMode;
|
||||
import dev.loki.loparkour.elytra.close.CloseMode;
|
||||
import dev.loki.loparkour.elytra.core.ElytraMode;
|
||||
import dev.loki.loparkour.elytra.minspeed.MinSpeedMode;
|
||||
import dev.loki.loparkour.elytra.obstacle.ObstacleMode;
|
||||
import dev.loki.loparkour.elytra.speeddemon.SpeedDemonMode;
|
||||
import dev.loki.loparkour.elytra.timetrial.TimeTrialMode;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.mode.impl.barrier.InvisibleBarrierMode;
|
||||
import dev.loki.loparkour.mode.impl.multi.CoopMode;
|
||||
|
|
@ -36,8 +36,10 @@ import org.bstats.charts.SimplePie;
|
|||
import org.bstats.charts.SingleLineChart;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.logging.Level;
|
||||
|
||||
/**
|
||||
* Wires plugin subsystems during {@link LoParkour#enable()} and {@link LoParkour#disable()}.
|
||||
* Wires plugin subsystems during {@link LoParkour#onEnable()} and {@link LoParkour#onDisable()}.
|
||||
*/
|
||||
public final class PluginBootstrap {
|
||||
|
||||
|
|
@ -117,16 +119,17 @@ public final class PluginBootstrap {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
plugin.loLogger().info("Creating parkour world...");
|
||||
plugin.getLogger().info("Creating parkour world...");
|
||||
World.create();
|
||||
plugin.loLogger().info("Parkour world created successfully!");
|
||||
plugin.getLogger().info("Parkour world created successfully!");
|
||||
} catch (Exception ex) {
|
||||
plugin.loLogger().error("Failed to create parkour world", ex);
|
||||
// Boundary: world creation must never break enable; provider behavior varies across versions.
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to create parkour world", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerEventsAndCommands(@NotNull LoParkour plugin) {
|
||||
dev.lolib.gui.GUIManager.init(plugin);
|
||||
dev.loki.loparkour.menu.gui.inventory.GuiManager.init(plugin);
|
||||
|
||||
final var pm = plugin.getServer().getPluginManager();
|
||||
pm.registerEvents(new PlayerConnectionListener(), plugin);
|
||||
|
|
@ -139,8 +142,8 @@ public final class PluginBootstrap {
|
|||
|
||||
private static void setupMetrics(@NotNull LoParkour plugin) {
|
||||
final Metrics metrics = new Metrics(plugin, BSTATS_PLUGIN_ID);
|
||||
metrics.addCustomChart(new SimplePie("using_sql", () -> Boolean.toString(Option.SQL)));
|
||||
metrics.addCustomChart(new SimplePie("using_rewards", () -> Boolean.toString(Rewards.REWARDS_ENABLED)));
|
||||
metrics.addCustomChart(new SimplePie("using_sql", () -> Boolean.toString(OptionSQL.enabled())));
|
||||
metrics.addCustomChart(new SimplePie("using_rewards", () -> Boolean.toString(Rewards.enabled())));
|
||||
metrics.addCustomChart(new SimplePie("locale_count", () -> Integer.toString(Locales.getLocaleCount())));
|
||||
metrics.addCustomChart(new SingleLineChart("player_joins", () ->
|
||||
dev.loki.loparkour.player.service.UserRegistry.getJoinCount()));
|
||||
|
|
|
|||
|
|
@ -26,17 +26,15 @@ public final class ForceJoinExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
joinEveryone(sender);
|
||||
return;
|
||||
}
|
||||
if ("nearest".equalsIgnoreCase(target)) {
|
||||
} else if ("nearest".equalsIgnoreCase(target)) {
|
||||
joinNearest(sender);
|
||||
return;
|
||||
} else {
|
||||
joinByName(target, sender);
|
||||
}
|
||||
joinByName(target, sender);
|
||||
}
|
||||
|
||||
private void joinEveryone(CommandSender sender) {
|
||||
Bukkit.getOnlinePlayers().forEach(p -> Modes.DEFAULT.create(p));
|
||||
Bukkit.getOnlinePlayers().forEach(p -> Modes.defaultMode().create(p));
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.force_join_everyone"));
|
||||
}
|
||||
|
||||
|
|
@ -45,7 +43,7 @@ public final class ForceJoinExecutor {
|
|||
if (closest == null) {
|
||||
return;
|
||||
}
|
||||
Modes.DEFAULT.create(closest);
|
||||
Modes.defaultMode().create(closest);
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.force_join_player").formatted(closest.getName()));
|
||||
}
|
||||
|
||||
|
|
@ -55,6 +53,6 @@ public final class ForceJoinExecutor {
|
|||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_online"));
|
||||
return;
|
||||
}
|
||||
Modes.DEFAULT.create(other);
|
||||
Modes.defaultMode().create(other);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ package dev.loki.loparkour.command.admin.ops;
|
|||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.command.player.PlayerCommandHandler;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import dev.loki.loparkour.command.admin.support.AdminResponses;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class ForceLeaveExecutor {
|
||||
|
|
@ -26,27 +26,25 @@ public final class ForceLeaveExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
leaveEveryone(sender);
|
||||
return;
|
||||
} else {
|
||||
leaveByName(target, sender);
|
||||
}
|
||||
leaveByName(target, sender);
|
||||
}
|
||||
|
||||
private void leaveEveryone(CommandSender sender) {
|
||||
ParkourPlayer.getPlayers().forEach(ParkourUser::leave);
|
||||
UserRegistry.getPlayers().forEach(ParkourUser::leave);
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.force_leave_everyone"));
|
||||
}
|
||||
|
||||
private void leaveByName(String target, CommandSender sender) {
|
||||
final Player other = Bukkit.getPlayer(target);
|
||||
final ParkourUser user = other == null ? null : ParkourUser.getUser(other);
|
||||
if (other == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_online"));
|
||||
return;
|
||||
}
|
||||
final ParkourUser user = ParkourUser.getUser(other);
|
||||
if (user == null) {
|
||||
} else if (user == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_playing"));
|
||||
return;
|
||||
} else {
|
||||
ParkourUser.leave(user);
|
||||
}
|
||||
ParkourUser.leave(user);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,9 +26,9 @@ public final class RecoverInventoryExecutor {
|
|||
final Player other = Bukkit.getPlayer(target);
|
||||
if (other == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_online"));
|
||||
return;
|
||||
} else {
|
||||
recover(other, sender);
|
||||
}
|
||||
recover(other, sender);
|
||||
}
|
||||
|
||||
private void recover(Player other, CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -29,9 +29,9 @@ public final class ResetExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
resetEveryone(sender);
|
||||
return;
|
||||
} else {
|
||||
resetPlayer(target, sender);
|
||||
}
|
||||
resetPlayer(target, sender);
|
||||
}
|
||||
|
||||
private void resetEveryone(CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -54,16 +54,13 @@ class CommandRouter {
|
|||
private void handle2(String a1, String a2, CommandSender sender, @Nullable Player p) {
|
||||
if (isAdminCommand(a1)) {
|
||||
admin.handle(a1, a2, sender, p);
|
||||
return;
|
||||
} else if (p != null) {
|
||||
if (canCreateSchematic(a1, p)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a2, sender, p, player);
|
||||
} else {
|
||||
handlePlayerSubcommand(a1, a2, sender, p);
|
||||
}
|
||||
}
|
||||
if (p == null) {
|
||||
return;
|
||||
}
|
||||
if (canCreateSchematic(a1, p)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a2, sender, p, player);
|
||||
return;
|
||||
}
|
||||
handlePlayerSubcommand(a1, a2, sender, p);
|
||||
}
|
||||
|
||||
private static boolean isAdminCommand(String a1) {
|
||||
|
|
@ -95,32 +92,24 @@ class CommandRouter {
|
|||
}
|
||||
|
||||
private void handle3(String a1, String a2, String a3, CommandSender sender, @Nullable Player p) {
|
||||
if (p == null) {
|
||||
if (p == null || !p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
if (!p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ("schematic".equalsIgnoreCase(a1)) {
|
||||
if ("create".equalsIgnoreCase(a2)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a3, sender, p, player);
|
||||
return;
|
||||
} else {
|
||||
SchematicCommandHandler.handleSubcommandWithName(a2, a3, sender, p);
|
||||
}
|
||||
SchematicCommandHandler.handleSubcommandWithName(a2, a3, sender, p);
|
||||
}
|
||||
}
|
||||
|
||||
private void handle4(String a1, String a2, String a3, String a4, CommandSender sender, @Nullable Player p) {
|
||||
if (p == null) {
|
||||
if (p == null || !p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
if (!p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
if ("schematic".equalsIgnoreCase(a1) && "create".equalsIgnoreCase(a2)) {
|
||||
SchematicCommandHandler.handleCreateWithDifficulty(a3, a4, sender, p, player);
|
||||
}
|
||||
if (!"schematic".equalsIgnoreCase(a1) || !"create".equalsIgnoreCase(a2)) {
|
||||
return;
|
||||
}
|
||||
SchematicCommandHandler.handleCreateWithDifficulty(a3, a4, sender, p, player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package dev.loki.loparkour.command.core;
|
|||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.api.core.Registry;
|
||||
import dev.loki.loparkour.menu.core.screen.ParkourOption;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.schematic.core.SchematicManager;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
|
@ -13,7 +13,7 @@ import java.util.ArrayList;
|
|||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
class CommandTabCompleter {
|
||||
final class CommandTabCompleter {
|
||||
|
||||
private static final int THREE_ARGS = 3;
|
||||
private static final int FOUR_ARGS = 4;
|
||||
|
|
@ -86,7 +86,7 @@ class CommandTabCompleter {
|
|||
final List<String> completions = new ArrayList<>();
|
||||
if (sender.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
completions.add("everyone");
|
||||
ParkourPlayer.getPlayers().forEach(pp -> completions.add(pp.getName()));
|
||||
UserRegistry.getPlayers().forEach(pp -> completions.add(pp.getName()));
|
||||
}
|
||||
return filter(input, completions);
|
||||
}
|
||||
|
|
@ -95,7 +95,7 @@ class CommandTabCompleter {
|
|||
final List<String> completions = new ArrayList<>();
|
||||
if (ParkourOption.JOIN.mayPerform(sender)) {
|
||||
Registry.getModes().forEach(m -> completions.add(m.getName()));
|
||||
ParkourPlayer.getPlayers().forEach(pp -> completions.add(pp.getName()));
|
||||
UserRegistry.getPlayers().forEach(pp -> completions.add(pp.getName()));
|
||||
}
|
||||
return filter(input, completions);
|
||||
}
|
||||
|
|
@ -187,4 +187,4 @@ class CommandTabCompleter {
|
|||
final String lower = input.toLowerCase();
|
||||
return options.stream().filter(s -> s.toLowerCase().startsWith(lower)).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ public class LoParkourCommand implements CommandExecutor, TabCompleter {
|
|||
final Player p = sender instanceof Player ? (Player) sender : null;
|
||||
router.dispatch(args, sender, p);
|
||||
return true;
|
||||
} catch (Throwable t) {
|
||||
} catch (RuntimeException t) {
|
||||
LoParkour.getPlugin().getLogger().log(Level.SEVERE,
|
||||
"LoParkour command failed (" + label + " " + String.join(" ", args) + ")", t);
|
||||
Locales.send(sender, "commands.error");
|
||||
|
|
@ -46,4 +46,4 @@ public class LoParkourCommand implements CommandExecutor, TabCompleter {
|
|||
@NotNull String alias, @NotNull String[] args) {
|
||||
return CommandTabCompleter.complete(sender, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import dev.loki.loparkour.mode.base.MultiMode;
|
|||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
|
@ -26,23 +27,21 @@ public class JoinCommandExecutor {
|
|||
final Mode mode = Registry.getMode(arg);
|
||||
if (mode != null) {
|
||||
mode.create(p);
|
||||
return;
|
||||
} else {
|
||||
joinPlayingPlayer(arg, sender, p);
|
||||
}
|
||||
joinPlayingPlayer(arg, sender, p);
|
||||
}
|
||||
|
||||
private void joinPlayingPlayer(String arg, CommandSender sender, Player p) {
|
||||
final Player other = Bukkit.getPlayer(arg);
|
||||
final ParkourPlayer pp = other == null ? null : UserRegistry.getPlayer(other);
|
||||
if (other == null) {
|
||||
CommandUtil.send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.unknown_player"));
|
||||
return;
|
||||
}
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(other);
|
||||
if (pp == null) {
|
||||
} else if (pp == null) {
|
||||
CommandUtil.send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.not_playing"));
|
||||
return;
|
||||
} else {
|
||||
joinSession(sender, p, pp.session);
|
||||
}
|
||||
joinSession(sender, p, pp.session);
|
||||
}
|
||||
|
||||
private void joinSession(CommandSender sender, Player p, Session session) {
|
||||
|
|
@ -53,16 +52,16 @@ public class JoinCommandExecutor {
|
|||
if (session.isAcceptingPlayers()) {
|
||||
joinAcceptingSession(p, session);
|
||||
} else {
|
||||
Modes.SPECTATOR.create(p, session);
|
||||
Modes.spectator().create(p, session);
|
||||
}
|
||||
}
|
||||
|
||||
private void joinAcceptingSession(Player p, Session session) {
|
||||
final Mode sessionMode = session.generator.getMode();
|
||||
final Mode sessionMode = session.generator().getMode();
|
||||
if (sessionMode instanceof MultiMode mm) {
|
||||
mm.join(p, session);
|
||||
} else {
|
||||
Modes.SPECTATOR.create(p, session);
|
||||
Modes.spectator().create(p, session);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,4 +24,4 @@ public class LeaderboardCommandExecutor {
|
|||
Menus.SINGLE_LEADERBOARD.open(p, mode, Leaderboard.Sort.SCORE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,10 +55,9 @@ public class PlayerCommandHandler {
|
|||
switch (lower) {
|
||||
case "join" -> handleJoin(sender, player);
|
||||
case "leave" -> {
|
||||
if (!cooldown(sender, "leave", COOLDOWN_MS)) {
|
||||
return;
|
||||
if (cooldown(sender, "leave", COOLDOWN_MS)) {
|
||||
ParkourUser.leave(player);
|
||||
}
|
||||
ParkourUser.leave(player);
|
||||
}
|
||||
case "play" -> {
|
||||
if (ParkourOption.PLAY.mayPerform(player)) {
|
||||
|
|
@ -71,19 +70,19 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
}
|
||||
case "leaderboard" -> {
|
||||
if (!ParkourOption.LEADERBOARDS.mayPerform(player)) {
|
||||
if (ParkourOption.LEADERBOARDS.mayPerform(player)) {
|
||||
Menus.LEADERBOARDS.open(player);
|
||||
} else {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
}
|
||||
Menus.LEADERBOARDS.open(player);
|
||||
}
|
||||
case "replay" -> new ReplayCommandExecutor().replay(null, sender, player, this);
|
||||
case "schematic" -> {
|
||||
if (!player.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
if (player.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
SchematicCommandHandler.sendHelp(player);
|
||||
} else {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
}
|
||||
SchematicCommandHandler.sendHelp(player);
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
|
|
@ -96,12 +95,9 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
if (!ParkourOption.JOIN.mayPerform(player)) {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
} else if (ParkourUser.getUser(player) == null) {
|
||||
Modes.defaultMode().create(player);
|
||||
}
|
||||
if (ParkourUser.getUser(player) != null) {
|
||||
return;
|
||||
}
|
||||
Modes.DEFAULT.create(player);
|
||||
}
|
||||
|
||||
private void handleReload(@NotNull CommandSender sender, @Nullable Player player) {
|
||||
|
|
@ -110,11 +106,11 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
if (!sender.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
send(sender, Locales.getString(sender, "other.no_do"));
|
||||
return;
|
||||
} else {
|
||||
Config.reload(false);
|
||||
dev.loki.loparkour.adaptive.bootstrap.AdaptiveServices.reload();
|
||||
send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.reload"));
|
||||
}
|
||||
Config.reload(false);
|
||||
dev.loki.loparkour.adaptive.bootstrap.AdaptiveServices.reload();
|
||||
send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.reload"));
|
||||
}
|
||||
|
||||
public void sendHelp(@NotNull CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import org.jetbrains.annotations.Nullable;
|
|||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Handles {@code /lp replay [index]}: plays back a player's recorded ghost runs.
|
||||
* Handles {@code /lpk replay [index]}: plays back a player's recorded ghost runs.
|
||||
*/
|
||||
public class ReplayCommandExecutor {
|
||||
|
||||
|
|
@ -30,14 +30,18 @@ public class ReplayCommandExecutor {
|
|||
final GhostService ghostService = LoParkour.getGhostService();
|
||||
if (ghostService == null || !Config.CONFIG.getBoolean("ghost-mode.enabled")) {
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.disabled"));
|
||||
return;
|
||||
} else {
|
||||
startRun(indexArg, sender, p, ghostService);
|
||||
}
|
||||
}
|
||||
|
||||
private static void startRun(@Nullable String indexArg, @NotNull CommandSender sender, @NotNull Player p,
|
||||
@NotNull GhostService ghostService) {
|
||||
final GhostData run = resolveRun(indexArg, sender, p, ghostService);
|
||||
if (run == null) {
|
||||
return;
|
||||
if (run != null) {
|
||||
ghostService.startReplay(p, run);
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.starting"));
|
||||
}
|
||||
ghostService.startReplay(p, run);
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.starting"));
|
||||
}
|
||||
|
||||
private static GhostData resolveRun(@Nullable String indexArg, @NotNull CommandSender sender,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ package dev.loki.loparkour.command.schematic;
|
|||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.command.player.PlayerCommandHandler;
|
||||
import dev.loki.loparkour.command.schematic.wand.SchematicWand;
|
||||
import dev.loki.loparkour.command.schematic.wand.SelectionStore;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.bukkit.Location;
|
||||
|
|
@ -16,7 +18,7 @@ import java.util.Map;
|
|||
/**
|
||||
* Admin schematic tools: wand, create, list, paste, reload.
|
||||
*/
|
||||
public class SchematicCommandHandler {
|
||||
public final class SchematicCommandHandler {
|
||||
|
||||
private static final int COOLDOWN_MS = 2500;
|
||||
|
||||
|
|
@ -88,4 +90,4 @@ public class SchematicCommandHandler {
|
|||
static boolean isValidSchematicName(String name) {
|
||||
return SchematicHandler.isValidSchematicName(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,4 +52,4 @@ final class SchematicDispatcher {
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,15 @@ final class SchematicHandler {
|
|||
SchematicMessenger.send(player, LoParkour.PREFIX + Locales.getString(player, "schematic.selection_incomplete"));
|
||||
return;
|
||||
}
|
||||
createSelected(sel, optionalName, difficultyRaw, player);
|
||||
}
|
||||
|
||||
private static void createSelected(
|
||||
Location[] sel,
|
||||
@Nullable String optionalName,
|
||||
@NotNull String difficultyRaw,
|
||||
Player player
|
||||
) {
|
||||
final double difficulty;
|
||||
try {
|
||||
difficulty = SchematicCreator.parseDifficulty(difficultyRaw);
|
||||
|
|
@ -60,18 +68,17 @@ final class SchematicHandler {
|
|||
static void paste(String name, CommandSender sender, Player player) {
|
||||
if (!isValidSchematicName(name)) {
|
||||
SchematicMessenger.send(player, LoParkour.PREFIX + Locales.getString(player, "schematic.invalid_name"));
|
||||
return;
|
||||
} else {
|
||||
final ParkourSchematic schematic = LoParkour.getSchematicManager().get(name);
|
||||
if (schematic == null) {
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.not_found")
|
||||
.formatted(name));
|
||||
} else {
|
||||
schematic.paste(player.getLocation(), player.getWorld());
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.pasted")
|
||||
.formatted(name));
|
||||
}
|
||||
}
|
||||
|
||||
final ParkourSchematic schematic = LoParkour.getSchematicManager().get(name);
|
||||
if (schematic == null) {
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.not_found")
|
||||
.formatted(name));
|
||||
return;
|
||||
}
|
||||
schematic.paste(player.getLocation(), player.getWorld());
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.pasted")
|
||||
.formatted(name));
|
||||
}
|
||||
|
||||
static void posCommand(Player player, Location[] existing, Location loc, int index) {
|
||||
|
|
@ -92,4 +99,4 @@ final class SchematicHandler {
|
|||
}
|
||||
return name.matches("^[a-zA-Z0-9_-]+$");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,4 +31,4 @@ final class SchematicMessenger {
|
|||
send(player, Locales.getString(player, "schematic.help.line_docs"));
|
||||
send(player, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package dev.loki.loparkour.command.schematic;
|
||||
package dev.loki.loparkour.command.schematic.wand;
|
||||
|
||||
import dev.loki.loparkour.command.schematic.SchematicCommandHandler;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.OptionGeneral;
|
||||
import dev.loki.loparkour.menu.core.screen.ParkourOption;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -9,7 +10,7 @@ import org.bukkit.inventory.ItemStack;
|
|||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
final class SchematicWand {
|
||||
public final class SchematicWand {
|
||||
|
||||
private static ItemStack cachedWand;
|
||||
|
||||
|
|
@ -17,11 +18,11 @@ final class SchematicWand {
|
|||
}
|
||||
|
||||
@NotNull
|
||||
static ItemStack getWand() {
|
||||
public static ItemStack getWand() {
|
||||
return build().clone();
|
||||
}
|
||||
|
||||
static boolean isWand(@Nullable ItemStack item) {
|
||||
public static boolean isWand(@Nullable ItemStack item) {
|
||||
if (item == null || !item.hasItemMeta()) {
|
||||
return false;
|
||||
}
|
||||
|
|
@ -30,7 +31,7 @@ final class SchematicWand {
|
|||
&& meta.getPersistentDataContainer().has(SchematicCommandHandler.WAND_KEY, PersistentDataType.BYTE);
|
||||
}
|
||||
|
||||
static void clearCache() {
|
||||
public static void clearCache() {
|
||||
cachedWand = null;
|
||||
}
|
||||
|
||||
|
|
@ -40,7 +41,7 @@ final class SchematicWand {
|
|||
return cachedWand;
|
||||
}
|
||||
|
||||
String locale = Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG);
|
||||
String locale = OptionGeneral.optionsDefaults().get(ParkourOption.LANG);
|
||||
if (locale == null || locale.isBlank()) {
|
||||
locale = "en";
|
||||
}
|
||||
|
|
@ -54,4 +55,4 @@ final class SchematicWand {
|
|||
cachedWand = item;
|
||||
return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,17 @@
|
|||
package dev.loki.loparkour.command.schematic;
|
||||
package dev.loki.loparkour.command.schematic.wand;
|
||||
|
||||
import dev.loki.loparkour.command.schematic.SchematicCommandHandler;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
final class SelectionStore {
|
||||
public final class SelectionStore {
|
||||
|
||||
private SelectionStore() {
|
||||
}
|
||||
|
||||
@NotNull
|
||||
static Location[] get(@NotNull Player player) {
|
||||
public static Location[] get(@NotNull Player player) {
|
||||
Location[] sel = SchematicCommandHandler.SELECTIONS.get(player);
|
||||
if (sel == null) {
|
||||
sel = new Location[]{null, null};
|
||||
|
|
@ -19,9 +20,9 @@ final class SelectionStore {
|
|||
return sel;
|
||||
}
|
||||
|
||||
static void set(@NotNull Player player, @NotNull Location loc, int index) {
|
||||
public static void set(@NotNull Player player, @NotNull Location loc, int index) {
|
||||
final Location[] updated = get(player).clone();
|
||||
updated[index] = loc.clone();
|
||||
SchematicCommandHandler.SELECTIONS.put(player, updated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -11,4 +11,4 @@ public final class CommandUtil {
|
|||
public static void send(CommandSender sender, String msg) {
|
||||
sender.sendMessage(ColorUtil.color(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,11 +18,11 @@ public enum Config {
|
|||
REWARDS("rewards-v2.yml", List.of("score-rewards", "interval-rewards", "one-time-rewards")),
|
||||
SCHEMATICS("schematics/schematics.yml", List.of("difficulty"));
|
||||
|
||||
public File path;
|
||||
private File path;
|
||||
public final String fileName;
|
||||
public final List<String> ignoredSections;
|
||||
public FileConfiguration fileConfiguration;
|
||||
|
||||
private FileConfiguration fileConfiguration;
|
||||
|
||||
private ConfigAccessor accessor;
|
||||
|
||||
Config(String fileName, @Nullable List<String> ignoredSections) {
|
||||
|
|
@ -31,12 +31,49 @@ public enum Config {
|
|||
this.path = null; // Resolved lazily
|
||||
}
|
||||
|
||||
/**
|
||||
* Location of this config on disk.
|
||||
*
|
||||
* @return The file this configuration is read from.
|
||||
*/
|
||||
public File path() {
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsed contents of this config.
|
||||
*
|
||||
* @return The parsed configuration currently held in memory.
|
||||
*/
|
||||
public FileConfiguration fileConfiguration() {
|
||||
return fileConfiguration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers where this configuration lives on disk. Only called while the config files are first resolved.
|
||||
*
|
||||
* @param file The resolved config file.
|
||||
*/
|
||||
public void bindPath(@NotNull File file) {
|
||||
this.path = file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the in-memory configuration and refreshes the accessor that delegates reads to it.
|
||||
*
|
||||
* @param configuration The freshly loaded configuration.
|
||||
*/
|
||||
public void apply(@NotNull FileConfiguration configuration) {
|
||||
this.fileConfiguration = configuration;
|
||||
this.accessor = new ConfigAccessor(configuration, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload all configuration files.
|
||||
*/
|
||||
public static void reload(boolean initialLoad) {
|
||||
ConfigLoader.reloadAllConfigs(initialLoad);
|
||||
|
||||
|
||||
// Update accessors for all configs
|
||||
for (final Config config : values()) {
|
||||
if (config.fileConfiguration != null) {
|
||||
|
|
@ -55,9 +92,8 @@ public enum Config {
|
|||
if (path == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.fileConfiguration = ConfigLoader.loadConfig(path);
|
||||
this.accessor = new ConfigAccessor(fileConfiguration, fileName);
|
||||
|
||||
apply(ConfigLoader.loadConfig(path));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -70,56 +106,56 @@ public enum Config {
|
|||
}
|
||||
|
||||
// Delegate all accessor methods to ConfigAccessor
|
||||
|
||||
public boolean isPath(@NotNull String path) {
|
||||
return accessor != null && accessor.isPath(path);
|
||||
|
||||
public boolean isPath(@NotNull String key) {
|
||||
return accessor != null && accessor.isPath(key);
|
||||
}
|
||||
|
||||
public Object get(@NotNull String path) {
|
||||
return accessor.get(path);
|
||||
public Object get(@NotNull String key) {
|
||||
return accessor.get(key);
|
||||
}
|
||||
|
||||
public boolean getBoolean(@NotNull String path) {
|
||||
return accessor.getBoolean(path);
|
||||
public boolean getBoolean(@NotNull String key) {
|
||||
return accessor.getBoolean(key);
|
||||
}
|
||||
|
||||
public boolean getBoolean(@NotNull String path, boolean defaultValue) {
|
||||
return accessor != null ? accessor.getBoolean(path, defaultValue) : defaultValue;
|
||||
public boolean getBoolean(@NotNull String key, boolean defaultValue) {
|
||||
return accessor != null ? accessor.getBoolean(key, defaultValue) : defaultValue;
|
||||
}
|
||||
|
||||
public int getInt(@NotNull String path) {
|
||||
return accessor.getInt(path);
|
||||
}
|
||||
|
||||
public int getInt(@NotNull String path, int defaultValue) {
|
||||
return accessor != null ? accessor.getInt(path, defaultValue) : defaultValue;
|
||||
public int getInt(@NotNull String key) {
|
||||
return accessor.getInt(key);
|
||||
}
|
||||
|
||||
public double getDouble(@NotNull String path) {
|
||||
return accessor.getDouble(path);
|
||||
public int getInt(@NotNull String key, int defaultValue) {
|
||||
return accessor != null ? accessor.getInt(key, defaultValue) : defaultValue;
|
||||
}
|
||||
|
||||
public double getDouble(@NotNull String path, double defaultValue) {
|
||||
return accessor != null ? accessor.getDouble(path, defaultValue) : defaultValue;
|
||||
public double getDouble(@NotNull String key) {
|
||||
return accessor.getDouble(key);
|
||||
}
|
||||
|
||||
public double getDouble(@NotNull String key, double defaultValue) {
|
||||
return accessor != null ? accessor.getDouble(key, defaultValue) : defaultValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getString(@NotNull String path) {
|
||||
return accessor.getString(path);
|
||||
public String getString(@NotNull String key) {
|
||||
return accessor.getString(key);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getStringList(@NotNull String path) {
|
||||
return accessor.getStringList(path);
|
||||
public List<String> getStringList(@NotNull String key) {
|
||||
return accessor.getStringList(key);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<Integer> getIntList(@NotNull String path) {
|
||||
return accessor.getIntList(path);
|
||||
public List<Integer> getIntList(@NotNull String key) {
|
||||
return accessor.getIntList(key);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getChildren(@NotNull String path, boolean... deep) {
|
||||
return accessor.getChildren(path, deep);
|
||||
public List<String> getChildren(@NotNull String key, boolean... deep) {
|
||||
return accessor.getChildren(key, deep);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,23 +14,23 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
* Provides safe access to configuration values with validation.
|
||||
*/
|
||||
public class ConfigAccessor {
|
||||
|
||||
|
||||
private final FileConfiguration config;
|
||||
private final String fileName;
|
||||
private final Set<String> warnedMissingPaths = ConcurrentHashMap.newKeySet();
|
||||
|
||||
|
||||
public ConfigAccessor(@NotNull FileConfiguration config, @NotNull String fileName) {
|
||||
this.config = config;
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if path exists in configuration.
|
||||
*/
|
||||
public boolean isPath(@NotNull String path) {
|
||||
return config.isSet(path);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get raw object value at path.
|
||||
*/
|
||||
|
|
@ -38,7 +38,7 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return config.get(path);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get boolean value at path.
|
||||
*/
|
||||
|
|
@ -56,7 +56,7 @@ public class ConfigAccessor {
|
|||
}
|
||||
return config.getBoolean(path, defaultValue);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get integer value at path.
|
||||
*/
|
||||
|
|
@ -64,7 +64,7 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return config.getInt(path, 0);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get integer value at path with default.
|
||||
*/
|
||||
|
|
@ -74,7 +74,7 @@ public class ConfigAccessor {
|
|||
}
|
||||
return config.getInt(path, defaultValue);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get double value at path.
|
||||
*/
|
||||
|
|
@ -90,7 +90,7 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return config.getDouble(path, defaultValue);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get string value at path.
|
||||
* Forces conversion to String even if YAML parsed as Boolean/Number.
|
||||
|
|
@ -105,7 +105,7 @@ public class ConfigAccessor {
|
|||
// Force toString() to handle Boolean/Number values
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get string list at path.
|
||||
*/
|
||||
|
|
@ -114,7 +114,7 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return config.getStringList(path);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get integer list at path.
|
||||
*/
|
||||
|
|
@ -123,7 +123,7 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return config.getIntegerList(path);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get child keys from configuration section.
|
||||
*/
|
||||
|
|
@ -133,16 +133,16 @@ public class ConfigAccessor {
|
|||
warnIfMissing(path);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
|
||||
final ConfigurationSection section = config.getConfigurationSection(path);
|
||||
if (section == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
|
||||
final boolean isDeep = deep.length > 0 && deep[0];
|
||||
return new ArrayList<>(section.getKeys(isDeep));
|
||||
}
|
||||
|
||||
|
||||
private void warnIfMissing(@NotNull String path) {
|
||||
if (isPath(path)) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import java.util.logging.Logger;
|
|||
/**
|
||||
* Handles loading, updating, and basic validation of configuration files.
|
||||
*/
|
||||
public class ConfigLoader {
|
||||
public final class ConfigLoader {
|
||||
|
||||
private ConfigLoader() {
|
||||
}
|
||||
|
|
@ -42,6 +42,7 @@ public class ConfigLoader {
|
|||
ConfigUpdater.update(configFile, resourceStream, "1.0", ignoredSections, plugin.getLogger());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// Boundary: config sync must never break enable/reload; template or disk may be corrupt.
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE,
|
||||
"Error while trying to update config file: " + fileName, ex);
|
||||
}
|
||||
|
|
@ -50,10 +51,10 @@ public class ConfigLoader {
|
|||
public static void reloadAllConfigs(boolean initialLoad) {
|
||||
for (final Config config : Config.values()) {
|
||||
if (initialLoad) {
|
||||
config.path = initializeConfigFile(config.fileName);
|
||||
updateConfig(config.fileName, config.path, config.ignoredSections);
|
||||
config.bindPath(initializeConfigFile(config.fileName));
|
||||
updateConfig(config.fileName, config.path(), config.ignoredSections);
|
||||
}
|
||||
config.fileConfiguration = loadConfig(config.path);
|
||||
config.load();
|
||||
}
|
||||
|
||||
validateConfigs();
|
||||
|
|
@ -79,14 +80,36 @@ public class ConfigLoader {
|
|||
}
|
||||
}
|
||||
|
||||
if (Config.GENERATION.isPath("generation.normal.height")) {
|
||||
final double sum = Config.GENERATION.getDouble("generation.normal.height.1")
|
||||
+ Config.GENERATION.getDouble("generation.normal.height.0")
|
||||
+ Config.GENERATION.getDouble("generation.normal.height.-1")
|
||||
+ Config.GENERATION.getDouble("generation.normal.height.-2");
|
||||
if (sum <= 0) {
|
||||
log.severe("Invalid config: generation height chances sum to %.1f, must be > 0".formatted(sum));
|
||||
if (Config.GENERATION.isPath("advanced.height.min") && Config.GENERATION.isPath("advanced.height.max")) {
|
||||
final int heightMax = Config.GENERATION.getInt("advanced.height.max");
|
||||
final int heightMin = Config.GENERATION.getInt("advanced.height.min");
|
||||
if (heightMax < heightMin) {
|
||||
log.severe("Invalid config: advanced.height.max (%d) must be >= advanced.height.min (%d)"
|
||||
.formatted(heightMax, heightMin));
|
||||
}
|
||||
}
|
||||
|
||||
validateWeights(log, "advanced.distance.chances");
|
||||
validateWeights(log, "advanced.height.chances");
|
||||
validateWeights(log, "advanced.type");
|
||||
}
|
||||
|
||||
/**
|
||||
* Block/jump weights are divided by their sum, so a section that adds up to
|
||||
* zero silently produces no blocks at all.
|
||||
*/
|
||||
private static void validateWeights(@NotNull Logger log, @NotNull String section) {
|
||||
if (!Config.GENERATION.isPath(section)) {
|
||||
return;
|
||||
}
|
||||
|
||||
double sum = 0.0;
|
||||
for (final String key : Config.GENERATION.getChildren(section)) {
|
||||
sum += Config.GENERATION.getDouble(section + "." + key);
|
||||
}
|
||||
|
||||
if (sum <= 0.0) {
|
||||
log.severe("Invalid config: %s weights sum to %.1f, must be > 0".formatted(section, sum));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import java.util.logging.Logger;
|
|||
* preserving user values while adding any new keys from the template.
|
||||
* Uses full YAML paths (e.g. "sql.enabled") to avoid key collisions.
|
||||
*/
|
||||
public class ConfigUpdater {
|
||||
public final class ConfigUpdater {
|
||||
|
||||
private final Logger logger;
|
||||
|
||||
|
|
@ -46,7 +46,7 @@ public class ConfigUpdater {
|
|||
final List<String> merged = new ConfigMergeProcessor().merge(templateStream, configFile, ignoredKeys);
|
||||
Files.write(configFile.toPath(), merged);
|
||||
logger.info("Configuration file synced: " + configFile.getName());
|
||||
} catch (Exception e) {
|
||||
} catch (IOException e) {
|
||||
if (backup != null && backup.exists()) {
|
||||
Files.copy(backup.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
logger.severe("Config sync failed, restored backup: " + e.getMessage());
|
||||
|
|
@ -69,4 +69,4 @@ public class ConfigUpdater {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ public class LocaleCache {
|
|||
final T result = extractor.apply(config);
|
||||
return result != null ? result : defaultValue;
|
||||
} catch (Exception e) {
|
||||
// Boundary: message formatting must never throw; locale data is arbitrary.
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ import java.util.stream.Stream;
|
|||
/**
|
||||
* Loads locale files from disk with validation and auto-fix.
|
||||
*/
|
||||
public class LocaleLoader {
|
||||
public final class LocaleLoader {
|
||||
|
||||
private LocaleLoader() {
|
||||
}
|
||||
|
|
@ -41,6 +41,7 @@ public class LocaleLoader {
|
|||
|
||||
return loadFromDisk(embedded);
|
||||
} catch (Exception ex) {
|
||||
// Boundary: locale loading must never break enable; disk files may be corrupt.
|
||||
plugin.getLogger().severe("Error while loading locale files: " + ex.getMessage());
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package dev.loki.loparkour.config.locale;
|
||||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.OptionGeneral;
|
||||
import dev.loki.loparkour.menu.core.screen.ParkourOption;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.loki.loparkour.util.text.ColorUtil;
|
||||
|
|
@ -24,7 +24,7 @@ import java.util.regex.Pattern;
|
|||
* Facade for locale system: loading, caching, and access.
|
||||
* Delegates to LocaleLoader and LocaleCache.
|
||||
*/
|
||||
public class Locales {
|
||||
public final class Locales {
|
||||
|
||||
private Locales() {
|
||||
}
|
||||
|
|
@ -56,8 +56,8 @@ public class Locales {
|
|||
if (sender instanceof Player player) {
|
||||
return getString(player, path);
|
||||
}
|
||||
String locale = Option.OPTIONS_DEFAULTS != null
|
||||
? Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG)
|
||||
String locale = OptionGeneral.optionsDefaults() != null
|
||||
? OptionGeneral.optionsDefaults().get(ParkourOption.LANG)
|
||||
: null;
|
||||
if (locale == null || locale.isBlank()) {
|
||||
locale = "en";
|
||||
|
|
@ -170,13 +170,13 @@ public class Locales {
|
|||
@NotNull
|
||||
private static String getPlayerLocale(@NotNull Player player) {
|
||||
final ParkourUser user = ParkourUser.getUser(player);
|
||||
String loc = user == null ? Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG) : user.locale;
|
||||
String loc = user == null ? OptionGeneral.optionsDefaults().get(ParkourOption.LANG) : user.locale();
|
||||
|
||||
// Fix legacy Boolean "true" values from old config parsing
|
||||
if ("true".equals(loc) || "false".equals(loc)) {
|
||||
loc = Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG);
|
||||
loc = OptionGeneral.optionsDefaults().get(ParkourOption.LANG);
|
||||
if (user != null) {
|
||||
user.locale = loc; // Update user's locale to fixed value
|
||||
user.setLocale(loc); // Update user's locale to fixed value
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,37 +2,25 @@ package dev.loki.loparkour.config.options;
|
|||
|
||||
import dev.loki.loparkour.api.core.Registry;
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.menu.core.screen.ParkourOption;
|
||||
import dev.loki.loparkour.style.core.RandomStyle;
|
||||
import dev.loki.loparkour.style.core.Style;
|
||||
import dev.loki.loparkour.util.particle.ParticleData;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import dev.loki.loparkour.config.options.section.OptionGeneration;
|
||||
import dev.loki.loparkour.config.options.section.OptionParticles;
|
||||
import dev.loki.loparkour.config.options.section.OptionSQL;
|
||||
import dev.loki.loparkour.config.options.section.OptionStyles;
|
||||
import java.util.function.BiFunction;
|
||||
import dev.loki.loparkour.style.core.RandomStyle;
|
||||
|
||||
/**
|
||||
* Facade for all config-derived constants.
|
||||
* Delegates to specialized option classes in config.options package.
|
||||
* Reload entry point for the option sections.
|
||||
*
|
||||
* <p>Each section owns its values and exposes them through accessors
|
||||
* ({@link OptionSQL}, {@link OptionParticles}, {@link OptionGeneration},
|
||||
* {@link OptionGeneral}); this class does not mirror them.</p>
|
||||
*/
|
||||
public class Option {
|
||||
public final class Option {
|
||||
|
||||
private Option() {
|
||||
}
|
||||
|
||||
// ── Initialization ────────────────────────────────────────────────────────
|
||||
|
||||
/** (Re)read every option section and re-register the configured styles. */
|
||||
public static void init(boolean firstLoad) {
|
||||
OptionSQL.init();
|
||||
OptionParticles.init();
|
||||
|
|
@ -40,129 +28,7 @@ public class Option {
|
|||
OptionGeneral.init(firstLoad);
|
||||
OptionGeneral.initOptions();
|
||||
|
||||
// Sync all fields to Option facade
|
||||
syncFields();
|
||||
|
||||
OptionStyles.initStyles("styles.list", Config.CONFIG.fileConfiguration, RandomStyle::new)
|
||||
OptionStyles.initStyles("styles.list", Config.CONFIG.fileConfiguration(), RandomStyle::new)
|
||||
.forEach(Registry::register);
|
||||
}
|
||||
|
||||
// ── Direct field re-exports for backward compatibility ───────────────────
|
||||
|
||||
// SQL
|
||||
public static boolean SQL;
|
||||
public static String SQL_URL;
|
||||
public static int SQL_PORT;
|
||||
public static String SQL_DB;
|
||||
public static String SQL_USERNAME;
|
||||
public static String SQL_PASSWORD;
|
||||
public static String SQL_PREFIX;
|
||||
|
||||
// Particles
|
||||
public static ParticleShape PARTICLE_SHAPE;
|
||||
public static Sound SOUND_TYPE;
|
||||
public static int SOUND_PITCH;
|
||||
public static int SOUND_VOLUME;
|
||||
public static Particle PARTICLE_TYPE;
|
||||
public static ParticleData<?> PARTICLE_DATA;
|
||||
|
||||
// Generation
|
||||
public static double TYPE_NORMAL;
|
||||
public static double TYPE_SPECIAL;
|
||||
public static double TYPE_SCHEMATICS;
|
||||
public static double SPECIAL_ICE;
|
||||
public static double SPECIAL_SLAB;
|
||||
public static double SPECIAL_PANE;
|
||||
public static double SPECIAL_FENCE;
|
||||
public static double NORMAL_DISTANCE_1;
|
||||
public static double NORMAL_DISTANCE_2;
|
||||
public static double NORMAL_DISTANCE_3;
|
||||
public static double NORMAL_DISTANCE_4;
|
||||
public static double NORMAL_HEIGHT_1;
|
||||
public static double NORMAL_HEIGHT_0;
|
||||
public static double NORMAL_HEIGHT_NEG1;
|
||||
public static double NORMAL_HEIGHT_NEG2;
|
||||
public static int MAX_Y;
|
||||
public static int MIN_Y;
|
||||
public static int BLOCK_CLEANUP_DISTANCE;
|
||||
public static int CLEANUP_INTERVAL;
|
||||
public static int TRAIL_KEEP_BEHIND;
|
||||
public static boolean JUMP_VALIDATION_ENABLED;
|
||||
public static double MAX_JUMP_DISTANCE;
|
||||
public static double MAX_HORIZONTAL_DISTANCE;
|
||||
public static double MAX_VERTICAL_UP;
|
||||
public static double MAX_VERTICAL_DOWN;
|
||||
|
||||
// General
|
||||
public static double BORDER_SIZE;
|
||||
public static List<Integer> POSSIBLE_LEADS;
|
||||
public static BlockFace HEADING;
|
||||
public static Location GO_BACK_LOC;
|
||||
public static Map<ParkourOption, Boolean> OPTIONS_ENABLED;
|
||||
public static Map<ParkourOption, String> OPTIONS_DEFAULTS;
|
||||
|
||||
private static void syncFields() {
|
||||
// SQL
|
||||
SQL = OptionSQL.SQL;
|
||||
SQL_URL = OptionSQL.SQL_URL;
|
||||
SQL_PORT = OptionSQL.SQL_PORT;
|
||||
SQL_DB = OptionSQL.SQL_DB;
|
||||
SQL_USERNAME = OptionSQL.SQL_USERNAME;
|
||||
SQL_PASSWORD = OptionSQL.SQL_PASSWORD;
|
||||
SQL_PREFIX = OptionSQL.SQL_PREFIX;
|
||||
|
||||
// Particles
|
||||
PARTICLE_SHAPE = OptionParticles.PARTICLE_SHAPE;
|
||||
SOUND_TYPE = OptionParticles.SOUND_TYPE;
|
||||
SOUND_PITCH = OptionParticles.SOUND_PITCH;
|
||||
SOUND_VOLUME = OptionParticles.SOUND_VOLUME;
|
||||
PARTICLE_TYPE = OptionParticles.PARTICLE_TYPE;
|
||||
PARTICLE_DATA = OptionParticles.PARTICLE_DATA;
|
||||
|
||||
// Generation
|
||||
TYPE_NORMAL = OptionGeneration.TYPE_NORMAL;
|
||||
TYPE_SPECIAL = OptionGeneration.TYPE_SPECIAL;
|
||||
TYPE_SCHEMATICS = OptionGeneration.TYPE_SCHEMATICS;
|
||||
SPECIAL_ICE = OptionGeneration.SPECIAL_ICE;
|
||||
SPECIAL_SLAB = OptionGeneration.SPECIAL_SLAB;
|
||||
SPECIAL_PANE = OptionGeneration.SPECIAL_PANE;
|
||||
SPECIAL_FENCE = OptionGeneration.SPECIAL_FENCE;
|
||||
NORMAL_DISTANCE_1 = OptionGeneration.NORMAL_DISTANCE_1;
|
||||
NORMAL_DISTANCE_2 = OptionGeneration.NORMAL_DISTANCE_2;
|
||||
NORMAL_DISTANCE_3 = OptionGeneration.NORMAL_DISTANCE_3;
|
||||
NORMAL_DISTANCE_4 = OptionGeneration.NORMAL_DISTANCE_4;
|
||||
NORMAL_HEIGHT_1 = OptionGeneration.NORMAL_HEIGHT_1;
|
||||
NORMAL_HEIGHT_0 = OptionGeneration.NORMAL_HEIGHT_0;
|
||||
NORMAL_HEIGHT_NEG1 = OptionGeneration.NORMAL_HEIGHT_NEG1;
|
||||
NORMAL_HEIGHT_NEG2 = OptionGeneration.NORMAL_HEIGHT_NEG2;
|
||||
MAX_Y = OptionGeneration.MAX_Y;
|
||||
MIN_Y = OptionGeneration.MIN_Y;
|
||||
BLOCK_CLEANUP_DISTANCE = OptionGeneration.BLOCK_CLEANUP_DISTANCE;
|
||||
CLEANUP_INTERVAL = OptionGeneration.CLEANUP_INTERVAL;
|
||||
TRAIL_KEEP_BEHIND = OptionGeneration.TRAIL_KEEP_BEHIND;
|
||||
JUMP_VALIDATION_ENABLED = OptionGeneration.JUMP_VALIDATION_ENABLED;
|
||||
MAX_JUMP_DISTANCE = OptionGeneration.MAX_JUMP_DISTANCE;
|
||||
MAX_HORIZONTAL_DISTANCE = OptionGeneration.MAX_HORIZONTAL_DISTANCE;
|
||||
MAX_VERTICAL_UP = OptionGeneration.MAX_VERTICAL_UP;
|
||||
MAX_VERTICAL_DOWN = OptionGeneration.MAX_VERTICAL_DOWN;
|
||||
|
||||
// General
|
||||
BORDER_SIZE = OptionGeneral.BORDER_SIZE;
|
||||
POSSIBLE_LEADS = OptionGeneral.POSSIBLE_LEADS;
|
||||
HEADING = OptionGeneral.HEADING;
|
||||
GO_BACK_LOC = OptionGeneral.GO_BACK_LOC;
|
||||
OPTIONS_ENABLED = OptionGeneral.OPTIONS_ENABLED;
|
||||
OPTIONS_DEFAULTS = OptionGeneral.OPTIONS_DEFAULTS;
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link OptionStyles#initStyles(String, FileConfiguration, BiFunction)} */
|
||||
@Deprecated
|
||||
public static Set<Style> initStyles(String path, FileConfiguration config,
|
||||
BiFunction<String, List<Material>, Style> fn) {
|
||||
return OptionStyles.initStyles(path, config, fn);
|
||||
}
|
||||
|
||||
// ── Inner types ───────────────────────────────────────────────────────────
|
||||
|
||||
public enum ParticleShape { DOT, CIRCLE, BOX }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import org.bukkit.block.BlockFace;
|
|||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
|
@ -17,7 +18,7 @@ import java.util.Map;
|
|||
/**
|
||||
* General configuration options (heading, border, leads, go-back location, parkour options).
|
||||
*/
|
||||
public class OptionGeneral {
|
||||
public final class OptionGeneral {
|
||||
|
||||
private static final int MAX_LEAD = 128;
|
||||
private static final int MIN_AXIS_VALUES = 4;
|
||||
|
|
@ -27,13 +28,12 @@ public class OptionGeneral {
|
|||
private OptionGeneral() {
|
||||
}
|
||||
|
||||
public static double BORDER_SIZE;
|
||||
public static List<Integer> POSSIBLE_LEADS;
|
||||
public static BlockFace HEADING;
|
||||
public static Location GO_BACK_LOC;
|
||||
|
||||
public static Map<ParkourOption, Boolean> OPTIONS_ENABLED;
|
||||
public static Map<ParkourOption, String> OPTIONS_DEFAULTS;
|
||||
private static double borderSize;
|
||||
private static List<Integer> possibleLeads;
|
||||
private static BlockFace heading;
|
||||
private static Location goBackLocation;
|
||||
private static Map<ParkourOption, Boolean> optionsEnabled;
|
||||
private static Map<ParkourOption, String> optionsDefaults;
|
||||
|
||||
public static void init(boolean firstLoad) {
|
||||
initGoBackLocation();
|
||||
|
|
@ -41,7 +41,7 @@ public class OptionGeneral {
|
|||
initHeading();
|
||||
|
||||
if (firstLoad) {
|
||||
BORDER_SIZE = Config.GENERATION.getDouble("advanced.border-size");
|
||||
borderSize = Config.GENERATION.getDouble("advanced.border-size");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -50,17 +50,45 @@ public class OptionGeneral {
|
|||
options.remove(ParkourOption.JOIN);
|
||||
options.remove(ParkourOption.ADMIN);
|
||||
|
||||
OPTIONS_DEFAULTS = new HashMap<>();
|
||||
OPTIONS_ENABLED = new HashMap<>();
|
||||
optionsDefaults = new HashMap<>();
|
||||
optionsEnabled = new HashMap<>();
|
||||
|
||||
for (final ParkourOption option : options) {
|
||||
applyOption(option);
|
||||
}
|
||||
}
|
||||
|
||||
public static double borderSize() {
|
||||
return borderSize;
|
||||
}
|
||||
|
||||
/** Read-only view; the live list is pruned on reload by {@link #initLeads()}. */
|
||||
public static List<Integer> possibleLeads() {
|
||||
return possibleLeads == null ? null : Collections.unmodifiableList(possibleLeads);
|
||||
}
|
||||
|
||||
public static BlockFace heading() {
|
||||
return heading;
|
||||
}
|
||||
|
||||
/** Copy of the configured location, so callers cannot mutate the stored one. */
|
||||
public static Location goBackLocation() {
|
||||
return goBackLocation == null ? null : goBackLocation.clone();
|
||||
}
|
||||
|
||||
/** Read-only view of the option switches. */
|
||||
public static Map<ParkourOption, Boolean> optionsEnabled() {
|
||||
return optionsEnabled == null ? null : Collections.unmodifiableMap(optionsEnabled);
|
||||
}
|
||||
|
||||
/** Read-only view of the option defaults. */
|
||||
public static Map<ParkourOption, String> optionsDefaults() {
|
||||
return optionsDefaults == null ? null : Collections.unmodifiableMap(optionsDefaults);
|
||||
}
|
||||
|
||||
private static void applyOption(ParkourOption option) {
|
||||
final String parent = "default-values." + option.path;
|
||||
OPTIONS_ENABLED.put(option, Config.CONFIG.getBoolean(parent + ".enabled"));
|
||||
optionsEnabled.put(option, Config.CONFIG.getBoolean(parent + ".enabled"));
|
||||
|
||||
final String defaultPath = parent + ".default";
|
||||
if (Config.CONFIG.isPath(defaultPath)) {
|
||||
|
|
@ -88,7 +116,7 @@ public class OptionGeneral {
|
|||
}
|
||||
|
||||
if (value != null && !value.isEmpty()) {
|
||||
OPTIONS_DEFAULTS.put(option, value);
|
||||
optionsDefaults.put(option, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -96,46 +124,46 @@ public class OptionGeneral {
|
|||
if (option == ParkourOption.LANG) {
|
||||
LoParkour.getPlugin().getLogger().warning("LANG default path not found: " + defaultPath);
|
||||
LoParkour.getPlugin().getLogger().warning(
|
||||
"Available keys: " + Config.CONFIG.fileConfiguration.getKeys(true));
|
||||
"Available keys: " + Config.CONFIG.fileConfiguration().getKeys(true));
|
||||
}
|
||||
}
|
||||
|
||||
private static void initGoBackLocation() {
|
||||
GO_BACK_LOC = parseLocation(Config.CONFIG.getString("bungeecord.go-back"));
|
||||
goBackLocation = parseLocation(Config.CONFIG.getString("bungeecord.go-back"));
|
||||
try {
|
||||
final String axesRaw = Config.CONFIG.getString("bungeecord.go-back-axes");
|
||||
if (!axesRaw.isEmpty()) {
|
||||
final String[] axes = axesRaw.split(",");
|
||||
if (axes.length >= 2) {
|
||||
GO_BACK_LOC.setPitch(Float.parseFloat(axes[0].trim()));
|
||||
GO_BACK_LOC.setYaw(Float.parseFloat(axes[1].trim()));
|
||||
goBackLocation.setPitch(Float.parseFloat(axes[0].trim()));
|
||||
goBackLocation.setYaw(Float.parseFloat(axes[1].trim()));
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
} catch (NumberFormatException ex) {
|
||||
LoParkour.getPlugin().getLogger().warning("Invalid bungeecord.go-back-axes, using 0,0");
|
||||
}
|
||||
}
|
||||
|
||||
private static void initLeads() {
|
||||
POSSIBLE_LEADS = Config.CONFIG.getIntList("options.leads.amount");
|
||||
for (final int lead : new ArrayList<>(POSSIBLE_LEADS)) {
|
||||
possibleLeads = Config.CONFIG.getIntList("options.leads.amount");
|
||||
for (final int lead : new ArrayList<>(possibleLeads)) {
|
||||
if (lead < 1 || lead > MAX_LEAD) {
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"Invalid lead: %d. Must be 1–128.".formatted(lead));
|
||||
POSSIBLE_LEADS.remove((Object) lead);
|
||||
possibleLeads.remove((Object) lead);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initHeading() {
|
||||
final String heading = Config.GENERATION.getString("advanced.island.parkour.heading");
|
||||
HEADING = switch (heading.toLowerCase()) {
|
||||
final String headingName = Config.GENERATION.getString("advanced.island.parkour.heading");
|
||||
heading = switch (headingName.toLowerCase()) {
|
||||
case "north" -> BlockFace.NORTH;
|
||||
case "south" -> BlockFace.SOUTH;
|
||||
case "west" -> BlockFace.WEST;
|
||||
case "east" -> BlockFace.EAST;
|
||||
default -> {
|
||||
LoParkour.getPlugin().getLogger().severe("Invalid heading: " + heading);
|
||||
LoParkour.getPlugin().getLogger().severe("Invalid heading: " + headingName);
|
||||
yield BlockFace.NORTH;
|
||||
}
|
||||
};
|
||||
|
|
@ -153,7 +181,7 @@ public class OptionGeneral {
|
|||
}
|
||||
return new Location(world, Double.parseDouble(values[0]),
|
||||
Double.parseDouble(values[1]), Double.parseDouble(values[2]));
|
||||
} catch (Exception ex) {
|
||||
} catch (IllegalArgumentException | IndexOutOfBoundsException ex) {
|
||||
LoParkour.getPlugin().getLogger().warning(
|
||||
"Invalid bungeecord.go-back value '" + location + "'. Falling back to spawn world origin.");
|
||||
final World fallback = Bukkit.getWorlds().isEmpty() ? null : Bukkit.getWorlds().get(0);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
package dev.loki.loparkour.config.options;
|
||||
|
||||
/**
|
||||
* Shape used when spawning trail particles.
|
||||
* Loaded from {@code particles.particle-shape} (see {@code OptionParticles}).
|
||||
*/
|
||||
public enum ParticleShape {
|
||||
|
||||
DOT,
|
||||
CIRCLE,
|
||||
BOX
|
||||
|
||||
}
|
||||
|
|
@ -4,110 +4,121 @@ import dev.loki.loparkour.LoParkour;
|
|||
import dev.loki.loparkour.config.core.Config;
|
||||
|
||||
/**
|
||||
* Generation-related configuration options (validation, memory).
|
||||
* Generation-related configuration options (bounds, memory, jump validation).
|
||||
*
|
||||
* <p>Block-type weights are not read here — they live in
|
||||
* {@code GeneratorProfileManager} / {@code GenerationProfileLoader}, which resolve
|
||||
* the {@code advanced.*} paths (see TODO: {@code generation.type|normal|special}
|
||||
* in generation.yml is currently ignored).</p>
|
||||
*/
|
||||
public class OptionGeneration {
|
||||
public final class OptionGeneration {
|
||||
|
||||
private static final double DEFAULT_MAX_JUMP_DISTANCE = 5.0;
|
||||
private static final double DEFAULT_MAX_HORIZONTAL_DISTANCE = 4.0;
|
||||
private static final double DEFAULT_MAX_VERTICAL_UP = 1.0;
|
||||
private static final double DEFAULT_MAX_VERTICAL_DOWN = 3.0;
|
||||
private static final int DEFAULT_BLOCK_CLEANUP_DISTANCE = 100;
|
||||
private static final int DEFAULT_CLEANUP_INTERVAL = 100;
|
||||
private static final int DEFAULT_TRAIL_KEEP_BEHIND = 10;
|
||||
private static final double PERCENT_DIVISOR = 100.0;
|
||||
private static final int DEFAULT_MIN_Y = 100;
|
||||
private static final int DEFAULT_MAX_Y = 200;
|
||||
|
||||
private OptionGeneration() {
|
||||
}
|
||||
|
||||
// ── Block generation probabilities ────────────────────────────────────────
|
||||
public static double TYPE_NORMAL;
|
||||
public static double TYPE_SPECIAL;
|
||||
public static double TYPE_SCHEMATICS;
|
||||
public static double SPECIAL_ICE;
|
||||
public static double SPECIAL_SLAB;
|
||||
public static double SPECIAL_PANE;
|
||||
public static double SPECIAL_FENCE;
|
||||
public static double NORMAL_DISTANCE_1;
|
||||
public static double NORMAL_DISTANCE_2;
|
||||
public static double NORMAL_DISTANCE_3;
|
||||
public static double NORMAL_DISTANCE_4;
|
||||
public static double NORMAL_HEIGHT_1;
|
||||
public static double NORMAL_HEIGHT_0;
|
||||
public static double NORMAL_HEIGHT_NEG1;
|
||||
public static double NORMAL_HEIGHT_NEG2;
|
||||
public static int MAX_Y;
|
||||
public static int MIN_Y;
|
||||
// ── World bounds ───────────────────────────────────────────────────────────
|
||||
private static int maxY;
|
||||
private static int minY;
|
||||
|
||||
// ── Memory / cleanup ──────────────────────────────────────────────────────
|
||||
public static int BLOCK_CLEANUP_DISTANCE;
|
||||
public static int CLEANUP_INTERVAL;
|
||||
public static int TRAIL_KEEP_BEHIND;
|
||||
// ── Memory / cleanup ───────────────────────────────────────────────────────
|
||||
private static int blockCleanupDistance;
|
||||
private static int cleanupInterval;
|
||||
private static int trailKeepBehind;
|
||||
|
||||
// ── Jump validation ───────────────────────────────────────────────────────
|
||||
public static boolean JUMP_VALIDATION_ENABLED;
|
||||
public static double MAX_JUMP_DISTANCE;
|
||||
public static double MAX_HORIZONTAL_DISTANCE;
|
||||
public static double MAX_VERTICAL_UP;
|
||||
public static double MAX_VERTICAL_DOWN;
|
||||
// ── Jump validation ────────────────────────────────────────────────────────
|
||||
private static boolean jumpValidationEnabled;
|
||||
private static double maxJumpDistance;
|
||||
private static double maxHorizontalDistance;
|
||||
private static double maxVerticalUp;
|
||||
private static double maxVerticalDown;
|
||||
|
||||
public static void init() {
|
||||
initBounds();
|
||||
initJumpValidation();
|
||||
initMemory();
|
||||
initGenerationProbabilities();
|
||||
}
|
||||
|
||||
private static void initJumpValidation() {
|
||||
JUMP_VALIDATION_ENABLED = Config.CONFIG.isPath("jump-validation.enabled")
|
||||
&& Config.CONFIG.getBoolean("jump-validation.enabled");
|
||||
MAX_JUMP_DISTANCE = Config.CONFIG.isPath("jump-validation.max-distance")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-distance") : DEFAULT_MAX_JUMP_DISTANCE;
|
||||
MAX_HORIZONTAL_DISTANCE = Config.CONFIG.isPath("jump-validation.max-horizontal")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-horizontal") : DEFAULT_MAX_HORIZONTAL_DISTANCE;
|
||||
MAX_VERTICAL_UP = Config.CONFIG.isPath("jump-validation.max-vertical-up")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-vertical-up") : 1.0;
|
||||
MAX_VERTICAL_DOWN = Config.CONFIG.isPath("jump-validation.max-vertical-down")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-vertical-down") : DEFAULT_MAX_VERTICAL_DOWN;
|
||||
}
|
||||
private static void initBounds() {
|
||||
maxY = Config.GENERATION.getInt("generation.settings.max-y");
|
||||
minY = Config.GENERATION.getInt("generation.settings.min-y");
|
||||
|
||||
private static void initMemory() {
|
||||
BLOCK_CLEANUP_DISTANCE = Config.CONFIG.isPath("memory.block-cleanup-distance")
|
||||
? Config.CONFIG.getInt("memory.block-cleanup-distance") : DEFAULT_BLOCK_CLEANUP_DISTANCE;
|
||||
CLEANUP_INTERVAL = Config.CONFIG.isPath("memory.cleanup-interval")
|
||||
? Config.CONFIG.getInt("memory.cleanup-interval") : DEFAULT_CLEANUP_INTERVAL;
|
||||
TRAIL_KEEP_BEHIND = Config.CONFIG.isPath("memory.trail-keep-behind")
|
||||
? Config.CONFIG.getInt("memory.trail-keep-behind") : DEFAULT_TRAIL_KEEP_BEHIND;
|
||||
}
|
||||
|
||||
private static void initGenerationProbabilities() {
|
||||
TYPE_NORMAL = Config.GENERATION.getInt("generation.type.normal") / PERCENT_DIVISOR;
|
||||
TYPE_SPECIAL = Config.GENERATION.getInt("generation.type.special") / PERCENT_DIVISOR;
|
||||
TYPE_SCHEMATICS = Config.GENERATION.getInt("generation.type.schematic") / PERCENT_DIVISOR;
|
||||
|
||||
SPECIAL_ICE = Config.GENERATION.getInt("generation.special.ice") / PERCENT_DIVISOR;
|
||||
SPECIAL_SLAB = Config.GENERATION.getInt("generation.special.slab") / PERCENT_DIVISOR;
|
||||
SPECIAL_PANE = Config.GENERATION.getInt("generation.special.pane") / PERCENT_DIVISOR;
|
||||
SPECIAL_FENCE = Config.GENERATION.getInt("generation.special.fence") / PERCENT_DIVISOR;
|
||||
|
||||
NORMAL_DISTANCE_1 = Config.GENERATION.getInt("generation.normal.distance.1") / PERCENT_DIVISOR;
|
||||
NORMAL_DISTANCE_2 = Config.GENERATION.getInt("generation.normal.distance.2") / PERCENT_DIVISOR;
|
||||
NORMAL_DISTANCE_3 = Config.GENERATION.getInt("generation.normal.distance.3") / PERCENT_DIVISOR;
|
||||
NORMAL_DISTANCE_4 = Config.GENERATION.getInt("generation.normal.distance.4") / PERCENT_DIVISOR;
|
||||
|
||||
NORMAL_HEIGHT_1 = Config.GENERATION.getInt("generation.normal.height.1") / PERCENT_DIVISOR;
|
||||
NORMAL_HEIGHT_0 = Config.GENERATION.getInt("generation.normal.height.0") / PERCENT_DIVISOR;
|
||||
NORMAL_HEIGHT_NEG1 = Config.GENERATION.getInt("generation.normal.height.-1") / PERCENT_DIVISOR;
|
||||
NORMAL_HEIGHT_NEG2 = Config.GENERATION.getInt("generation.normal.height.-2") / PERCENT_DIVISOR;
|
||||
|
||||
MAX_Y = Config.GENERATION.getInt("generation.settings.max-y");
|
||||
MIN_Y = Config.GENERATION.getInt("generation.settings.min-y");
|
||||
|
||||
if (MIN_Y >= MAX_Y) {
|
||||
MIN_Y = DEFAULT_MIN_Y;
|
||||
MAX_Y = DEFAULT_MAX_Y;
|
||||
if (minY >= maxY) {
|
||||
minY = DEFAULT_MIN_Y;
|
||||
maxY = DEFAULT_MAX_Y;
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"min-y >= max-y in generation.yml — using defaults 100/200.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void initJumpValidation() {
|
||||
jumpValidationEnabled = Config.CONFIG.isPath("jump-validation.enabled")
|
||||
&& Config.CONFIG.getBoolean("jump-validation.enabled");
|
||||
maxJumpDistance = Config.CONFIG.isPath("jump-validation.max-distance")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-distance") : DEFAULT_MAX_JUMP_DISTANCE;
|
||||
maxHorizontalDistance = Config.CONFIG.isPath("jump-validation.max-horizontal")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-horizontal") : DEFAULT_MAX_HORIZONTAL_DISTANCE;
|
||||
maxVerticalUp = Config.CONFIG.isPath("jump-validation.max-vertical-up")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-vertical-up") : DEFAULT_MAX_VERTICAL_UP;
|
||||
maxVerticalDown = Config.CONFIG.isPath("jump-validation.max-vertical-down")
|
||||
? Config.CONFIG.getDouble("jump-validation.max-vertical-down") : DEFAULT_MAX_VERTICAL_DOWN;
|
||||
}
|
||||
|
||||
private static void initMemory() {
|
||||
blockCleanupDistance = Config.CONFIG.isPath("memory.block-cleanup-distance")
|
||||
? Config.CONFIG.getInt("memory.block-cleanup-distance") : DEFAULT_BLOCK_CLEANUP_DISTANCE;
|
||||
cleanupInterval = Config.CONFIG.isPath("memory.cleanup-interval")
|
||||
? Config.CONFIG.getInt("memory.cleanup-interval") : DEFAULT_CLEANUP_INTERVAL;
|
||||
trailKeepBehind = Config.CONFIG.isPath("memory.trail-keep-behind")
|
||||
? Config.CONFIG.getInt("memory.trail-keep-behind") : DEFAULT_TRAIL_KEEP_BEHIND;
|
||||
}
|
||||
|
||||
public static int maxY() {
|
||||
return maxY;
|
||||
}
|
||||
|
||||
public static int minY() {
|
||||
return minY;
|
||||
}
|
||||
|
||||
public static int blockCleanupDistance() {
|
||||
return blockCleanupDistance;
|
||||
}
|
||||
|
||||
public static int cleanupInterval() {
|
||||
return cleanupInterval;
|
||||
}
|
||||
|
||||
public static int trailKeepBehind() {
|
||||
return trailKeepBehind;
|
||||
}
|
||||
|
||||
public static boolean jumpValidationEnabled() {
|
||||
return jumpValidationEnabled;
|
||||
}
|
||||
|
||||
public static double maxJumpDistance() {
|
||||
return maxJumpDistance;
|
||||
}
|
||||
|
||||
public static double maxHorizontalDistance() {
|
||||
return maxHorizontalDistance;
|
||||
}
|
||||
|
||||
public static double maxVerticalUp() {
|
||||
return maxVerticalUp;
|
||||
}
|
||||
|
||||
public static double maxVerticalDown() {
|
||||
return maxVerticalDown;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.loparkour.config.options.section;
|
|||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.ParticleShape;
|
||||
import dev.loki.loparkour.util.particle.ParticleData;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.Sound;
|
||||
|
|
@ -10,28 +10,52 @@ import org.bukkit.Sound;
|
|||
/**
|
||||
* Particle and sound configuration options.
|
||||
*/
|
||||
public class OptionParticles {
|
||||
public final class OptionParticles {
|
||||
|
||||
private static final int PARTICLE_SIZE = 10;
|
||||
|
||||
private OptionParticles() {
|
||||
}
|
||||
|
||||
public static Option.ParticleShape PARTICLE_SHAPE;
|
||||
public static Sound SOUND_TYPE;
|
||||
public static int SOUND_PITCH;
|
||||
public static int SOUND_VOLUME;
|
||||
public static Particle PARTICLE_TYPE;
|
||||
public static ParticleData<?> PARTICLE_DATA;
|
||||
private static ParticleShape shape;
|
||||
private static Sound soundType;
|
||||
private static int soundPitch;
|
||||
private static int soundVolume;
|
||||
private static Particle particleType;
|
||||
private static ParticleData<?> particleData;
|
||||
|
||||
public static void init() {
|
||||
SOUND_TYPE = resolveSound(Config.CONFIG.getString("particles.sound-type"));
|
||||
PARTICLE_TYPE = resolveParticle(Config.CONFIG.getString("particles.particle-type"));
|
||||
PARTICLE_SHAPE = resolveShape(Config.CONFIG.getString("particles.particle-shape"));
|
||||
soundType = resolveSound(Config.CONFIG.getString("particles.sound-type"));
|
||||
particleType = resolveParticle(Config.CONFIG.getString("particles.particle-type"));
|
||||
shape = resolveShape(Config.CONFIG.getString("particles.particle-shape"));
|
||||
|
||||
SOUND_PITCH = Config.CONFIG.getInt("particles.sound-pitch");
|
||||
SOUND_VOLUME = Config.CONFIG.getInt("particles.sound-volume");
|
||||
PARTICLE_DATA = new ParticleData<>(PARTICLE_TYPE, null, PARTICLE_SIZE);
|
||||
soundPitch = Config.CONFIG.getInt("particles.sound-pitch");
|
||||
soundVolume = Config.CONFIG.getInt("particles.sound-volume");
|
||||
particleData = new ParticleData<>(particleType, null, PARTICLE_SIZE);
|
||||
}
|
||||
|
||||
public static ParticleShape shape() {
|
||||
return shape;
|
||||
}
|
||||
|
||||
public static Sound soundType() {
|
||||
return soundType;
|
||||
}
|
||||
|
||||
public static int soundPitch() {
|
||||
return soundPitch;
|
||||
}
|
||||
|
||||
public static int soundVolume() {
|
||||
return soundVolume;
|
||||
}
|
||||
|
||||
public static Particle particleType() {
|
||||
return particleType;
|
||||
}
|
||||
|
||||
public static ParticleData<?> particleData() {
|
||||
return particleData;
|
||||
}
|
||||
|
||||
private static Sound resolveSound(String name) {
|
||||
|
|
@ -68,13 +92,13 @@ public class OptionParticles {
|
|||
return Particle.values()[0];
|
||||
}
|
||||
|
||||
private static Option.ParticleShape resolveShape(String name) {
|
||||
private static ParticleShape resolveShape(String name) {
|
||||
if (name != null && !name.isEmpty()) {
|
||||
try {
|
||||
return Option.ParticleShape.valueOf(name.toUpperCase());
|
||||
return ParticleShape.valueOf(name.toUpperCase());
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
return Option.ParticleShape.BOX;
|
||||
return ParticleShape.BOX;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,32 +5,66 @@ import dev.loki.loparkour.config.core.Config;
|
|||
/**
|
||||
* SQL database configuration options.
|
||||
*/
|
||||
public class OptionSQL {
|
||||
public final class OptionSQL {
|
||||
|
||||
private OptionSQL() {
|
||||
}
|
||||
|
||||
public static boolean SQL;
|
||||
public static String SQL_URL;
|
||||
public static int SQL_PORT;
|
||||
public static String SQL_DB;
|
||||
public static String SQL_USERNAME;
|
||||
public static String SQL_PASSWORD;
|
||||
public static String SQL_PREFIX;
|
||||
private static boolean sql;
|
||||
private static String url;
|
||||
private static int port;
|
||||
private static String database;
|
||||
private static String username;
|
||||
private static String password;
|
||||
private static String prefix;
|
||||
|
||||
public static void init() {
|
||||
SQL = Config.CONFIG.getBoolean("sql.enabled");
|
||||
SQL_PORT = Config.CONFIG.getInt("sql.port");
|
||||
SQL_DB = Config.CONFIG.getString("sql.database");
|
||||
SQL_URL = Config.CONFIG.getString("sql.url");
|
||||
SQL_USERNAME = Config.CONFIG.getString("sql.username");
|
||||
sql = Config.CONFIG.getBoolean("sql.enabled");
|
||||
port = Config.CONFIG.getInt("sql.port");
|
||||
database = Config.CONFIG.getString("sql.database");
|
||||
url = Config.CONFIG.getString("sql.url");
|
||||
username = Config.CONFIG.getString("sql.username");
|
||||
|
||||
// Environment variable override for password
|
||||
final String envPassword = System.getenv("LOPARKOUR_SQL_PASSWORD");
|
||||
SQL_PASSWORD = (envPassword != null && !envPassword.isEmpty())
|
||||
password = (envPassword != null && !envPassword.isEmpty())
|
||||
? envPassword
|
||||
: Config.CONFIG.getString("sql.password");
|
||||
|
||||
SQL_PREFIX = Config.CONFIG.getString("sql.prefix");
|
||||
prefix = Config.CONFIG.getString("sql.prefix");
|
||||
}
|
||||
|
||||
/** Whether SQL storage is active; turned off when the connection cannot be used. */
|
||||
public static boolean enabled() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
/** Turns SQL off for this session (local storage takes over). */
|
||||
public static void disable() {
|
||||
sql = false;
|
||||
}
|
||||
|
||||
public static String url() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public static int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public static String database() {
|
||||
return database;
|
||||
}
|
||||
|
||||
public static String username() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public static String password() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public static String prefix() {
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import java.util.function.BiFunction;
|
|||
/**
|
||||
* Style initialization utilities.
|
||||
*/
|
||||
public class OptionStyles {
|
||||
public final class OptionStyles {
|
||||
|
||||
private OptionStyles() {
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@ package dev.loki.loparkour.duels;
|
|||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.util.text.ColorUtil;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
|
@ -35,16 +35,16 @@ final class DuelsCountdown {
|
|||
private static final String DEFAULT_COLOR = "E120";
|
||||
|
||||
private final DuelsGenerator generator;
|
||||
private BukkitTask countdownTask;
|
||||
private ScheduledTask countdownTask;
|
||||
|
||||
DuelsCountdown(@NotNull DuelsGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
void giveStartItem(@NotNull ParkourPlayer owner) {
|
||||
Bukkit.getScheduler().runTaskLater(LoParkour.getPlugin(), () -> {
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
if (owner.player.isOnline()) {
|
||||
owner.player.getInventory().addItem(Locales.getItem(owner.locale, "play.multi.duels.start").build());
|
||||
owner.player.getInventory().addItem(Locales.getItem(owner.locale(), "play.multi.duels.start").build());
|
||||
}
|
||||
}, BANNER_DELAY_TICKS);
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ final class DuelsCountdown {
|
|||
void start() {
|
||||
cancel();
|
||||
final int[] counter = {COUNTDOWN_SECONDS};
|
||||
countdownTask = Bukkit.getScheduler().runTaskTimer(LoParkour.getPlugin(),
|
||||
countdownTask = Scheduler.get(LoParkour.getPlugin()).runTimer(
|
||||
() -> tick(counter), 0L, COUNTDOWN_PERIOD);
|
||||
}
|
||||
|
||||
|
|
@ -64,34 +64,32 @@ final class DuelsCountdown {
|
|||
}
|
||||
|
||||
void tick(@NotNull int[] counter) {
|
||||
if (generator.state.stopped) {
|
||||
if (generator.state.stopped()) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
final int current = counter[0]--;
|
||||
if (current == 0) {
|
||||
startRace();
|
||||
return;
|
||||
}
|
||||
if (current <= COUNTDOWN_COLOR_START) {
|
||||
sendCountdownTitle(current);
|
||||
} else {
|
||||
final int current = counter[0]--;
|
||||
if (current == 0) {
|
||||
startRace();
|
||||
} else if (current <= COUNTDOWN_COLOR_START) {
|
||||
sendCountdownTitle(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void startRace() {
|
||||
generator.allowJoining = false;
|
||||
generator.setAllowJoining(false);
|
||||
for (final Map.Entry<ParkourPlayer, SingleDuelsGenerator> entry : generator.playerGenerators.entrySet()) {
|
||||
final Location ps = generator.playerSpawns.get(entry.getKey());
|
||||
if (ps == null) {
|
||||
continue;
|
||||
}
|
||||
final Vector heading = entry.getValue().state.heading;
|
||||
final Vector heading = entry.getValue().state.heading();
|
||||
final Location bs = ps.clone().add(FIRST_BLOCK_FORWARD * heading.getX() - SPAWN_CENTER_OFFSET, 0,
|
||||
FIRST_BLOCK_FORWARD * heading.getZ() - SPAWN_CENTER_OFFSET);
|
||||
entry.getValue().generateFirst(ps, bs);
|
||||
}
|
||||
for (final ParkourPlayer pp : new ArrayList<>(generator.playerGenerators.keySet())) {
|
||||
pp.player.sendTitle(ColorUtil.color(Locales.getString(pp.locale, "play.multi.duels.go")), "", 0, TITLE_STAY, 0);
|
||||
pp.player.sendTitle(ColorUtil.color(Locales.getString(pp.locale(), "play.multi.duels.go")), "", 0, TITLE_STAY, 0);
|
||||
}
|
||||
cancel();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,17 +3,18 @@ package dev.loki.loparkour.duels;
|
|||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.OptionGeneral;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.text.ColorUtil;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
|
|
@ -35,7 +36,7 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
private static final int VICTORY_STAY = 100;
|
||||
private static final int VICTORY_FADE_OUT = 10;
|
||||
|
||||
public boolean allowJoining = true;
|
||||
private boolean allowJoining = true;
|
||||
public final ParkourPlayer owner;
|
||||
public final Map<ParkourPlayer, SingleDuelsGenerator> playerGenerators = new LinkedHashMap<>();
|
||||
public final int goal;
|
||||
|
|
@ -53,6 +54,22 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
countdown.giveStartItem(owner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True while new players may still join this duel.
|
||||
*/
|
||||
public boolean allowJoining() {
|
||||
return allowJoining;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens or closes the duel for new players.
|
||||
*
|
||||
* @param allowJoining Whether joining is allowed.
|
||||
*/
|
||||
public void setAllowJoining(boolean allowJoining) {
|
||||
this.allowJoining = allowJoining;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void generateFirst(Location spawn, Location block) {
|
||||
playerSpawns.put(owner, spawn);
|
||||
|
|
@ -65,76 +82,75 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
|
||||
@Override
|
||||
public void tick() {
|
||||
if (!state.stopped) {
|
||||
if (!state.stopped()) {
|
||||
playerGenerators.values().forEach(SingleDuelsGenerator::tick);
|
||||
}
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull ParkourPlayer pp) {
|
||||
if (!allowJoining || playerGenerators.containsKey(pp)) {
|
||||
return;
|
||||
if (allowJoining && !playerGenerators.containsKey(pp)) {
|
||||
final SingleDuelsGenerator gen = new SingleDuelsGenerator(session);
|
||||
gen.setOwningGenerator(this);
|
||||
gen.setOwnedPlayer(pp);
|
||||
gen.setPlayerIndex(playerGenerators.size());
|
||||
gen.state.setHeading(OptionGeneral.heading().getDirection());
|
||||
placePlayer(pp, gen, session.getSpawnLocation());
|
||||
}
|
||||
final SingleDuelsGenerator gen = new SingleDuelsGenerator(session);
|
||||
gen.owningGenerator = this;
|
||||
gen.setOwnedPlayer(pp);
|
||||
gen.setPlayerIndex(playerGenerators.size());
|
||||
gen.state.heading = Option.HEADING.getDirection();
|
||||
final Location spawnBase = session.getSpawnLocation();
|
||||
if (spawnBase == null || spawnBase.getWorld() == null) {
|
||||
return;
|
||||
}
|
||||
Location platformCenter = spawnBase;
|
||||
if (pp != owner) {
|
||||
platformCenter = spawnBase.clone().add(0, 0, islandDistance * (double) playerGenerators.size());
|
||||
for (int dx = -PLATFORM_RADIUS; dx <= PLATFORM_RADIUS; dx++) {
|
||||
for (int dz = -PLATFORM_RADIUS; dz <= PLATFORM_RADIUS; dz++) {
|
||||
platformCenter.getBlock().getRelative(dx, 0, dz).setType(Material.STONE);
|
||||
}
|
||||
|
||||
private void placePlayer(@NotNull ParkourPlayer pp, @NotNull SingleDuelsGenerator gen,
|
||||
@Nullable Location spawnBase) {
|
||||
if (spawnBase != null && spawnBase.getWorld() != null) {
|
||||
Location platformCenter = spawnBase;
|
||||
if (pp != owner) {
|
||||
platformCenter = spawnBase.clone().add(0, 0, islandDistance * (double) playerGenerators.size());
|
||||
for (int dx = -PLATFORM_RADIUS; dx <= PLATFORM_RADIUS; dx++) {
|
||||
for (int dz = -PLATFORM_RADIUS; dz <= PLATFORM_RADIUS; dz++) {
|
||||
platformCenter.getBlock().getRelative(dx, 0, dz).setType(Material.STONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
final Location playerSpawn = platformCenter.clone().add(SPAWN_CENTER_OFFSET, 1, SPAWN_CENTER_OFFSET);
|
||||
playerSpawns.put(pp, playerSpawn);
|
||||
playerGenerators.put(pp, gen);
|
||||
pp.player.teleport(playerSpawn);
|
||||
}
|
||||
final Location playerSpawn = platformCenter.clone().add(SPAWN_CENTER_OFFSET, 1, SPAWN_CENTER_OFFSET);
|
||||
playerSpawns.put(pp, playerSpawn);
|
||||
playerGenerators.put(pp, gen);
|
||||
pp.player.teleport(playerSpawn);
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull ParkourPlayer pp) {
|
||||
final SingleDuelsGenerator gen = playerGenerators.remove(pp);
|
||||
if (gen == null) {
|
||||
return;
|
||||
}
|
||||
gen.reset(false);
|
||||
if (pp == owner) {
|
||||
countdown.cancel();
|
||||
returnToLobby();
|
||||
return;
|
||||
}
|
||||
if (playerGenerators.size() == 1) {
|
||||
win(new ArrayList<>(playerGenerators.keySet()).get(0));
|
||||
if (gen != null) {
|
||||
gen.reset(false);
|
||||
if (pp == owner) {
|
||||
countdown.cancel();
|
||||
returnToLobby();
|
||||
} else if (playerGenerators.size() == 1) {
|
||||
win(new ArrayList<>(playerGenerators.keySet()).get(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void win(@NotNull ParkourPlayer winner) {
|
||||
if (state.stopped) {
|
||||
if (state.stopped()) {
|
||||
return;
|
||||
}
|
||||
state.stopped = true;
|
||||
state.setStopped(true);
|
||||
countdown.cancel();
|
||||
final String winningName = winner.getName();
|
||||
final String winningTime = playerGenerators.get(winner).getFormattedTime();
|
||||
final List<Map.Entry<ParkourPlayer, SingleDuelsGenerator>> leaderboard =
|
||||
new ArrayList<>(playerGenerators.entrySet());
|
||||
leaderboard.sort((one, two) -> two.getValue().state.score - one.getValue().state.score);
|
||||
leaderboard.sort((one, two) -> two.getValue().state.score() - one.getValue().state.score());
|
||||
for (final ParkourPlayer pp : new ArrayList<>(playerGenerators.keySet())) {
|
||||
pp.send(Locales.getString(pp.locale, "play.multi.duels.overview").formatted(winningName, winningTime));
|
||||
pp.send(Locales.getString(pp.locale(), "play.multi.duels.overview").formatted(winningName, winningTime));
|
||||
for (int i = 0; i < leaderboard.size(); i++) {
|
||||
pp.send(Locales.getString(pp.locale, "play.multi.duels.place")
|
||||
.formatted(i + 1, leaderboard.get(i).getKey().getName(), leaderboard.get(i).getValue().state.score));
|
||||
pp.send(Locales.getString(pp.locale(), "play.multi.duels.place")
|
||||
.formatted(i + 1, leaderboard.get(i).getKey().getName(), leaderboard.get(i).getValue().state.score()));
|
||||
}
|
||||
pp.player.sendTitle(ColorUtil.color(Locales.getString(pp.locale,
|
||||
pp.player.sendTitle(ColorUtil.color(Locales.getString(pp.locale(),
|
||||
pp == winner ? "play.multi.duels.victory" : "play.multi.duels.loss")), "", VICTORY_FADE_IN, VICTORY_STAY, VICTORY_FADE_OUT);
|
||||
}
|
||||
Bukkit.getScheduler().runTaskLater(LoParkour.getPlugin(), () -> returnToLobby(), WIN_RETURN_DELAY_TICKS);
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(this::returnToLobby, WIN_RETURN_DELAY_TICKS);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -155,13 +171,13 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
private void returnToLobby() {
|
||||
for (final ParkourPlayer pp : new ArrayList<>(playerGenerators.keySet())) {
|
||||
if (pp.player.isOnline() && playerGenerators.containsKey(pp)) {
|
||||
Modes.DEFAULT.create(pp.player);
|
||||
Modes.defaultMode().create(pp.player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mode getMode() {
|
||||
return Modes.DUELS;
|
||||
return Modes.duels();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import dev.loki.loparkour.player.core.ParkourPlayer;
|
|||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -42,8 +43,8 @@ public class DuelsMode implements MultiMode {
|
|||
|
||||
@Override
|
||||
public void create(Player player) {
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator instanceof DuelsGenerator) {
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof DuelsGenerator) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -51,7 +52,7 @@ public class DuelsMode implements MultiMode {
|
|||
|
||||
final int maxPlayers = getMaxPlayers();
|
||||
Session.create(DuelsGenerator::new,
|
||||
session -> session.getPlayers().size() < maxPlayers && ((DuelsGenerator) session.generator).allowJoining,
|
||||
session -> session.getPlayers().size() < maxPlayers && ((DuelsGenerator) session.generator()).allowJoining(),
|
||||
null,
|
||||
player);
|
||||
}
|
||||
|
|
@ -66,16 +67,16 @@ public class DuelsMode implements MultiMode {
|
|||
|
||||
final ParkourPlayer pp = ParkourUser.register(player, session);
|
||||
session.addPlayers(pp);
|
||||
((DuelsGenerator) session.generator).addPlayer(pp);
|
||||
((DuelsGenerator) session.generator()).addPlayer(pp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void leave(Player player, Session session) {
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp == null || session.getPlayers().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
((DuelsGenerator) session.generator).removePlayer(pp);
|
||||
((DuelsGenerator) session.generator()).removePlayer(pp);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import java.util.List;
|
|||
* One parkour course per duels player, isolated from everyone else.
|
||||
*
|
||||
* <p>Scoring only looks at the owned player: {@link #getPlayers()} returns just
|
||||
* the owned player, so {@code state.history}/{@code state.score} belong to that
|
||||
* the owned player, so {@code state.history}/{@code state.score()} belong to that
|
||||
* single course. The owning {@link DuelsGenerator} ticks every instance.</p>
|
||||
*/
|
||||
public class SingleDuelsGenerator extends ParkourGenerator {
|
||||
|
|
@ -26,7 +26,7 @@ public class SingleDuelsGenerator extends ParkourGenerator {
|
|||
Material.LIGHT_GRAY_CONCRETE, Material.BLACK_CONCRETE, Material.GREEN_CONCRETE, Material.BROWN_CONCRETE,
|
||||
Material.CYAN_CONCRETE, Material.PURPLE_CONCRETE, Material.GRAY_CONCRETE, Material.PINK_CONCRETE);
|
||||
|
||||
public DuelsGenerator owningGenerator;
|
||||
private DuelsGenerator owningGenerator;
|
||||
private ParkourPlayer ownedPlayer;
|
||||
private BlockData blockData;
|
||||
private boolean won;
|
||||
|
|
@ -52,6 +52,10 @@ public class SingleDuelsGenerator extends ParkourGenerator {
|
|||
state.specialChances.clear();
|
||||
}
|
||||
|
||||
public void setOwningGenerator(@NotNull DuelsGenerator generator) {
|
||||
this.owningGenerator = generator;
|
||||
}
|
||||
|
||||
public void setOwnedPlayer(@NotNull ParkourPlayer pp) {
|
||||
this.ownedPlayer = pp;
|
||||
}
|
||||
|
|
@ -95,7 +99,7 @@ public class SingleDuelsGenerator extends ParkourGenerator {
|
|||
}
|
||||
|
||||
private void checkWin() {
|
||||
if (!won && owningGenerator != null && state.score >= owningGenerator.goal) {
|
||||
if (!won && owningGenerator != null && state.score() >= owningGenerator.goal) {
|
||||
won = true;
|
||||
owningGenerator.win(ownedPlayer);
|
||||
}
|
||||
|
|
@ -103,6 +107,6 @@ public class SingleDuelsGenerator extends ParkourGenerator {
|
|||
|
||||
@Override
|
||||
public Mode getMode() {
|
||||
return Modes.DUELS;
|
||||
return Modes.duels();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.close;
|
||||
|
||||
import dev.loki.loparkour.elytra.core.ElytraGenerator;
|
||||
import dev.loki.loparkour.elytra.section.ElytraPointType;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
|
||||
/**
|
||||
|
|
@ -9,6 +11,6 @@ import dev.loki.loparkour.session.core.Session;
|
|||
public class CloseGenerator extends ElytraGenerator {
|
||||
|
||||
public CloseGenerator(Session session) {
|
||||
super(session, ElytraPointType.FLAT);
|
||||
super(session, ElytraPointType.FLAT, Modes.close());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.close;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.CloseGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class CloseMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof CloseMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof CloseMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(CloseGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(CloseGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.core;
|
||||
|
||||
import dev.loki.loparkour.elytra.section.ElytraSection;
|
||||
import dev.loki.loparkour.util.misc.Compat;
|
||||
|
|
@ -28,19 +28,21 @@ final class ElytraBoost {
|
|||
private int boostedSectionIdx = Integer.MIN_VALUE;
|
||||
|
||||
void tick(Player player, ElytraSection section, int idx) {
|
||||
if (!section.isAscending()) {
|
||||
return;
|
||||
if (section.isAscending()) {
|
||||
boostIfValid(player, section, idx);
|
||||
}
|
||||
}
|
||||
|
||||
private void boostIfValid(Player player, ElytraSection section, int idx) {
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
final Vector direction = section.end().clone().subtract(section.beginning()).normalize();
|
||||
if (direction.lengthSquared() < EPSILON) {
|
||||
return;
|
||||
}
|
||||
if (idx != boostedSectionIdx && section.isNearKnot(pos, 0, NEAR_KNOT_DISTANCE)) {
|
||||
applyInitialBoost(player, idx, direction);
|
||||
}
|
||||
if (pos.getX() >= section.beginning().getX() && pos.getX() < section.end().getX()) {
|
||||
sustain(player, direction);
|
||||
if (direction.lengthSquared() >= EPSILON) {
|
||||
if (idx != boostedSectionIdx && section.isNearKnot(pos, 0, NEAR_KNOT_DISTANCE)) {
|
||||
applyInitialBoost(player, idx, direction);
|
||||
}
|
||||
if (pos.getX() >= section.beginning().getX() && pos.getX() < section.end().getX()) {
|
||||
sustain(player, direction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.core;
|
||||
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.elytra.section.ClientBlockChanger;
|
||||
|
|
@ -15,6 +15,7 @@ import org.bukkit.Material;
|
|||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
|
@ -25,23 +26,29 @@ public class ElytraGenerator extends ParkourGenerator {
|
|||
private static final double GENERATE_DISTANCE = 6.0;
|
||||
public final Map<Integer, ElytraSection> sections = new LinkedHashMap<>();
|
||||
public final ClientBlockChanger blockChanger = new ClientBlockChanger();
|
||||
protected double movementScore = 0.0;
|
||||
private double movementScore = 0.0;
|
||||
private Long startTime = null;
|
||||
private Vector playerSpawn;
|
||||
private Vector blockSpawn;
|
||||
private Random random;
|
||||
protected final ElytraPointType pointType;
|
||||
private final Mode mode;
|
||||
private final int radius;
|
||||
private final Material material;
|
||||
private final ElytraBoost boost = new ElytraBoost();
|
||||
|
||||
public ElytraGenerator(Session session) {
|
||||
this(session, ElytraPointType.CIRCLE);
|
||||
this(session, ElytraPointType.CIRCLE, Modes.elytra());
|
||||
}
|
||||
|
||||
protected ElytraGenerator(Session session, ElytraPointType pointType) {
|
||||
protected ElytraGenerator(Session session, Mode mode) {
|
||||
this(session, ElytraPointType.CIRCLE, mode);
|
||||
}
|
||||
|
||||
protected ElytraGenerator(Session session, ElytraPointType pointType, Mode mode) {
|
||||
super(session);
|
||||
this.pointType = pointType;
|
||||
this.mode = mode;
|
||||
this.radius = Config.GENERATION.getInt("elytra.radius", DEFAULT_RADIUS);
|
||||
this.material = Materials.parseOr(Config.GENERATION.getString("advanced.island.parkour.first-block-material"), Material.WHITE_STAINED_GLASS);
|
||||
}
|
||||
|
|
@ -87,25 +94,27 @@ public class ElytraGenerator extends ParkourGenerator {
|
|||
@Override
|
||||
public void tick() {
|
||||
final Player player = getPlayer();
|
||||
if (player == null || sections.isEmpty()) {
|
||||
return;
|
||||
if (player != null && !sections.isEmpty()) {
|
||||
tickPlayer(player);
|
||||
}
|
||||
}
|
||||
|
||||
private void tickPlayer(@NotNull Player player) {
|
||||
final int idx = sections.keySet().stream().max(Integer::compareTo).orElse(-1);
|
||||
final ElytraSection section = sections.get(idx);
|
||||
if (section == null) {
|
||||
return;
|
||||
}
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
applyScoring(player, pos);
|
||||
blockChanger.check(player, material);
|
||||
removeOldest(player);
|
||||
if (shouldReset(player, pos)) {
|
||||
reset(true);
|
||||
return;
|
||||
}
|
||||
boost.tick(player, section, idx);
|
||||
if (section.isNearKnot(pos, 2, GENERATE_DISTANCE)) {
|
||||
generate();
|
||||
if (section != null) {
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
applyScoring(player, pos);
|
||||
blockChanger.check(player, material);
|
||||
removeOldest(player);
|
||||
if (shouldReset(player, pos)) {
|
||||
reset(true);
|
||||
} else {
|
||||
boost.tick(player, section, idx);
|
||||
if (section.isNearKnot(pos, 2, GENERATE_DISTANCE)) {
|
||||
generate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +142,12 @@ public class ElytraGenerator extends ParkourGenerator {
|
|||
|
||||
@Override
|
||||
public Mode getMode() {
|
||||
return Modes.ELYTRA;
|
||||
return mode;
|
||||
}
|
||||
|
||||
/** The configured {@code elytra.radius}. Sub-modes build their own geometry on top of the same value. */
|
||||
protected int radius() {
|
||||
return radius;
|
||||
}
|
||||
|
||||
public int getElytraScore() {
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.core;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.ElytraGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class ElytraMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof ElytraMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ElytraMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(ElytraGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(ElytraGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.minspeed;
|
||||
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.elytra.core.ElytraGenerator;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
|
@ -18,7 +20,7 @@ public class MinSpeedGenerator extends ElytraGenerator {
|
|||
private int ticksTooSlow = 0;
|
||||
|
||||
public MinSpeedGenerator(Session session) {
|
||||
super(session);
|
||||
super(session, Modes.minSpeed());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.minspeed;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.MinSpeedGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class MinSpeedMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof MinSpeedMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof MinSpeedMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(MinSpeedGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(MinSpeedGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.obstacle;
|
||||
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.elytra.core.ElytraGenerator;
|
||||
import dev.loki.loparkour.elytra.section.ElytraPointType;
|
||||
import dev.loki.loparkour.elytra.section.ElytraSection;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
|
@ -21,16 +22,13 @@ import java.util.concurrent.ThreadLocalRandom;
|
|||
*/
|
||||
public class ObstacleGenerator extends ElytraGenerator {
|
||||
|
||||
private static final int DEFAULT_RADIUS = 3;
|
||||
private static final int OBSTACLE_STEP = 3;
|
||||
private static final int OBSTACLE_KNOT = 3;
|
||||
|
||||
private final Map<Integer, List<Vector>> obstacles = new HashMap<>();
|
||||
private final int radius;
|
||||
|
||||
public ObstacleGenerator(Session session) {
|
||||
super(session);
|
||||
radius = Config.GENERATION.getInt("elytra.radius", DEFAULT_RADIUS);
|
||||
super(session, Modes.obstacle());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -47,16 +45,12 @@ public class ObstacleGenerator extends ElytraGenerator {
|
|||
|
||||
private void generateObstacle(int idx, ElytraSection section, int knotIdx) {
|
||||
final Obstacle obstacle = Obstacle.values()[ThreadLocalRandom.current().nextInt(Obstacle.values().length)];
|
||||
final List<Vector> points = obstacle.getPoints(section.getKnot(knotIdx), radius);
|
||||
if (points.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final List<Vector> points = obstacle.getPoints(section.getKnot(knotIdx), radius());
|
||||
final Player player = getPlayer();
|
||||
if (player == null) {
|
||||
return;
|
||||
if (!points.isEmpty() && player != null) {
|
||||
blockChanger.sendNow(player, points, Material.YELLOW_CONCRETE);
|
||||
obstacles.computeIfAbsent(idx, key -> new ArrayList<>()).addAll(points);
|
||||
}
|
||||
blockChanger.sendNow(player, points, Material.YELLOW_CONCRETE);
|
||||
obstacles.computeIfAbsent(idx, key -> new ArrayList<>()).addAll(points);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.obstacle;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.ObstacleGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class ObstacleMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof ObstacleMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ObstacleMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(ObstacleGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(ObstacleGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.speeddemon;
|
||||
|
||||
import dev.loki.loparkour.elytra.core.ElytraGenerator;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
|
@ -13,7 +15,7 @@ public class SpeedDemonGenerator extends ElytraGenerator {
|
|||
private double maxSpeed = 0;
|
||||
|
||||
public SpeedDemonGenerator(Session session) {
|
||||
super(session);
|
||||
super(session, Modes.speedDemon());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.speeddemon;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.SpeedDemonGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class SpeedDemonMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof SpeedDemonMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof SpeedDemonMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(SpeedDemonGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(SpeedDemonGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
package dev.loki.loparkour.elytra.generator;
|
||||
package dev.loki.loparkour.elytra.timetrial;
|
||||
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.elytra.core.ElytraGenerator;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
|
||||
/**
|
||||
|
|
@ -11,7 +13,7 @@ public class TimeTrialGenerator extends ElytraGenerator {
|
|||
private static final int SCORE = Config.GENERATION.getInt("mode-settings.time-trial.score", 500);
|
||||
|
||||
public TimeTrialGenerator(Session session) {
|
||||
super(session);
|
||||
super(session, Modes.timeTrial());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.loparkour.elytra.mode;
|
||||
package dev.loki.loparkour.elytra.timetrial;
|
||||
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.elytra.generator.TimeTrialGenerator;
|
||||
import dev.loki.loparkour.leaderboard.core.Leaderboard;
|
||||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.ModeMessages;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Item;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
|
@ -43,13 +43,10 @@ public class TimeTrialMode implements Mode {
|
|||
return;
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof TimeTrialMode) {
|
||||
return;
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof TimeTrialMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(TimeTrialGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(TimeTrialGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.loparkour.generator.core.coordinator;
|
||||
|
||||
import dev.loki.loparkour.generator.jump.calculation.JumpType;
|
||||
import dev.loki.loparkour.generator.jump.model.JumpType;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
|
|
|||
|
|
@ -170,8 +170,8 @@ public class GeneratorProfileManager {
|
|||
}
|
||||
|
||||
normalizeMap(generator.state.specialChances);
|
||||
} catch (Exception ignored) {
|
||||
// special blocks config optional
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// special blocks config optional: bad numbers/materials only disable specials
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,20 +6,22 @@ import dev.loki.loparkour.leaderboard.model.Score;
|
|||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Manages generator statistics and time formatting.
|
||||
*/
|
||||
public class GeneratorStatistics {
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
|
||||
|
||||
public GeneratorStatistics(@NotNull ParkourGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get formatted time string.
|
||||
*/
|
||||
|
|
@ -27,7 +29,7 @@ public class GeneratorStatistics {
|
|||
public String getFormattedTime() {
|
||||
return getTime("mm:ss.SSS");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get detailed time string.
|
||||
*/
|
||||
|
|
@ -35,14 +37,14 @@ public class GeneratorStatistics {
|
|||
public String getDetailedTime() {
|
||||
return getTime("HH:mm:ss.SSS");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register score in leaderboard.
|
||||
*/
|
||||
public void registerScore(@NotNull String time, @NotNull String difficulty, int score) {
|
||||
final Mode mode = generator.getMode();
|
||||
final Leaderboard leaderboard = mode.getLeaderboard();
|
||||
|
||||
|
||||
for (final ParkourPlayer player : generator.getPlayers()) {
|
||||
final Score playerScore = new Score(
|
||||
player.player.getName(),
|
||||
|
|
@ -50,42 +52,43 @@ public class GeneratorStatistics {
|
|||
difficulty,
|
||||
score
|
||||
);
|
||||
|
||||
|
||||
leaderboard.put(player.getUUID(), playerScore);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Send fall message to players.
|
||||
*/
|
||||
public void sendFallMessage(int record) {
|
||||
for (final ParkourPlayer player : generator.getPlayers()) {
|
||||
final String message;
|
||||
|
||||
if (generator.state.score > record) {
|
||||
|
||||
if (generator.state.score() > record) {
|
||||
// New record
|
||||
message = Locales.getString(player.player, "parkour.fall.new-record")
|
||||
.replace("%score%", String.valueOf(generator.state.score))
|
||||
.replace("%score%", String.valueOf(generator.state.score()))
|
||||
.replace("%time%", getFormattedTime());
|
||||
} else {
|
||||
// Regular fall
|
||||
message = Locales.getString(player.player, "parkour.fall.regular")
|
||||
.replace("%score%", String.valueOf(generator.state.score))
|
||||
.replace("%score%", String.valueOf(generator.state.score()))
|
||||
.replace("%record%", String.valueOf(record))
|
||||
.replace("%time%", getFormattedTime());
|
||||
}
|
||||
|
||||
|
||||
player.player.sendMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@NotNull
|
||||
private String getTime(@NotNull String format) {
|
||||
if (generator.state.start == null) {
|
||||
final @Nullable Instant start = generator.state.start();
|
||||
if (start == null) {
|
||||
return "00:00.000";
|
||||
}
|
||||
|
||||
final long elapsed = java.time.Duration.between(generator.state.start, java.time.Instant.now()).toMillis();
|
||||
final long elapsed = Duration.between(start, Instant.now()).toMillis();
|
||||
final Duration d = Duration.ofMillis(elapsed);
|
||||
|
||||
if ("HH:mm:ss.SSS".equals(format)) {
|
||||
|
|
|
|||
|
|
@ -26,13 +26,13 @@ import java.util.List;
|
|||
* Coordinates profile management, statistics, and core generation.
|
||||
*/
|
||||
public class ParkourGenerator {
|
||||
|
||||
|
||||
public final Session session;
|
||||
public final Island island;
|
||||
public final Profile profile;
|
||||
public final GeneratorState state;
|
||||
public final GeneratorOption[] generatorOptions;
|
||||
|
||||
|
||||
protected final BlockPlacer placer;
|
||||
protected final GeneratorLifecycle lifecycle;
|
||||
public final GeneratorProfileManager profileManager;
|
||||
|
|
@ -40,7 +40,7 @@ public class ParkourGenerator {
|
|||
|
||||
// Event listeners for adaptive system integration
|
||||
private final List<GeneratorEventListener> eventListeners;
|
||||
|
||||
|
||||
public ParkourGenerator(@NotNull Session session, GeneratorOption... generatorOptions) {
|
||||
this.session = session;
|
||||
this.generatorOptions = generatorOptions;
|
||||
|
|
@ -55,7 +55,7 @@ public class ParkourGenerator {
|
|||
if (selection == null || selection.length < 2) {
|
||||
throw new IllegalArgumentException("Invalid session zone: selection must contain at least 2 locations");
|
||||
}
|
||||
this.state.zone = selection;
|
||||
this.state.setZone(selection);
|
||||
}
|
||||
|
||||
// Initialize components
|
||||
|
|
@ -68,8 +68,8 @@ public class ParkourGenerator {
|
|||
profileManager.overrideProfile();
|
||||
profileManager.calculateChances();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// Core generation methods
|
||||
public void generate() {
|
||||
placer.generate();
|
||||
|
|
@ -99,52 +99,52 @@ public class ParkourGenerator {
|
|||
protected void score() {
|
||||
lifecycle.score();
|
||||
}
|
||||
|
||||
|
||||
public void reset(boolean regenerate) {
|
||||
lifecycle.reset(regenerate);
|
||||
|
||||
|
||||
if (regenerate) {
|
||||
profileManager.overrideProfile();
|
||||
profileManager.calculateChances();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Statistics and scoring
|
||||
public void registerScore(String time, String difficulty, int score) {
|
||||
statistics.registerScore(time, difficulty, score);
|
||||
}
|
||||
|
||||
|
||||
public double getDifficultyScore() {
|
||||
return profileManager.getDifficultyScore();
|
||||
}
|
||||
|
||||
|
||||
public String getFormattedTime() {
|
||||
return statistics.getFormattedTime();
|
||||
}
|
||||
|
||||
|
||||
public String getDetailedTime() {
|
||||
return statistics.getDetailedTime();
|
||||
}
|
||||
|
||||
|
||||
// UI and player management
|
||||
public void menu(ParkourPlayer player) {
|
||||
Menus.PARKOUR_SETTINGS.open(player);
|
||||
public void menu(ParkourPlayer player) {
|
||||
Menus.PARKOUR_SETTINGS.open(player);
|
||||
}
|
||||
|
||||
public Mode getMode() {
|
||||
return Modes.DEFAULT;
|
||||
|
||||
public Mode getMode() {
|
||||
return Modes.defaultMode();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<ParkourPlayer> getPlayers() {
|
||||
return session.getPlayers();
|
||||
|
||||
@NotNull
|
||||
public List<ParkourPlayer> getPlayers() {
|
||||
return session.getPlayers();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<ParkourSpectator> getSpectators() {
|
||||
return session.getSpectators();
|
||||
|
||||
@NotNull
|
||||
public List<ParkourSpectator> getSpectators() {
|
||||
return session.getSpectators();
|
||||
}
|
||||
|
||||
|
||||
/** Last generated block, or {@code null} if history is empty. */
|
||||
public @Nullable Block getLatest() {
|
||||
if (state.history.isEmpty()) {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import org.bukkit.Location;
|
|||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
|
|
@ -14,36 +15,30 @@ import java.util.Map;
|
|||
|
||||
/**
|
||||
* Holds all state data for parkour generation.
|
||||
* No logic - just data and getters/setters.
|
||||
* No logic - just data and accessors.
|
||||
*/
|
||||
public class GeneratorState {
|
||||
|
||||
// Score state
|
||||
public int score = 0;
|
||||
public int totalScore = 0;
|
||||
public int schematicCooldown;
|
||||
public boolean stopped = false;
|
||||
private int score;
|
||||
private boolean stopped;
|
||||
|
||||
// Location state
|
||||
public Location blockSpawn;
|
||||
public Location playerSpawn;
|
||||
public Location lastStandingPlayerLocation;
|
||||
public Vector heading;
|
||||
public Location[] zone; // [min, max] bounding box for generation area
|
||||
// Location state — seeded before the first jump is calculated: the zone by ParkourGenerator,
|
||||
// the heading by Island, the spawn by BlockPlacer, so readers treat all three as non-null.
|
||||
private Location playerSpawn;
|
||||
private Vector heading;
|
||||
private Location[] zone; // [min, max] bounding box for generation area
|
||||
|
||||
// Time state
|
||||
public Instant start;
|
||||
// Time state — null until the first block is scored.
|
||||
private @Nullable Instant start;
|
||||
|
||||
// Block history — all access is main-thread-only (Bukkit scheduler runTimer), so no sync wrapper needed.
|
||||
// Iteration is safe without external synchronization as all mutations happen on the same thread.
|
||||
public final List<Block> history = new ArrayList<>();
|
||||
public int lastPositionIndexPlayer = -1;
|
||||
public int generatedBlocks = 0;
|
||||
private int generatedBlocks;
|
||||
|
||||
// Schematic state
|
||||
public boolean deleteSchematic = false;
|
||||
public boolean waitForSchematicCompletion = false;
|
||||
public List<Block> schematicBlocks = new ArrayList<>();
|
||||
// Schematic state — null while no schematic is pasted.
|
||||
private @Nullable List<Block> schematicBlocks;
|
||||
|
||||
// Chance maps
|
||||
public final Map<Integer, Double> distanceChances = new HashMap<>();
|
||||
|
|
@ -51,21 +46,78 @@ public class GeneratorState {
|
|||
public final Map<BlockData, Double> specialChances = new HashMap<>();
|
||||
public final Map<ParkourGenerator.BlockGenerationType, Double> defaultChances = new HashMap<>();
|
||||
|
||||
public GeneratorState() {}
|
||||
public int score() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(int score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
/** Zeroes the score and restarts the timer. */
|
||||
public void resetScore() {
|
||||
score = 0;
|
||||
start = null;
|
||||
}
|
||||
|
||||
public void clearHistory() {
|
||||
history.clear();
|
||||
lastPositionIndexPlayer = 0;
|
||||
public boolean stopped() {
|
||||
return stopped;
|
||||
}
|
||||
|
||||
public void resetSchematicState() {
|
||||
waitForSchematicCompletion = false;
|
||||
deleteSchematic = true;
|
||||
schematicBlocks.clear();
|
||||
public void setStopped(boolean stopped) {
|
||||
this.stopped = stopped;
|
||||
}
|
||||
|
||||
public Location playerSpawn() {
|
||||
return playerSpawn;
|
||||
}
|
||||
|
||||
public void setPlayerSpawn(Location playerSpawn) {
|
||||
this.playerSpawn = playerSpawn;
|
||||
}
|
||||
|
||||
public Vector heading() {
|
||||
return heading;
|
||||
}
|
||||
|
||||
public void setHeading(Vector heading) {
|
||||
this.heading = heading;
|
||||
}
|
||||
|
||||
public Location[] zone() {
|
||||
return zone;
|
||||
}
|
||||
|
||||
public void setZone(Location[] zone) {
|
||||
this.zone = zone;
|
||||
}
|
||||
|
||||
public @Nullable Instant start() {
|
||||
return start;
|
||||
}
|
||||
|
||||
public void setStart(Instant start) {
|
||||
this.start = start;
|
||||
}
|
||||
|
||||
public int generatedBlocks() {
|
||||
return generatedBlocks;
|
||||
}
|
||||
|
||||
public void setGeneratedBlocks(int generatedBlocks) {
|
||||
this.generatedBlocks = generatedBlocks;
|
||||
}
|
||||
|
||||
/** Counts blocks placed by one generation step (a schematic may place several at once). */
|
||||
public void addGeneratedBlocks(int count) {
|
||||
generatedBlocks += count;
|
||||
}
|
||||
|
||||
public @Nullable List<Block> schematicBlocks() {
|
||||
return schematicBlocks;
|
||||
}
|
||||
|
||||
public void setSchematicBlocks(@Nullable List<Block> schematicBlocks) {
|
||||
this.schematicBlocks = schematicBlocks;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.loparkour.generator.core.model;
|
|||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.core.Config;
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.OptionGeneral;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.item.Materials;
|
||||
|
||||
|
|
@ -11,7 +11,6 @@ import org.bukkit.Material;
|
|||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
|
@ -30,7 +29,7 @@ public final class Island {
|
|||
|
||||
public final Session session;
|
||||
|
||||
public List<Block> blocks;
|
||||
private List<Block> blocks;
|
||||
|
||||
public Island(@NotNull Session session) {
|
||||
this.session = session;
|
||||
|
|
@ -46,14 +45,13 @@ public final class Island {
|
|||
final int cy = location.getBlockY();
|
||||
final int cz = location.getBlockZ();
|
||||
|
||||
final BlockFace face = Option.HEADING;
|
||||
final BlockFace face = OptionGeneral.heading();
|
||||
final int hx = face.getModX();
|
||||
final int hz = face.getModZ();
|
||||
|
||||
if (session.generator.state.heading == null) {
|
||||
session.generator.state.heading = face.getDirection();
|
||||
if (session.generator().state.heading() == null) {
|
||||
session.generator().state.setHeading(face.getDirection());
|
||||
}
|
||||
final Vector h = session.generator.state.heading;
|
||||
|
||||
String firstBlockStr = Config.GENERATION.getString("advanced.island.parkour.first-block-material");
|
||||
if (firstBlockStr.isBlank()) {
|
||||
|
|
@ -85,12 +83,12 @@ public final class Island {
|
|||
|
||||
final Location parkourStart = world.getBlockAt(qx, qy, qz).getLocation();
|
||||
|
||||
session.generator.generateFirst(ps, parkourStart);
|
||||
session.generator.startTick();
|
||||
session.generator().generateFirst(ps, parkourStart);
|
||||
session.generator().startTick();
|
||||
session.getPlayers().forEach(pp -> pp.setup(ps));
|
||||
|
||||
if (LoParkour.getGhostService() != null) {
|
||||
LoParkour.getGhostService().startRun(session.generator);
|
||||
LoParkour.getGhostService().startRun(session.generator());
|
||||
}
|
||||
|
||||
this.blocks = placed;
|
||||
|
|
|
|||
|
|
@ -51,16 +51,16 @@ public class JumpCalculator {
|
|||
*/
|
||||
@NotNull
|
||||
public Block calculateNextBlock(@NotNull Block current, int distance, int height) {
|
||||
if (generator.state.zone == null || generator.state.zone.length < 2) {
|
||||
if (generator.state.zone() == null || generator.state.zone().length < 2) {
|
||||
throw new IllegalStateException("Generator zone not initialized");
|
||||
}
|
||||
|
||||
final JumpDirector director = new JumpDirector(
|
||||
BoundingBox.of(generator.state.zone[0], generator.state.zone[1]),
|
||||
BoundingBox.of(generator.state.zone()[0], generator.state.zone()[1]),
|
||||
current.getLocation().toVector()
|
||||
);
|
||||
|
||||
generator.state.heading = director.getRecommendedHeading(generator.state.heading);
|
||||
generator.state.setHeading(director.getRecommendedHeading(generator.state.heading()));
|
||||
int resolvedHeight = director.getRecommendedHeight(height);
|
||||
|
||||
final JumpConstraints constraints = calculateJumpConstraints(current);
|
||||
|
|
@ -76,7 +76,7 @@ public class JumpCalculator {
|
|||
|
||||
final double randomOffsetSd = Arrays.asList(generator.generatorOptions)
|
||||
.contains(GeneratorOption.REDUCE_RANDOM_BLOCK_SELECTION_ANGLE) ? RANDOM_OFFSET_SD : DEFAULT_RANDOM_OFFSET_SD;
|
||||
final Location candidate = validateAndRetryJump(current.getLocation(), generator.state.heading,
|
||||
final Location candidate = validateAndRetryJump(current.getLocation(), generator.state.heading(),
|
||||
resolvedDistance, resolvedHeight, ThreadLocalRandom.current(), randomOffsetSd);
|
||||
return candidate.getBlock();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ public class JumpOffsetGenerator {
|
|||
final Map<Double, Double> distribution = java.util.stream.IntStream.range(-maxOffset, maxOffset + 1)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(
|
||||
offset -> (double) offset,
|
||||
offset -> (double) offset,
|
||||
offset -> Probs.normalpdf(mean, standardDeviation, (double) offset)
|
||||
));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.loparkour.generator.jump.calculation;
|
||||
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.section.OptionGeneration;
|
||||
import dev.loki.loparkour.util.misc.MaterialUtil;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.util.Vector;
|
||||
|
|
@ -24,10 +24,10 @@ public class JumpValidator {
|
|||
|
||||
public JumpValidator() {
|
||||
this(
|
||||
Option.JUMP_VALIDATION_ENABLED ? Option.MAX_JUMP_DISTANCE : MAX_JUMP_DISTANCE,
|
||||
Option.JUMP_VALIDATION_ENABLED ? Option.MAX_HORIZONTAL_DISTANCE : MAX_HORIZONTAL_DISTANCE,
|
||||
Option.JUMP_VALIDATION_ENABLED ? Option.MAX_VERTICAL_UP : MAX_VERTICAL_UP,
|
||||
Option.JUMP_VALIDATION_ENABLED ? Option.MAX_VERTICAL_DOWN : MAX_VERTICAL_DOWN
|
||||
OptionGeneration.jumpValidationEnabled() ? OptionGeneration.maxJumpDistance() : MAX_JUMP_DISTANCE,
|
||||
OptionGeneration.jumpValidationEnabled() ? OptionGeneration.maxHorizontalDistance() : MAX_HORIZONTAL_DISTANCE,
|
||||
OptionGeneration.jumpValidationEnabled() ? OptionGeneration.maxVerticalUp() : MAX_VERTICAL_UP,
|
||||
OptionGeneration.jumpValidationEnabled() ? OptionGeneration.maxVerticalDown() : MAX_VERTICAL_DOWN
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -43,13 +43,13 @@ public class JumpValidator {
|
|||
if (from == null || to == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Check if jumping from a bottom slab - adjust limits accordingly
|
||||
final double heightAdjustment = getSlabHeightAdjustment(from);
|
||||
|
||||
|
||||
return canJumpWithAdjustment(from.toVector(), to.toVector(), heightAdjustment);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get height adjustment for slab blocks.
|
||||
* Returns negative value for bottom slabs (player is lower).
|
||||
|
|
@ -67,59 +67,46 @@ public class JumpValidator {
|
|||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Mock blocks in tests cannot be inspected; fall back to no adjustment
|
||||
// Boundary: block inspection may fail on mocks or across versions; fall back to no adjustment.
|
||||
}
|
||||
return 0.0; // No adjustment for full blocks
|
||||
}
|
||||
|
||||
|
||||
private boolean canJumpWithAdjustment(@NotNull Vector from, @NotNull Vector to, double heightAdjustment) {
|
||||
// Null safety check
|
||||
if (from == null || to == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
final double dx = to.getX() - from.getX();
|
||||
final double dy = to.getY() - from.getY();
|
||||
final double dz = to.getZ() - from.getZ();
|
||||
|
||||
// Check if same location (no jump)
|
||||
// Same-location check (no jump)
|
||||
final double horizontalDistance = Math.sqrt(dx * dx + dz * dz);
|
||||
if (horizontalDistance < SAME_LOCATION_EPSILON && Math.abs(dy) < SAME_LOCATION_EPSILON) {
|
||||
return false; // Same location
|
||||
}
|
||||
|
||||
// Check horizontal distance limit
|
||||
if (horizontalDistance > maxHorizontal) {
|
||||
return false;
|
||||
}
|
||||
final boolean sameLocation = horizontalDistance < SAME_LOCATION_EPSILON && Math.abs(dy) < SAME_LOCATION_EPSILON;
|
||||
|
||||
// Adjust vertical limits based on slab height
|
||||
double adjustedMaxVerticalUp = maxVerticalUp;
|
||||
double adjustedMaxVerticalDown = maxVerticalDown;
|
||||
|
||||
if (heightAdjustment < 0) {
|
||||
// Player is lower (bottom slab), reduce upward jump capability
|
||||
adjustedMaxVerticalUp = maxVerticalUp + heightAdjustment; // Reduce max up jump
|
||||
adjustedMaxVerticalDown = maxVerticalDown - heightAdjustment; // Increase max down jump
|
||||
}
|
||||
final double adjustedMaxVerticalUp = heightAdjustment < 0
|
||||
? maxVerticalUp + heightAdjustment
|
||||
: maxVerticalUp;
|
||||
final double adjustedMaxVerticalDown = heightAdjustment < 0
|
||||
? maxVerticalDown - heightAdjustment
|
||||
: maxVerticalDown;
|
||||
|
||||
// Check vertical limits with adjustment
|
||||
if (dy > adjustedMaxVerticalUp || dy < -adjustedMaxVerticalDown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For upward jumps, reduce max horizontal distance
|
||||
// Player can't jump as far when jumping up
|
||||
if (dy > 0) {
|
||||
final double adjustedMaxHorizontal = maxHorizontal - (dy * VERTICAL_REDUCTION_FACTOR); // Reduce by 0.5 blocks per block up
|
||||
if (horizontalDistance > adjustedMaxHorizontal) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// For upward jumps, reduce max horizontal distance (player can't jump as far when jumping up)
|
||||
final double effectiveMaxHorizontal = dy > 0
|
||||
? maxHorizontal - (dy * VERTICAL_REDUCTION_FACTOR)
|
||||
: maxHorizontal;
|
||||
|
||||
// Check total distance
|
||||
final boolean verticalOk = dy <= adjustedMaxVerticalUp && dy >= -adjustedMaxVerticalDown;
|
||||
final double totalDistance = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
return totalDistance <= maxDistance;
|
||||
|
||||
return !sameLocation
|
||||
&& horizontalDistance <= maxHorizontal
|
||||
&& verticalOk
|
||||
&& horizontalDistance <= effectiveMaxHorizontal
|
||||
&& totalDistance <= maxDistance;
|
||||
}
|
||||
|
||||
// Check if jump is possible: sqrt(dx² + dy² + dz²) <= maxDistance
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
package dev.loki.loparkour.generator.jump.calculation;
|
||||
package dev.loki.loparkour.generator.jump.model;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
|
@ -2,6 +2,7 @@ package dev.loki.loparkour.generator.jump.placement;
|
|||
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.generator.jump.calculation.JumpCalculator;
|
||||
import dev.loki.loparkour.generator.jump.placement.schematic.SchematicBlockPlacer;
|
||||
import dev.loki.loparkour.util.misc.Probs;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.block.Block;
|
||||
|
|
@ -54,8 +55,8 @@ public class BlockPlacer {
|
|||
|
||||
worldPlacer.place(block, blockData);
|
||||
generator.state.history.add(block);
|
||||
generator.state.generatedBlocks++;
|
||||
generator.state.playerSpawn = spawn;
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
generator.state.setPlayerSpawn(spawn);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -94,32 +95,27 @@ public class BlockPlacer {
|
|||
|
||||
final boolean tall = targetSelector.isTallMaterial(blockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
if (!blocks.isEmpty()) {
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, blockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, blockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.generatedBlocks++;
|
||||
}
|
||||
|
||||
private void placeSpecialBlock() {
|
||||
final BlockData specialBlockData = Probs.random(generator.state.specialChances);
|
||||
if (specialBlockData == null) {
|
||||
placeNormalBlock();
|
||||
return;
|
||||
} else {
|
||||
final boolean tall = targetSelector.isTallMaterial(specialBlockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (!blocks.isEmpty()) {
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, specialBlockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
}
|
||||
|
||||
final boolean tall = targetSelector.isTallMaterial(specialBlockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, specialBlockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.generatedBlocks++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.loparkour.generator.jump.placement;
|
|||
|
||||
import dev.loki.loparkour.api.core.Registry;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.generator.jump.calculation.JumpType;
|
||||
import dev.loki.loparkour.generator.jump.model.JumpType;
|
||||
import dev.loki.loparkour.style.core.Style;
|
||||
import dev.loki.loparkour.util.misc.MaterialUtil;
|
||||
import org.bukkit.Material;
|
||||
|
|
@ -16,13 +16,13 @@ import java.util.List;
|
|||
* Handles selection of block types and materials for parkour generation.
|
||||
*/
|
||||
public class BlockSelector {
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
|
||||
|
||||
public BlockSelector(@NotNull ParkourGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
|
||||
private static final int MAX_STYLE_PICKS = 64;
|
||||
private static final int MAX_SLAB_PICKS = 20;
|
||||
|
||||
|
|
@ -66,7 +66,7 @@ public class BlockSelector {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Select jump type based on current configuration and probabilities.
|
||||
*/
|
||||
|
|
@ -76,7 +76,7 @@ public class BlockSelector {
|
|||
final JumpType[] types = JumpType.values();
|
||||
return types[(int) (Math.random() * types.length)];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a slab material from the current player's style.
|
||||
*/
|
||||
|
|
@ -87,7 +87,7 @@ public class BlockSelector {
|
|||
if (style == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// Try to get a slab material from the style multiple times
|
||||
for (int i = 0; i < MAX_SLAB_PICKS; i++) {
|
||||
final Material material = style.getNext();
|
||||
|
|
@ -100,7 +100,7 @@ public class BlockSelector {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if material is a special block type that affects jump mechanics.
|
||||
*/
|
||||
|
|
@ -114,7 +114,7 @@ public class BlockSelector {
|
|||
isTrapdoorMaterial(material) ||
|
||||
material == Material.LADDER;
|
||||
}
|
||||
|
||||
|
||||
public boolean isFenceMaterial(@NotNull Material material) {
|
||||
return material == Material.OAK_FENCE ||
|
||||
material == Material.BIRCH_FENCE ||
|
||||
|
|
@ -127,7 +127,7 @@ public class BlockSelector {
|
|||
material == Material.WARPED_FENCE ||
|
||||
material == Material.NETHER_BRICK_FENCE;
|
||||
}
|
||||
|
||||
|
||||
public boolean isTrapdoorMaterial(@NotNull Material material) {
|
||||
return material == Material.OAK_TRAPDOOR ||
|
||||
material == Material.BIRCH_TRAPDOOR ||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import java.util.List;
|
|||
/**
|
||||
* Computes the target block position for generated parkour blocks based on jump parameters.
|
||||
*/
|
||||
class BlockTargetSelector {
|
||||
public class BlockTargetSelector {
|
||||
|
||||
private static final int NO_FORCED_HEIGHT = Integer.MIN_VALUE;
|
||||
|
||||
|
|
@ -32,7 +32,7 @@ class BlockTargetSelector {
|
|||
}
|
||||
|
||||
@NotNull
|
||||
List<Block> selectBlocks() {
|
||||
public List<Block> selectBlocks() {
|
||||
return selectBlocks(NO_FORCED_HEIGHT);
|
||||
}
|
||||
|
||||
|
|
@ -49,4 +49,4 @@ class BlockTargetSelector {
|
|||
blocks.add(nextBlock);
|
||||
return blocks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ import org.bukkit.Sound;
|
|||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Applies block data to the world and plays placement effects for all players.
|
||||
|
|
@ -45,9 +48,11 @@ class BlockWorldPlacer {
|
|||
}
|
||||
|
||||
void deleteSchematic() {
|
||||
if (generator.state.schematicBlocks != null) {
|
||||
generator.state.schematicBlocks.forEach(block -> block.setType(Material.AIR));
|
||||
generator.state.schematicBlocks.clear();
|
||||
final @Nullable List<Block> blocks = generator.state.schematicBlocks();
|
||||
if (blocks == null) {
|
||||
return;
|
||||
}
|
||||
blocks.forEach(block -> block.setType(Material.AIR));
|
||||
blocks.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
package dev.loki.loparkour.generator.jump.placement;
|
||||
package dev.loki.loparkour.generator.jump.placement.schematic;
|
||||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.api.event.generation.ParkourSchematicGenerateEvent;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.generator.jump.placement.BlockTargetSelector;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.schematic.core.ParkourSchematic;
|
||||
import dev.loki.loparkour.schematic.core.SchematicManager;
|
||||
|
|
@ -15,24 +16,24 @@ import java.util.List;
|
|||
/**
|
||||
* Pastes schematic parkour sections into the world and fires the related event.
|
||||
*/
|
||||
class SchematicBlockPlacer {
|
||||
public class SchematicBlockPlacer {
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
private final BlockTargetSelector targetSelector;
|
||||
|
||||
SchematicBlockPlacer(@NotNull ParkourGenerator generator, @NotNull BlockTargetSelector targetSelector) {
|
||||
public SchematicBlockPlacer(@NotNull ParkourGenerator generator, @NotNull BlockTargetSelector targetSelector) {
|
||||
this.generator = generator;
|
||||
this.targetSelector = targetSelector;
|
||||
}
|
||||
|
||||
boolean placeSchematic() {
|
||||
public boolean placeSchematic() {
|
||||
final SchematicManager manager = LoParkour.getSchematicManager();
|
||||
if (manager == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final double maxDifficulty = generator.getPlayers().stream()
|
||||
.mapToDouble(p -> p.schematicDifficulty)
|
||||
.mapToDouble(p -> p.settings().schematicDifficulty())
|
||||
.min()
|
||||
.orElse(1.0);
|
||||
|
||||
|
|
@ -53,12 +54,12 @@ class SchematicBlockPlacer {
|
|||
}
|
||||
|
||||
generator.state.history.addAll(schematicBlocks);
|
||||
generator.state.generatedBlocks += schematicBlocks.size();
|
||||
generator.state.schematicBlocks = schematicBlocks;
|
||||
generator.state.addGeneratedBlocks(schematicBlocks.size());
|
||||
generator.state.setSchematicBlocks(schematicBlocks);
|
||||
|
||||
for (final ParkourPlayer player : generator.getPlayers()) {
|
||||
new ParkourSchematicGenerateEvent(schematic, generator, player).call();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ import org.jetbrains.annotations.NotNull;
|
|||
/**
|
||||
* Refactored GeneratorLifecycle using composition pattern.
|
||||
* Coordinates tick management, player interactions, and visual updates.
|
||||
*
|
||||
*
|
||||
* Responsibilities delegated to:
|
||||
* - LifecycleTickManager: Tick cycle and periodic operations
|
||||
* - PlayerInteractionHandler: Block interactions and scoring
|
||||
|
|
@ -23,7 +23,7 @@ public class GeneratorLifecycle {
|
|||
private final LifecycleVisualUpdater visualUpdater;
|
||||
private final LifecycleEventManager eventManager;
|
||||
private final GeneratorCleanup cleanup;
|
||||
|
||||
|
||||
public GeneratorLifecycle(@NotNull ParkourGenerator generator) {
|
||||
this.eventManager = new LifecycleEventManager(generator);
|
||||
this.cleanup = new GeneratorCleanup(generator);
|
||||
|
|
@ -31,14 +31,14 @@ public class GeneratorLifecycle {
|
|||
this.tickManager = new LifecycleTickManager(generator, cleanup, visualUpdater);
|
||||
this.interactionHandler = new PlayerInteractionHandler(generator, eventManager, cleanup);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Start the tick cycle.
|
||||
*/
|
||||
public void startTick() {
|
||||
tickManager.startTick();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main tick method called every server tick.
|
||||
*/
|
||||
|
|
@ -46,21 +46,21 @@ public class GeneratorLifecycle {
|
|||
tickManager.tick();
|
||||
interactionHandler.checkAllPlayers();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle player scoring.
|
||||
*/
|
||||
public void score() {
|
||||
interactionHandler.handleScore();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle player falling.
|
||||
*/
|
||||
public void fall() {
|
||||
interactionHandler.handleFall();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reset the lifecycle state.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import dev.loki.loparkour.reward.core.Rewards;
|
|||
import org.bukkit.Bukkit;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
|
@ -19,13 +18,13 @@ import java.util.Map;
|
|||
* Manages lifecycle events for parkour generator.
|
||||
*/
|
||||
public class LifecycleEventManager {
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
|
||||
|
||||
public LifecycleEventManager(@NotNull ParkourGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle score event and check rewards.
|
||||
*/
|
||||
|
|
@ -35,11 +34,11 @@ public class LifecycleEventManager {
|
|||
final ParkourScoreEvent scoreEvent = new ParkourScoreEvent(player);
|
||||
Bukkit.getPluginManager().callEvent(scoreEvent);
|
||||
}
|
||||
|
||||
|
||||
// Check for rewards
|
||||
checkRewards();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle fall event.
|
||||
*/
|
||||
|
|
@ -49,37 +48,37 @@ public class LifecycleEventManager {
|
|||
final ParkourFallEvent fallEvent = new ParkourFallEvent(player);
|
||||
Bukkit.getPluginManager().callEvent(fallEvent);
|
||||
}
|
||||
|
||||
|
||||
// Process fall logic
|
||||
processFall();
|
||||
}
|
||||
|
||||
|
||||
private void checkRewards() {
|
||||
if (!Rewards.REWARDS_ENABLED) {
|
||||
if (!Rewards.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final Mode mode = generator.getMode();
|
||||
|
||||
|
||||
for (final ParkourPlayer player : generator.getPlayers()) {
|
||||
final int score = generator.state.score;
|
||||
final int score = generator.state.score();
|
||||
applyScoreRewards(player, mode, score);
|
||||
applyIntervalRewards(player, mode, score);
|
||||
applyOneTimeRewards(player, mode, score);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void applyScoreRewards(@NotNull ParkourPlayer player, @NotNull Mode mode, int score) {
|
||||
if (!Rewards.SCORE_REWARDS.containsKey(score)) {
|
||||
if (!Rewards.scoreRewards().containsKey(score)) {
|
||||
return;
|
||||
}
|
||||
for (final Reward reward : Rewards.SCORE_REWARDS.get(score)) {
|
||||
for (final Reward reward : Rewards.scoreRewards().get(score)) {
|
||||
reward.execute(player, mode);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void applyIntervalRewards(@NotNull ParkourPlayer player, @NotNull Mode mode, int score) {
|
||||
for (final Map.Entry<Integer, List<Reward>> entry : Rewards.INTERVAL_REWARDS.entrySet()) {
|
||||
for (final Map.Entry<Integer, List<Reward>> entry : Rewards.intervalRewards().entrySet()) {
|
||||
if (score > 0 && score % entry.getKey() == 0) {
|
||||
for (final Reward reward : entry.getValue()) {
|
||||
reward.execute(player, mode);
|
||||
|
|
@ -87,37 +86,31 @@ public class LifecycleEventManager {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void applyOneTimeRewards(@NotNull ParkourPlayer player, @NotNull Mode mode, int score) {
|
||||
if (!Rewards.ONE_TIME_REWARDS.containsKey(score)) {
|
||||
return;
|
||||
}
|
||||
if (player.collectedRewards == null) {
|
||||
player.collectedRewards = new ArrayList<>();
|
||||
}
|
||||
final String rewardKey = String.valueOf(score);
|
||||
if (player.collectedRewards.contains(rewardKey)) {
|
||||
return;
|
||||
if (Rewards.oneTimeRewards().containsKey(score)
|
||||
&& !player.settings().collectedRewards().contains(rewardKey)) {
|
||||
for (final Reward reward : Rewards.oneTimeRewards().get(score)) {
|
||||
reward.execute(player, mode);
|
||||
}
|
||||
player.settings().collectedRewards().add(rewardKey);
|
||||
player.save(false);
|
||||
}
|
||||
for (final Reward reward : Rewards.ONE_TIME_REWARDS.get(score)) {
|
||||
reward.execute(player, mode);
|
||||
}
|
||||
player.collectedRewards.add(rewardKey);
|
||||
player.save(false);
|
||||
}
|
||||
|
||||
|
||||
private void processFall() {
|
||||
// Record statistics
|
||||
final int score = generator.state.score;
|
||||
final int score = generator.state.score();
|
||||
final String time = generator.getFormattedTime();
|
||||
final String difficulty = String.valueOf(generator.getDifficultyScore());
|
||||
|
||||
generator.registerScore(time, difficulty, generator.state.score);
|
||||
generator.registerScore(time, difficulty, generator.state.score());
|
||||
|
||||
// Teleport players back to spawn before reset
|
||||
for (final ParkourPlayer player : generator.getPlayers()) {
|
||||
if (generator.state.playerSpawn != null) {
|
||||
player.teleport(generator.state.playerSpawn);
|
||||
if (generator.state.playerSpawn() != null) {
|
||||
player.teleport(generator.state.playerSpawn());
|
||||
}
|
||||
// Clear scored blocks so same coordinates can be re-scored after respawn
|
||||
player.clearScoredBlocks();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.loparkour.generator.lifecycle.loop;
|
||||
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.section.OptionGeneration;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.generator.lifecycle.player.GeneratorCleanup;
|
||||
import org.bukkit.block.Block;
|
||||
|
|
@ -10,18 +10,18 @@ import org.jetbrains.annotations.NotNull;
|
|||
* Manages tick cycle and periodic operations for generator lifecycle.
|
||||
*/
|
||||
public class LifecycleTickManager {
|
||||
|
||||
|
||||
private static final int TIME_UI_INTERVAL = 20; // 1 second — time display tick
|
||||
private static final int GENERATION_LEAD = 2; // keep only 2 blocks ahead, generate more when player approaches end
|
||||
private static final int FALL_THRESHOLD_OFFSET = 30;
|
||||
private static final int MAX_GENERATE_PER_TICK = 5;
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
private final GeneratorCleanup cleanup;
|
||||
private final LifecycleVisualUpdater visualUpdater;
|
||||
|
||||
|
||||
private int tickCounter = 0;
|
||||
|
||||
|
||||
public LifecycleTickManager(
|
||||
@NotNull ParkourGenerator generator,
|
||||
@NotNull GeneratorCleanup cleanup,
|
||||
|
|
@ -30,7 +30,7 @@ public class LifecycleTickManager {
|
|||
this.cleanup = cleanup;
|
||||
this.visualUpdater = visualUpdater;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Start the tick cycle.
|
||||
*/
|
||||
|
|
@ -40,7 +40,7 @@ public class LifecycleTickManager {
|
|||
// Generate initial blocks ahead of the player
|
||||
generator.generate(2);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main tick method called every server tick.
|
||||
*/
|
||||
|
|
@ -50,7 +50,7 @@ public class LifecycleTickManager {
|
|||
// Check if players fell below threshold
|
||||
checkPlayerFall();
|
||||
|
||||
if (tickCounter % Option.CLEANUP_INTERVAL == 0) {
|
||||
if (tickCounter % OptionGeneration.cleanupInterval() == 0) {
|
||||
cleanup.cleanupDistantBlocks();
|
||||
}
|
||||
if (tickCounter % TIME_UI_INTERVAL == 0) {
|
||||
|
|
@ -68,12 +68,12 @@ public class LifecycleTickManager {
|
|||
* Check if any player fell below the threshold.
|
||||
*/
|
||||
private void checkPlayerFall() {
|
||||
if (generator.state.playerSpawn == null) {
|
||||
if (generator.state.playerSpawn() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Block latest = generator.getLatest();
|
||||
final double referenceY = latest != null ? latest.getY() : generator.state.playerSpawn.getY();
|
||||
final double referenceY = latest != null ? latest.getY() : generator.state.playerSpawn().getY();
|
||||
final double fallThreshold = referenceY - FALL_THRESHOLD_OFFSET;
|
||||
|
||||
for (final var player : generator.getPlayers()) {
|
||||
|
|
@ -83,17 +83,17 @@ public class LifecycleTickManager {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reset tick counter.
|
||||
*/
|
||||
public void reset() {
|
||||
tickCounter = 0;
|
||||
}
|
||||
|
||||
|
||||
private void maintainBlockLead() {
|
||||
final int currentBlocks = generator.state.generatedBlocks;
|
||||
final int targetBlocks = generator.state.score + generationLead();
|
||||
final int currentBlocks = generator.state.generatedBlocks();
|
||||
final int targetBlocks = generator.state.score() + generationLead();
|
||||
|
||||
if (currentBlocks < targetBlocks) {
|
||||
final int needed = targetBlocks - currentBlocks;
|
||||
|
|
|
|||
|
|
@ -8,13 +8,13 @@ import org.jetbrains.annotations.NotNull;
|
|||
* Manages visual updates for players during parkour lifecycle.
|
||||
*/
|
||||
public class LifecycleVisualUpdater {
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
|
||||
|
||||
public LifecycleVisualUpdater(@NotNull ParkourGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update visuals for all players.
|
||||
*/
|
||||
|
|
@ -23,7 +23,7 @@ public class LifecycleVisualUpdater {
|
|||
updatePlayerVisuals(player);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update time displays for all players.
|
||||
*/
|
||||
|
|
@ -32,17 +32,17 @@ public class LifecycleVisualUpdater {
|
|||
updatePlayerTimeDisplay(player);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void updatePlayerVisuals(@NotNull ParkourPlayer player) {
|
||||
// Update scoreboard if enabled
|
||||
if (player.showScoreboard != null && player.showScoreboard) {
|
||||
if (player.settings().showScoreboard() != null && player.settings().showScoreboard()) {
|
||||
player.updateScoreboard(generator);
|
||||
}
|
||||
|
||||
|
||||
// Update action bar with time and score
|
||||
updatePlayerTimeDisplay(player);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unused") // reserved for action bar
|
||||
private void updatePlayerTimeDisplay(@NotNull ParkourPlayer player) {
|
||||
// Placeholder for action bar (Paper adventure); scoreboard already shows time/score.
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
package dev.loki.loparkour.generator.lifecycle.player;
|
||||
|
||||
import dev.loki.loparkour.config.options.Option;
|
||||
import dev.loki.loparkour.config.options.OptionGeneral;
|
||||
import dev.loki.loparkour.config.options.section.OptionGeneration;
|
||||
import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
|
@ -21,11 +23,11 @@ public class GeneratorCleanup {
|
|||
private static final int FIRST_BLOCK_OFFSET = 6;
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
|
||||
|
||||
public GeneratorCleanup(@NotNull ParkourGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove only trail blocks <strong>behind</strong> players (oldest indices).
|
||||
* Distance-based cleanup was removing blocks ahead of the player and breaking scoring.
|
||||
|
|
@ -37,17 +39,13 @@ public class GeneratorCleanup {
|
|||
}
|
||||
|
||||
final int minStandingIndex = findMinStandingIndex();
|
||||
if (minStandingIndex == Integer.MAX_VALUE) {
|
||||
return;
|
||||
if (minStandingIndex != Integer.MAX_VALUE) {
|
||||
final int keepBehind = Math.max(0, OptionGeneration.trailKeepBehind());
|
||||
final int removeCount = minStandingIndex - keepBehind;
|
||||
if (removeCount > 0) {
|
||||
clearHistoryHead(history, removeCount);
|
||||
}
|
||||
}
|
||||
|
||||
final int keepBehind = Math.max(0, Option.TRAIL_KEEP_BEHIND);
|
||||
final int removeCount = minStandingIndex - keepBehind;
|
||||
if (removeCount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearHistoryHead(history, removeCount);
|
||||
}
|
||||
|
||||
private int findMinStandingIndex() {
|
||||
|
|
@ -91,13 +89,13 @@ public class GeneratorCleanup {
|
|||
final Block below = loc.subtract(0, 1, 0).getBlock();
|
||||
return below.getType() != Material.AIR ? below : null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove schematic blocks once the player completes them.
|
||||
* The end block is kept in history so the landing player can score it.
|
||||
*/
|
||||
public void removeSchematicBlocks() {
|
||||
final List<Block> schematicBlocks = generator.state.schematicBlocks;
|
||||
final @Nullable List<Block> schematicBlocks = generator.state.schematicBlocks();
|
||||
if (schematicBlocks == null || schematicBlocks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -114,22 +112,21 @@ public class GeneratorCleanup {
|
|||
}
|
||||
|
||||
generator.state.history.removeIf(remove::contains);
|
||||
generator.state.schematicBlocks = null;
|
||||
generator.state.setSchematicBlocks(null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reset generator state and clean up all blocks.
|
||||
*/
|
||||
public void reset(boolean regenerate) {
|
||||
clearBlocks(generator.state.history);
|
||||
clearSchematicBlocks();
|
||||
|
||||
|
||||
// Reset state
|
||||
generator.state.history.clear();
|
||||
generator.state.generatedBlocks = 0;
|
||||
generator.state.score = 0;
|
||||
generator.state.start = null;
|
||||
|
||||
generator.state.setGeneratedBlocks(0);
|
||||
generator.state.resetScore();
|
||||
|
||||
if (regenerate) {
|
||||
regenerateFirstBlock();
|
||||
}
|
||||
|
|
@ -144,15 +141,16 @@ public class GeneratorCleanup {
|
|||
}
|
||||
|
||||
private void clearSchematicBlocks() {
|
||||
if (generator.state.schematicBlocks == null) {
|
||||
final @Nullable List<Block> blocks = generator.state.schematicBlocks();
|
||||
if (blocks == null) {
|
||||
return;
|
||||
}
|
||||
clearBlocks(generator.state.schematicBlocks);
|
||||
generator.state.schematicBlocks.clear();
|
||||
clearBlocks(blocks);
|
||||
blocks.clear();
|
||||
}
|
||||
|
||||
private void regenerateFirstBlock() {
|
||||
final Location spawn = generator.state.playerSpawn;
|
||||
final Location spawn = generator.state.playerSpawn();
|
||||
if (spawn == null) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -164,13 +162,13 @@ public class GeneratorCleanup {
|
|||
|
||||
private static void applyHeading(@NotNull Location blockSpawn) {
|
||||
// Move block forward based on heading (6 blocks forward, same height)
|
||||
switch (Option.HEADING) {
|
||||
switch (OptionGeneral.heading()) {
|
||||
case NORTH -> blockSpawn.add(0, 0, -FIRST_BLOCK_OFFSET);
|
||||
case SOUTH -> blockSpawn.add(0, 0, FIRST_BLOCK_OFFSET);
|
||||
case WEST -> blockSpawn.add(-FIRST_BLOCK_OFFSET, 0, 0);
|
||||
case EAST -> blockSpawn.add(FIRST_BLOCK_OFFSET, 0, 0);
|
||||
default -> {}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,14 +18,14 @@ import java.util.List;
|
|||
* Handles player interactions with parkour blocks.
|
||||
*/
|
||||
public class PlayerInteractionHandler {
|
||||
|
||||
|
||||
private static final int GENERATION_LEAD = 5;
|
||||
private static final double BLOCK_CENTER_XZ_OFFSET = 0.5;
|
||||
|
||||
|
||||
private final ParkourGenerator generator;
|
||||
private final LifecycleEventManager eventManager;
|
||||
private final GeneratorCleanup cleanup;
|
||||
|
||||
|
||||
public PlayerInteractionHandler(
|
||||
@NotNull ParkourGenerator generator,
|
||||
@NotNull LifecycleEventManager eventManager,
|
||||
|
|
@ -34,7 +34,7 @@ public class PlayerInteractionHandler {
|
|||
this.eventManager = eventManager;
|
||||
this.cleanup = cleanup;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check all players for block interactions.
|
||||
*/
|
||||
|
|
@ -61,17 +61,17 @@ public class PlayerInteractionHandler {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle player scoring on a block.
|
||||
*/
|
||||
public void handleScore() {
|
||||
// Start the timer on the very first scored block
|
||||
if (generator.state.start == null) {
|
||||
generator.state.start = Instant.now();
|
||||
if (generator.state.start() == null) {
|
||||
generator.state.setStart(Instant.now());
|
||||
}
|
||||
|
||||
generator.state.score++;
|
||||
generator.state.setScore(generator.state.score() + 1);
|
||||
eventManager.handleScore();
|
||||
|
||||
// Fire event listeners for adaptive system
|
||||
|
|
@ -88,7 +88,7 @@ public class PlayerInteractionHandler {
|
|||
// Block generation is handled by LifecycleTickManager.maintainBlockLead()
|
||||
// to avoid runaway generation in multiplayer (N players = N generates per tick otherwise).
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle player falling.
|
||||
*/
|
||||
|
|
@ -108,7 +108,7 @@ public class PlayerInteractionHandler {
|
|||
}
|
||||
AdaptiveServices.refreshGeneratorDifficulty(generator);
|
||||
}
|
||||
|
||||
|
||||
private void handleBlockInteraction(@NotNull ParkourPlayer player, @NotNull Block block) {
|
||||
// Check if it's a schematic end block
|
||||
if (isSchematicEndBlock(block)) {
|
||||
|
|
@ -127,19 +127,19 @@ public class PlayerInteractionHandler {
|
|||
|
||||
/** Check if block is any schematic block (not just the last one). */
|
||||
private boolean isOnSchematicBlock(@NotNull Block block) {
|
||||
return generator.state.schematicBlocks != null
|
||||
&& historyContains(generator.state.schematicBlocks, block);
|
||||
final @Nullable List<Block> blocks = generator.state.schematicBlocks();
|
||||
return blocks != null && historyContains(blocks, block);
|
||||
}
|
||||
|
||||
|
||||
private void handleSchematicEndBlock() {
|
||||
cleanup.removeSchematicBlocks();
|
||||
|
||||
// Continue normal generation
|
||||
generator.generate(GENERATION_LEAD);
|
||||
}
|
||||
|
||||
|
||||
private boolean isSchematicEndBlock(@NotNull Block block) {
|
||||
final List<Block> schematicBlocks = generator.state.schematicBlocks;
|
||||
final @Nullable List<Block> schematicBlocks = generator.state.schematicBlocks();
|
||||
if (schematicBlocks == null || schematicBlocks.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
|
@ -147,7 +147,7 @@ public class PlayerInteractionHandler {
|
|||
final Block last = schematicBlocks.get(schematicBlocks.size() - 1);
|
||||
return isSameBlock(block, last);
|
||||
}
|
||||
|
||||
|
||||
/** Block directly under feet; {@code null} in air — scoring runs when landed. */
|
||||
@Nullable
|
||||
private Block getBlockBelow(@NotNull ParkourPlayer player) {
|
||||
|
|
|
|||
|
|
@ -105,12 +105,11 @@ public class GhostManager {
|
|||
final File file = new File(playerFolder, data.getTimestamp() + FILE_EXTENSION);
|
||||
try {
|
||||
data.saveToFile(file);
|
||||
evictOldRuns(playerFolder);
|
||||
} catch (IOException e) {
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"Failed to save ghost run for " + data.getPlayerName() + ": " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
evictOldRuns(playerFolder);
|
||||
}
|
||||
|
||||
/** Max runs kept per player; read from config each call so reloads apply. */
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package dev.loki.loparkour.ghost.core;
|
|||
import dev.loki.loparkour.ghost.model.GhostFrame;
|
||||
import dev.loki.loparkour.ghost.model.GhostData;
|
||||
|
||||
import dev.lolib.scheduler.Scheduler;
|
||||
import dev.lolib.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
|
|
@ -17,9 +17,9 @@ import org.jetbrains.annotations.NotNull;
|
|||
*
|
||||
* <p>Bugs fixed vs original:
|
||||
* <ul>
|
||||
* <li>Duplicate import of {@code dev.lolib.scheduler.Scheduler} — removed.</li>
|
||||
* <li>Duplicate field declaration {@code dev.lolib.scheduler.ScheduledTask task}
|
||||
* shadowed the already-imported type — removed the fully-qualified duplicate.</li>
|
||||
* <li>Duplicate scheduler import — removed.</li>
|
||||
* <li>Duplicate {@code ScheduledTask task} field shadowed the already-imported
|
||||
* type — removed the fully-qualified duplicate.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class GhostPlayer {
|
||||
|
|
|
|||
|
|
@ -37,16 +37,11 @@ public class GhostRecorder {
|
|||
}
|
||||
|
||||
public void recordFrame(@NotNull Location currentLocation) {
|
||||
if (!recording) {
|
||||
return;
|
||||
if (recording && lastLocation.distance(currentLocation) >= MIN_MOVEMENT) {
|
||||
final long timestamp = System.currentTimeMillis() - startTime;
|
||||
frames.add(new GhostFrame(timestamp, currentLocation.clone()));
|
||||
lastLocation = currentLocation.clone();
|
||||
}
|
||||
if (lastLocation.distance(currentLocation) < MIN_MOVEMENT) {
|
||||
return;
|
||||
}
|
||||
|
||||
final long timestamp = System.currentTimeMillis() - startTime;
|
||||
frames.add(new GhostFrame(timestamp, currentLocation.clone()));
|
||||
lastLocation = currentLocation.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import dev.loki.loparkour.ghost.model.GhostData;
|
|||
import dev.loki.loparkour.ghost.model.GhostFrame;
|
||||
import dev.loki.loparkour.ghost.replay.PlayerGhost;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.lolib.scheduler.ScheduledTask;
|
||||
import dev.lolib.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
|
|
@ -57,24 +57,24 @@ public class GhostReplay {
|
|||
public void start() {
|
||||
if (run.getFrames().isEmpty()) {
|
||||
onFinish.run();
|
||||
return;
|
||||
} else {
|
||||
final ParkourUser user = ParkourUser.getUser(viewer);
|
||||
if (user != null) {
|
||||
ParkourUser.leave(viewer);
|
||||
}
|
||||
final Location start = run.getFrames().get(FIRST_FRAME).toLocation(world);
|
||||
viewer.teleport(start);
|
||||
moved = true;
|
||||
ghost = new PlayerGhost(viewer, run.getPlayerName());
|
||||
if (ghost.spawn(start)) {
|
||||
startTime = System.currentTimeMillis();
|
||||
frameIndex = FIRST_FRAME;
|
||||
current = start;
|
||||
task = Scheduler.get(LoParkour.getPlugin()).runTimer(this::tick, TICK_DELAY, TICK_PERIOD);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
final ParkourUser user = ParkourUser.getUser(viewer);
|
||||
if (user != null) {
|
||||
ParkourUser.leave(viewer);
|
||||
}
|
||||
final Location start = run.getFrames().get(FIRST_FRAME).toLocation(world);
|
||||
viewer.teleport(start);
|
||||
moved = true;
|
||||
ghost = new PlayerGhost(viewer, run.getPlayerName());
|
||||
if (!ghost.spawn(start)) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
startTime = System.currentTimeMillis();
|
||||
frameIndex = FIRST_FRAME;
|
||||
current = start;
|
||||
task = Scheduler.get(LoParkour.getPlugin()).runTimer(this::tick, TICK_DELAY, TICK_PERIOD);
|
||||
}
|
||||
|
||||
private void tick() {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ public class GhostService {
|
|||
private boolean recordingEnabled(ParkourPlayer pp) {
|
||||
return serverEnabled()
|
||||
&& !replaying.contains(pp.getUUID())
|
||||
&& Boolean.TRUE.equals(pp.ghostRecording);
|
||||
&& Boolean.TRUE.equals(pp.settings().ghostRecording());
|
||||
}
|
||||
|
||||
public void startRun(ParkourGenerator generator) {
|
||||
|
|
@ -79,11 +79,11 @@ public class GhostService {
|
|||
return replaying.contains(uuid);
|
||||
}
|
||||
|
||||
public void setReplaying(UUID uuid, boolean replaying) {
|
||||
if (replaying) {
|
||||
this.replaying.add(uuid);
|
||||
public void setReplaying(UUID uuid, boolean active) {
|
||||
if (active) {
|
||||
replaying.add(uuid);
|
||||
} else {
|
||||
this.replaying.remove(uuid);
|
||||
replaying.remove(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package dev.loki.loparkour.hook.floodgate;
|
|||
import org.bukkit.entity.Player;
|
||||
import org.geysermc.floodgate.api.FloodgateApi;
|
||||
|
||||
public class FloodgateHook {
|
||||
public final class FloodgateHook {
|
||||
|
||||
private FloodgateHook() {}
|
||||
private FloodgateHook() { }
|
||||
|
||||
/**
|
||||
* Whether this player is a bedrock player.
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ import dev.loki.loparkour.leaderboard.model.Score;
|
|||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import me.filoghost.holographicdisplays.api.HolographicDisplaysAPI;
|
||||
|
||||
public class HoloHook {
|
||||
public final class HoloHook {
|
||||
|
||||
private static final int PLACEHOLDER_REFRESH_TICKS = 100;
|
||||
private static final double EASY_DIFFICULTY_MAX = 0.25;
|
||||
private static final double MEDIUM_DIFFICULTY_MAX = 0.5;
|
||||
private static final double HARD_DIFFICULTY_MAX = 0.75;
|
||||
|
||||
private HoloHook() {}
|
||||
private HoloHook() { }
|
||||
|
||||
/**
|
||||
* Initializes this hook.
|
||||
|
|
@ -22,7 +22,7 @@ public class HoloHook {
|
|||
public static void init() {
|
||||
try {
|
||||
Class.forName("me.filoghost.holographicdisplays.api.HolographicDisplaysAPI");
|
||||
} catch (Exception ex) {
|
||||
} catch (ClassNotFoundException | LinkageError ex) {
|
||||
LoParkour.getPlugin().getLogger().warning("##");
|
||||
LoParkour.getPlugin().getLogger().warning("## LoParkour only supports Holographic Displays v3.0.0 or higher!");
|
||||
LoParkour.getPlugin().getLogger().warning("## This hook will now be disabled.");
|
||||
|
|
@ -30,50 +30,47 @@ public class HoloHook {
|
|||
return;
|
||||
}
|
||||
|
||||
HolographicDisplaysAPI.get(LoParkour.getPlugin()).registerGlobalPlaceholder("ip_leaderboard", PLACEHOLDER_REFRESH_TICKS, argument -> {
|
||||
HolographicDisplaysAPI.get(LoParkour.getPlugin())
|
||||
.registerGlobalPlaceholder("ip_leaderboard", PLACEHOLDER_REFRESH_TICKS, HoloHook::resolveLeaderboard);
|
||||
}
|
||||
|
||||
if (argument == null) {
|
||||
return "?";
|
||||
}
|
||||
/** Resolves the {@code {ip_leaderboard: mode, type, #rank}} global placeholder. */
|
||||
private static String resolveLeaderboard(String argument) {
|
||||
if (argument == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
// {ip_leaderboard: default, score, #1}
|
||||
final String[] split = argument.replace(" ", "").split(",");
|
||||
// {ip_leaderboard: default, score, #1}
|
||||
final String[] split = argument.replace(" ", "").split(",");
|
||||
final Mode mode = Registry.getMode(split[0].toLowerCase());
|
||||
final Leaderboard leaderboard = mode == null ? null : mode.getLeaderboard();
|
||||
if (leaderboard == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
final Mode mode = Registry.getMode(split[0].toLowerCase());
|
||||
final String type = split[1].toLowerCase();
|
||||
final String rank = split[2].replace("#", "");
|
||||
final Score score = lookupScore(leaderboard, rank);
|
||||
if (score == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
if (mode == null) {
|
||||
return "?";
|
||||
}
|
||||
return switch (type) {
|
||||
case "score" -> Integer.toString(score.score());
|
||||
case "name" -> score.name();
|
||||
case "time" -> score.time();
|
||||
case "difficulty" -> score.difficulty();
|
||||
case "difficulty_string" -> parseDifficulty(score.difficulty());
|
||||
default -> "?";
|
||||
};
|
||||
}
|
||||
|
||||
final Leaderboard leaderboard = mode.getLeaderboard();
|
||||
|
||||
if (leaderboard == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
final String type = split[1].toLowerCase();
|
||||
final String rank = split[2].replace("#", "");
|
||||
|
||||
final Score score;
|
||||
try {
|
||||
score = leaderboard.getScoreAtRank(Integer.parseInt(rank));
|
||||
} catch (NumberFormatException e) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
if (score == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
return switch (type) {
|
||||
case "score" -> Integer.toString(score.score());
|
||||
case "name" -> score.name();
|
||||
case "time" -> score.time();
|
||||
case "difficulty" -> score.difficulty();
|
||||
case "difficulty_string" -> parseDifficulty(score.difficulty());
|
||||
default -> "?";
|
||||
};
|
||||
});
|
||||
private static Score lookupScore(Leaderboard leaderboard, String rank) {
|
||||
try {
|
||||
return leaderboard.getScoreAtRank(Integer.parseInt(rank));
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String parseDifficulty(String string) {
|
||||
|
|
|
|||
|
|
@ -38,4 +38,4 @@ public class PAPIHook extends PlaceholderExpansion {
|
|||
public String onPlaceholderRequest(Player player, @NotNull String params) {
|
||||
return dispatcher.dispatch(player, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,4 +20,4 @@ class PlaceholderDispatcher {
|
|||
}
|
||||
return playerResolver.resolve(player, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue