Commit Graph
15 Commits
Author SHA1 Message Date
Josh Shippam 60463d7c31 Client, Script & Plugin Improvements (#687)
* fix(audio,client): start music immediately on login/track change and remove non-HD tooltip jitter

Eliminates artificial client-side music start and fade-out delays across all platforms, prioritizes music packets at the start of server login, and replaces jittery non-HD hover tooltips in Game.java.

### Core & Client Rendering
- 2006Scape Client/src/main/java/Game.java:
  - Updated method49() to call method853(musicVolume2, is, aBoolean995) directly on all platforms instead of routing through method684/method899 fade-out queues.
  - Reset anInt720 to 0 in constructMusic(), method853(), and method368() when stopped so the initial track and post-login music start without a 20-tick (~400ms) delay.
  - Replaced the non-HD chatTextDrawingArea.method390(..., loopCycle / 1000, ...) fallback with chatTextDrawingArea.textLeftShadow(...) so Walk here and hover tooltips render crisply with HD disabled.

### Server Login Audio
- 2006Scape Server/src/main/java/com/rs2/net/PacketSender.java:
  - Moved music/sound volume configs (168, 169), player.getPlayList().sendMusicConfigs(), and Music.playMusic(player) to run right after frame 249 and duplicate-login checks in loginPlayer(), flushing the login song before quest, skill, sidebar, and equipment packets.

* refactor(ui): use ClientSettings.SERVER_NAME in Plugin Hub modal title

Replaces the hardcoded RUNELITE prefix in the Plugin Hub modal header with ClientSettings.SERVER_NAME so the UI branding stays consistent with the configured server name.

### UI & Styling
- 2006Scape Client/src/main/java/PluginPanelUI.java:
  - Updated drawViewportModal title formatting to use ClientSettings.SERVER_NAME + " PLUGIN & SCRIPT HUB" (and " PLUGIN HUB" when scripts are unavailable).

* feat(client): migrate Ground Items and Menu Entry Swapper plugins to online repository

Removes the built-in `GroundItemsOverlayPlugin` and `MenuEntrySwapperPlugin` classes from the client bundle so players install them manually from the Online Repo tab (`2006scape-plugins`), and adds minimal `ScriptInterpreter`, `PluginContext`, and `PluginGraphics` host support so both plugins run natively in the interpreted plugin dialect.

### Plugin Host Infrastructure
- `ScriptInterpreter.java`:
  - Added `@defaultEnabled` metadata parsing (`ScriptMetadata.defaultEnabled`) and overrode `InterpretedPlugin.isEnabledByDefault()`.
  - Registered `MenuEntry.class` in `compile(String)` so interpreted plugins can invoke `MenuEntry.stripColorTags(...)` and menu entry helpers.
  - Overrode `InterpretedPlugin.onCommand(String, String[])` to forward chat commands (`command`, joined `args`) to interpreted plugins.
- `PluginContext.java`:
  - Added `createList()` and `createMap()` collection helpers for interpreted plugins.
- `PluginGraphics.java`:
  - Added `worldToScreenList(int, int, int)` returning a 2-element `List<Integer>` for array-free coordinate projection.

### Cleanups & Deprecations
- `PluginManager.java`:
  - Removed `MenuEntrySwapperPlugin` and `GroundItemsOverlayPlugin` registrations from `registerBuiltIns()`, leaving `Hd317Plugin`.
- `MenuEntrySwapperPlugin.java`, `GroundItemsOverlayPlugin.java`:
  - Removed built-in plugin classes (migrated to `2006scape-plugins/plugins/MenuEntrySwapper.java` and `GroundItems.java`).

* perf(plugins): optimize ScriptInterpreter/PluginContext and fix Web Online Repo SHA lookup

Improve script/plugin execution speed for TeaVM/Web and Desktop/Android, add throttled in-game chat error reporting, and fix Online Repo commit SHA resolution on Web.

### Script & Plugin Engine
- `PluginContext.java`
  - Added `getGroundItems(int radius)` to scan only `[plx - radius, plx + radius]` x `[ply - radius, ply + radius]` instead of the full 104x104 tile grid, with a `game == null` fallback to `getGroundItems()` for unit test mocks.
- `ScriptInterpreter.java`
  - Pre-parsed `FunctionDef` bodies into `List<Stmt>` (`parseBlock`, `parseIfStatement`, `parseSimpleStatement`) at compile time, removing per-execution substring scanning in `executeStmts`.
  - Added `METHOD_CACHE` (`getCachedMethods`) to index public methods by lowercase name per `Class<?>`, eliminating repeated `clazz.getMethods()` scans in `invokeReflectiveMethod`.
  - Added `Environment.reportedErrors` and `reportRuntimeError` to surface the first uncaught runtime error per function to in-game chat.
- `PluginManager.java`
  - Added `reportedPluginErrors` (cleared on `reloadExternal()`) and `reportPluginError` across `onGameTick`, `onPostBuildMenu`, and `onRenderOverlays` to surface the first error per plugin/phase to in-game chat.

### Online Repository
- `PluginRepoClient.java`
  - Added `REPO_COMMIT_API_URL` using `PLUGIN_REPO_SLUG` (`2006-Scape/Client-Extensions`) and `PLUGIN_REPO_BRANCH` (`main`) as a CORS-friendly fallback in `resolveLatestMainSha()` when `.git/info/refs` is unavailable in the browser.

* perf(graphics): add native drawTileLabelBatches for ground item overlays

Move per-frame ground item tile and label rendering loops from interpreted script execution into compiled Java on `PluginGraphics` to eliminate per-frame TeaVM reflection and AST overhead.

### Graphics Pipeline
- `PluginGraphics.java`
  - Added `drawTileLabelBatches(List<?>, int, int)` to project cached tile coordinates (`worldToScreen` with `worldToScreenList` fallback for unit test mocks), lazily cache `getTextWidth`, render lootbeams, and draw label boxes/text in compiled Java.

* perf(plugins): add ground item signature and native tile batch builder to PluginContext

Eliminate periodic stutters caused by `GroundItems` rebuilding its tile cache in `ScriptInterpreter` every 500ms by providing a zero-allocation ground item fingerprint and compiled batch builder.

### Plugin API
- `PluginContext.java`
  - Added `getGroundItemsSignature(int radius)` to compute a lightweight FNV-1a fingerprint of ground items within `radius` tiles without allocating `GroundItemWrapper` objects or looking up `ItemDef`.
  - Added `buildGroundItemTiles(...)` to perform wildcard filtering, duplicate collapsing, sorting, label/quantity/value formatting, and border/lootbeam preparation in compiled Java.

* refactor(plugins): remove GroundItems-specific buildGroundItemTiles from PluginContext

Keep `PluginContext` limited to generic client API primitives (`getGroundItems(int)` and `getGroundItemsSignature(int)`) while moving Ground Items-specific grouping, tier coloring, and label formatting back into the plugin.

### Cleanups & Deprecations
- `PluginContext.java`
  - Removed `buildGroundItemTiles(...)` and its private helpers (`matchesAnyPattern`, `getGroundItemColor`, `formatItemQuantity`, `formatItemValue`) along with unused `Map`/`HashMap`/`LinkedHashMap` imports.

* feat(scripts): add ternary, modulo, compound assignments, constructors, list literals, and indexing

Expand `ScriptInterpreter` expression and statement support to simplify plugin and script authoring across Desktop, Android, and Web.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added short-circuiting ternary (`cond ? a : b` with `findMatchingTernaryColon`), `%` modulo operator, and unified `+=`, `-=`, `*=`, `/=`, `%=` compound assignments.
  - Added `target[index]` reads and `target[index] = value` writes for `List`, `Map`, arrays, and `String`, plus bracket-aware `findTopLevelOp` and `parseArguments`.
  - Added `[a, b, c]` list literals and `new ClassName(...)` constructors (`ArrayList`, `HashMap`, `LinkedHashMap`, `HashSet`, `StringBuilder`, `WorldArea`, `MenuEntry`, plus reflective constructor fallback).
  - Fast-pathed `StringBuilder` (`append`, `toString`, `length`, `setLength`) in `invokeMethod` and fixed `findMethodOpenParen` to ignore parentheses inside string literals.
- `ScriptInterpreterTest.java`
  - Added `evaluatesTernaryModuloConstructorsAndIndexing` covering ternary, `%`, `*=`, `/=`, `%=`, list literals, `new HashMap()`, `new StringBuilder()`, indexing, and unbalanced parentheses inside strings.

* fix(scripts): support long literals with L suffix in ScriptInterpreter

Parse integer literals ending in `l` or `L` (e.g. `0L`) as `Long` instead of returning `null`.

### Bug Fixes & Edge Cases
- `ScriptInterpreter.java`
  - Added `^-?\d+[lL]$` literal handling in `evalExpression` before standard integer literal parsing.

* feat(scripts): add for/for-each/switch/break/continue, braceless blocks, and TeaVM fast-paths

Expand `ScriptInterpreter` control-flow support and add direct non-reflective fast-paths for `PluginContext`, `PluginGraphics`, `MenuEntry`, and `GroundItemWrapper` to eliminate TeaVM `Class.getMethods()` `ReferenceError`s and per-tick reflection overhead.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added `for (init; cond; update)`, enhanced `for (var : iterable)`, `switch`/`case`/`default`, `break`/`continue` (`BreakSignal`, `ContinueSignal`), and braceless single-statement bodies (`parseBodyOrSingleStatement`) for `if`, `else`, `while`, and `for`.
  - Added direct fast-paths in `invokeMethod` for `PluginContext` (`isLoggedIn`, `getGroundItems`, `getGroundItemsSignature`, `createList`, `createMap`, `sendClientMessage`, `getPlayerX`, `getPlayerY`, `getPlayerAnim`, `isBankOpen`, `getInventoryCount`, `walkTo`), `PluginContext.GroundItemWrapper` (`getDistance`), `MenuEntry` (`stripColorTags`, `matches`, `getAction`, `getTarget`, `getRawText`, `setRawText`), and `PluginGraphics` (`drawTileLabelBatches`, `fillRect`, `drawRect`, `drawCenteredString`, `drawString`, `drawStringBold`, `getTextWidth`, `getTextWidthBold`, `worldToScreenList`, `drawLootbeam`, `getViewportWidth`, `getViewportHeight`).
  - Added `try/catch` guard around `clazz.getMethods()` in `getCachedMethods` and included `[expr|phase]` diagnostics in `reportRuntimeError`.

### Unit Tests
- `ScriptInterpreterTest.java`
  - Added `evaluatesForLoopsBreakContinueBracelessAndSwitch` covering `for`, `for-each`, `break`, `continue`, braceless `if`, `switch` fallthrough/default, and `MenuEntry` fast-paths.

* feat(plugin-hub): add multi-line STRING config editor overlay and localStorage config seeding

Replaces the non-editable "(Edit in .properties or chat)" placeholder in Plugin Hub settings with an interactive multi-line text editor overlay supporting cursor navigation and click positioning. Also seeds plugin settings on first boot and adds live localStorage reload support for web/cross-platform storage editing.

### Command Infrastructure
- `PluginManager.java`:
  - Added `reloadStorage()` and `applyConfigToPlugin(...)` so external storage edits hot-reload `2006scape_plugin_settings` and `2006scape_script_*` entries into active plugins and scripts.
  - Updated `loadConfig()` to call `saveConfig()` when `DesktopHooks.loadPluginConfig()` returns `null`, seeding `2006scape_plugin_settings` on first boot.
- `RSApplet.java`:
  - Queued Left (`1`) and Right (`2`) arrow keys into `charQueue` when `PluginPanelUI.isSearchFocused()` is true so arrow-key cursor movement reaches the modal editor without affecting normal gameplay.

### UI & Edge Cases
- `PluginPanelUI.java`:
  - Replaced `(Edit in .properties or chat)` with a `220px` preview box in `drawConfigEditor` and `handleConfigTab`.
  - Added `drawConfigStringEditorOverlay`, `getStringEditorBounds`, and `wrapTextForWidth` to render a focused multi-line wrapped editor (up to 1,024 chars) with Clear, Cancel, and Save buttons.
  - Added `editingStringCursor` with Left/Right arrow, Home/End, mid-string insert/backspace, vertical gold caret rendering, auto-scroll to keep the cursor line visible, and pixel-accurate click-to-place-cursor support.
  - Added `commitStringEdit(PluginManager)` to auto-commit on blur, Back, or Close.
2026-12-02 18:29:47 +00:00
Josh Shippam c37e3e8dfb Various Changes & Issue Fixes (#686)
* fix(client): restore authentic 317/377 minimap fallback walk radius in doWalkTo

Restores the client-side pathfinding fallback search radius in `Game.doWalkTo` to match authentic 2006 RS2 / 317 client behavior when clicking unreachable tiles such as underground void or blocked terrain. Previously, the search radius was restricted to a single tile, causing minimap and ground clicks more than one tile into unwalkable areas to be silently ignored.

### Bug Fixes & Edge Cases
- `2006Scape Client/src/main/java/Game.java` (`doWalkTo`):
  - Expanded the alternative-destination search loop from `k5 < 2` (1-tile radius) to `k5 < 11` (10-tile Chebyshev radius, matching authentic 317/377 clients) when `flag` is `true` and the exact target tile is unreachable.
  - Preserves the existing `i5 = 100` maximum path-cost threshold and `104x104` region boundary checks (`i6 >= 0 && l6 >= 0 && i6 < 104 && l6 < 104`), allowing players to walk to the nearest reachable tile when clicking black void on the minimap.

Closes #380

* fix(firemaking): fix fire lighting race, object sync, level scaling, and log walk-on

Fixes firemaking reliability, object lifecycle desyncs, and authentic 2006 RS2 movement and level-scaling behavior on the server. Previously, rapid firemaking could cancel the next attempt and still spawn phantom ashes, fires were spawned on hardcoded height 0 with mismatched ObjectManager/ObjectHandler state, and ground-log lighting triggered from an adjacent tile instead of walking onto the logs first.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/content/skills/firemaking/Firemaking.java`:
  - Removed the delayed `stopFiremaking(c)` call from the 2-tick post-lighting `turnPlayerTo` event so rapid consecutive firemaking attempts no longer cancel the next log's cycle.
  - Moved the `100 + Misc.random(98)` tick fire-despawn and ashes (`592`) event inside the lit branch so aborted/cancelled attempts never leave behind phantom ashes.
  - Spawned fires on `c.heightLevel` (instead of `0`) and removed `fireObj` directly from `GameEngine.objectManager.objects` via `updateObject(fireObj)` on burnout, eliminating `ObjectManager` stale-entry desyncs.
  - Replaced the redundant 4-iteration `firemakingItems` loop with `isFiremakingItem(...)`, gated colored firelighters (`7329`, `7330`, `7331`) to regular logs (`1511`), and ensured `stopFiremaking` / skilling interruptions call `container.stop()`.
- `2006Scape Server/src/main/java/com/rs2/game/items/UseItem.java`:
  - Fixed the `||` / `&&` operator precedence bug on `firemakingItems` checks and added `break` after matching a firemaking item.
- `2006Scape Server/src/main/java/com/rs2/net/packets/impl/ItemOnGroundItem.java`:
  - Added `isFiremakingItem(...)` and `isInRange(...)` so using a tinderbox or firelighter on ground logs requires standing on `(gItemX, gItemY)` rather than stopping 1 tile away.

### Authentic 2006 RS2 Behavior
- `2006Scape Server/src/main/java/com/rs2/game/content/skills/firemaking/Firemaking.java`:
  - Moved `Region.getClipping` step-off (`West -> East -> South -> North`) and `walkTo` to execute when the fire catches rather than when lighting begins, and turned the player to `(x, y)` after stepping off.
  - Added `canLightLog(int level, LogData log)` using RS2 `interpolate(low, high, level)` rolls out of 256 (re-rolling every 3 ticks on failure with animation `733` and `SoundList.FIRE_LIGHT`).
- `2006Scape Server/src/main/java/com/rs2/world/clip/Region.java` & `Firemaking.java`:
  - Added `Region.hasSceneryObject(x, y, z)` (`objectType >= 9 && objectType != 22`) and `Firemaking.isTileBlocked(x, y, height)` checking `ObjectManager`, `ObjectHandler`, static scenery objects, and tile clipping (`0x1280100`) before starting and before spawning the fire.

Closes #295
Closes #543

* fix(objects): preserve cache-defined orientation when opening and closing chests

Fixes chest and toggleable object rotation bugs where opening or closing an object not listed in `ObjectDefaults.GET_FACE` rotated it to face South (`0`), and `OpenObject` passed swapped `type`/`face` arguments to `Region.addObject`. Looking up the existing object's orientation from `Region` and `ObjectHandler` ensures all toggleable objects preserve their cache-defined facing across the world.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/objects/ObjectDefaults.java`:
  - Updated `getObjectFace(Player, int)` to check `Region.getObject(...)` and `GameEngine.objectHandler.objectExists(...)` for the current object's `objectFace` before falling back to the hardcoded `GET_FACE` / `switch` defaults.
- `2006Scape Server/src/main/java/com/rs2/game/objects/impl/OpenObject.java`:
  - Preserved the object's `face` and `objectType` when toggling between closed and open IDs in `OBJECT_DATA`.
  - Removed the previous object from `Region` and `GameEngine.objectHandler.globalObjects` before adding and placing the toggled object, and fixed the swapped `type`/`face` parameter order in `Region.addObject(newId, x, y, h, type, face, false)`.

Closes #549

* fix(desert): start desert heat timer on entry and remove shared static state

Fixes instantaneous desert heat damage when entering the desert, eliminates per-tick `CycleEvent` accumulation, and removes shared `static` state across players. Previously, `player.lastDesert` defaulted to `0` on login and was never reset on exit, causing immediate damage on the first tick inside `Boundary.DESERT`, while `Player.process()` queued a new `CycleEvent` every tick.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/players/Player.java`:
  - Updated `process()` to invoke `DesertHeat.callHeat(this)` unconditionally so `lastDesert` resets whenever the player leaves `Boundary.DESERT`, moves off `heightLevel == 0`, or enters `Boundary.NO_HEAT`.
- `2006Scape Server/src/main/java/com/rs2/game/content/traveling/DesertHeat.java`:
  - Initialized `player.lastDesert = now` on desert heat entry (`lastDesert == 0`) instead of applying damage on the first tick, and reset `lastDesert = 0` when outside desert heat.
  - Evaluated the `90s` base (`+10s` per equipped desert clothing piece) timer directly per tick in `callHeat(Player)` rather than spawning duplicate 1-tick `CycleEvent`s.
  - Replaced shared `static int DAMAGE` and `static int waterskin` fields with per-hit `1 + Misc.random(9)` (`1-10`) damage rolls and a local `checkWaterskin(Player)` loop.
  - Replaced hardcoded waterskin item IDs with `StaticItemList.WATERSKIN0` through `StaticItemList.WATERSKIN4` ordered from lowest to highest dose.

Closes #596

* fix(shops): start restock timer on purchase from full stock

Fixes instantaneous restocking of the first item purchased from a fully stocked shop and cleans up shop tick processing. Previously, `shopItemsRestock[shop_id][j]` remained `0` (or stale) when a player bought from full stock, causing `ShopHandler.process()` to immediately restock 1 item on the next tick.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/shops/ShopHandler.java`:
  - Updated `buyItem(int, int, int)` to set `shopItemsRestock[shop_id][j] = System.currentTimeMillis()` and reset `shopItemsDelay[shop_id][j] = 0` when a purchase reduces stock from at/above standard stock (`shopItemsSN`) to below `shopItemsSN`, without resetting an in-progress restock timer on subsequent purchases.
  - Fixed the off-by-one standard-stock boundary in `process()` (`j < shopItemsStandard[i]` instead of `<=`), removed the redundant `shopItemsDelay[i][j] = 1;` assignment, and gated `refreshshop(i)` on `shopUpdated` so unchanged shops are not broadcast every tick.
  - Cleared `shopItemsRestock[shopID][ArrayID] = 0` in `ResetItem(int, int)` when a shop slot is emptied.

Closes #595

* feat(randomevents): migrate random events, lamps, and Thessalia to Kotlin plugins and add ::randomevent

Rewrite all legacy Java random events, experience lamps, and Thessalia interactions into Kotlin plugins under plugins/game/content/randomevents/, plugins/game/content/items/lamps/, plugins/npc/thessalia/, and Revision 377 quest packages, while adding Zanaris Choir and developer testing commands. Core Java hooks now post RandomActionEvent and NpcDeathEvent, preserve legacy save migration via PlayerPluginData, and enforce authentic 2006 RS2 (Revision 377) mechanics, dialogues, and variable XP rate scaling.

### Command Infrastructure
- `RandomActionEvent.java` & `NpcDeathEvent.java`:
  - Added core event classes posted from skilling/action/shop handlers (`Fishing`, `Woodcutting`, `Mining`, `Prayer`, `ShopAssistant.openShop`, `Cooking`, `Potatoes`, `Runecrafting`, `SoftClay`, `SearchForTraps`, `Pickpocket`, `Stalls`, `MagicTeleports`, `PlayerAssistant`, `NpcHandler`) and NPC death processing.
- `ClickNPC.java` & `NpcHandler.java`:
  - Fixed `ClickNPC` to pass `npc.npcId` instead of `player.npcClickIndex` (which `firstClickNpc` resets to `0`) to `NpcFirstClickEvent`.
  - Added `NpcHandler.spawnNpcReturn` and guarded `npcs[i] == null` after `Player.postNpcTick` to prevent NPEs when tick plugins despawn NPCs.
- `Player.java` & `PlayerSave.java`:
  - Removed obsolete random event fields from `Player` while migrating legacy `randomActions` and `recievedReward` save keys into `PlayerPluginData`.

### Migrated Command Plugins
- `RandomToggle.kt` (`::random`, `::randomtoggle`, `::togglerandom`):
  - Migrated `randomEventsEnabled` toggling out of `Commands.java` into `plugins/commands/`.
- `Teleport.kt` (`::teleport`, `::tele`):
  - Added `zanaris` (`2452, 4470, 0`) to `NAMED_LOCATIONS` and `VALID_CITIES_MESSAGES`.

### New Search Commands
- `TriggerRandomEvent.kt` (`::randomevent <name>`, `::randomevents`, `::revent`):
  - Added developer command plugin to trigger `sandwich`, `chicken`, `forester`, `swarm`, `genie`, `frog`, `troll`, `golem`, `spirit`, `shade`, `zombie`, and `choir` on demand, with multi-line help and Zanaris location hint.

### Random Event & Lamp Plugins
- `RandomEventSupport.kt`, `RandomEventDispatcherPlugin.kt`, `RandomEventNpcDeathPlugin.kt`, & `RandomEventFollowPlugin.kt`:
  - Implemented per-player session state, clipped adjacent tile spawning, active NPC slot tracking, unified non-combat NPC following/facing/despawn (`GENIE`, `SANDWICH_LADY`, `FROG_PRINCE`, `FROG_PRINCESS`, `ZANARIS_CHOIR`), and global guards (`randomEventsEnabled`, `!inFightCaves()`, `tutorialProgress >= 36`, `MONKEY_GREEGREE`).
- `CombatRandoms.kt`:
  - Unified `EvilChicken`, `RiverTroll` (Fishing), `RockGolem` (Mining), `TreeSpirit` (Woodcutting), `Shade` & `Zombie` (Prayer bone burying), and `Swarm` with full `3..138` combat level coverage.
- `GeniePlugin.kt`, `SandwichLadyPlugin.kt`, `SandwichLadyTalkPlugin.kt`, `FrogPlugin.kt`, `FreakyForesterPlugin.kt`, `FreakyForesterPortalPlugin.kt`, `ZanarisChoirPlugin.kt`, & `ZanarisChoirTalkPlugin.kt`:
  - Implemented authentic 2006 RS2 NPC spawns, dialogues (`Master`/`Mistress` Genie greeting, Kiss-the-Frog, Freaky Forester 1–4 tail pheasants, Sandwich Lady tray `16135`, Zanaris Choir), and `DialogueFactory.onAction` reward/despawn sequencing.
- `LampInterfaceSupport.kt` & Revision 377 Lamp Plugins:
  - Replaced `ExperienceLamp.java` with config `261` (`1..21`) skill highlighting and `VARIABLE_XP_RATE` / `XP_RATE` scaling across Genie Lamp (`2528`, `10 * level`), One Small Favour (`4447`, level 30+, `10,000` XP), A Tail of Two Cats (`6543`, level 30+, `2,500` XP), Shadow of the Storm (`6796`, combat skills, `10,000` XP), and Recipe for Disaster (`7498`, level 50+, `20,000` XP).
- `ThessaliaFirstClickPlugin.kt` & `ThessaliaSecondClickPlugin.kt`:
  - Migrated Thessalia (`548`) Talk-to shop/Frog Token (`6183`) exchange and Trade (`shop 12`) actions out of `DialogueHandler` and `Shops.java` into `plugins/npc/thessalia/`.

### Cleanups & Deprecations
- Removed all 12 legacy Java classes under `com/rs2/game/content/randomevents/`, `ExperienceLamp.java`, and dead random-event/dialogue/button hooks across `ClickingButtons.java`, `ClickItem.java`, `DialogueHandler.java`, `NpcActions.java`, `ObjectsActions.java`, and `Shops.java`.

* feat(audio): overhaul 377 music, audio playback, and GameOptionsPlugin

Overhauls the 2006Scape Server and Client audio systems to match authentic 2006 RS2 (Revision 377) behavior, fixing MIDI deadlocks, volume persistence, title-screen music handoff, and varp-driven track unlocking. Consolidates all interface 904 Settings-tab buttons into a single Kotlin plugin and populates PlayList and Music with cache-verified 377 track and region mappings.

### Audio & Client Playback Fixes
- `Class56_Sub1_Sub1.java` & `Class56.java` & `Class56_Sub1_Sub2.java`
  - Split `RECEIVER_LOCK` from `MIDI_LOCK` so Java Sound's `Sequencer.stop()` cannot deadlock against `Receiver.send(...)` when switching tracks.
  - Replaced `method835(0, i, -1L)` with `method840(i, -1L)` in `method827` to reset all 16 channel volumes and unconditionally apply `musicVolume` on track changes.
  - Added `setLoop(boolean loop, boolean restartIfStopped)` to toggle looping live via `config 19` and rewind/restart finished tracks when `LOOP` is enabled while unmuted.
- `Game.java` & `DesktopHooks.java` & `SoundPlayer.java`
  - Stops title-screen `Scape Main` on login (`method55(false); currentSong = -1;`) so region music starts immediately.
  - Respects `!loggedIn || variousSettings[19] == 1` for track looping while keeping jingles one-shot.
  - Replaced unbounded per-sound thread creation in `SoundPlayer` with a 4-thread daemon executor and try-with-resources stream/line cleanup, and fixed `DesktopHooks` MIDI receiver/synthesizer cleanup.
- `HdMaterial.java`
  - Added `populateSingleLayer(int layerId, ByteBuffer diffuseLayerBuf, ByteBuffer normalLayerBuf)` sharing `writeLayerToBuffers` for memory-constrained Android texture streaming.

### Server Music & Playlist Architecture
- `PlayList.java`
  - Mapped all 383 clickable songs from `interface 962` to cache-verified `idx3` MIDI IDs and the 14 native RS2 music unlock varps (`20, 21, 22, 23, 24, 25, 298, 311, 346, 414, 464, 598, 662, 721`), fixing 25 legacy mis-mapped song IDs and `FAITHLESS` `childId` (`10129`).
  - Replaced `fixAllColors()` `sendColor` bursts with `sendMusicConfigs()` sending the 14 music varps plus `config 18` (`AUTO`/`MAN`) and `config 19` (`LOOP`), handling `Strange Place` (`464`, bit `17`) natively.
  - Fixed `AUTO` (`24125`), `MAN` (`24126`), and `LOOP` (`38197`) action button IDs in `handleButton`.
- `Music.java`
  - Expanded `MUSIC_DATA` to 517 unique regions cross-checked against the 377 `map_index`, `LostCityRS`, and OSRS Wiki polygons, and fixed Ape Atoll `(43, 43)` to `303` (`Monkey Madness`) and 73 legacy mismatches.
  - Removed `player.musicOn` gates in `Music.playMusic`, `ChangeRegions`, `ClickingButtons`, and `PacketSender.login` so tracks still unlock and `PlayList` controls work while muted.
- `PacketSender.java` & `Player.java` & `PlayerSave.java`
  - Flushed `sendSong` immediately and standardized `sendSound` on packet 174 (`id`, `volume`, `delay`).
  - Persisted `musicVolume`, `soundVolume`, `mouseButton`, `chatEffects`, and `acceptAid` in `PlayerSave` and synced configs `168`, `169`, `170`, `171`, `287`, and `427` on login.

### New & Migrated Plugins
- `GameOptionsPlugin.kt`
  - Migrated `BrightnessButtons.java`, `MusicVolumeButtons.java`, `SoundVolumeButtons.java`, and `ToggleSplitChatButtons.java` plus `Mouse Buttons` (`3145`/`3146`), `Chat Effects` (`3147`/`3148`), and `Accept Aid` (`48176`/`48177`) into a single Kotlin plugin using named constants and lookup maps, removing legacy `500`–`503` configs and stale `74176`/`74180`/`74188` cases from `ClickingButtons.java`.
- `UnlockSongs.kt`
  - Added developer command `::unlocksongs` (`::unlockmusic`, `::allsongs`) to unlock all playlist tracks and refresh music varps.

* fix(client): replace ThreadFactory lambda in SoundPlayer for JDK 8 javac

Replaces the `ThreadFactory` lambda in `SoundPlayer.SOUND_EXECUTOR` with an anonymous `ThreadFactory` class to resolve a JDK 8 `javac` definite-assignment bug (`variable r might not have been initialized`) hit by GitHub Actions CI on PR #686.

### Bug Fixes
- `SoundPlayer.java`
  - Replaced `r -> { ... }` in `Executors.newFixedThreadPool(4, ...)` with an anonymous `ThreadFactory` implementation.

* refactor(combat): replace DeprecatedItems.getItemName with ItemDefinition.lookup in AutocastCancelButtonPlugin

Removes the deprecated `DeprecatedItems.getItemName(weaponId)` call from `AutocastCancelButtonPlugin.kt` in favor of `ItemDefinition.lookup(weaponId)?.name`, eliminating the Kotlin compiler deprecation warning.

### Cleanups & Deprecations
- `AutocastCancelButtonPlugin.kt`
  - Replaced `DeprecatedItems.getItemName(weaponId)` with `ItemDefinition.lookup(weaponId)?.name ?: "Unarmed"` (preserving `"Unarmed"` when `weaponId == -1`).

* build(maven): set explicit UTF-8 source and reporting encoding across modules

Configures `project.build.sourceEncoding` and `project.reporting.outputEncoding` to `UTF-8` in the root and server POMs so resource filtering and Java compilation are platform-independent and free of platform-encoding warnings.

### Build Configuration
- `pom.xml` & `2006Scape Server/pom.xml`
  - Added `<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>` and `<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>`.

* style(client): fix space-before-tab indentation in Class56_Sub1_Sub2

Replace mixed space-and-tab indentation with spaces in Class56_Sub1_Sub2 to clear the git diff --check whitespace lint prior to merging PR #686.

### Cleanups & Deprecations
- 2006Scape Client/src/main/java/Class56_Sub1_Sub2.java:
  - Normalized line 34 indentation inside setLoop(boolean, boolean) from space-before-tab to 8 spaces.

* fix(audio): remove post-377 Stronghold of Security song entries from Music

Remove the four legacy Stronghold of Security region music mappings from Music.java so MUSIC_DATA stays strictly aligned with Revision 377 (May 2006) tracks and PlayList idx3 entries.

### Cleanups & Deprecations
- 2006Scape Server/src/main/java/com/rs2/game/content/music/Music.java:
  - Removed pre-existing post-377 Stronghold of Security entries { 29, 81, 537 }, { 31, 81, 558 }, { 33, 82, 559 }, and { 36, 81, 560 } from MUSIC_DATA.
2026-12-02 00:08:13 +00:00
Dark98 9570a35bae Rewrite Al-Kharid gate interactions and border guard dialogues closes (#661)
- Updated NpcFirstClickEvent to include npcIndex for better handling of NPC interactions.
- Enhanced Npc and NpcHandler classes to support new interaction logic and ensure NPCs face players correctly.
- Refined packet handling for NPC clicks and button actions to integrate new dialogue and interaction flows.
2026-11-10 02:52:33 +00:00
ipkpjersi cad090d8fe Various fixes and improvements (#640)
* Added more client settings for winter and hide roofs

* Removed unnecessary local var and added Javadoc comment

* Fixed dark wizards casting magic in melee range

* Added AttackType enum

* Removed extra asterisk

* Removed attackType magic numbers

* Enabled snow toggles by default

* Combined snow month into one variable

* Added option for fixes without custom settings

Added option for fixes (and QoL tab) without overriding specific features.

* Added more main args

* Fixed typo

* Added player sound saving

We have it for music, so why not for sounds too?

* Fixed typos

* Added closed client exception to ignores

* Fixed NPC definitions not loading

* Replaced NPC definitions XML with JSON

* Replaced NPCDefinition Array with HashMap

* Use err for early exit output

* Fixed KQ death causing client crash

It had the wrong anims.

* Added zoom level to debug info

* Added zoom level messages option

* Added fire breath attack type enum

* Replaced remaining fire breath attack types

* Fixed client lag

This should technically not be necessary, but it's more of a workaround due to server inefficiencies (if you kill a bunch of cows, your client will start to lag and you will even stack hits, I suspect it's due to the ground items) until we fix the server inefficiencies. There's not really any downsides in changing this from 5 to 100, so it's a good change for now.

* Make definitions private

* Fixed dark wizards not attacking back

* Improved comments

* Removed extra giant mole spawns

* Added mole lair rope action

* Only send yes chat head when talking to NPC

* Fixed removing item does not reset autocast

* Fixed picking up stackable items with full inv

* Fixed lvl 7 dark wizard anims

* Added confirm param to xprate command and fixed players command

* Removed usages of Misc.println

This hides which file the println is actually called from, so it's actually better to remove this helper.

* Don't move player when clicking on barrows check

This is both unauthentic and unnecessary.

* Removed unnecessary commented out code

We don't even need it commented out tbh.

* Fixed incorrect barrows NPC attack anims

* Improved slayer points message

* Fixed slayer task message cut off

* Might as well make this naming consistent

* Fixed typo

* Fixed stronghold slayer dungeon getting stuck in wall

* Require control key for zooming

It's too easy to accidentally zoom in/out with the scroll wheel, so let's make it so you need the control key held to scroll wheel zoom in/out.

* Added option for control key zooming

This way, it's off by default so it works the way it always did by default.

* Added alias for control key zoom

* Fixed quest interface not emptying out completely

* Updated slayer point dialogue to be more accurate

* Fixed compile error

* Fixed formatting

* More formatting fixes

* Added 5th click object handling (fixes pick-lock crash)

* Fixed lower level NPCs always hitting 0

* Fixed NPCs having incorrect max hit

Chickens were hitting 3's, ouch...

* Fixed NPCs still hitting 0s

This is much better now. Combat feels good.

* Fixed boss max hits

* Fixed al-kharid gate talking option

* Copied over max hits from spawns.json to npcDefinitions.json

This fixes a lot of NPCs. Many NPCs already seem to be correct.

* Added workaround preventing players stuck in level 28 wildy

* Changed comment to TODO

* Added control key zoom toggle

* Extracted config option to ClientSettings

* added message for control key zooming
2024-09-21 01:30:57 +01:00
Josh Shippam 55ca851d07 Various Changes (#614)
* Clean Old Log Files

* Various Changes

* Moved minutes.log to log folder
* Made SERVER_LOG_DIR constant
* Moved FILE_SYSTEM_DIR to GameConstants & Deleted org.apollo.jagcached.Constants
* Removed unused minutes.log from data/data
* Removed Duplicate RSAKeyGen
* Moved RSAKeyGen from com.rs2.net.rsa to com.rs2.util.rsa

* Removed data/net.xml & Created Moved NetworkConstants.java

* Add HTTP & Jaggrab Port's to ConfigLoader

* IntelliJ Reformat ConfigLoader.java

* Fix Mistake

* Attempt #2

* Woops, wrong port
2023-02-09 01:05:06 +00:00
MatthewBishop eab153ee3f Def cleanup (#585)
* Object definition cleanup

* Update ShopAssistant.java

* stackables

* notables

* unused files

* more junk

* almost done

* working

* moving old methods to deprecated

* update

* fixed pickpocket typos

* Update Pickpocket.java

* Remove redundant method. Fix stall stealing

* Documentation for deprecated methods

* WIP commit partial removal. Has test and dump classes

* Final cleanup

* Move definitions from data folder to cfg

* Temporarily moving definition loaders to GameEngine

This is until loading can be done asynchronously.

* Correct indentation.
2023-02-05 22:30:29 +00:00
Josh Shippam 209dae48a6 Fix X11 Error On Headless Servers With GUI Disabled (#573) 2023-02-02 05:00:54 +00:00
Josh Shippam 0754b24aa7 Implemented & Adapted RobGob69's Server ControlPanel (#568) 2023-01-30 22:27:20 +00:00
MatthewBishopandDark98 e46b7142c3 Network cleanup (#552)
* Replaced packetType/Size with packet

* Replace Instream with Packet

Read data directly from packet to ease future network upgrade

* Update Packet.java

Removed unused methods to ease netty migration and network rewrite.

* Moved packet sizes.

* Removed unused stream methods

* Added readhex method for buttons

* preparing to replace mina

* Packet->GamePacket for refactoring

* Netty 3.6.6

* formatting

* formatting

* Apollo core

* Update net.xml

Added variables for 2006scape

* Netty 4 migration. Jagcached replaced with Apollo Core

* Porting network into apollo

* WIP Packet Changes

Do not merge. This is broken.

* Packet read methods converted to netty buffer

* Replacing game network and login with apollo

* Netty 4

* Cleanup

* Same port for update and game server.

* Cleanup login for integration with apollo

* Login works. fixing packets

* Running on apollo netcode.

* Server runs

* Update apollo-core.jar

* Disable encoder. write outstream directly to channel.

* Update RS2ProtocolDecoder.java

Added apollo decoder

* Add constant

* Synchronization not needed

* Update apollo-core.jar

* Better performance.

* Commit pre PR

* Update apollo-core.jar

* Fixup Port Binding Based On World

* Apollo files

* Additional Commit

---------

Co-authored-by: Dark98 <darkaidz98@gmail.com>
2023-01-28 05:31:19 +00:00
Josh ShippamandDanial e1a8d85408 Second World Setup (#518)
* Start Setting Up Second World

Added World Number To Login Message
Added World Number To Login Interface
Made World 2 Listen On Different Port
Made Client Connect To 43597 For World 2

* Small Cleanup For World 2 Support

Calculate Port For World Based On World Number
Use Existing World int For World In Server

* Woops Wrong Ports

* Set Server Port After Loading Config

* Add xpRate Var & Include With XPRate Calculations

* Add -w/-world arg to client

* Add XP Rate Multiplier For Non-Bot Worlds

* More Multi World Stuff

Update Integrations(Discord Bot/Website Stuff) For Multiple Worlds
Added More XP Rate Dialogue Stuff

* Add Kick Command To Discord Bot & Fix Type In ConfigLoader

* Create/Use commandPrefix Var For Discord Bot

* Small Fixup For World 2

Renamed BOT_WORLD to VARIABLE_XP_RATE
Fixed Dialogue/Message grammar
Added a check for VARIABLE_XP_RATES to ::xprate command

* More Discord Commands(GameKick, MoveHome & Update)

*GameKick kicks A player if their client froze but acc stayed logged in
*MoveHome removes the need for ::stuck which removes potential for abuse
*Update schedules A server update

* Minor fixup

* 43597 → 43598

* Fix XP Rate Multiplier & add ::xprate to cooamnds list if enabled

* Use Either VARIABLE_SKILL_RATE OR XP_RATE Not Both

TODO(Convert Player.xpRate Into An Array For Easier Rate Changes)

* Create/Use PLAYER_XP_RATES For Easier Rate Changes

* Fixed Abusive Client Command Privileges & Added myxprate/checkxprate

* Allow Loading VARIABLE_XP_RATES & PLAYER_XP_RATES From Config

* Properly Update Client Title Logo

If The Cache Has Already Been Downloaded You Will Need To Delete It & Let The Client ReDownload It

* Fix Cache CRC Checks For The Client(Allows Cache To Actually Check For Updates)

* Add -no-crc & -dev Arguments To Client

* Fix Naming For Some Vars

* Make CHECK_CRC Description More Descriptive

* Fix More Var Descriptions

* Cleanup Unused GameConstants Vars & Add More Vars To ConfigLoader

Co-authored-by: Danial <admin@redsparr0w.com>
2021-12-31 03:47:48 +00:00
Danial c526aa5f4d [Mage Training Arena] Enchanting, and some other stuff (#507)
* Handle some more stairs...

* Remove message sent to player

* Bolts/Tips making

* Tidy up

* Free alchs occasionally within training arena

* [Mage Training Arena] Enchanting

* Remove enchanting room specific items when leaving area
2021-10-02 17:38:45 +00:00
Danial bbe1587e20 Mage Training Arena and stuff (#504)
* Fixup door/stairs in mage training arena

* Fixup bedsheets, should be worn on head, not weapon slot

* [Mage Training Arena] spawn rewards guardian

* [Mage Training Arena] Add arena teleports (non functioning)

* Just adding some comments

* [Mage Training Arena] Basic mage training arena stuff

* [Mage Training Arena] Allow shop to open and show items correctly

* [Mage Training Arena] Show shop prices when clicked

* noclip

* [Mage Training Arena] Add 2nd option handler (filler)

* [Mage Training Arena] Be able to purchase stuff, lock bones to peaches

* Update MageArena.java

* [Mage Training Arena] setup boundary

* Readability

* Tidy up enchanting

* MageArena -> MageTrainingArena

* Create Alchemy.java

* Update RSInterface.java

* [Mage Training Arena] Spawn entrance npcs

* [Mage Training Arena] Initial Alchemy

* [Mage Training Arena]  Add comments

* [Mage Training Arena] Handle alchemy while in arena

* [Mage Training Arena] Show interface for alchemy room

* [Mage Training Arena] Display values, Search cupboards

* [Mage Training Arena] Don't allow the player to wear items from the Alchemy game

* [Mage Training Arena] Announce when items are changing

* Don't allow the player to bring any coins with them

* Sort by values

* [Mage Training Arena] Allow alching items etc

* Update method name

* Show magic tab after using alch even if can't alch

* [Mage Training Arena] Coin collector - temp

* [Mage Training Arena] Give player points, take items, add bonus xp, add bank items

* [Mage Training Arena] Remove items when player leaves the alchemy training area

* Fixup staffs for runes, Tidy up checks

Was missing all Mystic staff
2021-09-30 22:25:48 +01:00
Danial 8589277ece Implement Party Room, A bunch of client side changes, Other stuff (#503)
* Fixup Discord links

* Fix required level to chop Dramen tree

* More Discord link fixes

* Show bots as (store)

* Fixup port

move to port 8080 as used by file server

* Fixup report handler

* Some client changes

* minor changes

Show mod status

* Show item value on ground

* Mark stores and players differently on mini map

* Some tidy up

* default to world 1

* Update trade with text

* revert nodeID changes

* Update RS Guide name

* Remove some command aliases

* Log bots and players differently

* Fixup

* minor changes

* Fixup colors

* Update RSInterface.java

* Settings for controlling options

* Add memory command

* Update server skill magic numbers

* Update server skill magic numbers

* Update colors for ground item text

* Update .gitignore

* Update player health value more often

* Add in game item/NPC/object search

* Item amounts and value displayed

* Update examine text

* Start with volume off

* Fixup tab 7 still showing with other interfaces

* Fixup search

* Fixup entering numbers after letter in amounts

* minor fixup

* fix indentation

* change type of value

* Fixup values shown

* Fix when clicking while tab 7 open

* Fixup negative amounts

* Update some method names

* Fixup method name

* tidy up method values

* Initial move for overlays

* Update more method names, variables

* Update debug menu

* Update experience info area

* Update Signlink.java

* more refactoring/deob

* Tidy up

* refresh skills

* Update method name, debug display

* fixup

* Show wrench icon on custom settings tab

* alignment

* Modify zoom

* Use smaller numbers for exp/h

* Update interface command

* tidy up

* Fixup tele location

* Fixup if interface doesn't exist

* Add some interface options

* Update checks

* Open bank interface for item search

TODO:
change title
maybe not display in chat
change options for items?
change command to searchitem - open the bank interface, open a text input interface

* re-fix

* Show open interface ID

* Update bank string shown

* Update search function

* Scroll zooming

* Only fill chat with search if not searching for an item

* add comments

* Change system update message

* Remove fps command

* Increase draw distance

* fixup

* Draw distance option

* [Party Room] Fix party room stairs

* Add new free slots method to check for stackable items counting as a free slot

* [Party Room] Deposit/Withdraw items all working

* [Party Room] Fully working

* [Party Room] Don't spawn balloons on the table

Players cannot pickup the items

* Fixup boundary

* Drop items in random amounts up to 4 stacks

* Update swampy boat to work

* Minor fixup

* Update Game.java

* Move player name up slightly

* Update some naming

* Tidy up

* Add ectoplasm agility shortcuts

* Update ObjectsActions.java

* Ectofuntus stuff

* fixup

* Ectofuntus bone grinder get status

* auto worship

* Allow claiming ecto-tokens

* change variable

* fixup

* Make use of GameConstants.WORLD

* Randomize bot passwords

* Don't show player shops as online

* Update opening oysters

* Update GemCutting.java

* Dragontooth island transport

* Ectofuntus stuff

* More constants

* Bill teach travel to Mos Le'Harmless and back

Also able to explore the whole ship

* Use better looking buttons

* Update .gitignore
2021-09-28 23:40:34 +01:00
Danial d30e833dd8 Update server skill magic numbers (#502) 2021-09-23 08:34:58 -04:00
dark98 3bf473129d Rename & Repackage 2021-03-11 00:30:16 +00:00