From 31ba87262a6d671e140325c6cb1f3a3bd3764a4a Mon Sep 17 00:00:00 2001 From: Major- Date: Wed, 9 Jul 2014 23:29:46 +0100 Subject: [PATCH] Clean-up and format; use diamond operator. --- .../burtleburtle/bob/rand/IsaacRandom.java | 504 ++-- src/org/apollo/Server.java | 248 +- src/org/apollo/ServerContext.java | 90 +- src/org/apollo/Service.java | 48 +- src/org/apollo/ServiceManager.java | 178 +- src/org/apollo/fs/FileDescriptor.java | 68 +- src/org/apollo/fs/FileSystemConstants.java | 60 +- src/org/apollo/fs/Index.java | 100 +- src/org/apollo/fs/IndexedFileSystem.java | 474 ++-- src/org/apollo/fs/archive/Archive.java | 160 +- src/org/apollo/fs/archive/ArchiveEntry.java | 68 +- .../fs/decoder/ItemDefinitionDecoder.java | 262 +- .../fs/decoder/NpcDefinitionDecoder.java | 260 +- .../fs/decoder/ObjectDefinitionDecoder.java | 236 +- .../fs/decoder/StaticObjectDecoder.java | 154 +- src/org/apollo/game/GameConstants.java | 26 +- src/org/apollo/game/GamePulseHandler.java | 48 +- src/org/apollo/game/GameService.java | 278 +- src/org/apollo/game/action/Action.java | 72 +- .../apollo/game/action/DistancedAction.java | 108 +- src/org/apollo/game/command/Command.java | 68 +- .../game/command/CommandDispatcher.java | 60 +- .../apollo/game/command/CommandListener.java | 76 +- .../game/command/CreditsCommandListener.java | 56 +- .../game/event/handler/EventHandler.java | 16 +- .../event/handler/EventHandlerContext.java | 8 +- .../handler/chain/EventHandlerChain.java | 102 +- .../handler/chain/EventHandlerChainGroup.java | 64 +- .../handler/impl/BankButtonEventHandler.java | 30 +- .../event/handler/impl/BankEventHandler.java | 120 +- .../event/handler/impl/ChatEventHandler.java | 8 +- .../handler/impl/ChatVerificationHandler.java | 14 +- .../impl/ClosedInterfaceEventHandler.java | 10 +- .../handler/impl/CommandEventHandler.java | 18 +- .../handler/impl/DialogueButtonHandler.java | 16 +- .../impl/DialogueContinueEventHandler.java | 10 +- .../impl/EnteredAmountEventHandler.java | 8 +- .../event/handler/impl/EquipEventHandler.java | 150 +- .../impl/ItemOnItemVerificationHandler.java | 58 +- .../impl/ItemOnObjectVerificationHandler.java | 42 +- .../handler/impl/ItemVerificationHandler.java | 58 +- .../impl/NpcActionVerificationHandler.java | 24 +- .../impl/PlayerDesignEventHandler.java | 12 +- .../impl/PlayerDesignVerificationHandler.java | 118 +- .../handler/impl/RemoveEventHandler.java | 62 +- .../handler/impl/SwitchItemEventHandler.java | 50 +- .../event/handler/impl/WalkEventHandler.java | 40 +- .../game/event/impl/AddFriendEvent.java | 40 +- .../event/impl/AddGlobalTileItemEvent.java | 130 +- .../game/event/impl/AddIgnoreEvent.java | 40 +- .../game/event/impl/AddTileItemEvent.java | 100 +- .../apollo/game/event/impl/ArrowKeyEvent.java | 62 +- .../apollo/game/event/impl/ButtonEvent.java | 40 +- src/org/apollo/game/event/impl/ChatEvent.java | 124 +- .../apollo/game/event/impl/CommandEvent.java | 40 +- .../apollo/game/event/impl/ConfigEvent.java | 68 +- .../event/impl/DialogueContinueEvent.java | 40 +- .../event/impl/DisplayCrossbonesEvent.java | 40 +- .../event/impl/DisplayTabInterfaceEvent.java | 40 +- .../game/event/impl/EnteredAmountEvent.java | 40 +- .../game/event/impl/FifthItemActionEvent.java | 20 +- .../game/event/impl/FifthItemOptionEvent.java | 20 +- .../event/impl/FifthPlayerActionEvent.java | 16 +- .../game/event/impl/FirstItemActionEvent.java | 20 +- .../game/event/impl/FirstItemOptionEvent.java | 20 +- .../game/event/impl/FirstNpcActionEvent.java | 16 +- .../event/impl/FirstObjectActionEvent.java | 18 +- .../event/impl/FirstPlayerActionEvent.java | 16 +- .../game/event/impl/FocusUpdateEvent.java | 40 +- .../impl/ForwardPrivateMessageEvent.java | 94 +- .../event/impl/FourthItemActionEvent.java | 20 +- .../event/impl/FourthItemOptionEvent.java | 20 +- .../event/impl/FourthPlayerActionEvent.java | 16 +- .../event/impl/FriendServerStatusEvent.java | 40 +- .../game/event/impl/IdAssignmentEvent.java | 68 +- .../game/event/impl/IgnoreListEvent.java | 40 +- .../game/event/impl/InventoryItemEvent.java | 124 +- .../game/event/impl/ItemActionEvent.java | 22 +- .../game/event/impl/ItemOnItemEvent.java | 106 +- .../game/event/impl/ItemOnObjectEvent.java | 78 +- .../game/event/impl/ItemOptionEvent.java | 22 +- .../game/event/impl/KeepAliveEvent.java | 36 +- .../game/event/impl/MagicOnItemEvent.java | 48 +- .../game/event/impl/MouseClickEvent.java | 128 +- .../game/event/impl/NpcActionEvent.java | 68 +- .../event/impl/NpcSynchronizationEvent.java | 96 +- .../game/event/impl/ObjectActionEvent.java | 96 +- .../impl/OpenDialogueInterfaceEvent.java | 40 +- .../game/event/impl/OpenInterfaceEvent.java | 40 +- .../event/impl/OpenInterfaceSidebarEvent.java | 68 +- .../game/event/impl/PlayerActionEvent.java | 68 +- .../game/event/impl/PlayerDesignEvent.java | 40 +- .../impl/PlayerSynchronizationEvent.java | 182 +- .../apollo/game/event/impl/PositionEvent.java | 68 +- .../game/event/impl/PrivacyOptionEvent.java | 96 +- .../game/event/impl/PrivateMessageEvent.java | 96 +- .../game/event/impl/RegionChangeEvent.java | 40 +- .../game/event/impl/RemoveFriendEvent.java | 40 +- .../game/event/impl/RemoveIgnoreEvent.java | 40 +- .../game/event/impl/RemoveTileItemEvent.java | 84 +- .../event/impl/SecondItemActionEvent.java | 20 +- .../event/impl/SecondItemOptionEvent.java | 20 +- .../game/event/impl/SecondNpcActionEvent.java | 16 +- .../event/impl/SecondObjectActionEvent.java | 18 +- .../event/impl/SecondPlayerActionEvent.java | 16 +- .../game/event/impl/SendFriendEvent.java | 68 +- .../game/event/impl/ServerMessageEvent.java | 58 +- .../game/event/impl/SetPlayerActionEvent.java | 116 +- .../event/impl/SetWidgetItemModelEvent.java | 96 +- .../impl/SetWidgetModelAnimationEvent.java | 68 +- .../event/impl/SetWidgetNpcModelEvent.java | 68 +- .../event/impl/SetWidgetPlayerModelEvent.java | 40 +- .../game/event/impl/SetWidgetTextEvent.java | 68 +- .../event/impl/SetWidgetVisibilityEvent.java | 68 +- .../game/event/impl/SpamPacketEvent.java | 40 +- .../game/event/impl/SwitchItemEvent.java | 140 +- .../event/impl/SwitchTabInterfaceEvent.java | 68 +- .../game/event/impl/TakeTileItemEvent.java | 68 +- .../game/event/impl/ThirdItemActionEvent.java | 20 +- .../game/event/impl/ThirdItemOptionEvent.java | 20 +- .../game/event/impl/ThirdNpcActionEvent.java | 16 +- .../event/impl/ThirdObjectActionEvent.java | 18 +- .../event/impl/ThirdPlayerActionEvent.java | 16 +- .../game/event/impl/UpdateItemsEvent.java | 68 +- .../game/event/impl/UpdateRunEnergyEvent.java | 40 +- .../game/event/impl/UpdateSkillEvent.java | 68 +- .../event/impl/UpdateSlottedItemsEvent.java | 68 +- .../game/event/impl/UpdateTileItemEvent.java | 130 +- .../game/event/impl/UpdateWeightEvent.java | 40 +- src/org/apollo/game/event/impl/WalkEvent.java | 72 +- .../apollo/game/login/LoginDispatcher.java | 42 +- src/org/apollo/game/login/LoginListener.java | 12 +- .../apollo/game/login/LogoutDispatcher.java | 42 +- src/org/apollo/game/login/LogoutListener.java | 12 +- src/org/apollo/game/model/Animation.java | 316 +-- src/org/apollo/game/model/Appearance.java | 152 +- src/org/apollo/game/model/Direction.java | 202 +- src/org/apollo/game/model/Graphic.java | 138 +- src/org/apollo/game/model/Item.java | 126 +- src/org/apollo/game/model/Position.java | 384 +-- src/org/apollo/game/model/World.java | 652 ++--- src/org/apollo/game/model/WorldConstants.java | 26 +- src/org/apollo/game/model/area/Sector.java | 248 +- .../game/model/area/SectorCoordinates.java | 120 +- .../game/model/area/SectorListener.java | 14 +- .../game/model/area/SectorRepository.java | 170 +- .../game/model/def/EquipmentDefinition.java | 478 ++-- .../apollo/game/model/def/ItemDefinition.java | 754 +++--- .../apollo/game/model/def/NpcDefinition.java | 678 ++--- .../game/model/def/ObjectDefinition.java | 458 ++-- src/org/apollo/game/model/entity/Entity.java | 158 +- .../game/model/entity/EquipmentConstants.java | 98 +- src/org/apollo/game/model/entity/Mob.java | 740 +++--- src/org/apollo/game/model/entity/Npc.java | 174 +- src/org/apollo/game/model/entity/Player.java | 1774 ++++++------- src/org/apollo/game/model/entity/Skill.java | 312 +-- .../apollo/game/model/entity/SkillSet.java | 534 ++-- .../game/model/entity/WalkingQueue.java | 402 +-- .../game/model/inter/EnterAmountListener.java | 12 +- .../game/model/inter/InterfaceConstants.java | 88 +- .../game/model/inter/InterfaceListener.java | 8 +- .../apollo/game/model/inter/InterfaceSet.java | 368 +-- .../game/model/inter/InterfaceType.java | 50 +- .../game/model/inter/bank/BankConstants.java | 42 +- .../bank/BankDepositEnterAmountListener.java | 60 +- .../inter/bank/BankInterfaceListener.java | 58 +- .../game/model/inter/bank/BankUtils.java | 196 +- .../bank/BankWithdrawEnterAmountListener.java | 60 +- .../model/inter/dialogue/DialogueAdapter.java | 20 +- .../inter/dialogue/DialogueListener.java | 30 +- .../inv/AppearanceInventoryListener.java | 52 +- .../game/model/inv/FullInventoryListener.java | 60 +- src/org/apollo/game/model/inv/Inventory.java | 1148 ++++---- .../game/model/inv/InventoryAdapter.java | 18 +- .../game/model/inv/InventoryConstants.java | 34 +- .../game/model/inv/InventoryListener.java | 40 +- .../apollo/game/model/inv/SlottedItem.java | 100 +- .../inv/SynchronizationInventoryListener.java | 68 +- src/org/apollo/game/model/obj/GameObject.java | 118 +- src/org/apollo/game/model/sector/Sector.java | 262 +- .../game/model/sector/SectorCoordinates.java | 120 +- .../game/model/sector/SectorListener.java | 14 +- .../game/model/sector/SectorRepository.java | 168 +- .../apollo/game/model/settings/Gender.java | 32 +- .../game/model/settings/PrivacyState.java | 134 +- .../game/model/settings/PrivilegeLevel.java | 66 +- .../game/model/settings/ScreenBrightness.java | 74 +- .../game/model/settings/ServerStatus.java | 68 +- .../model/skill/LevelUpSkillListener.java | 48 +- .../apollo/game/model/skill/SkillAdapter.java | 18 +- .../game/model/skill/SkillListener.java | 44 +- .../skill/SynchronizationSkillListener.java | 50 +- .../apollo/game/scheduling/ScheduledTask.java | 128 +- src/org/apollo/game/scheduling/Scheduler.java | 62 +- .../impl/SkillNormalizationTask.java | 40 +- .../apollo/game/sync/ClientSynchronizer.java | 8 +- .../game/sync/ParallelClientSynchronizer.java | 128 +- .../sync/SequentialClientSynchronizer.java | 60 +- .../game/sync/block/AnimationBlock.java | 40 +- .../game/sync/block/AppearanceBlock.java | 284 +- src/org/apollo/game/sync/block/ChatBlock.java | 116 +- .../game/sync/block/ForceChatBlock.java | 40 +- .../game/sync/block/ForceMovementBlock.java | 186 +- .../apollo/game/sync/block/GraphicBlock.java | 40 +- .../game/sync/block/HitUpdateBlock.java | 124 +- .../game/sync/block/InteractingMobBlock.java | 40 +- .../sync/block/SecondaryHitUpdateBlock.java | 124 +- .../game/sync/block/SynchronizationBlock.java | 210 +- .../sync/block/SynchronizationBlockSet.java | 124 +- .../game/sync/block/TransformBlock.java | 40 +- .../game/sync/block/TurnToPositionBlock.java | 40 +- .../apollo/game/sync/seg/AddNpcSegment.java | 108 +- .../game/sync/seg/AddPlayerSegment.java | 80 +- .../apollo/game/sync/seg/MovementSegment.java | 74 +- .../game/sync/seg/RemoveMobSegment.java | 28 +- src/org/apollo/game/sync/seg/SegmentType.java | 48 +- .../game/sync/seg/SynchronizationSegment.java | 52 +- .../apollo/game/sync/seg/TeleportSegment.java | 52 +- .../sync/task/NpcSynchronizationTask.java | 106 +- .../sync/task/PhasedSynchronizationTask.java | 52 +- .../sync/task/PlayerSynchronizationTask.java | 160 +- .../sync/task/PostNpcSynchronizationTask.java | 34 +- .../task/PostPlayerSynchronizationTask.java | 46 +- .../sync/task/PreNpcSynchronizationTask.java | 32 +- .../task/PrePlayerSynchronizationTask.java | 80 +- .../apollo/io/EquipmentDefinitionParser.java | 94 +- .../apollo/io/EventHandlerChainParser.java | 158 +- src/org/apollo/io/PluginMetaDataParser.java | 188 +- src/org/apollo/io/RsaKeyParser.java | 82 +- src/org/apollo/io/player/PlayerLoader.java | 16 +- .../io/player/PlayerLoaderResponse.java | 98 +- src/org/apollo/io/player/PlayerSaver.java | 14 +- .../io/player/impl/BinaryPlayerLoader.java | 248 +- .../io/player/impl/BinaryPlayerSaver.java | 202 +- .../io/player/impl/BinaryPlayerUtil.java | 52 +- .../io/player/impl/DiscardPlayerSaver.java | 8 +- .../io/player/impl/DummyPlayerLoader.java | 24 +- .../io/player/impl/JdbcPlayerLoader.java | 8 +- .../io/player/impl/JdbcPlayerSaver.java | 6 +- src/org/apollo/login/LoginService.java | 168 +- src/org/apollo/login/PlayerLoaderWorker.java | 78 +- src/org/apollo/login/PlayerSaverWorker.java | 76 +- src/org/apollo/net/ApolloHandler.java | 104 +- .../apollo/net/HttpChannelInitializer.java | 56 +- .../apollo/net/JagGrabChannelInitializer.java | 86 +- src/org/apollo/net/NetworkConstants.java | 74 +- .../apollo/net/ServiceChannelInitializer.java | 38 +- src/org/apollo/net/codec/game/AccessMode.java | 16 +- .../apollo/net/codec/game/DataConstants.java | 32 +- src/org/apollo/net/codec/game/DataOrder.java | 32 +- .../net/codec/game/DataTransformation.java | 32 +- src/org/apollo/net/codec/game/DataType.java | 80 +- .../net/codec/game/GameDecoderState.java | 30 +- .../net/codec/game/GameEventDecoder.java | 40 +- .../net/codec/game/GameEventEncoder.java | 38 +- src/org/apollo/net/codec/game/GamePacket.java | 122 +- .../net/codec/game/GamePacketBuilder.java | 794 +++--- .../net/codec/game/GamePacketDecoder.java | 236 +- .../net/codec/game/GamePacketEncoder.java | 78 +- .../net/codec/game/GamePacketReader.java | 748 +++--- .../codec/handshake/HandshakeConstants.java | 26 +- .../net/codec/handshake/HandshakeDecoder.java | 52 +- .../net/codec/handshake/HandshakeMessage.java | 40 +- .../net/codec/jaggrab/JagGrabRequest.java | 40 +- .../codec/jaggrab/JagGrabRequestDecoder.java | 16 +- .../net/codec/jaggrab/JagGrabResponse.java | 40 +- .../codec/jaggrab/JagGrabResponseEncoder.java | 8 +- .../net/codec/login/LoginConstants.java | 186 +- .../apollo/net/codec/login/LoginDecoder.java | 336 +-- .../net/codec/login/LoginDecoderState.java | 30 +- .../apollo/net/codec/login/LoginEncoder.java | 24 +- .../apollo/net/codec/login/LoginRequest.java | 208 +- .../apollo/net/codec/login/LoginResponse.java | 96 +- .../net/codec/update/OnDemandRequest.java | 228 +- .../net/codec/update/OnDemandResponse.java | 124 +- .../net/codec/update/UpdateDecoder.java | 18 +- .../net/codec/update/UpdateEncoder.java | 28 +- src/org/apollo/net/meta/PacketMetaData.java | 142 +- .../apollo/net/meta/PacketMetaDataGroup.java | 102 +- src/org/apollo/net/meta/PacketType.java | 32 +- src/org/apollo/net/release/EventDecoder.java | 14 +- src/org/apollo/net/release/EventEncoder.java | 14 +- src/org/apollo/net/release/Release.java | 170 +- .../release/r317/AddFriendEventDecoder.java | 12 +- .../r317/AddGlobalTileItemEventEncoder.java | 18 +- .../release/r317/AddIgnoreEventDecoder.java | 12 +- .../release/r317/AddTileItemEventEncoder.java | 16 +- .../release/r317/ArrowKeyEventDecoder.java | 14 +- .../net/release/r317/ButtonEventDecoder.java | 12 +- .../net/release/r317/ChatEventDecoder.java | 32 +- .../r317/CloseInterfaceEventEncoder.java | 10 +- .../r317/ClosedInterfaceEventDecoder.java | 8 +- .../net/release/r317/CommandEventDecoder.java | 10 +- .../net/release/r317/ConfigEventEncoder.java | 30 +- .../r317/DialogueContinueEventEncoder.java | 12 +- .../r317/DisplayCrossbonesEventEncoder.java | 12 +- .../r317/DisplayTabInterfaceEventEncoder.java | 12 +- .../release/r317/EnterAmountEventEncoder.java | 8 +- .../r317/EnteredAmountEventDecoder.java | 12 +- .../r317/FifthItemActionEventDecoder.java | 16 +- .../r317/FifthItemOptionEventDecoder.java | 16 +- .../r317/FifthPlayerActionEventDecoder.java | 12 +- .../r317/FirstItemActionEventDecoder.java | 16 +- .../r317/FirstItemOptionEventDecoder.java | 16 +- .../r317/FirstNpcActionEventDecoder.java | 12 +- .../r317/FirstObjectActionEventDecoder.java | 16 +- .../r317/FirstPlayerActionEventDecoder.java | 12 +- .../release/r317/FocusUpdateEventDecoder.java | 12 +- .../ForwardPrivateMessageEventEncoder.java | 26 +- .../r317/FourthItemActionEventDecoder.java | 16 +- .../r317/FourthItemOptionEventDecoder.java | 16 +- .../r317/FourthPlayerActionEventDecoder.java | 12 +- .../r317/FriendServerStatusEventEncoder.java | 12 +- .../r317/IdAssignmentEventEncoder.java | 14 +- .../release/r317/IgnoreListEventEncoder.java | 18 +- .../release/r317/ItemOnItemEventDecoder.java | 22 +- .../r317/ItemOnObjectEventDecoder.java | 22 +- .../release/r317/KeepAliveEventDecoder.java | 8 +- .../net/release/r317/LogoutEventEncoder.java | 10 +- .../release/r317/MagicOnItemEventDecoder.java | 18 +- .../r317/MobAnimationResetEventEncoder.java | 8 +- .../release/r317/MouseClickEventDecoder.java | 38 +- .../r317/NpcSynchronizationEventEncoder.java | 494 ++-- .../OpenDialogueInterfaceEventEncoder.java | 12 +- .../r317/OpenInterfaceEventEncoder.java | 12 +- .../OpenInterfaceSidebarEventEncoder.java | 14 +- .../r317/PlayerDesignEventDecoder.java | 34 +- .../PlayerSynchronizationEventEncoder.java | 782 +++--- .../release/r317/PositionEventEncoder.java | 16 +- .../r317/PrivacyOptionEventDecoder.java | 16 +- .../r317/PrivacyOptionEventEncoder.java | 16 +- .../r317/PrivateMessageEventDecoder.java | 30 +- .../r317/RegionChangeEventEncoder.java | 14 +- .../apollo/net/release/r317/Release317.java | 272 +- .../r317/RemoveFriendEventDecoder.java | 12 +- .../r317/RemoveIgnoreEventDecoder.java | 12 +- .../r317/RemoveTileItemEventEncoder.java | 14 +- .../r317/SecondItemActionEventDecoder.java | 16 +- .../r317/SecondItemOptionEventDecoder.java | 16 +- .../r317/SecondNpcActionEventDecoder.java | 12 +- .../r317/SecondObjectActionEventDecoder.java | 16 +- .../r317/SecondPlayerActionEventDecoder.java | 12 +- .../release/r317/SendFriendEventEncoder.java | 14 +- .../r317/ServerMessageEventEncoder.java | 12 +- .../r317/SetPlayerActionEventEncoder.java | 16 +- .../r317/SetWidgetItemModelEventEncoder.java | 16 +- .../SetWidgetModelAnimationEventEncoder.java | 14 +- .../r317/SetWidgetNpcModelEventEncoder.java | 14 +- .../SetWidgetPlayerModelEventEncoder.java | 12 +- .../r317/SetWidgetTextEventEncoder.java | 14 +- .../r317/SetWidgetVisibilityEventEncoder.java | 14 +- .../release/r317/SpamPacketEventDecoder.java | 8 +- .../release/r317/SwitchItemEventDecoder.java | 18 +- .../r317/SwitchTabInterfaceEventEncoder.java | 14 +- .../r317/TakeTileItemEventDecoder.java | 16 +- .../r317/ThirdItemActionEventDecoder.java | 16 +- .../r317/ThirdItemOptionEventDecoder.java | 16 +- .../r317/ThirdNpcActionEventDecoder.java | 12 +- .../r317/ThirdObjectActionEventDecoder.java | 18 +- .../r317/ThirdPlayerActionEventDecoder.java | 12 +- .../release/r317/UpdateItemsEventEncoder.java | 38 +- .../r317/UpdateRunEnergyEventEncoder.java | 12 +- .../release/r317/UpdateSkillEventEncoder.java | 18 +- .../r317/UpdateSlottedItemsEventEncoder.java | 40 +- .../r317/UpdateTileItemEventEncoder.java | 18 +- .../r317/UpdateWeightEventEncoder.java | 12 +- .../net/release/r317/WalkEventDecoder.java | 52 +- .../release/r377/AddFriendEventDecoder.java | 12 +- .../r377/AddGlobalTileItemEventEncoder.java | 18 +- .../release/r377/AddIgnoreEventDecoder.java | 12 +- .../release/r377/AddTileItemEventEncoder.java | 16 +- .../release/r377/ArrowKeyEventDecoder.java | 14 +- .../net/release/r377/ButtonEventDecoder.java | 12 +- .../net/release/r377/ChatEventDecoder.java | 30 +- .../r377/CloseInterfaceEventEncoder.java | 10 +- .../r377/ClosedInterfaceEventDecoder.java | 8 +- .../net/release/r377/CommandEventDecoder.java | 10 +- .../net/release/r377/ConfigEventEncoder.java | 30 +- .../r377/DialogueContinueEventDecoder.java | 12 +- .../r377/DisplayCrossbonesEventEncoder.java | 12 +- .../r377/DisplayTabInterfaceEventEncoder.java | 12 +- .../release/r377/EnterAmountEventEncoder.java | 8 +- .../r377/EnteredAmountEventDecoder.java | 12 +- .../r377/FifthItemActionEventDecoder.java | 16 +- .../r377/FifthItemOptionEventDecoder.java | 16 +- .../r377/FifthPlayerActionEventDecoder.java | 12 +- .../r377/FirstItemActionEventDecoder.java | 16 +- .../r377/FirstItemOptionEventDecoder.java | 16 +- .../r377/FirstNpcActionEventDecoder.java | 12 +- .../r377/FirstObjectActionEventDecoder.java | 16 +- .../r377/FirstPlayerActionEventDecoder.java | 12 +- .../release/r377/FocusUpdateEventDecoder.java | 10 +- .../ForwardPrivateMessageEventEncoder.java | 26 +- .../r377/FourthItemActionEventDecoder.java | 16 +- .../r377/FourthItemOptionEventDecoder.java | 16 +- .../r377/FourthPlayerActionEventDecoder.java | 12 +- .../r377/FriendServerStatusEventEncoder.java | 12 +- .../r377/IdAssignmentEventEncoder.java | 14 +- .../release/r377/IgnoreListEventEncoder.java | 18 +- .../release/r377/ItemOnItemEventDecoder.java | 22 +- .../r377/ItemOnObjectEventDecoder.java | 22 +- .../release/r377/KeepAliveEventDecoder.java | 8 +- .../net/release/r377/LogoutEventEncoder.java | 10 +- .../release/r377/MagicOnItemEventDecoder.java | 18 +- .../r377/MobAnimationResetEventEncoder.java | 8 +- .../release/r377/MouseClickEventDecoder.java | 38 +- .../r377/NpcSynchronizationEventEncoder.java | 492 ++-- .../OpenDialogueInterfaceEventEncoder.java | 12 +- .../r377/OpenInterfaceEventEncoder.java | 12 +- .../OpenInterfaceSidebarEventEncoder.java | 14 +- .../r377/PlayerDesignEventDecoder.java | 34 +- .../PlayerSynchronizationEventEncoder.java | 786 +++--- .../release/r377/PositionEventEncoder.java | 16 +- .../r377/PrivacyOptionEventDecoder.java | 16 +- .../r377/PrivacyOptionEventEncoder.java | 16 +- .../r377/PrivateMessageEventDecoder.java | 28 +- .../r377/RegionChangeEventEncoder.java | 14 +- .../apollo/net/release/r377/Release377.java | 262 +- .../r377/RemoveFriendEventDecoder.java | 12 +- .../r377/RemoveIgnoreEventDecoder.java | 12 +- .../r377/RemoveTileItemEventEncoder.java | 14 +- .../r377/SecondItemActionEventDecoder.java | 16 +- .../r377/SecondItemOptionEventDecoder.java | 16 +- .../r377/SecondNpcActionEventDecoder.java | 12 +- .../r377/SecondObjectActionEventDecoder.java | 16 +- .../r377/SecondPlayerActionEventDecoder.java | 12 +- .../release/r377/SendFriendEventEncoder.java | 14 +- .../r377/ServerMessageEventEncoder.java | 12 +- .../r377/SetPlayerActionEventEncoder.java | 16 +- .../r377/SetWidgetItemModelEventEncoder.java | 16 +- .../SetWidgetModelAnimationEventEncoder.java | 14 +- .../r377/SetWidgetNpcModelEventEncoder.java | 14 +- .../SetWidgetPlayerModelEventEncoder.java | 12 +- .../r377/SetWidgetTextEventEncoder.java | 14 +- .../r377/SetWidgetVisibilityEventEncoder.java | 14 +- .../release/r377/SpamPacketEventDecoder.java | 8 +- .../release/r377/SwitchItemEventDecoder.java | 18 +- .../r377/SwitchTabInterfaceEventEncoder.java | 14 +- .../r377/TakeTileItemEventDecoder.java | 16 +- .../r377/ThirdItemActionEventDecoder.java | 16 +- .../r377/ThirdItemOptionEventDecoder.java | 16 +- .../r377/ThirdNpcActionEventDecoder.java | 12 +- .../r377/ThirdObjectActionEventDecoder.java | 16 +- .../r377/ThirdPlayerActionEventDecoder.java | 12 +- .../release/r377/UpdateItemsEventEncoder.java | 38 +- .../r377/UpdateRunEnergyEventEncoder.java | 12 +- .../release/r377/UpdateSkillEventEncoder.java | 18 +- .../r377/UpdateSlottedItemsEventEncoder.java | 40 +- .../r377/UpdateTileItemEventEncoder.java | 18 +- .../r377/UpdateWeightEventEncoder.java | 12 +- .../net/release/r377/WalkEventDecoder.java | 54 +- src/org/apollo/net/session/GameSession.java | 188 +- src/org/apollo/net/session/LoginSession.java | 184 +- src/org/apollo/net/session/Session.java | 62 +- src/org/apollo/net/session/UpdateSession.java | 60 +- src/org/apollo/security/IsaacRandomPair.java | 68 +- .../apollo/security/PlayerCredentials.java | 183 +- src/org/apollo/tools/EquipmentConstants.java | 152 +- src/org/apollo/tools/EquipmentUpdater.java | 2342 ++++++++--------- src/org/apollo/tools/NoteUpdater.java | 76 +- src/org/apollo/update/ChannelRequest.java | 84 +- src/org/apollo/update/HttpRequestWorker.java | 218 +- .../apollo/update/JagGrabRequestWorker.java | 44 +- .../apollo/update/OnDemandRequestWorker.java | 78 +- src/org/apollo/update/RequestWorker.java | 142 +- src/org/apollo/update/UpdateConstants.java | 10 +- src/org/apollo/update/UpdateDispatcher.java | 152 +- src/org/apollo/update/UpdateService.java | 134 +- .../resource/CombinedResourceProvider.java | 48 +- .../resource/HypertextResourceProvider.java | 78 +- .../update/resource/ResourceProvider.java | 32 +- .../resource/VirtualResourceProvider.java | 96 +- src/org/apollo/util/BufferUtil.java | 104 +- src/org/apollo/util/CompressionUtil.java | 198 +- src/org/apollo/util/EnumerationUtil.java | 56 +- src/org/apollo/util/LanguageUtil.java | 32 +- src/org/apollo/util/MobRepository.java | 344 +-- src/org/apollo/util/NameUtil.java | 108 +- src/org/apollo/util/NamedThreadFactory.java | 42 +- src/org/apollo/util/Point.java | 68 +- src/org/apollo/util/StatefulFrameDecoder.java | 138 +- src/org/apollo/util/StreamUtil.java | 62 +- src/org/apollo/util/TextUtil.java | 260 +- .../util/plugin/DependencyException.java | 24 +- src/org/apollo/util/plugin/PluginContext.java | 158 +- .../apollo/util/plugin/PluginEnvironment.java | 26 +- src/org/apollo/util/plugin/PluginManager.java | 296 +-- .../apollo/util/plugin/PluginMetaData.java | 236 +- .../util/plugin/RubyPluginEnvironment.java | 68 +- src/org/apollo/util/xml/XmlNode.java | 394 +-- src/org/apollo/util/xml/XmlParser.java | 242 +- 491 files changed, 22126 insertions(+), 22125 deletions(-) diff --git a/src/net/burtleburtle/bob/rand/IsaacRandom.java b/src/net/burtleburtle/bob/rand/IsaacRandom.java index d09d7320..38b220d9 100644 --- a/src/net/burtleburtle/bob/rand/IsaacRandom.java +++ b/src/net/burtleburtle/bob/rand/IsaacRandom.java @@ -25,281 +25,281 @@ package net.burtleburtle.bob.rand; */ public final class IsaacRandom { - /** - * The golden ratio. - */ - private static final int GOLDEN_RATIO = 0x9e3779b9; + /** + * The golden ratio. + */ + private static final int GOLDEN_RATIO = 0x9e3779b9; - /** - * The log of the size of the result and memory arrays. - */ - private static final int LOG_SIZE = 8; + /** + * The log of the size of the result and memory arrays. + */ + private static final int LOG_SIZE = 8; - /** - * The size of the result and memory arrays. - */ - private static final int SIZE = 1 << LOG_SIZE; + /** + * The size of the result and memory arrays. + */ + private static final int SIZE = 1 << LOG_SIZE; - /** - * A mask for pseudorandom lookup. - */ - private static int MASK = SIZE - 1 << 2; + /** + * A mask for pseudorandom lookup. + */ + private static int MASK = SIZE - 1 << 2; - /** - * The accumulator. - */ - private int a; + /** + * The accumulator. + */ + private int a; - /** - * The last result. - */ - private int b; + /** + * The last result. + */ + private int b; - /** - * The counter. - */ - private int c; + /** + * The counter. + */ + private int c; - /** - * The count through the results in the results array. - */ - private int count; + /** + * The count through the results in the results array. + */ + private int count; - /** - * The internal state. - */ - private int[] mem; + /** + * The internal state. + */ + private int[] mem; - /** - * The results given to the user. - */ - private int[] rsl; + /** + * The results given to the user. + */ + private int[] rsl; - /** - * Creates the random number generator without an initial seed. - */ - public IsaacRandom() { - mem = new int[SIZE]; - rsl = new int[SIZE]; - init(false); + /** + * Creates the random number generator without an initial seed. + */ + public IsaacRandom() { + mem = new int[SIZE]; + rsl = new int[SIZE]; + init(false); + } + + /** + * Creates the random number generator with the specified seed. + * + * @param seed The seed. + */ + public IsaacRandom(int[] seed) { + mem = new int[SIZE]; + rsl = new int[SIZE]; + for (int i = 0; i < seed.length; ++i) { + rsl[i] = seed[i]; + } + init(true); + } + + /** + * Initialises this random number generator. + * + * @param hasSeed Set to {@code true} if a seed was passed to the constructor. + */ + private void init(boolean hasSeed) { + int i; + int a, b, c, d, e, f, g, h; + a = b = c = d = e = f = g = h = GOLDEN_RATIO; + + for (i = 0; i < 4; ++i) { + a ^= b << 11; + d += a; + b += c; + b ^= c >>> 2; + e += b; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h += e; + f += g; + f ^= g >>> 4; + a += f; + g += h; + g ^= h << 8; + b += g; + h += a; + h ^= a >>> 9; + c += h; + a += b; } - /** - * Creates the random number generator with the specified seed. - * - * @param seed The seed. - */ - public IsaacRandom(int[] seed) { - mem = new int[SIZE]; - rsl = new int[SIZE]; - for (int i = 0; i < seed.length; ++i) { - rsl[i] = seed[i]; - } - init(true); + for (i = 0; i < SIZE; i += 8) { /* fill in mem[] with messy stuff */ + if (hasSeed) { + a += rsl[i]; + b += rsl[i + 1]; + c += rsl[i + 2]; + d += rsl[i + 3]; + e += rsl[i + 4]; + f += rsl[i + 5]; + g += rsl[i + 6]; + h += rsl[i + 7]; + } + a ^= b << 11; + d += a; + b += c; + b ^= c >>> 2; + e += b; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h += e; + f += g; + f ^= g >>> 4; + a += f; + g += h; + g ^= h << 8; + b += g; + h += a; + h ^= a >>> 9; + c += h; + a += b; + mem[i] = a; + mem[i + 1] = b; + mem[i + 2] = c; + mem[i + 3] = d; + mem[i + 4] = e; + mem[i + 5] = f; + mem[i + 6] = g; + mem[i + 7] = h; } - /** - * Initialises this random number generator. - * - * @param hasSeed Set to {@code true} if a seed was passed to the constructor. - */ - private void init(boolean hasSeed) { - int i; - int a, b, c, d, e, f, g, h; - a = b = c = d = e = f = g = h = GOLDEN_RATIO; - - for (i = 0; i < 4; ++i) { - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - } - - for (i = 0; i < SIZE; i += 8) { /* fill in mem[] with messy stuff */ - if (hasSeed) { - a += rsl[i]; - b += rsl[i + 1]; - c += rsl[i + 2]; - d += rsl[i + 3]; - e += rsl[i + 4]; - f += rsl[i + 5]; - g += rsl[i + 6]; - h += rsl[i + 7]; - } - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - mem[i] = a; - mem[i + 1] = b; - mem[i + 2] = c; - mem[i + 3] = d; - mem[i + 4] = e; - mem[i + 5] = f; - mem[i + 6] = g; - mem[i + 7] = h; - } - - if (hasSeed) { /* second pass makes all of seed affect all of mem */ - for (i = 0; i < SIZE; i += 8) { - a += mem[i]; - b += mem[i + 1]; - c += mem[i + 2]; - d += mem[i + 3]; - e += mem[i + 4]; - f += mem[i + 5]; - g += mem[i + 6]; - h += mem[i + 7]; - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - mem[i] = a; - mem[i + 1] = b; - mem[i + 2] = c; - mem[i + 3] = d; - mem[i + 4] = e; - mem[i + 5] = f; - mem[i + 6] = g; - mem[i + 7] = h; - } - } - - isaac(); - count = SIZE; + if (hasSeed) { /* second pass makes all of seed affect all of mem */ + for (i = 0; i < SIZE; i += 8) { + a += mem[i]; + b += mem[i + 1]; + c += mem[i + 2]; + d += mem[i + 3]; + e += mem[i + 4]; + f += mem[i + 5]; + g += mem[i + 6]; + h += mem[i + 7]; + a ^= b << 11; + d += a; + b += c; + b ^= c >>> 2; + e += b; + c += d; + c ^= d << 8; + f += c; + d += e; + d ^= e >>> 16; + g += d; + e += f; + e ^= f << 10; + h += e; + f += g; + f ^= g >>> 4; + a += f; + g += h; + g ^= h << 8; + b += g; + h += a; + h ^= a >>> 9; + c += h; + a += b; + mem[i] = a; + mem[i + 1] = b; + mem[i + 2] = c; + mem[i + 3] = d; + mem[i + 4] = e; + mem[i + 5] = f; + mem[i + 6] = g; + mem[i + 7] = h; + } } - /** - * Generates 256 results. - */ - private void isaac() { - int i, j, x, y; + isaac(); + count = SIZE; + } - b += ++c; - for (i = 0, j = SIZE / 2; i < SIZE / 2;) { - x = mem[i]; - a ^= a << 13; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + /** + * Generates 256 results. + */ + private void isaac() { + int i, j, x, y; - x = mem[i]; - a ^= a >>> 6; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + b += ++c; + for (i = 0, j = SIZE / 2; i < SIZE / 2;) { + x = mem[i]; + a ^= a << 13; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - x = mem[i]; - a ^= a << 2; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + x = mem[i]; + a ^= a >>> 6; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - x = mem[i]; - a ^= a >>> 16; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - } + x = mem[i]; + a ^= a << 2; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - for (j = 0; j < SIZE / 2;) { - x = mem[i]; - a ^= a << 13; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - - x = mem[i]; - a ^= a >>> 6; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - - x = mem[i]; - a ^= a << 2; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - - x = mem[i]; - a ^= a >>> 16; - a += mem[j++]; - mem[i] = y = mem[(x & MASK) >> 2] + a + b; - rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; - } + x = mem[i]; + a ^= a >>> 16; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; } - /** - * Gets the next random value. - * - * @return The next random value. - */ - public int nextInt() { - if (0 == count--) { - isaac(); - count = SIZE - 1; - } - return rsl[count]; + for (j = 0; j < SIZE / 2;) { + x = mem[i]; + a ^= a << 13; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + + x = mem[i]; + a ^= a >>> 6; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + + x = mem[i]; + a ^= a << 2; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; + + x = mem[i]; + a ^= a >>> 16; + a += mem[j++]; + mem[i] = y = mem[(x & MASK) >> 2] + a + b; + rsl[i++] = b = mem[(y >> LOG_SIZE & MASK) >> 2] + x; } + } + + /** + * Gets the next random value. + * + * @return The next random value. + */ + public int nextInt() { + if (0 == count--) { + isaac(); + count = SIZE - 1; + } + return rsl[count]; + } } \ No newline at end of file diff --git a/src/org/apollo/Server.java b/src/org/apollo/Server.java index b691b492..cdce95aa 100644 --- a/src/org/apollo/Server.java +++ b/src/org/apollo/Server.java @@ -32,144 +32,144 @@ import org.apollo.util.plugin.PluginManager; */ public final class Server { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(Server.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(Server.class.getName()); - /** - * The entry point of the Apollo server application. - * - * @param args The command-line arguments passed to the application. - */ - public static void main(String[] args) { - try { - Server server = new Server(); - server.init(args.length == 1 ? args[0] : Release317.class.getName()); + /** + * The entry point of the Apollo server application. + * + * @param args The command-line arguments passed to the application. + */ + public static void main(String[] args) { + try { + Server server = new Server(); + server.init(args.length == 1 ? args[0] : Release317.class.getName()); - SocketAddress service = new InetSocketAddress(NetworkConstants.SERVICE_PORT); - SocketAddress http = new InetSocketAddress(NetworkConstants.HTTP_PORT); - SocketAddress jaggrab = new InetSocketAddress(NetworkConstants.JAGGRAB_PORT); + SocketAddress service = new InetSocketAddress(NetworkConstants.SERVICE_PORT); + SocketAddress http = new InetSocketAddress(NetworkConstants.HTTP_PORT); + SocketAddress jaggrab = new InetSocketAddress(NetworkConstants.JAGGRAB_PORT); - server.start(); - server.bind(service, http, jaggrab); - } catch (Throwable t) { - logger.log(Level.SEVERE, "Error whilst starting server.", t); - } + server.start(); + server.bind(service, http, jaggrab); + } catch (Throwable t) { + logger.log(Level.SEVERE, "Error whilst starting server.", t); + } + } + + /** + * The server's context. + */ + private ServerContext context; + + /** + * The {@link ServerBootstrap} for the HTTP listener. + */ + private final ServerBootstrap httpBootstrap = new ServerBootstrap(); + + /** + * The {@link ServerBootstrap} for the JAGGRAB listener. + */ + private final ServerBootstrap jagGrabBootstrap = new ServerBootstrap(); + + /** + * The {@link ServerBootstrap} for the service listener. + */ + private final ServerBootstrap serviceBootstrap = new ServerBootstrap(); + + /** + * The event loop group. + */ + private final EventLoopGroup loopGroup = new NioEventLoopGroup(); + + /** + * The service manager. + */ + private final ServiceManager serviceManager; + + /** + * Creates the Apollo server. + * + * @throws Exception If an error occurs whilst creating services. + */ + public Server() throws Exception { + logger.info("Starting Apollo..."); + serviceManager = new ServiceManager(); + } + + /** + * Binds the server to the specified address. + * + * @param serviceAddress The service address to bind to. + * @param httpAddress The HTTP address to bind to. + * @param jagGrabAddress The JAGGRAB address to bind to. + */ + public void bind(SocketAddress serviceAddress, SocketAddress httpAddress, SocketAddress jagGrabAddress) { + logger.info("Binding service listener to address: " + serviceAddress + "..."); + serviceBootstrap.bind(serviceAddress); + + logger.info("Binding HTTP listener to address: " + httpAddress + "..."); + try { + httpBootstrap.bind(httpAddress); + } catch (Throwable t) { + logger.log(Level.WARNING, + "Binding to HTTP failed: client will use JAGGRAB as a fallback (not recommended)!", t); } - /** - * The server's context. - */ - private ServerContext context; + logger.info("Binding JAGGRAB listener to address: " + jagGrabAddress + "..."); + jagGrabBootstrap.bind(jagGrabAddress); - /** - * The {@link ServerBootstrap} for the HTTP listener. - */ - private final ServerBootstrap httpBootstrap = new ServerBootstrap(); + logger.info("Ready for connections."); + } - /** - * The {@link ServerBootstrap} for the JAGGRAB listener. - */ - private final ServerBootstrap jagGrabBootstrap = new ServerBootstrap(); + /** + * Initialises the server. + * + * @param releaseClassName The class name of the current active {@link Release}. + * @throws ClassNotFoundException If the release class could not be found. + * @throws IllegalAccessException If the release class could not be accessed. + * @throws InstantiationException If the release class could not be instantiated. + */ + public void init(String releaseClassName) throws ClassNotFoundException, InstantiationException, + IllegalAccessException { + Class clazz = Class.forName(releaseClassName); + Release release = (Release) clazz.newInstance(); - /** - * The {@link ServerBootstrap} for the service listener. - */ - private final ServerBootstrap serviceBootstrap = new ServerBootstrap(); + logger.info("Initialized release #" + release.getReleaseNumber() + "."); - /** - * The event loop group. - */ - private final EventLoopGroup loopGroup = new NioEventLoopGroup(); + serviceBootstrap.group(loopGroup); + httpBootstrap.group(loopGroup); + jagGrabBootstrap.group(loopGroup); - /** - * The service manager. - */ - private final ServiceManager serviceManager; + context = new ServerContext(release, serviceManager); + ApolloHandler handler = new ApolloHandler(context); - /** - * Creates the Apollo server. - * - * @throws Exception If an error occurs whilst creating services. - */ - public Server() throws Exception { - logger.info("Starting Apollo..."); - serviceManager = new ServiceManager(); - } + ChannelInitializer serviceInitializer = new ServiceChannelInitializer(handler); + serviceBootstrap.channel(NioServerSocketChannel.class); + serviceBootstrap.childHandler(serviceInitializer); - /** - * Binds the server to the specified address. - * - * @param serviceAddress The service address to bind to. - * @param httpAddress The HTTP address to bind to. - * @param jagGrabAddress The JAGGRAB address to bind to. - */ - public void bind(SocketAddress serviceAddress, SocketAddress httpAddress, SocketAddress jagGrabAddress) { - logger.info("Binding service listener to address: " + serviceAddress + "..."); - serviceBootstrap.bind(serviceAddress); + ChannelInitializer httpInitializer = new HttpChannelInitializer(handler); + httpBootstrap.channel(NioServerSocketChannel.class); + httpBootstrap.childHandler(httpInitializer); - logger.info("Binding HTTP listener to address: " + httpAddress + "..."); - try { - httpBootstrap.bind(httpAddress); - } catch (Throwable t) { - logger.log(Level.WARNING, - "Binding to HTTP failed: client will use JAGGRAB as a fallback (not recommended)!", t); - } + ChannelInitializer jagGrabInitializer = new JagGrabChannelInitializer(handler); + jagGrabBootstrap.channel(NioServerSocketChannel.class); + jagGrabBootstrap.childHandler(jagGrabInitializer); + } - logger.info("Binding JAGGRAB listener to address: " + jagGrabAddress + "..."); - jagGrabBootstrap.bind(jagGrabAddress); + /** + * Starts the server. + * + * @throws Exception If an error occurs. + */ + public void start() throws Exception { + PluginManager manager = new PluginManager(new PluginContext(context)); + serviceManager.startAll(); - logger.info("Ready for connections."); - } - - /** - * Initialises the server. - * - * @param releaseClassName The class name of the current active {@link Release}. - * @throws ClassNotFoundException If the release class could not be found. - * @throws IllegalAccessException If the release class could not be accessed. - * @throws InstantiationException If the release class could not be instantiated. - */ - public void init(String releaseClassName) throws ClassNotFoundException, InstantiationException, - IllegalAccessException { - Class clazz = Class.forName(releaseClassName); - Release release = (Release) clazz.newInstance(); - - logger.info("Initialized release #" + release.getReleaseNumber() + "."); - - serviceBootstrap.group(loopGroup); - httpBootstrap.group(loopGroup); - jagGrabBootstrap.group(loopGroup); - - context = new ServerContext(release, serviceManager); - ApolloHandler handler = new ApolloHandler(context); - - ChannelInitializer serviceInitializer = new ServiceChannelInitializer(handler); - serviceBootstrap.channel(NioServerSocketChannel.class); - serviceBootstrap.childHandler(serviceInitializer); - - ChannelInitializer httpInitializer = new HttpChannelInitializer(handler); - httpBootstrap.channel(NioServerSocketChannel.class); - httpBootstrap.childHandler(httpInitializer); - - ChannelInitializer jagGrabInitializer = new JagGrabChannelInitializer(handler); - jagGrabBootstrap.channel(NioServerSocketChannel.class); - jagGrabBootstrap.childHandler(jagGrabInitializer); - } - - /** - * Starts the server. - * - * @throws Exception If an error occurs. - */ - public void start() throws Exception { - PluginManager manager = new PluginManager(new PluginContext(context)); - serviceManager.startAll(); - - int releaseNo = context.getRelease().getReleaseNumber(); - IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + releaseNo), true); - World.getWorld().init(releaseNo, fs, manager); - } + int releaseNo = context.getRelease().getReleaseNumber(); + IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + releaseNo), true); + World.getWorld().init(releaseNo, fs, manager); + } } \ No newline at end of file diff --git a/src/org/apollo/ServerContext.java b/src/org/apollo/ServerContext.java index 821943c1..af184e8c 100644 --- a/src/org/apollo/ServerContext.java +++ b/src/org/apollo/ServerContext.java @@ -11,55 +11,55 @@ import org.apollo.net.release.Release; */ public final class ServerContext { - /** - * The current release. - */ - private final Release release; + /** + * The current release. + */ + private final Release release; - /** - * The service manager. - */ - private final ServiceManager serviceManager; + /** + * The service manager. + */ + private final ServiceManager serviceManager; - /** - * Creates a new server context. - * - * @param release The current release. - * @param serviceManager The service manager. - */ - ServerContext(Release release, ServiceManager serviceManager) { - this.release = release; - this.serviceManager = serviceManager; - this.serviceManager.setContext(this); - } + /** + * Creates a new server context. + * + * @param release The current release. + * @param serviceManager The service manager. + */ + ServerContext(Release release, ServiceManager serviceManager) { + this.release = release; + this.serviceManager = serviceManager; + this.serviceManager.setContext(this); + } - /** - * Gets the current release. - * - * @return The current release. - */ - public Release getRelease() { - return release; - } + /** + * Gets the current release. + * + * @return The current release. + */ + public Release getRelease() { + return release; + } - /** - * Gets a service. This method is shorthand for {@code getServiceManager().getService(...)}. - * - * @param The type of service. - * @param clazz The service class. - * @return The service, or {@code null} if it could not be found. - */ - public S getService(Class clazz) { - return serviceManager.getService(clazz); - } + /** + * Gets a service. This method is shorthand for {@code getServiceManager().getService(...)}. + * + * @param The type of service. + * @param clazz The service class. + * @return The service, or {@code null} if it could not be found. + */ + public S getService(Class clazz) { + return serviceManager.getService(clazz); + } - /** - * Gets the service manager. - * - * @return The service manager. - */ - public ServiceManager getServiceManager() { - return serviceManager; - } + /** + * Gets the service manager. + * + * @return The service manager. + */ + public ServiceManager getServiceManager() { + return serviceManager; + } } \ No newline at end of file diff --git a/src/org/apollo/Service.java b/src/org/apollo/Service.java index 16637b5f..2fb3c232 100644 --- a/src/org/apollo/Service.java +++ b/src/org/apollo/Service.java @@ -7,32 +7,32 @@ package org.apollo; */ public abstract class Service { - /** - * The server context. - */ - private ServerContext context; + /** + * The server context. + */ + private ServerContext context; - /** - * Gets the {@link ServerContext}. - * - * @return The context. - */ - public final ServerContext getContext() { - return context; - } + /** + * Gets the {@link ServerContext}. + * + * @return The context. + */ + public final ServerContext getContext() { + return context; + } - /** - * Sets the {@link ServerContext}. - * - * @param context The context. - */ - public final void setContext(ServerContext context) { - this.context = context; - } + /** + * Sets the {@link ServerContext}. + * + * @param context The context. + */ + public final void setContext(ServerContext context) { + this.context = context; + } - /** - * Starts the service. - */ - public abstract void start(); + /** + * Starts the service. + */ + public abstract void start(); } \ No newline at end of file diff --git a/src/org/apollo/ServiceManager.java b/src/org/apollo/ServiceManager.java index 9828a1a6..ef68e869 100644 --- a/src/org/apollo/ServiceManager.java +++ b/src/org/apollo/ServiceManager.java @@ -18,108 +18,108 @@ import org.xml.sax.SAXException; */ public final class ServiceManager { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(ServiceManager.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(ServiceManager.class.getName()); - /** - * The service map. - */ - private Map, Service> services = new HashMap, Service>(); + /** + * The service map. + */ + private Map, Service> services = new HashMap, Service>(); - /** - * Creates and initializes the {@link ServiceManager}. - * - * @throws Exception If an error occurs. - */ - public ServiceManager() throws Exception { - init(); + /** + * Creates and initializes the {@link ServiceManager}. + * + * @throws Exception If an error occurs. + */ + public ServiceManager() throws Exception { + init(); + } + + /** + * Gets a service. + * + * @param The type of service. + * @param clazz The service class. + * @return The service. + */ + @SuppressWarnings("unchecked") + public S getService(Class clazz) { + return (S) services.get(clazz); + } + + /** + * Initializes this service manager. + * + * @throws SAXException If the service XML file could not be parsed. + * @throws IOException If the file could not be accessed. + * @throws IllegalAccessException If the service could not be accessed. + * @throws InstantiationException If the service could not be instantiated. + * @throws ClassNotFoundException If the service could not be found. + */ + @SuppressWarnings("unchecked") + private void init() throws SAXException, IOException, InstantiationException, IllegalAccessException, + ClassNotFoundException { + logger.info("Registering services..."); + + XmlParser parser = new XmlParser(); + XmlNode rootNode; + + try (InputStream is = new FileInputStream("data/services.xml")) { + rootNode = parser.parse(is); } - /** - * Gets a service. - * - * @param The type of service. - * @param clazz The service class. - * @return The service. - */ - @SuppressWarnings("unchecked") - public S getService(Class clazz) { - return (S) services.get(clazz); + if (!rootNode.getName().equals("services")) { + throw new IOException("Unexpected name of root node."); } - /** - * Initializes this service manager. - * - * @throws SAXException If the service XML file could not be parsed. - * @throws IOException If the file could not be accessed. - * @throws IllegalAccessException If the service could not be accessed. - * @throws InstantiationException If the service could not be instantiated. - * @throws ClassNotFoundException If the service could not be found. - */ - @SuppressWarnings("unchecked") - private void init() throws SAXException, IOException, InstantiationException, IllegalAccessException, - ClassNotFoundException { - logger.info("Registering services..."); + for (XmlNode childNode : rootNode) { + if (!childNode.getName().equals("service")) { + throw new IOException("Unexpected name of child node."); + } - XmlParser parser = new XmlParser(); - XmlNode rootNode; + if (!childNode.hasValue()) { + throw new IOException("Child node must have a value."); + } - try (InputStream is = new FileInputStream("data/services.xml")) { - rootNode = parser.parse(is); - } - - if (!rootNode.getName().equals("services")) { - throw new IOException("Unexpected name of root node."); - } - - for (XmlNode childNode : rootNode) { - if (!childNode.getName().equals("service")) { - throw new IOException("Unexpected name of child node."); - } - - if (!childNode.hasValue()) { - throw new IOException("Child node must have a value."); - } - - Class clazz = (Class) Class.forName(childNode.getValue()); - register((Class) clazz, clazz.newInstance()); - } + Class clazz = (Class) Class.forName(childNode.getValue()); + register((Class) clazz, clazz.newInstance()); } + } - /** - * Registers a service. - * - * @param The type of service. - * @param clazz The service's class. - * @param service The service. - */ - private void register(Class clazz, S service) { - logger.fine("Registering service: " + clazz + "..."); - services.put(clazz, service); - } + /** + * Registers a service. + * + * @param The type of service. + * @param clazz The service's class. + * @param service The service. + */ + private void register(Class clazz, S service) { + logger.fine("Registering service: " + clazz + "..."); + services.put(clazz, service); + } - /** - * Sets the context of all services. - * - * @param ctx The server context. - */ - public void setContext(ServerContext ctx) { - for (Service service : services.values()) { - service.setContext(ctx); - } + /** + * Sets the context of all services. + * + * @param ctx The server context. + */ + public void setContext(ServerContext ctx) { + for (Service service : services.values()) { + service.setContext(ctx); } + } - /** - * Starts all the services. - */ - public void startAll() { - logger.info("Starting services..."); - for (Service service : services.values()) { - logger.fine("Starting service: " + service.getClass().getName() + "..."); - service.start(); - } + /** + * Starts all the services. + */ + public void startAll() { + logger.info("Starting services..."); + for (Service service : services.values()) { + logger.fine("Starting service: " + service.getClass().getName() + "..."); + service.start(); } + } } \ No newline at end of file diff --git a/src/org/apollo/fs/FileDescriptor.java b/src/org/apollo/fs/FileDescriptor.java index 902bfb99..a916df7f 100644 --- a/src/org/apollo/fs/FileDescriptor.java +++ b/src/org/apollo/fs/FileDescriptor.java @@ -7,43 +7,43 @@ package org.apollo.fs; */ public final class FileDescriptor { - /** - * The file id. - */ - private final int file; + /** + * The file id. + */ + private final int file; - /** - * The file type. - */ - private final int type; + /** + * The file type. + */ + private final int type; - /** - * Creates the file descriptor. - * - * @param type The file type. - * @param file The file id. - */ - public FileDescriptor(int type, int file) { - this.type = type; - this.file = file; - } + /** + * Creates the file descriptor. + * + * @param type The file type. + * @param file The file id. + */ + public FileDescriptor(int type, int file) { + this.type = type; + this.file = file; + } - /** - * Gets the file id. - * - * @return The file id. - */ - public int getFile() { - return file; - } + /** + * Gets the file id. + * + * @return The file id. + */ + public int getFile() { + return file; + } - /** - * Gets the file type. - * - * @return The file type. - */ - public int getType() { - return type; - } + /** + * Gets the file type. + * + * @return The file type. + */ + public int getType() { + return type; + } } \ No newline at end of file diff --git a/src/org/apollo/fs/FileSystemConstants.java b/src/org/apollo/fs/FileSystemConstants.java index b87d4747..ae65566a 100644 --- a/src/org/apollo/fs/FileSystemConstants.java +++ b/src/org/apollo/fs/FileSystemConstants.java @@ -7,41 +7,41 @@ package org.apollo.fs; */ public final class FileSystemConstants { - /** - * The number of archives in cache 0. - */ - public static final int ARCHIVE_COUNT = 9; + /** + * The number of archives in cache 0. + */ + public static final int ARCHIVE_COUNT = 9; - /** - * The size of a chunk. - */ - public static final int CHUNK_SIZE = 512; + /** + * The size of a chunk. + */ + public static final int CHUNK_SIZE = 512; - /** - * The size of a header. - */ - public static final int HEADER_SIZE = 8; + /** + * The size of a header. + */ + public static final int HEADER_SIZE = 8; - /** - * The size of a block. - */ - public static final int BLOCK_SIZE = HEADER_SIZE + CHUNK_SIZE; + /** + * The size of a block. + */ + public static final int BLOCK_SIZE = HEADER_SIZE + CHUNK_SIZE; - /** - * The number of caches. - */ - public static final int CACHE_COUNT = 5; + /** + * The number of caches. + */ + public static final int CACHE_COUNT = 5; - /** - * The size of an index. - */ - public static final int INDEX_SIZE = 6; + /** + * The size of an index. + */ + public static final int INDEX_SIZE = 6; - /** - * Default private constructor to prevent instantiation. - */ - private FileSystemConstants() { - - } + /** + * Default private constructor to prevent instantiation. + */ + private FileSystemConstants() { + + } } \ No newline at end of file diff --git a/src/org/apollo/fs/Index.java b/src/org/apollo/fs/Index.java index 3716ef0b..b3af9e6b 100644 --- a/src/org/apollo/fs/Index.java +++ b/src/org/apollo/fs/Index.java @@ -7,61 +7,61 @@ package org.apollo.fs; */ public final class Index { - /** - * Decodes a buffer into an index. - * - * @param buffer The buffer. - * @return The decoded {@link Index}. - * @throws IllegalArgumentException If the buffer length is invalid. - */ - public static Index decode(byte[] buffer) { - if (buffer.length != FileSystemConstants.INDEX_SIZE) { - throw new IllegalArgumentException("Incorrect buffer length."); - } - - int size = (buffer[0] & 0xFF) << 16 | (buffer[1] & 0xFF) << 8 | buffer[2] & 0xFF; - int block = (buffer[3] & 0xFF) << 16 | (buffer[4] & 0xFF) << 8 | buffer[5] & 0xFF; - - return new Index(size, block); + /** + * Decodes a buffer into an index. + * + * @param buffer The buffer. + * @return The decoded {@link Index}. + * @throws IllegalArgumentException If the buffer length is invalid. + */ + public static Index decode(byte[] buffer) { + if (buffer.length != FileSystemConstants.INDEX_SIZE) { + throw new IllegalArgumentException("Incorrect buffer length."); } - /** - * The first block of the file. - */ - private final int block; + int size = (buffer[0] & 0xFF) << 16 | (buffer[1] & 0xFF) << 8 | buffer[2] & 0xFF; + int block = (buffer[3] & 0xFF) << 16 | (buffer[4] & 0xFF) << 8 | buffer[5] & 0xFF; - /** - * The size of the file. - */ - private final int size; + return new Index(size, block); + } - /** - * Creates the index. - * - * @param size The size of the file. - * @param block The first block of the file. - */ - public Index(int size, int block) { - this.size = size; - this.block = block; - } + /** + * The first block of the file. + */ + private final int block; - /** - * Gets the first block of the file. - * - * @return The first block of the file. - */ - public int getBlock() { - return block; - } + /** + * The size of the file. + */ + private final int size; - /** - * Gets the size of the file. - * - * @return The size of the file. - */ - public int getSize() { - return size; - } + /** + * Creates the index. + * + * @param size The size of the file. + * @param block The first block of the file. + */ + public Index(int size, int block) { + this.size = size; + this.block = block; + } + + /** + * Gets the first block of the file. + * + * @return The first block of the file. + */ + public int getBlock() { + return block; + } + + /** + * Gets the size of the file. + * + * @return The size of the file. + */ + public int getSize() { + return size; + } } \ No newline at end of file diff --git a/src/org/apollo/fs/IndexedFileSystem.java b/src/org/apollo/fs/IndexedFileSystem.java index 002a1df8..c9bd55c8 100644 --- a/src/org/apollo/fs/IndexedFileSystem.java +++ b/src/org/apollo/fs/IndexedFileSystem.java @@ -16,275 +16,275 @@ import java.util.zip.CRC32; */ public final class IndexedFileSystem implements Closeable { - /** - * The cached CRC table. - */ - private ByteBuffer crcTable; + /** + * The cached CRC table. + */ + private ByteBuffer crcTable; - /** - * The data file. - */ - private RandomAccessFile data; + /** + * The data file. + */ + private RandomAccessFile data; - /** - * The index files. - */ - private RandomAccessFile[] indices = new RandomAccessFile[256]; + /** + * The index files. + */ + private RandomAccessFile[] indices = new RandomAccessFile[256]; - /** - * Read only flag. - */ - private final boolean readOnly; + /** + * Read only flag. + */ + private final boolean readOnly; - /** - * Creates the file system with the specified base directory. - * - * @param base The base directory. - * @param readOnly Indicates whether the file system will be read only or not. - * @throws FileNotFoundException If the data files could not be found. - */ - public IndexedFileSystem(File base, boolean readOnly) throws FileNotFoundException { - this.readOnly = readOnly; - detectLayout(base); + /** + * Creates the file system with the specified base directory. + * + * @param base The base directory. + * @param readOnly Indicates whether the file system will be read only or not. + * @throws FileNotFoundException If the data files could not be found. + */ + public IndexedFileSystem(File base, boolean readOnly) throws FileNotFoundException { + this.readOnly = readOnly; + detectLayout(base); + } + + @Override + public void close() throws IOException { + if (data != null) { + synchronized (data) { + data.close(); + } } - @Override - public void close() throws IOException { - if (data != null) { - synchronized (data) { - data.close(); - } + for (RandomAccessFile index : indices) { + if (index != null) { + synchronized (index) { + index.close(); } + } + } + } - for (RandomAccessFile index : indices) { - if (index != null) { - synchronized (index) { - index.close(); - } - } - } + /** + * Automatically detect the layout of the specified directory. + * + * @param base The base directory. + * @throws FileNotFoundException If the data files could not be found. + */ + private void detectLayout(File base) throws FileNotFoundException { + int indexCount = 0; + for (int index = 0; index < indices.length; index++) { + File f = new File(base.getAbsolutePath() + "/main_file_cache.idx" + index); + if (f.exists() && !f.isDirectory()) { + indexCount++; + indices[index] = new RandomAccessFile(f, readOnly ? "r" : "rw"); + } + } + if (indexCount <= 0) { + throw new FileNotFoundException("No index file(s) present."); } - /** - * Automatically detect the layout of the specified directory. - * - * @param base The base directory. - * @throws FileNotFoundException If the data files could not be found. - */ - private void detectLayout(File base) throws FileNotFoundException { - int indexCount = 0; - for (int index = 0; index < indices.length; index++) { - File f = new File(base.getAbsolutePath() + "/main_file_cache.idx" + index); - if (f.exists() && !f.isDirectory()) { - indexCount++; - indices[index] = new RandomAccessFile(f, readOnly ? "r" : "rw"); - } - } - if (indexCount <= 0) { - throw new FileNotFoundException("No index file(s) present."); - } + File oldEngineData = new File(base.getAbsolutePath() + "/main_file_cache.dat"); + File newEngineData = new File(base.getAbsolutePath() + "/main_file_cache.dat2"); + if (oldEngineData.exists() && !oldEngineData.isDirectory()) { + data = new RandomAccessFile(oldEngineData, readOnly ? "r" : "rw"); + } else if (newEngineData.exists() && !oldEngineData.isDirectory()) { + data = new RandomAccessFile(newEngineData, readOnly ? "r" : "rw"); + } else { + throw new FileNotFoundException("No data file present."); + } + } - File oldEngineData = new File(base.getAbsolutePath() + "/main_file_cache.dat"); - File newEngineData = new File(base.getAbsolutePath() + "/main_file_cache.dat2"); - if (oldEngineData.exists() && !oldEngineData.isDirectory()) { - data = new RandomAccessFile(oldEngineData, readOnly ? "r" : "rw"); - } else if (newEngineData.exists() && !oldEngineData.isDirectory()) { - data = new RandomAccessFile(newEngineData, readOnly ? "r" : "rw"); - } else { - throw new FileNotFoundException("No data file present."); + /** + * Gets the CRC table. + * + * @return The CRC table. + * @throws IOException If an I/O error occurs. + */ + public ByteBuffer getCrcTable() throws IOException { + if (readOnly) { + synchronized (this) { + if (crcTable != null) { + return crcTable.duplicate(); } + } + + int archives = getFileCount(0); + int hash = 1234; + int[] crcs = new int[archives]; + + // calculate the CRCs + CRC32 crc32 = new CRC32(); + for (int i = 1; i < crcs.length; i++) { + crc32.reset(); + + ByteBuffer buffer = getFile(0, i); + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes, 0, bytes.length); + crc32.update(bytes, 0, bytes.length); + + crcs[i] = (int) crc32.getValue(); + } + + // hash the CRCs and place them in the buffer + ByteBuffer buffer = ByteBuffer.allocate(crcs.length * 4 + 4); + for (int crc : crcs) { + hash = (hash << 1) + crc; + buffer.putInt(crc); + } + + buffer.putInt(hash); + buffer.flip(); + + synchronized (this) { + crcTable = buffer.asReadOnlyBuffer(); + return crcTable.duplicate(); + } + } + throw new IOException("Cannot get CRC table from a writable file system."); + } + + /** + * Gets a file. + * + * @param descriptor The {@link FileDescriptor} which points to the file. + * @return A {@link ByteBuffer} which contains the contents of the file. + * @throws IOException If an I/O error occurs. + */ + public ByteBuffer getFile(FileDescriptor descriptor) throws IOException { + Index index = getIndex(descriptor); + ByteBuffer buffer = ByteBuffer.allocate(index.getSize()); + + // calculate some initial values + long ptr = index.getBlock() * FileSystemConstants.BLOCK_SIZE; + int read = 0; + int size = index.getSize(); + int blocks = size / FileSystemConstants.CHUNK_SIZE; + if (size % FileSystemConstants.CHUNK_SIZE != 0) { + blocks++; } - /** - * Gets the CRC table. - * - * @return The CRC table. - * @throws IOException If an I/O error occurs. - */ - public ByteBuffer getCrcTable() throws IOException { - if (readOnly) { - synchronized (this) { - if (crcTable != null) { - return crcTable.duplicate(); - } - } + for (int i = 0; i < blocks; i++) { + // read header + byte[] header = new byte[FileSystemConstants.HEADER_SIZE]; + synchronized (data) { + data.seek(ptr); + data.readFully(header); + } - int archives = getFileCount(0); - int hash = 1234; - int[] crcs = new int[archives]; + // increment pointers + ptr += FileSystemConstants.HEADER_SIZE; - // calculate the CRCs - CRC32 crc32 = new CRC32(); - for (int i = 1; i < crcs.length; i++) { - crc32.reset(); + // parse header + int nextFile = (header[0] & 0xFF) << 8 | header[1] & 0xFF; + int curChunk = (header[2] & 0xFF) << 8 | header[3] & 0xFF; + int nextBlock = (header[4] & 0xFF) << 16 | (header[5] & 0xFF) << 8 | header[6] & 0xFF; + int nextType = header[7] & 0xFF; - ByteBuffer buffer = getFile(0, i); - byte[] bytes = new byte[buffer.remaining()]; - buffer.get(bytes, 0, bytes.length); - crc32.update(bytes, 0, bytes.length); + // check expected chunk id is correct + if (i != curChunk) { + throw new IOException("Chunk id mismatch."); + } - crcs[i] = (int) crc32.getValue(); - } + // calculate how much we can read + int chunkSize = size - read; + if (chunkSize > FileSystemConstants.CHUNK_SIZE) { + chunkSize = FileSystemConstants.CHUNK_SIZE; + } - // hash the CRCs and place them in the buffer - ByteBuffer buffer = ByteBuffer.allocate(crcs.length * 4 + 4); - for (int crc : crcs) { - hash = (hash << 1) + crc; - buffer.putInt(crc); - } + // read the next chunk and put it in the buffer + byte[] chunk = new byte[chunkSize]; + synchronized (data) { + data.seek(ptr); + data.readFully(chunk); + } + buffer.put(chunk); - buffer.putInt(hash); - buffer.flip(); + // increment pointers + read += chunkSize; + ptr = (long) nextBlock * (long) FileSystemConstants.BLOCK_SIZE; - synchronized (this) { - crcTable = buffer.asReadOnlyBuffer(); - return crcTable.duplicate(); - } + // if we still have more data to read, check the validity of the header + if (size > read) { + if (nextType != descriptor.getType() + 1) { + throw new IOException("File type mismatch."); } - throw new IOException("Cannot get CRC table from a writable file system."); + + if (nextFile != descriptor.getFile()) { + throw new IOException("File id mismatch."); + } + } } - /** - * Gets a file. - * - * @param descriptor The {@link FileDescriptor} which points to the file. - * @return A {@link ByteBuffer} which contains the contents of the file. - * @throws IOException If an I/O error occurs. - */ - public ByteBuffer getFile(FileDescriptor descriptor) throws IOException { - Index index = getIndex(descriptor); - ByteBuffer buffer = ByteBuffer.allocate(index.getSize()); + buffer.flip(); + return buffer; + } - // calculate some initial values - long ptr = index.getBlock() * FileSystemConstants.BLOCK_SIZE; - int read = 0; - int size = index.getSize(); - int blocks = size / FileSystemConstants.CHUNK_SIZE; - if (size % FileSystemConstants.CHUNK_SIZE != 0) { - blocks++; - } + /** + * Gets a file. + * + * @param type The file type. + * @param file The file id. + * @return A {@link ByteBuffer} which contains the contents of the file. + * @throws IOException If an I/O error occurs. + */ + public ByteBuffer getFile(int type, int file) throws IOException { + return getFile(new FileDescriptor(type, file)); + } - for (int i = 0; i < blocks; i++) { - // read header - byte[] header = new byte[FileSystemConstants.HEADER_SIZE]; - synchronized (data) { - data.seek(ptr); - data.readFully(header); - } - - // increment pointers - ptr += FileSystemConstants.HEADER_SIZE; - - // parse header - int nextFile = (header[0] & 0xFF) << 8 | header[1] & 0xFF; - int curChunk = (header[2] & 0xFF) << 8 | header[3] & 0xFF; - int nextBlock = (header[4] & 0xFF) << 16 | (header[5] & 0xFF) << 8 | header[6] & 0xFF; - int nextType = header[7] & 0xFF; - - // check expected chunk id is correct - if (i != curChunk) { - throw new IOException("Chunk id mismatch."); - } - - // calculate how much we can read - int chunkSize = size - read; - if (chunkSize > FileSystemConstants.CHUNK_SIZE) { - chunkSize = FileSystemConstants.CHUNK_SIZE; - } - - // read the next chunk and put it in the buffer - byte[] chunk = new byte[chunkSize]; - synchronized (data) { - data.seek(ptr); - data.readFully(chunk); - } - buffer.put(chunk); - - // increment pointers - read += chunkSize; - ptr = (long) nextBlock * (long) FileSystemConstants.BLOCK_SIZE; - - // if we still have more data to read, check the validity of the header - if (size > read) { - if (nextType != descriptor.getType() + 1) { - throw new IOException("File type mismatch."); - } - - if (nextFile != descriptor.getFile()) { - throw new IOException("File id mismatch."); - } - } - } - - buffer.flip(); - return buffer; + /** + * Gets the number of files with the specified type. + * + * @param type The type. + * @return The number of files. + * @throws IOException If an I/O error occurs. + */ + private int getFileCount(int type) throws IOException { + if (type < 0 || type >= indices.length) { + throw new IndexOutOfBoundsException("File type out of bounds."); } - /** - * Gets a file. - * - * @param type The file type. - * @param file The file id. - * @return A {@link ByteBuffer} which contains the contents of the file. - * @throws IOException If an I/O error occurs. - */ - public ByteBuffer getFile(int type, int file) throws IOException { - return getFile(new FileDescriptor(type, file)); + RandomAccessFile indexFile = indices[type]; + synchronized (indexFile) { + return (int) (indexFile.length() / FileSystemConstants.INDEX_SIZE); + } + } + + /** + * Gets the index of a file. + * + * @param descriptor The {@link FileDescriptor} which points to the file. + * @return The {@link Index}. + * @throws IOException If an I/O error occurs. + */ + private Index getIndex(FileDescriptor descriptor) throws IOException { + int index = descriptor.getType(); + if (index < 0 || index >= indices.length) { + throw new IndexOutOfBoundsException("File descriptor type out of bounds."); } - /** - * Gets the number of files with the specified type. - * - * @param type The type. - * @return The number of files. - * @throws IOException If an I/O error occurs. - */ - private int getFileCount(int type) throws IOException { - if (type < 0 || type >= indices.length) { - throw new IndexOutOfBoundsException("File type out of bounds."); - } - - RandomAccessFile indexFile = indices[type]; - synchronized (indexFile) { - return (int) (indexFile.length() / FileSystemConstants.INDEX_SIZE); - } + byte[] buffer = new byte[FileSystemConstants.INDEX_SIZE]; + RandomAccessFile indexFile = indices[index]; + synchronized (indexFile) { + long ptr = descriptor.getFile() * FileSystemConstants.INDEX_SIZE; + if (ptr >= 0 && indexFile.length() >= ptr + FileSystemConstants.INDEX_SIZE) { + indexFile.seek(ptr); + indexFile.readFully(buffer); + } else { + throw new FileNotFoundException("Could not find find index."); + } } - /** - * Gets the index of a file. - * - * @param descriptor The {@link FileDescriptor} which points to the file. - * @return The {@link Index}. - * @throws IOException If an I/O error occurs. - */ - private Index getIndex(FileDescriptor descriptor) throws IOException { - int index = descriptor.getType(); - if (index < 0 || index >= indices.length) { - throw new IndexOutOfBoundsException("File descriptor type out of bounds."); - } + return Index.decode(buffer); + } - byte[] buffer = new byte[FileSystemConstants.INDEX_SIZE]; - RandomAccessFile indexFile = indices[index]; - synchronized (indexFile) { - long ptr = descriptor.getFile() * FileSystemConstants.INDEX_SIZE; - if (ptr >= 0 && indexFile.length() >= ptr + FileSystemConstants.INDEX_SIZE) { - indexFile.seek(ptr); - indexFile.readFully(buffer); - } else { - throw new FileNotFoundException("Could not find find index."); - } - } - - return Index.decode(buffer); - } - - /** - * Checks if this {@link IndexedFileSystem} is read only. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isReadOnly() { - return readOnly; - } + /** + * Checks if this {@link IndexedFileSystem} is read only. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isReadOnly() { + return readOnly; + } } \ No newline at end of file diff --git a/src/org/apollo/fs/archive/Archive.java b/src/org/apollo/fs/archive/Archive.java index 5ed7ede8..7750ab9b 100644 --- a/src/org/apollo/fs/archive/Archive.java +++ b/src/org/apollo/fs/archive/Archive.java @@ -14,92 +14,92 @@ import org.apollo.util.CompressionUtil; */ public final class Archive { - /** - * Decodes the archive in the specified buffer. - * - * @param buffer The buffer. - * @return The archive. - * @throws IOException If an I/O error occurs. - */ - public static Archive decode(ByteBuffer buffer) throws IOException { - int extractedSize = BufferUtil.readUnsignedTriByte(buffer); - int size = BufferUtil.readUnsignedTriByte(buffer); - boolean extracted = false; + /** + * Decodes the archive in the specified buffer. + * + * @param buffer The buffer. + * @return The archive. + * @throws IOException If an I/O error occurs. + */ + public static Archive decode(ByteBuffer buffer) throws IOException { + int extractedSize = BufferUtil.readUnsignedTriByte(buffer); + int size = BufferUtil.readUnsignedTriByte(buffer); + boolean extracted = false; - if (size != extractedSize) { - byte[] compressed = new byte[size]; - byte[] uncompressed = new byte[extractedSize]; - buffer.get(compressed); - CompressionUtil.unbzip2(compressed, uncompressed); - buffer = ByteBuffer.wrap(uncompressed); - extracted = true; - } - - int entries = buffer.getShort() & 0xFFFF; - int[] identifiers = new int[entries]; - int[] extractedSizes = new int[entries]; - int[] sizes = new int[entries]; - - for (int i = 0; i < entries; i++) { - identifiers[i] = buffer.getInt(); - extractedSizes[i] = BufferUtil.readUnsignedTriByte(buffer); - sizes[i] = BufferUtil.readUnsignedTriByte(buffer); - } - - ArchiveEntry[] entry = new ArchiveEntry[entries]; - for (int i = 0; i < entries; i++) { - ByteBuffer entryBuffer; - if (!extracted) { - byte[] compressed = new byte[sizes[i]]; - byte[] uncompressed = new byte[extractedSizes[i]]; - buffer.get(compressed); - CompressionUtil.unbzip2(compressed, uncompressed); - entryBuffer = ByteBuffer.wrap(uncompressed); - } else { - byte[] buf = new byte[extractedSizes[i]]; - buffer.get(buf); - entryBuffer = ByteBuffer.wrap(buf); - } - entry[i] = new ArchiveEntry(identifiers[i], entryBuffer); - } - return new Archive(entry); + if (size != extractedSize) { + byte[] compressed = new byte[size]; + byte[] uncompressed = new byte[extractedSize]; + buffer.get(compressed); + CompressionUtil.unbzip2(compressed, uncompressed); + buffer = ByteBuffer.wrap(uncompressed); + extracted = true; } - /** - * The entries in this archive. - */ - private final ArchiveEntry[] entries; + int entries = buffer.getShort() & 0xFFFF; + int[] identifiers = new int[entries]; + int[] extractedSizes = new int[entries]; + int[] sizes = new int[entries]; - /** - * Creates a new archive. - * - * @param entries The entries in this archive. - */ - public Archive(ArchiveEntry[] entries) { - this.entries = entries; + for (int i = 0; i < entries; i++) { + identifiers[i] = buffer.getInt(); + extractedSizes[i] = BufferUtil.readUnsignedTriByte(buffer); + sizes[i] = BufferUtil.readUnsignedTriByte(buffer); } - /** - * Gets an entry by its name. - * - * @param name The name. - * @return The entry. - * @throws FileNotFoundException If the file could not be found. - */ - public ArchiveEntry getEntry(String name) throws FileNotFoundException { - int hash = 0; - name = name.toUpperCase(); - - for (int i = 0; i < name.length(); i++) { - hash = hash * 61 + name.charAt(i) - 32; - } - - for (ArchiveEntry entry : entries) { - if (entry.getIdentifier() == hash) { - return entry; - } - } - throw new FileNotFoundException("Could not find entry: " + name + "."); + ArchiveEntry[] entry = new ArchiveEntry[entries]; + for (int i = 0; i < entries; i++) { + ByteBuffer entryBuffer; + if (!extracted) { + byte[] compressed = new byte[sizes[i]]; + byte[] uncompressed = new byte[extractedSizes[i]]; + buffer.get(compressed); + CompressionUtil.unbzip2(compressed, uncompressed); + entryBuffer = ByteBuffer.wrap(uncompressed); + } else { + byte[] buf = new byte[extractedSizes[i]]; + buffer.get(buf); + entryBuffer = ByteBuffer.wrap(buf); + } + entry[i] = new ArchiveEntry(identifiers[i], entryBuffer); } + return new Archive(entry); + } + + /** + * The entries in this archive. + */ + private final ArchiveEntry[] entries; + + /** + * Creates a new archive. + * + * @param entries The entries in this archive. + */ + public Archive(ArchiveEntry[] entries) { + this.entries = entries; + } + + /** + * Gets an entry by its name. + * + * @param name The name. + * @return The entry. + * @throws FileNotFoundException If the file could not be found. + */ + public ArchiveEntry getEntry(String name) throws FileNotFoundException { + int hash = 0; + name = name.toUpperCase(); + + for (int i = 0; i < name.length(); i++) { + hash = hash * 61 + name.charAt(i) - 32; + } + + for (ArchiveEntry entry : entries) { + if (entry.getIdentifier() == hash) { + return entry; + } + } + throw new FileNotFoundException("Could not find entry: " + name + "."); + } } \ No newline at end of file diff --git a/src/org/apollo/fs/archive/ArchiveEntry.java b/src/org/apollo/fs/archive/ArchiveEntry.java index a8a9ffbf..a609c02e 100644 --- a/src/org/apollo/fs/archive/ArchiveEntry.java +++ b/src/org/apollo/fs/archive/ArchiveEntry.java @@ -9,43 +9,43 @@ import java.nio.ByteBuffer; */ public final class ArchiveEntry { - /** - * The buffer of this entry. - */ - private final ByteBuffer buffer; + /** + * The buffer of this entry. + */ + private final ByteBuffer buffer; - /** - * The identifier of this entry. - */ - private final int identifier; + /** + * The identifier of this entry. + */ + private final int identifier; - /** - * Creates a new archive entry. - * - * @param identifier The identifier. - * @param buffer The buffer. - */ - public ArchiveEntry(int identifier, ByteBuffer buffer) { - this.identifier = identifier; - this.buffer = buffer.asReadOnlyBuffer(); - } + /** + * Creates a new archive entry. + * + * @param identifier The identifier. + * @param buffer The buffer. + */ + public ArchiveEntry(int identifier, ByteBuffer buffer) { + this.identifier = identifier; + this.buffer = buffer.asReadOnlyBuffer(); + } - /** - * Gets the buffer of this entry. - * - * @return This buffer of this entry. - */ - public ByteBuffer getBuffer() { - return buffer.duplicate(); - } + /** + * Gets the buffer of this entry. + * + * @return This buffer of this entry. + */ + public ByteBuffer getBuffer() { + return buffer.duplicate(); + } - /** - * Gets the identifier of this entry. - * - * @return The identifier of this entry. - */ - public int getIdentifier() { - return identifier; - } + /** + * Gets the identifier of this entry. + * + * @return The identifier of this entry. + */ + public int getIdentifier() { + return identifier; + } } \ No newline at end of file diff --git a/src/org/apollo/fs/decoder/ItemDefinitionDecoder.java b/src/org/apollo/fs/decoder/ItemDefinitionDecoder.java index ce28391a..da6475e9 100644 --- a/src/org/apollo/fs/decoder/ItemDefinitionDecoder.java +++ b/src/org/apollo/fs/decoder/ItemDefinitionDecoder.java @@ -15,144 +15,144 @@ import org.apollo.util.BufferUtil; */ public final class ItemDefinitionDecoder { - /** - * The {@link IndexedFileSystem}. - */ - private final IndexedFileSystem fs; + /** + * The {@link IndexedFileSystem}. + */ + private final IndexedFileSystem fs; - /** - * Creates the item definition decoder. - * - * @param fs The indexed file system. - */ - public ItemDefinitionDecoder(IndexedFileSystem fs) { - this.fs = fs; + /** + * Creates the item definition decoder. + * + * @param fs The indexed file system. + */ + public ItemDefinitionDecoder(IndexedFileSystem fs) { + this.fs = fs; + } + + /** + * Decodes the item definitions. + * + * @return The item definitions. + * @throws IOException If an I/O error occurs. + */ + public ItemDefinition[] decode() throws IOException { + Archive config = Archive.decode(fs.getFile(0, 2)); + ByteBuffer data = config.getEntry("obj.dat").getBuffer(); + ByteBuffer idx = config.getEntry("obj.idx").getBuffer(); + + int count = idx.getShort(), index = 2; + int[] indices = new int[count]; + for (int i = 0; i < count; i++) { + indices[i] = index; + index += idx.getShort(); } - /** - * Decodes the item definitions. - * - * @return The item definitions. - * @throws IOException If an I/O error occurs. - */ - public ItemDefinition[] decode() throws IOException { - Archive config = Archive.decode(fs.getFile(0, 2)); - ByteBuffer data = config.getEntry("obj.dat").getBuffer(); - ByteBuffer idx = config.getEntry("obj.idx").getBuffer(); - - int count = idx.getShort(), index = 2; - int[] indices = new int[count]; - for (int i = 0; i < count; i++) { - indices[i] = index; - index += idx.getShort(); - } - - ItemDefinition[] defs = new ItemDefinition[count]; - for (int i = 0; i < count; i++) { - data.position(indices[i]); - defs[i] = decode(i, data); - } - - return defs; + ItemDefinition[] defs = new ItemDefinition[count]; + for (int i = 0; i < count; i++) { + data.position(indices[i]); + defs[i] = decode(i, data); } - /** - * Decodes a single definition. - * - * @param id The item's id. - * @param buffer The buffer. - * @return The {@link ItemDefinition}. - */ - private ItemDefinition decode(int id, ByteBuffer buffer) { - ItemDefinition definition = new ItemDefinition(id); - while (true) { - int opcode = buffer.get() & 0xFF; + return defs; + } - if (opcode == 0) { - return definition; - } else if (opcode == 1) { - buffer.getShort(); - } else if (opcode == 2) { - definition.setName(BufferUtil.readString(buffer)); - } else if (opcode == 3) { - definition.setDescription(BufferUtil.readString(buffer)); - } else if (opcode == 4) { - buffer.getShort(); - } else if (opcode == 5) { - buffer.getShort(); - } else if (opcode == 6) { - buffer.getShort(); - } else if (opcode == 7) { - buffer.getShort(); - } else if (opcode == 8) { - buffer.getShort(); - } else if (opcode == 10) { - buffer.getShort(); - } else if (opcode == 11) { - definition.setStackable(true); - } else if (opcode == 12) { - definition.setValue(buffer.getInt()); - } else if (opcode == 16) { - definition.setMembersOnly(true); - } else if (opcode == 23) { - buffer.getShort(); - buffer.get(); - } else if (opcode == 24) { - buffer.getShort(); - } else if (opcode == 25) { - buffer.getShort(); - buffer.get(); - } else if (opcode == 26) { - buffer.getShort(); - } else if (opcode >= 30 && opcode < 35) { - String str = BufferUtil.readString(buffer); - if (str.equalsIgnoreCase("hidden")) { - str = null; - } - definition.setGroundAction(opcode - 30, str); - } else if (opcode >= 35 && opcode < 40) { - definition.setInventoryAction(opcode - 35, BufferUtil.readString(buffer)); - } else if (opcode == 40) { - int colourCount = buffer.get() & 0xFF; - for (int i = 0; i < colourCount; i++) { - buffer.getShort(); - buffer.getShort(); - } - } else if (opcode == 78) { - buffer.getShort(); - } else if (opcode == 79) { - buffer.getShort(); - } else if (opcode == 90) { - buffer.getShort(); - } else if (opcode == 91) { - buffer.getShort(); - } else if (opcode == 92) { - buffer.getShort(); - } else if (opcode == 93) { - buffer.getShort(); - } else if (opcode == 95) { - buffer.getShort(); - } else if (opcode == 97) { - definition.setNoteInfoId(buffer.getShort() & 0xFFFF); - } else if (opcode == 98) { - definition.setNoteGraphicId(buffer.getShort() & 0xFFFF); - } else if (opcode >= 100 && opcode < 110) { - buffer.getShort(); - buffer.getShort(); - } else if (opcode == 110) { - buffer.getShort(); - } else if (opcode == 111) { - buffer.getShort(); - } else if (opcode == 112) { - buffer.getShort(); - } else if (opcode == 113) { - buffer.get(); - } else if (opcode == 114) { - buffer.getShort(); - } else if (opcode == 115) { - definition.setTeam(buffer.get() & 0xFF); - } + /** + * Decodes a single definition. + * + * @param id The item's id. + * @param buffer The buffer. + * @return The {@link ItemDefinition}. + */ + private ItemDefinition decode(int id, ByteBuffer buffer) { + ItemDefinition definition = new ItemDefinition(id); + while (true) { + int opcode = buffer.get() & 0xFF; + + if (opcode == 0) { + return definition; + } else if (opcode == 1) { + buffer.getShort(); + } else if (opcode == 2) { + definition.setName(BufferUtil.readString(buffer)); + } else if (opcode == 3) { + definition.setDescription(BufferUtil.readString(buffer)); + } else if (opcode == 4) { + buffer.getShort(); + } else if (opcode == 5) { + buffer.getShort(); + } else if (opcode == 6) { + buffer.getShort(); + } else if (opcode == 7) { + buffer.getShort(); + } else if (opcode == 8) { + buffer.getShort(); + } else if (opcode == 10) { + buffer.getShort(); + } else if (opcode == 11) { + definition.setStackable(true); + } else if (opcode == 12) { + definition.setValue(buffer.getInt()); + } else if (opcode == 16) { + definition.setMembersOnly(true); + } else if (opcode == 23) { + buffer.getShort(); + buffer.get(); + } else if (opcode == 24) { + buffer.getShort(); + } else if (opcode == 25) { + buffer.getShort(); + buffer.get(); + } else if (opcode == 26) { + buffer.getShort(); + } else if (opcode >= 30 && opcode < 35) { + String str = BufferUtil.readString(buffer); + if (str.equalsIgnoreCase("hidden")) { + str = null; } + definition.setGroundAction(opcode - 30, str); + } else if (opcode >= 35 && opcode < 40) { + definition.setInventoryAction(opcode - 35, BufferUtil.readString(buffer)); + } else if (opcode == 40) { + int colourCount = buffer.get() & 0xFF; + for (int i = 0; i < colourCount; i++) { + buffer.getShort(); + buffer.getShort(); + } + } else if (opcode == 78) { + buffer.getShort(); + } else if (opcode == 79) { + buffer.getShort(); + } else if (opcode == 90) { + buffer.getShort(); + } else if (opcode == 91) { + buffer.getShort(); + } else if (opcode == 92) { + buffer.getShort(); + } else if (opcode == 93) { + buffer.getShort(); + } else if (opcode == 95) { + buffer.getShort(); + } else if (opcode == 97) { + definition.setNoteInfoId(buffer.getShort() & 0xFFFF); + } else if (opcode == 98) { + definition.setNoteGraphicId(buffer.getShort() & 0xFFFF); + } else if (opcode >= 100 && opcode < 110) { + buffer.getShort(); + buffer.getShort(); + } else if (opcode == 110) { + buffer.getShort(); + } else if (opcode == 111) { + buffer.getShort(); + } else if (opcode == 112) { + buffer.getShort(); + } else if (opcode == 113) { + buffer.get(); + } else if (opcode == 114) { + buffer.getShort(); + } else if (opcode == 115) { + definition.setTeam(buffer.get() & 0xFF); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/fs/decoder/NpcDefinitionDecoder.java b/src/org/apollo/fs/decoder/NpcDefinitionDecoder.java index 21fdf00b..17265671 100644 --- a/src/org/apollo/fs/decoder/NpcDefinitionDecoder.java +++ b/src/org/apollo/fs/decoder/NpcDefinitionDecoder.java @@ -15,144 +15,144 @@ import org.apollo.util.BufferUtil; */ public final class NpcDefinitionDecoder { - /** - * The {@link IndexedFileSystem}. - */ - private final IndexedFileSystem fs; + /** + * The {@link IndexedFileSystem}. + */ + private final IndexedFileSystem fs; - /** - * Creates the npc definition decoder. - * - * @param fs The indexed file system. - */ - public NpcDefinitionDecoder(IndexedFileSystem fs) { - this.fs = fs; + /** + * Creates the npc definition decoder. + * + * @param fs The indexed file system. + */ + public NpcDefinitionDecoder(IndexedFileSystem fs) { + this.fs = fs; + } + + /** + * Decodes the npc definitions. + * + * @return An array of all parsed npc definitions. + * @throws IOException If an I/O error occurs. + */ + public NpcDefinition[] decode() throws IOException { + Archive config = Archive.decode(fs.getFile(0, 2)); + ByteBuffer data = config.getEntry("npc.dat").getBuffer(); + ByteBuffer idx = config.getEntry("npc.idx").getBuffer(); + + int count = idx.getShort(), index = 2; + int[] indices = new int[count]; + for (int i = 0; i < count; i++) { + indices[i] = index; + index += idx.getShort(); } - /** - * Decodes the npc definitions. - * - * @return An array of all parsed npc definitions. - * @throws IOException If an I/O error occurs. - */ - public NpcDefinition[] decode() throws IOException { - Archive config = Archive.decode(fs.getFile(0, 2)); - ByteBuffer data = config.getEntry("npc.dat").getBuffer(); - ByteBuffer idx = config.getEntry("npc.idx").getBuffer(); - - int count = idx.getShort(), index = 2; - int[] indices = new int[count]; - for (int i = 0; i < count; i++) { - indices[i] = index; - index += idx.getShort(); - } - - NpcDefinition[] defs = new NpcDefinition[count]; - for (int i = 0; i < count; i++) { - data.position(indices[i]); - defs[i] = decode(i, data); - } - - return defs; + NpcDefinition[] defs = new NpcDefinition[count]; + for (int i = 0; i < count; i++) { + data.position(indices[i]); + defs[i] = decode(i, data); } - /** - * Decodes a single definition. - * - * @param id The npc's id. - * @param buffer The buffer. - * @return The {@link NpcDefinition}. - */ - private NpcDefinition decode(int id, ByteBuffer buffer) { - NpcDefinition definition = new NpcDefinition(id); - while (true) { - int opcode = buffer.get() & 0xFF; + return defs; + } - if (opcode == 0) { - return definition; - } else if (opcode == 1) { - int length = buffer.get() & 0xFF; - int[] models = new int[length]; - for (int i = 0; i < length; i++) { - models[i] = buffer.getShort(); - } - } else if (opcode == 2) { - definition.setName(BufferUtil.readString(buffer)); - } else if (opcode == 3) { - definition.setDescription(BufferUtil.readString(buffer)); - } else if (opcode == 12) { - definition.setSize(buffer.get()); - } else if (opcode == 13) { - definition.setStandAnimation(buffer.getShort()); - } else if (opcode == 14) { - definition.setWalkAnimation(buffer.getShort()); - } else if (opcode == 17) { - definition - .setWalkAnimations(buffer.getShort(), buffer.getShort(), buffer.getShort(), buffer.getShort()); - } else if (opcode >= 30 && opcode < 40) { - String str = BufferUtil.readString(buffer); - if (str.equals("hidden")) { - str = null; - } - definition.setInteraction(opcode - 30, str); - } else if (opcode == 40) { - int length = buffer.get() & 0xFF; - int[] originalColours = new int[length]; - int[] replacementColours = new int[length]; - for (int i = 0; i < length; i++) { - originalColours[i] = buffer.getShort(); - replacementColours[i] = buffer.getShort(); - } - } else if (opcode == 60) { - int length = buffer.get() & 0xFF; - int[] additionalModels = new int[length]; - for (int i = 0; i < length; i++) { - additionalModels[i] = buffer.getShort(); - } - } else if (opcode == 90) { - buffer.getShort(); // Dummy - } else if (opcode == 91) { - buffer.getShort(); // Dummy - } else if (opcode == 92) { - buffer.getShort(); // Dummy - } else if (opcode == 95) { - definition.setCombatLevel(buffer.getShort()); - } else if (opcode == 97) { - buffer.getShort(); - } else if (opcode == 98) { - buffer.getShort(); - } else if (opcode == 100) { - buffer.get(); - } else if (opcode == 101) { - buffer.get(); - } else if (opcode == 102) { - buffer.getShort(); - } else if (opcode == 103) { - buffer.getShort(); - } else if (opcode == 106) { - int morphVariableBitsIndex = buffer.getShort(); - if (morphVariableBitsIndex == 65535) { - morphVariableBitsIndex = -1; - } - int morphismCount = buffer.getShort(); - if (morphismCount == 65535) { - morphismCount = -1; - } + /** + * Decodes a single definition. + * + * @param id The npc's id. + * @param buffer The buffer. + * @return The {@link NpcDefinition}. + */ + private NpcDefinition decode(int id, ByteBuffer buffer) { + NpcDefinition definition = new NpcDefinition(id); + while (true) { + int opcode = buffer.get() & 0xFF; - int count = buffer.get() & 0xFF; - int[] morphisms = new int[count + 1]; - for (int i = 0; i <= count; i++) { - int morphism = buffer.getShort(); - if (morphism == 65535) { - morphism = -1; - } - morphisms[i] = morphism; - } - } else if (opcode == 107) { - @SuppressWarnings("unused") - boolean clickable = false; - } + if (opcode == 0) { + return definition; + } else if (opcode == 1) { + int length = buffer.get() & 0xFF; + int[] models = new int[length]; + for (int i = 0; i < length; i++) { + models[i] = buffer.getShort(); } + } else if (opcode == 2) { + definition.setName(BufferUtil.readString(buffer)); + } else if (opcode == 3) { + definition.setDescription(BufferUtil.readString(buffer)); + } else if (opcode == 12) { + definition.setSize(buffer.get()); + } else if (opcode == 13) { + definition.setStandAnimation(buffer.getShort()); + } else if (opcode == 14) { + definition.setWalkAnimation(buffer.getShort()); + } else if (opcode == 17) { + definition + .setWalkAnimations(buffer.getShort(), buffer.getShort(), buffer.getShort(), buffer.getShort()); + } else if (opcode >= 30 && opcode < 40) { + String str = BufferUtil.readString(buffer); + if (str.equals("hidden")) { + str = null; + } + definition.setInteraction(opcode - 30, str); + } else if (opcode == 40) { + int length = buffer.get() & 0xFF; + int[] originalColours = new int[length]; + int[] replacementColours = new int[length]; + for (int i = 0; i < length; i++) { + originalColours[i] = buffer.getShort(); + replacementColours[i] = buffer.getShort(); + } + } else if (opcode == 60) { + int length = buffer.get() & 0xFF; + int[] additionalModels = new int[length]; + for (int i = 0; i < length; i++) { + additionalModels[i] = buffer.getShort(); + } + } else if (opcode == 90) { + buffer.getShort(); // Dummy + } else if (opcode == 91) { + buffer.getShort(); // Dummy + } else if (opcode == 92) { + buffer.getShort(); // Dummy + } else if (opcode == 95) { + definition.setCombatLevel(buffer.getShort()); + } else if (opcode == 97) { + buffer.getShort(); + } else if (opcode == 98) { + buffer.getShort(); + } else if (opcode == 100) { + buffer.get(); + } else if (opcode == 101) { + buffer.get(); + } else if (opcode == 102) { + buffer.getShort(); + } else if (opcode == 103) { + buffer.getShort(); + } else if (opcode == 106) { + int morphVariableBitsIndex = buffer.getShort(); + if (morphVariableBitsIndex == 65535) { + morphVariableBitsIndex = -1; + } + int morphismCount = buffer.getShort(); + if (morphismCount == 65535) { + morphismCount = -1; + } + + int count = buffer.get() & 0xFF; + int[] morphisms = new int[count + 1]; + for (int i = 0; i <= count; i++) { + int morphism = buffer.getShort(); + if (morphism == 65535) { + morphism = -1; + } + morphisms[i] = morphism; + } + } else if (opcode == 107) { + @SuppressWarnings("unused") + boolean clickable = false; + } } + } } \ No newline at end of file diff --git a/src/org/apollo/fs/decoder/ObjectDefinitionDecoder.java b/src/org/apollo/fs/decoder/ObjectDefinitionDecoder.java index 890cb49d..ddf815c0 100644 --- a/src/org/apollo/fs/decoder/ObjectDefinitionDecoder.java +++ b/src/org/apollo/fs/decoder/ObjectDefinitionDecoder.java @@ -15,131 +15,131 @@ import org.apollo.util.BufferUtil; */ public final class ObjectDefinitionDecoder { - /** - * The {@link IndexedFileSystem}. - */ - private final IndexedFileSystem fs; + /** + * The {@link IndexedFileSystem}. + */ + private final IndexedFileSystem fs; - /** - * Creates the decoder. - * - * @param fs The {@link IndexedFileSystem}. - */ - public ObjectDefinitionDecoder(IndexedFileSystem fs) { - this.fs = fs; + /** + * Creates the decoder. + * + * @param fs The {@link IndexedFileSystem}. + */ + public ObjectDefinitionDecoder(IndexedFileSystem fs) { + this.fs = fs; + } + + /** + * Decodes all of the data into {@link ObjectDefinition}s. + * + * @return The definitions. + * @throws IOException If an error occurs when decoding the archive or finding an entry. + */ + public ObjectDefinition[] decode() throws IOException { + Archive config = Archive.decode(fs.getFile(0, 2)); + ByteBuffer data = config.getEntry("loc.dat").getBuffer(); + ByteBuffer idx = config.getEntry("loc.idx").getBuffer(); + + int count = idx.getShort(), index = 2; + int[] indices = new int[count]; + for (int i = 0; i < count; i++) { + indices[i] = index; + index += idx.getShort(); } - /** - * Decodes all of the data into {@link ObjectDefinition}s. - * - * @return The definitions. - * @throws IOException If an error occurs when decoding the archive or finding an entry. - */ - public ObjectDefinition[] decode() throws IOException { - Archive config = Archive.decode(fs.getFile(0, 2)); - ByteBuffer data = config.getEntry("loc.dat").getBuffer(); - ByteBuffer idx = config.getEntry("loc.idx").getBuffer(); - - int count = idx.getShort(), index = 2; - int[] indices = new int[count]; - for (int i = 0; i < count; i++) { - indices[i] = index; - index += idx.getShort(); - } - - ObjectDefinition[] defs = new ObjectDefinition[count]; - for (int i = 0; i < count; i++) { - data.position(indices[i]); - defs[i] = decode(i, data); - } - return defs; + ObjectDefinition[] defs = new ObjectDefinition[count]; + for (int i = 0; i < count; i++) { + data.position(indices[i]); + defs[i] = decode(i, data); } + return defs; + } - /** - * Decodes data from the cache into an {@link ObjectDefinition}. - * - * @param id The id of the object. - * @param data The {@link ByteBuffer} containing the data. - * @return The object definition. - */ - public ObjectDefinition decode(int id, ByteBuffer data) { - ObjectDefinition definition = new ObjectDefinition(id); - while (true) { - int opcode = data.get() & 0xFF; + /** + * Decodes data from the cache into an {@link ObjectDefinition}. + * + * @param id The id of the object. + * @param data The {@link ByteBuffer} containing the data. + * @return The object definition. + */ + public ObjectDefinition decode(int id, ByteBuffer data) { + ObjectDefinition definition = new ObjectDefinition(id); + while (true) { + int opcode = data.get() & 0xFF; - if (opcode == 0) { - return definition; - } else if (opcode == 1) { - int amount = data.get() & 0xFF; - for (int i = 0; i < amount; i++) { - data.getShort(); - data.get(); - } - } else if (opcode == 2) { - definition.setName(BufferUtil.readString(data)); - } else if (opcode == 3) { - definition.setDescription(BufferUtil.readString(data)); - } else if (opcode == 5) { - int amount = data.get() & 0xFF; - for (int i = 0; i < amount; i++) { - data.getShort(); - } - } else if (opcode == 14) { - definition.setWidth(data.get() & 0xFF); - } else if (opcode == 15) { - definition.setHeight(data.get() & 0xFF); - } else if (opcode == 17) { - definition.setSolid(false); - } else if (opcode == 18) { - definition.setImpenetrable(false); - } else if (opcode == 19) { - definition.setInteractive((data.get() & 0xFF) == 1); - } else if (opcode == 24) { - data.getShort(); - } else if (opcode == 28) { - data.get(); - } else if (opcode == 29) { - data.get(); - } else if (opcode >= 30 && opcode < 39) { - String[] actions = definition.getMenuActions(); - if (actions == null) { - actions = new String[10]; - } - String action = BufferUtil.readString(data); - actions[opcode - 30] = action; - definition.setMenuActions(actions); - } else if (opcode == 39) { - data.get(); - } else if (opcode == 40) { - int amount = data.get() & 0xFF; - for (int i = 0; i < amount; i++) { - data.getShort(); - data.getShort(); - } - } else if (opcode == 60) { - data.getShort(); - } else if (opcode == 65) { - data.getShort(); - } else if (opcode == 66) { - data.getShort(); - } else if (opcode == 67) { - data.getShort(); - } else if (opcode == 68) { - data.getShort(); - } else if (opcode == 69) { - data.get(); - } else if (opcode == 70) { - data.getShort(); - } else if (opcode == 71) { - data.getShort(); - } else if (opcode == 72) { - data.getShort(); - } else if (opcode == 75) { - data.get(); - } else { - continue; - } + if (opcode == 0) { + return definition; + } else if (opcode == 1) { + int amount = data.get() & 0xFF; + for (int i = 0; i < amount; i++) { + data.getShort(); + data.get(); } + } else if (opcode == 2) { + definition.setName(BufferUtil.readString(data)); + } else if (opcode == 3) { + definition.setDescription(BufferUtil.readString(data)); + } else if (opcode == 5) { + int amount = data.get() & 0xFF; + for (int i = 0; i < amount; i++) { + data.getShort(); + } + } else if (opcode == 14) { + definition.setWidth(data.get() & 0xFF); + } else if (opcode == 15) { + definition.setHeight(data.get() & 0xFF); + } else if (opcode == 17) { + definition.setSolid(false); + } else if (opcode == 18) { + definition.setImpenetrable(false); + } else if (opcode == 19) { + definition.setInteractive((data.get() & 0xFF) == 1); + } else if (opcode == 24) { + data.getShort(); + } else if (opcode == 28) { + data.get(); + } else if (opcode == 29) { + data.get(); + } else if (opcode >= 30 && opcode < 39) { + String[] actions = definition.getMenuActions(); + if (actions == null) { + actions = new String[10]; + } + String action = BufferUtil.readString(data); + actions[opcode - 30] = action; + definition.setMenuActions(actions); + } else if (opcode == 39) { + data.get(); + } else if (opcode == 40) { + int amount = data.get() & 0xFF; + for (int i = 0; i < amount; i++) { + data.getShort(); + data.getShort(); + } + } else if (opcode == 60) { + data.getShort(); + } else if (opcode == 65) { + data.getShort(); + } else if (opcode == 66) { + data.getShort(); + } else if (opcode == 67) { + data.getShort(); + } else if (opcode == 68) { + data.getShort(); + } else if (opcode == 69) { + data.get(); + } else if (opcode == 70) { + data.getShort(); + } else if (opcode == 71) { + data.getShort(); + } else if (opcode == 72) { + data.getShort(); + } else if (opcode == 75) { + data.get(); + } else { + continue; + } } + } } \ No newline at end of file diff --git a/src/org/apollo/fs/decoder/StaticObjectDecoder.java b/src/org/apollo/fs/decoder/StaticObjectDecoder.java index 3ea829f8..863726e1 100644 --- a/src/org/apollo/fs/decoder/StaticObjectDecoder.java +++ b/src/org/apollo/fs/decoder/StaticObjectDecoder.java @@ -20,100 +20,100 @@ import org.apollo.util.CompressionUtil; */ public final class StaticObjectDecoder { - /** - * The {@link IndexedFileSystem}. - */ - private final IndexedFileSystem fs; + /** + * The {@link IndexedFileSystem}. + */ + private final IndexedFileSystem fs; - /** - * Creates the decoder. - * - * @param fs The indexed file system. - */ - public StaticObjectDecoder(IndexedFileSystem fs) { - this.fs = fs; + /** + * Creates the decoder. + * + * @param fs The indexed file system. + */ + public StaticObjectDecoder(IndexedFileSystem fs) { + this.fs = fs; + } + + /** + * Decodes all static objects and places them in the returned array. + * + * @return The decoded objects. + * @throws IOException If an I/O error occurs. + */ + public GameObject[] decode() throws IOException { + Archive versionList = Archive.decode(fs.getFile(0, 5)); + ByteBuffer buffer = versionList.getEntry("map_index").getBuffer(); + + int indices = buffer.remaining() / 7; + int[] areas = new int[indices]; + int[] landscapes = new int[indices]; + + for (int i = 0; i < indices; i++) { + areas[i] = buffer.getShort() & 0xFFFF; + + @SuppressWarnings("unused") + int mapFile = buffer.getShort() & 0xFFFF; + + landscapes[i] = buffer.getShort() & 0xFFFF; + + @SuppressWarnings("unused") + boolean members = (buffer.get() & 0xFF) == 1; } - /** - * Decodes all static objects and places them in the returned array. - * - * @return The decoded objects. - * @throws IOException If an I/O error occurs. - */ - public GameObject[] decode() throws IOException { - Archive versionList = Archive.decode(fs.getFile(0, 5)); - ByteBuffer buffer = versionList.getEntry("map_index").getBuffer(); + List objects = new ArrayList<>(); - int indices = buffer.remaining() / 7; - int[] areas = new int[indices]; - int[] landscapes = new int[indices]; + for (int i = 0; i < indices; i++) { + ByteBuffer compressed = fs.getFile(4, landscapes[i]); + ByteBuffer uncompressed = ByteBuffer.wrap(CompressionUtil.ungzip(compressed)); - for (int i = 0; i < indices; i++) { - areas[i] = buffer.getShort() & 0xFFFF; - - @SuppressWarnings("unused") - int mapFile = buffer.getShort() & 0xFFFF; - - landscapes[i] = buffer.getShort() & 0xFFFF; - - @SuppressWarnings("unused") - boolean members = (buffer.get() & 0xFF) == 1; - } - - List objects = new ArrayList(); - - for (int i = 0; i < indices; i++) { - ByteBuffer compressed = fs.getFile(4, landscapes[i]); - ByteBuffer uncompressed = ByteBuffer.wrap(CompressionUtil.ungzip(compressed)); - - Collection areaObjects = parseArea(areas[i], uncompressed); - objects.addAll(areaObjects); - } - - return objects.toArray(new GameObject[objects.size()]); + Collection areaObjects = parseArea(areas[i], uncompressed); + objects.addAll(areaObjects); } - /** - * Parses a single area from the specified buffer. - * - * @param area The identifier of that area. - * @param buffer The buffer which holds the area's data. - * @return A collection of all parsed objects. - */ - private Collection parseArea(int area, ByteBuffer buffer) { - List objects = new ArrayList(); + return objects.toArray(new GameObject[objects.size()]); + } - int x = (area >> 8 & 0xFF) * 64; - int y = (area & 0xFF) * 64; + /** + * Parses a single area from the specified buffer. + * + * @param area The identifier of that area. + * @param buffer The buffer which holds the area's data. + * @return A collection of all parsed objects. + */ + private Collection parseArea(int area, ByteBuffer buffer) { + List objects = new ArrayList<>(); - int id = -1; - int idOffset; + int x = (area >> 8 & 0xFF) * 64; + int y = (area & 0xFF) * 64; - while ((idOffset = BufferUtil.readSmart(buffer)) != 0) { - id += idOffset; + int id = -1; + int idOffset; - int position = 0; - int positionOffset; + while ((idOffset = BufferUtil.readSmart(buffer)) != 0) { + id += idOffset; - while ((positionOffset = BufferUtil.readSmart(buffer)) != 0) { - position += positionOffset - 1; + int position = 0; + int positionOffset; - int localX = position >> 6 & 0x3F; - int localY = position & 0x3F; - int height = position >> 12; + while ((positionOffset = BufferUtil.readSmart(buffer)) != 0) { + position += positionOffset - 1; - int info = buffer.get() & 0xFF; - int type = info >> 2; - int rotation = info & 3; + int localX = position >> 6 & 0x3F; + int localY = position & 0x3F; + int height = position >> 12; - Position pos = new Position(x + localX, y + localY, height); + int info = buffer.get() & 0xFF; + int type = info >> 2; + int rotation = info & 3; - GameObject object = new GameObject(id, pos, type, rotation); - objects.add(object); - } - } + Position pos = new Position(x + localX, y + localY, height); - return objects; + GameObject object = new GameObject(id, pos, type, rotation); + objects.add(object); + } } + return objects; + } + } \ No newline at end of file diff --git a/src/org/apollo/game/GameConstants.java b/src/org/apollo/game/GameConstants.java index 38d186c7..d19a1c8e 100644 --- a/src/org/apollo/game/GameConstants.java +++ b/src/org/apollo/game/GameConstants.java @@ -7,21 +7,21 @@ package org.apollo.game; */ public final class GameConstants { - /** - * The maximum events per pulse per session. - */ - public static final int EVENTS_PER_PULSE = 10; + /** + * The maximum events per pulse per session. + */ + public static final int EVENTS_PER_PULSE = 10; - /** - * The delay between consecutive pulses, in milliseconds. - */ - public static final int PULSE_DELAY = 600; + /** + * The delay between consecutive pulses, in milliseconds. + */ + public static final int PULSE_DELAY = 600; - /** - * Default private constructor to prevent instantiation by other classes. - */ - private GameConstants() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private GameConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/GamePulseHandler.java b/src/org/apollo/game/GamePulseHandler.java index 1ec13290..fe484360 100644 --- a/src/org/apollo/game/GamePulseHandler.java +++ b/src/org/apollo/game/GamePulseHandler.java @@ -10,32 +10,32 @@ import java.util.logging.Logger; */ public final class GamePulseHandler implements Runnable { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(GamePulseHandler.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(GamePulseHandler.class.getName()); - /** - * The {@link GameService}. - */ - private final GameService service; + /** + * The {@link GameService}. + */ + private final GameService service; - /** - * Creates the game pulse handler object. - * - * @param service The {@link GameService}. - */ - GamePulseHandler(GameService service) { - this.service = service; - } - - @Override - public void run() { - try { - service.pulse(); - } catch (Throwable t) { - logger.log(Level.SEVERE, "Exception during pulse.", t); - } + /** + * Creates the game pulse handler object. + * + * @param service The {@link GameService}. + */ + GamePulseHandler(GameService service) { + this.service = service; + } + + @Override + public void run() { + try { + service.pulse(); + } catch (Throwable t) { + logger.log(Level.SEVERE, "Exception during pulse.", t); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/GameService.java b/src/org/apollo/game/GameService.java index dd0e7213..b33b854f 100644 --- a/src/org/apollo/game/GameService.java +++ b/src/org/apollo/game/GameService.java @@ -31,157 +31,157 @@ import org.xml.sax.SAXException; */ public final class GameService extends Service { - /** - * The number of times to unregister players per cycle. This is to ensure the saving threads don't get swamped with - * requests and slow everything down. - */ - private static final int UNREGISTERS_PER_CYCLE = 50; + /** + * The number of times to unregister players per cycle. This is to ensure the saving threads don't get swamped with + * requests and slow everything down. + */ + private static final int UNREGISTERS_PER_CYCLE = 50; - /** - * The {@link EventHandlerChainGroup}. - */ - private EventHandlerChainGroup chainGroup; + /** + * The {@link EventHandlerChainGroup}. + */ + private EventHandlerChainGroup chainGroup; - /** - * A queue of players to remove. - */ - private final Queue oldPlayers = new ConcurrentLinkedQueue(); + /** + * A queue of players to remove. + */ + private final Queue oldPlayers = new ConcurrentLinkedQueue<>(); - /** - * The scheduled executor service. - */ - private final ScheduledExecutorService scheduledExecutor = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("GameService")); + /** + * The scheduled executor service. + */ + private final ScheduledExecutorService scheduledExecutor = Executors + .newSingleThreadScheduledExecutor(new NamedThreadFactory("GameService")); - /** - * The {@link ClientSynchronizer}. - */ - private ClientSynchronizer synchronizer; + /** + * The {@link ClientSynchronizer}. + */ + private ClientSynchronizer synchronizer; - /** - * Creates the game service. - * - * @throws Exception If an error occurs during initialization. - */ - public GameService() throws Exception { - init(); + /** + * Creates the game service. + * + * @throws Exception If an error occurs during initialization. + */ + public GameService() throws Exception { + init(); + } + + /** + * Finalizes the unregistration of a player. + * + * @param player The player. + */ + public void finalizePlayerUnregistration(Player player) { + synchronized (this) { + World.getWorld().unregister(player); + } + } + + /** + * Gets the event handler chains. + * + * @return The event handler chains. + */ + public EventHandlerChainGroup getEventHandlerChains() { + return chainGroup; + } + + /** + * Initializes the game service. + * + * @throws IOException If there is an error with the file (e.g. does not exist, cannot be read, does not contain + * valid nodes). + * @throws SAXException If there is an error parsing the file. + * @throws ClassNotFoundException If an event handler could not be found. + * @throws InstantiationException If an event handler could not be instantiated. + * @throws IllegalAccessException If an event handler could not be accessed. + */ + private void init() throws IOException, SAXException, ClassNotFoundException, InstantiationException, + IllegalAccessException { + try (InputStream is = new FileInputStream("data/events.xml")) { + EventHandlerChainParser chainGroupParser = new EventHandlerChainParser(is); + chainGroup = chainGroupParser.parse(); } - /** - * Finalizes the unregistration of a player. - * - * @param player The player. - */ - public void finalizePlayerUnregistration(Player player) { - synchronized (this) { - World.getWorld().unregister(player); + try (InputStream is = new FileInputStream("data/synchronizer.xml")) { + XmlParser parser = new XmlParser(); + XmlNode rootNode = parser.parse(is); + + if (!rootNode.getName().equals("synchronizer")) { + throw new IOException("Invalid root node name."); + } + + XmlNode activeNode = rootNode.getChild("active"); + if (activeNode == null || !activeNode.hasValue()) { + throw new IOException("No active node/value."); + } + + Class clazz = Class.forName(activeNode.getValue()); + synchronizer = (ClientSynchronizer) clazz.newInstance(); + } + + try (InputStream is = new FileInputStream("data/rsa.xml")) { + RsaKeyParser parser = new RsaKeyParser(is); + parser.parse(); + } + } + + /** + * Called every pulse. + */ + public void pulse() { + synchronized (this) { + LoginService loginService = getContext().getService(LoginService.class); + World world = World.getWorld(); + + int unregistered = 0; + Player old; + while (unregistered < UNREGISTERS_PER_CYCLE && (old = oldPlayers.poll()) != null) { + loginService.submitSaveRequest(old.getSession(), old); + unregistered++; + } + + for (Player p : world.getPlayerRepository()) { + GameSession session = p.getSession(); + if (session != null) { + session.handlePendingEvents(chainGroup); } + } + + world.pulse(); + synchronizer.synchronize(); } + } - /** - * Gets the event handler chains. - * - * @return The event handler chains. - */ - public EventHandlerChainGroup getEventHandlerChains() { - return chainGroup; + /** + * Registers a player (may block!). + * + * @param player The player. + * @return A {@link RegistrationStatus}. + */ + public RegistrationStatus registerPlayer(Player player) { + synchronized (this) { + return World.getWorld().register(player); } + } - /** - * Initializes the game service. - * - * @throws IOException If there is an error with the file (e.g. does not exist, cannot be read, does not contain - * valid nodes). - * @throws SAXException If there is an error parsing the file. - * @throws ClassNotFoundException If an event handler could not be found. - * @throws InstantiationException If an event handler could not be instantiated. - * @throws IllegalAccessException If an event handler could not be accessed. - */ - private void init() throws IOException, SAXException, ClassNotFoundException, InstantiationException, - IllegalAccessException { - try (InputStream is = new FileInputStream("data/events.xml")) { - EventHandlerChainParser chainGroupParser = new EventHandlerChainParser(is); - chainGroup = chainGroupParser.parse(); - } + /** + * Starts the game service. + */ + @Override + public void start() { + scheduledExecutor.scheduleAtFixedRate(new GamePulseHandler(this), GameConstants.PULSE_DELAY, + GameConstants.PULSE_DELAY, TimeUnit.MILLISECONDS); + } - try (InputStream is = new FileInputStream("data/synchronizer.xml")) { - XmlParser parser = new XmlParser(); - XmlNode rootNode = parser.parse(is); - - if (!rootNode.getName().equals("synchronizer")) { - throw new IOException("Invalid root node name."); - } - - XmlNode activeNode = rootNode.getChild("active"); - if (activeNode == null || !activeNode.hasValue()) { - throw new IOException("No active node/value."); - } - - Class clazz = Class.forName(activeNode.getValue()); - synchronizer = (ClientSynchronizer) clazz.newInstance(); - } - - try (InputStream is = new FileInputStream("data/rsa.xml")) { - RsaKeyParser parser = new RsaKeyParser(is); - parser.parse(); - } - } - - /** - * Called every pulse. - */ - public void pulse() { - synchronized (this) { - LoginService loginService = getContext().getService(LoginService.class); - World world = World.getWorld(); - - int unregistered = 0; - Player old; - while (unregistered < UNREGISTERS_PER_CYCLE && (old = oldPlayers.poll()) != null) { - loginService.submitSaveRequest(old.getSession(), old); - unregistered++; - } - - for (Player p : world.getPlayerRepository()) { - GameSession session = p.getSession(); - if (session != null) { - session.handlePendingEvents(chainGroup); - } - } - - world.pulse(); - synchronizer.synchronize(); - } - } - - /** - * Registers a player (may block!). - * - * @param player The player. - * @return A {@link RegistrationStatus}. - */ - public RegistrationStatus registerPlayer(Player player) { - synchronized (this) { - return World.getWorld().register(player); - } - } - - /** - * Starts the game service. - */ - @Override - public void start() { - scheduledExecutor.scheduleAtFixedRate(new GamePulseHandler(this), GameConstants.PULSE_DELAY, - GameConstants.PULSE_DELAY, TimeUnit.MILLISECONDS); - } - - /** - * Unregisters a player. Returns immediately. The player is unregistered at the start of the next cycle. - * - * @param player The player. - */ - public void unregisterPlayer(Player player) { - oldPlayers.add(player); - } + /** + * Unregisters a player. Returns immediately. The player is unregistered at the start of the next cycle. + * + * @param player The player. + */ + public void unregisterPlayer(Player player) { + oldPlayers.add(player); + } } \ No newline at end of file diff --git a/src/org/apollo/game/action/Action.java b/src/org/apollo/game/action/Action.java index 2c34b19e..b5232f76 100644 --- a/src/org/apollo/game/action/Action.java +++ b/src/org/apollo/game/action/Action.java @@ -14,44 +14,44 @@ import org.apollo.game.scheduling.ScheduledTask; */ public abstract class Action extends ScheduledTask { - /** - * The mob performing the action. - */ - protected final T mob; + /** + * The mob performing the action. + */ + protected final T mob; - /** - * A flag indicating if this action is stopping. - */ - private boolean stopping = false; + /** + * A flag indicating if this action is stopping. + */ + private boolean stopping = false; - /** - * Creates a new action. - * - * @param delay The delay in pulses. - * @param immediate A flag indicating if the action should happen immediately. - * @param mob The mob performing the action. - */ - public Action(int delay, boolean immediate, T mob) { - super(delay, immediate); - this.mob = mob; - } - - /** - * Gets the mob which performed the action. - * - * @return The mob. - */ - public T getMob() { - return mob; - } - - @Override - public void stop() { - super.stop(); - if (!stopping) { - stopping = true; - mob.stopAction(); - } + /** + * Creates a new action. + * + * @param delay The delay in pulses. + * @param immediate A flag indicating if the action should happen immediately. + * @param mob The mob performing the action. + */ + public Action(int delay, boolean immediate, T mob) { + super(delay, immediate); + this.mob = mob; + } + + /** + * Gets the mob which performed the action. + * + * @return The mob. + */ + public T getMob() { + return mob; + } + + @Override + public void stop() { + super.stop(); + if (!stopping) { + stopping = true; + mob.stopAction(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/action/DistancedAction.java b/src/org/apollo/game/action/DistancedAction.java index 5beae597..0603b37e 100644 --- a/src/org/apollo/game/action/DistancedAction.java +++ b/src/org/apollo/game/action/DistancedAction.java @@ -11,66 +11,66 @@ import org.apollo.game.model.entity.Mob; */ public abstract class DistancedAction extends Action { - /** - * The delay once the threshold is reached. - */ - private final int delay; + /** + * The delay once the threshold is reached. + */ + private final int delay; - /** - * The minimum distance before the action fires. - */ - private final int distance; + /** + * The minimum distance before the action fires. + */ + private final int distance; - /** - * A flag indicating if this action fires immediately after the threshold is reached. - */ - private final boolean immediate; + /** + * A flag indicating if this action fires immediately after the threshold is reached. + */ + private final boolean immediate; - /** - * The position to distance check with. - */ - private final Position position; + /** + * The position to distance check with. + */ + private final Position position; - /** - * A flag indicating if the distance has been reached yet. - */ - private boolean reached = false; + /** + * A flag indicating if the distance has been reached yet. + */ + private boolean reached = false; - /** - * Creates a new DistancedAction. - * - * @param delay The delay between executions once the distance threshold is reached. - * @param immediate Whether or not this action fires immediately after the distance threshold is reached. - * @param mob The mob. - * @param position The position. - * @param distance The distance. - */ - public DistancedAction(int delay, boolean immediate, T mob, Position position, int distance) { - super(0, true, mob); - this.position = position; - this.distance = distance; - this.delay = delay; - this.immediate = immediate; + /** + * Creates a new DistancedAction. + * + * @param delay The delay between executions once the distance threshold is reached. + * @param immediate Whether or not this action fires immediately after the distance threshold is reached. + * @param mob The mob. + * @param position The position. + * @param distance The distance. + */ + public DistancedAction(int delay, boolean immediate, T mob, Position position, int distance) { + super(0, true, mob); + this.position = position; + this.distance = distance; + this.delay = delay; + this.immediate = immediate; + } + + @Override + public void execute() { + if (reached) { + // some actions (e.g. agility) will cause the player to move away again + // so we don't check once the player got close enough once + executeAction(); + } else if (mob.getPosition().getDistance(position) <= distance) { + reached = true; + setDelay(delay); + if (immediate) { + executeAction(); + } } + } - @Override - public void execute() { - if (reached) { - // some actions (e.g. agility) will cause the player to move away again - // so we don't check once the player got close enough once - executeAction(); - } else if (mob.getPosition().getDistance(position) <= distance) { - reached = true; - setDelay(delay); - if (immediate) { - executeAction(); - } - } - } - - /** - * Executes the actual action. Called when the distance requirement is met. - */ - public abstract void executeAction(); + /** + * Executes the actual action. Called when the distance requirement is met. + */ + public abstract void executeAction(); } \ No newline at end of file diff --git a/src/org/apollo/game/command/Command.java b/src/org/apollo/game/command/Command.java index b5bf90b4..2ad9dd44 100644 --- a/src/org/apollo/game/command/Command.java +++ b/src/org/apollo/game/command/Command.java @@ -7,43 +7,43 @@ package org.apollo.game.command; */ public final class Command { - /** - * The command's arguments. - */ - private final String[] arguments; + /** + * The command's arguments. + */ + private final String[] arguments; - /** - * The name of the command. - */ - private final String name; + /** + * The name of the command. + */ + private final String name; - /** - * Creates the command. - * - * @param name The name of the command. - * @param arguments The command's arguments. - */ - public Command(String name, String[] arguments) { - this.name = name; - this.arguments = arguments; - } + /** + * Creates the command. + * + * @param name The name of the command. + * @param arguments The command's arguments. + */ + public Command(String name, String[] arguments) { + this.name = name; + this.arguments = arguments; + } - /** - * Gets the command's arguments. - * - * @return The command's arguments. - */ - public String[] getArguments() { - return arguments; - } + /** + * Gets the command's arguments. + * + * @return The command's arguments. + */ + public String[] getArguments() { + return arguments; + } - /** - * Gets the name of the command. - * - * @return The name of the command. - */ - public String getName() { - return name; - } + /** + * Gets the name of the command. + * + * @return The name of the command. + */ + public String getName() { + return name; + } } \ No newline at end of file diff --git a/src/org/apollo/game/command/CommandDispatcher.java b/src/org/apollo/game/command/CommandDispatcher.java index be3015db..fb479fb8 100644 --- a/src/org/apollo/game/command/CommandDispatcher.java +++ b/src/org/apollo/game/command/CommandDispatcher.java @@ -12,39 +12,39 @@ import org.apollo.game.model.entity.Player; */ public final class CommandDispatcher { - /** - * A map of event listeners. - */ - private final Map listeners = new HashMap(); + /** + * A map of event listeners. + */ + private final Map listeners = new HashMap(); - /** - * Creates the command dispatcher and registers a listener for the credits command. - */ - public CommandDispatcher() { - listeners.put("credits", new CreditsCommandListener()); - } + /** + * Creates the command dispatcher and registers a listener for the credits command. + */ + public CommandDispatcher() { + listeners.put("credits", new CreditsCommandListener()); + } - /** - * Dispatches a command to the appropriate listener. - * - * @param player The player. - * @param command The command. - */ - public void dispatch(Player player, Command command) { - CommandListener listener = listeners.get(command.getName().toLowerCase()); - if (listener != null) { - listener.executePrivileged(player, command); - } + /** + * Dispatches a command to the appropriate listener. + * + * @param player The player. + * @param command The command. + */ + public void dispatch(Player player, Command command) { + CommandListener listener = listeners.get(command.getName().toLowerCase()); + if (listener != null) { + listener.executePrivileged(player, command); } + } - /** - * Registers a listener with the dispatcher. - * - * @param command The command's name. - * @param listener The listener. - */ - public void register(String command, CommandListener listener) { - listeners.put(command.toLowerCase(), listener); - } + /** + * Registers a listener with the dispatcher. + * + * @param command The command's name. + * @param listener The listener. + */ + public void register(String command, CommandListener listener) { + listeners.put(command.toLowerCase(), listener); + } } \ No newline at end of file diff --git a/src/org/apollo/game/command/CommandListener.java b/src/org/apollo/game/command/CommandListener.java index 48b2e029..8c8f5e4f 100644 --- a/src/org/apollo/game/command/CommandListener.java +++ b/src/org/apollo/game/command/CommandListener.java @@ -11,45 +11,45 @@ import org.apollo.game.model.settings.PrivilegeLevel; */ public abstract class CommandListener { - /** - * The minimum privilege level. - */ - private final PrivilegeLevel level; + /** + * The minimum privilege level. + */ + private final PrivilegeLevel level; - /** - * Creates a new command listener with a {@link PrivilegeLevel#STANDARD} requirement. - */ - public CommandListener() { - this(PrivilegeLevel.STANDARD); - } - - /** - * Creates a new command listener. - * - * @param level The required {@link PrivilegeLevel}. - */ - public CommandListener(PrivilegeLevel level) { - this.level = level; - } - - /** - * Executes the action for this command. - * - * @param player The player. - * @param command The command. - */ - public abstract void execute(Player player, Command command); - - /** - * Executes a privileged command. - * - * @param player The player. - * @param command The command. - */ - public final void executePrivileged(Player player, Command command) { - if (player.getPrivilegeLevel().toInteger() >= level.toInteger()) { - execute(player, command); - } + /** + * Creates a new command listener with a {@link PrivilegeLevel#STANDARD} requirement. + */ + public CommandListener() { + this(PrivilegeLevel.STANDARD); + } + + /** + * Creates a new command listener. + * + * @param level The required {@link PrivilegeLevel}. + */ + public CommandListener(PrivilegeLevel level) { + this.level = level; + } + + /** + * Executes the action for this command. + * + * @param player The player. + * @param command The command. + */ + public abstract void execute(Player player, Command command); + + /** + * Executes a privileged command. + * + * @param player The player. + * @param command The command. + */ + public final void executePrivileged(Player player, Command command) { + if (player.getPrivilegeLevel().toInteger() >= level.toInteger()) { + execute(player, command); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/command/CreditsCommandListener.java b/src/org/apollo/game/command/CreditsCommandListener.java index 44d1900c..2ec4e3b3 100644 --- a/src/org/apollo/game/command/CreditsCommandListener.java +++ b/src/org/apollo/game/command/CreditsCommandListener.java @@ -15,36 +15,36 @@ import org.apollo.util.plugin.PluginManager; */ public final class CreditsCommandListener extends CommandListener { - /* - * If you are considering removing this command, please bear in mind that Apollo took several people thousands of - * hours to create. We released it to the world for free and it isn't much to ask to leave this command in. It isn't - * very obtrusive and gives us some well-deserved recognition for the work we have done. Thank you! - * - * The list of authors is generated from the plugin manager. If you create a custom plugin, make sure you add your - * name to the plugin.xml file and it'll appear here automatically! - */ + /* + * If you are considering removing this command, please bear in mind that Apollo took several people thousands of + * hours to create. We released it to the world for free and it isn't much to ask to leave this command in. It isn't + * very obtrusive and gives us some well-deserved recognition for the work we have done. Thank you! + * + * The list of authors is generated from the plugin manager. If you create a custom plugin, make sure you add your + * name to the plugin.xml file and it'll appear here automatically! + */ - @Override - public void execute(Player player, Command command) { - PluginManager mgr = World.getWorld().getPluginManager(); - final Set authors = mgr.getAuthors(); + @Override + public void execute(Player player, Command command) { + PluginManager mgr = World.getWorld().getPluginManager(); + final Set authors = mgr.getAuthors(); - List text = new ArrayList(12 + authors.size()); - text.add("@dre@Apollo"); - text.add("@dre@Introduction"); - text.add(""); - text.add("This server is based on Apollo, a lightweight, fast, secure"); - text.add("and open-source RuneScape emulator. For more"); - text.add("information about Apollo, visit the website at:"); - text.add("@dbl@https://github.com/apollo-rsps/apollo"); - text.add(""); - text.add("Apollo is released under the terms of the ISC license."); - text.add(""); - text.add("@dre@Credits"); - text.add(""); - text.addAll(authors); + List text = new ArrayList<>(12 + authors.size()); + text.add("@dre@Apollo"); + text.add("@dre@Introduction"); + text.add(""); + text.add("This server is based on Apollo, a lightweight, fast, secure"); + text.add("and open-source RuneScape emulator. For more"); + text.add("information about Apollo, visit the website at:"); + text.add("@dbl@https://github.com/apollo-rsps/apollo"); + text.add(""); + text.add("Apollo is released under the terms of the ISC license."); + text.add(""); + text.add("@dre@Credits"); + text.add(""); + text.addAll(authors); - player.sendQuestInterface(text); - } + player.sendQuestInterface(text); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/EventHandler.java b/src/org/apollo/game/event/handler/EventHandler.java index b4cdc5b5..0131e966 100644 --- a/src/org/apollo/game/event/handler/EventHandler.java +++ b/src/org/apollo/game/event/handler/EventHandler.java @@ -11,13 +11,13 @@ import org.apollo.game.model.entity.Player; */ public abstract class EventHandler { - /** - * Handles an event. - * - * @param ctx The context. - * @param player The player. - * @param event The event. - */ - public abstract void handle(EventHandlerContext ctx, Player player, E event); + /** + * Handles an event. + * + * @param ctx The context. + * @param player The player. + * @param event The event. + */ + public abstract void handle(EventHandlerContext ctx, Player player, E event); } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/EventHandlerContext.java b/src/org/apollo/game/event/handler/EventHandlerContext.java index 3720fe27..2b2e2cd8 100644 --- a/src/org/apollo/game/event/handler/EventHandlerContext.java +++ b/src/org/apollo/game/event/handler/EventHandlerContext.java @@ -9,9 +9,9 @@ import org.apollo.game.event.handler.chain.EventHandlerChain; */ public abstract class EventHandlerContext { - /** - * Breaks the handler chain. - */ - public abstract void breakHandlerChain(); + /** + * Breaks the handler chain. + */ + public abstract void breakHandlerChain(); } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/chain/EventHandlerChain.java b/src/org/apollo/game/event/handler/chain/EventHandlerChain.java index d67c443a..cc9d99c8 100644 --- a/src/org/apollo/game/event/handler/chain/EventHandlerChain.java +++ b/src/org/apollo/game/event/handler/chain/EventHandlerChain.java @@ -13,58 +13,58 @@ import org.apollo.game.model.entity.Player; */ public final class EventHandlerChain { - /** - * The handlers. - */ - private EventHandler[] handlers; + /** + * The handlers. + */ + private EventHandler[] handlers; - /** - * Creates the event handler chain. - * - * @param handlers The handlers. - */ - @SafeVarargs - public EventHandlerChain(EventHandler... handlers) { - this.handlers = handlers; - } - - /** - * Dynamically adds an event handler to the end of the chain. - * - * @param handler The handler. - */ - @SuppressWarnings("unchecked") - public void addLast(EventHandler handler) { - EventHandler[] old = handlers; - handlers = new EventHandler[old.length + 1]; - System.arraycopy(old, 0, handlers, 0, old.length); - handlers[old.length] = handler; - } - - /** - * Handles the event, passing it down the chain until the chain is broken or the event reaches the end of the chain. - * - * @param player The player. - * @param event The event. - */ - public void handle(Player player, E event) { - final boolean[] running = new boolean[1]; - running[0] = true; - - EventHandlerContext ctx = new EventHandlerContext() { - - @Override - public void breakHandlerChain() { - running[0] = false; - } - }; - - for (EventHandler handler : handlers) { - handler.handle(ctx, player, event); - if (!running[0]) { - break; - } - } + /** + * Creates the event handler chain. + * + * @param handlers The handlers. + */ + @SafeVarargs + public EventHandlerChain(EventHandler... handlers) { + this.handlers = handlers; + } + + /** + * Dynamically adds an event handler to the end of the chain. + * + * @param handler The handler. + */ + @SuppressWarnings("unchecked") + public void addLast(EventHandler handler) { + EventHandler[] old = handlers; + handlers = new EventHandler[old.length + 1]; + System.arraycopy(old, 0, handlers, 0, old.length); + handlers[old.length] = handler; + } + + /** + * Handles the event, passing it down the chain until the chain is broken or the event reaches the end of the chain. + * + * @param player The player. + * @param event The event. + */ + public void handle(Player player, E event) { + final boolean[] running = new boolean[1]; + running[0] = true; + + EventHandlerContext ctx = new EventHandlerContext() { + + @Override + public void breakHandlerChain() { + running[0] = false; + } + }; + + for (EventHandler handler : handlers) { + handler.handle(ctx, player, event); + if (!running[0]) { + break; + } } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/chain/EventHandlerChainGroup.java b/src/org/apollo/game/event/handler/chain/EventHandlerChainGroup.java index f3a8bf5e..ba83658f 100644 --- a/src/org/apollo/game/event/handler/chain/EventHandlerChainGroup.java +++ b/src/org/apollo/game/event/handler/chain/EventHandlerChainGroup.java @@ -11,40 +11,40 @@ import org.apollo.game.event.Event; */ public final class EventHandlerChainGroup { - /** - * The map of event classes to event handler chains. - */ - private final Map, EventHandlerChain> chains; + /** + * The map of event classes to event handler chains. + */ + private final Map, EventHandlerChain> chains; - /** - * Creates the event handler chain group. - * - * @param chains The chains map. - */ - public EventHandlerChainGroup(Map, EventHandlerChain> chains) { - this.chains = chains; - } + /** + * Creates the event handler chain group. + * + * @param chains The chains map. + */ + public EventHandlerChainGroup(Map, EventHandlerChain> chains) { + this.chains = chains; + } - /** - * Gets an {@link EventHandlerChain} from this group. - * - * @param The type of event. - * @param clazz The event class. - * @return The {@link EventHandlerChain} if one was found, {@code null} otherwise. - */ - @SuppressWarnings("unchecked") - public EventHandlerChain getChain(Class clazz) { - return (EventHandlerChain) chains.get(clazz); - } + /** + * Gets an {@link EventHandlerChain} from this group. + * + * @param The type of event. + * @param clazz The event class. + * @return The {@link EventHandlerChain} if one was found, {@code null} otherwise. + */ + @SuppressWarnings("unchecked") + public EventHandlerChain getChain(Class clazz) { + return (EventHandlerChain) chains.get(clazz); + } - /** - * Registers an {@link EventHandlerChain} associated with the specified {@link Class} to this group. - * - * @param clazz The event class. - * @param chain The event handler chain. - */ - public void register(Class clazz, EventHandlerChain chain) { - chains.put(clazz, chain); - } + /** + * Registers an {@link EventHandlerChain} associated with the specified {@link Class} to this group. + * + * @param clazz The event class. + * @param chain The event handler chain. + */ + public void register(Class clazz, EventHandlerChain chain) { + chains.put(clazz, chain); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/BankButtonEventHandler.java b/src/org/apollo/game/event/handler/impl/BankButtonEventHandler.java index 37623a06..03e25e5b 100644 --- a/src/org/apollo/game/event/handler/impl/BankButtonEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/BankButtonEventHandler.java @@ -12,23 +12,23 @@ import org.apollo.game.model.entity.Player; */ public final class BankButtonEventHandler extends EventHandler { - /** - * The withdraw as item button id. - */ - private static final int WITHDRAW_AS_ITEM = 5387; + /** + * The withdraw as item button id. + */ + private static final int WITHDRAW_AS_ITEM = 5387; - /** - * The withdraw as note button id. - */ - private static final int WITHDRAW_AS_NOTE = 5386; + /** + * The withdraw as note button id. + */ + private static final int WITHDRAW_AS_NOTE = 5386; - @Override - public void handle(EventHandlerContext ctx, Player player, ButtonEvent event) { - if (event.getWidgetId() == WITHDRAW_AS_ITEM) { - player.setWithdrawingNotes(false); - } else if (event.getWidgetId() == WITHDRAW_AS_NOTE) { - player.setWithdrawingNotes(true); - } + @Override + public void handle(EventHandlerContext ctx, Player player, ButtonEvent event) { + if (event.getWidgetId() == WITHDRAW_AS_ITEM) { + player.setWithdrawingNotes(false); + } else if (event.getWidgetId() == WITHDRAW_AS_NOTE) { + player.setWithdrawingNotes(true); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/BankEventHandler.java b/src/org/apollo/game/event/handler/impl/BankEventHandler.java index 8f5199c9..5d1cd33d 100644 --- a/src/org/apollo/game/event/handler/impl/BankEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/BankEventHandler.java @@ -16,72 +16,72 @@ import org.apollo.game.model.inter.bank.BankWithdrawEnterAmountListener; */ public final class BankEventHandler extends EventHandler { - /** - * Converts an option to an amount. - * - * @param option The option. - * @return The amount. - * @throws IllegalArgumentException If the option is invalid. - */ - private static final int optionToAmount(int option) { - switch (option) { - case 1: - return 1; - case 2: - return 5; - case 3: - return 10; - case 4: - return Integer.MAX_VALUE; - case 5: - return -1; - } - throw new IllegalArgumentException("Invalid option supplied."); + /** + * Converts an option to an amount. + * + * @param option The option. + * @return The amount. + * @throws IllegalArgumentException If the option is invalid. + */ + private static final int optionToAmount(int option) { + switch (option) { + case 1: + return 1; + case 2: + return 5; + case 3: + return 10; + case 4: + return Integer.MAX_VALUE; + case 5: + return -1; } + throw new IllegalArgumentException("Invalid option supplied."); + } - /** - * Handles a deposit action. - * - * @param ctx The event handler context. - * @param player The player. - * @param event The event. - */ - private void deposit(EventHandlerContext ctx, Player player, ItemActionEvent event) { - int amount = optionToAmount(event.getOption()); - if (amount == -1) { - player.getInterfaceSet().openEnterAmountDialogue( - new BankDepositEnterAmountListener(player, event.getSlot(), event.getId())); - } else if (!BankUtils.deposit(player, event.getSlot(), event.getId(), amount)) { - ctx.breakHandlerChain(); - } + /** + * Handles a deposit action. + * + * @param ctx The event handler context. + * @param player The player. + * @param event The event. + */ + private void deposit(EventHandlerContext ctx, Player player, ItemActionEvent event) { + int amount = optionToAmount(event.getOption()); + if (amount == -1) { + player.getInterfaceSet().openEnterAmountDialogue( + new BankDepositEnterAmountListener(player, event.getSlot(), event.getId())); + } else if (!BankUtils.deposit(player, event.getSlot(), event.getId(), amount)) { + ctx.breakHandlerChain(); } + } - @Override - public void handle(EventHandlerContext ctx, Player player, ItemActionEvent event) { - if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { - if (event.getInterfaceId() == BankConstants.SIDEBAR_INVENTORY_ID) { - deposit(ctx, player, event); - } else if (event.getInterfaceId() == BankConstants.BANK_INVENTORY_ID) { - withdraw(ctx, player, event); - } - } + @Override + public void handle(EventHandlerContext ctx, Player player, ItemActionEvent event) { + if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { + if (event.getInterfaceId() == BankConstants.SIDEBAR_INVENTORY_ID) { + deposit(ctx, player, event); + } else if (event.getInterfaceId() == BankConstants.BANK_INVENTORY_ID) { + withdraw(ctx, player, event); + } } + } - /** - * Handles a withdraw action. - * - * @param ctx The event handler context. - * @param player The player. - * @param event The event. - */ - private void withdraw(EventHandlerContext ctx, Player player, ItemActionEvent event) { - int amount = optionToAmount(event.getOption()); - if (amount == -1) { - player.getInterfaceSet().openEnterAmountDialogue( - new BankWithdrawEnterAmountListener(player, event.getSlot(), event.getId())); - } else if (!BankUtils.withdraw(player, event.getSlot(), event.getId(), amount)) { - ctx.breakHandlerChain(); - } + /** + * Handles a withdraw action. + * + * @param ctx The event handler context. + * @param player The player. + * @param event The event. + */ + private void withdraw(EventHandlerContext ctx, Player player, ItemActionEvent event) { + int amount = optionToAmount(event.getOption()); + if (amount == -1) { + player.getInterfaceSet().openEnterAmountDialogue( + new BankWithdrawEnterAmountListener(player, event.getSlot(), event.getId())); + } else if (!BankUtils.withdraw(player, event.getSlot(), event.getId(), amount)) { + ctx.breakHandlerChain(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ChatEventHandler.java b/src/org/apollo/game/event/handler/impl/ChatEventHandler.java index 5cde13f9..13da017a 100644 --- a/src/org/apollo/game/event/handler/impl/ChatEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/ChatEventHandler.java @@ -13,9 +13,9 @@ import org.apollo.game.sync.block.SynchronizationBlock; */ public final class ChatEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ChatEvent event) { - player.getBlockSet().add(SynchronizationBlock.createChatBlock(player, event)); - } + @Override + public void handle(EventHandlerContext ctx, Player player, ChatEvent event) { + player.getBlockSet().add(SynchronizationBlock.createChatBlock(player, event)); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ChatVerificationHandler.java b/src/org/apollo/game/event/handler/impl/ChatVerificationHandler.java index b750d6c8..fed49357 100644 --- a/src/org/apollo/game/event/handler/impl/ChatVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/ChatVerificationHandler.java @@ -12,13 +12,13 @@ import org.apollo.game.model.entity.Player; */ public final class ChatVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ChatEvent event) { - int color = event.getTextColor(); - int effects = event.getTextEffects(); - if (color < 0 || color > 11 || effects < 0 || effects > 5) { - ctx.breakHandlerChain(); - } + @Override + public void handle(EventHandlerContext ctx, Player player, ChatEvent event) { + int color = event.getTextColor(); + int effects = event.getTextEffects(); + if (color < 0 || color > 11 || effects < 0 || effects > 5) { + ctx.breakHandlerChain(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ClosedInterfaceEventHandler.java b/src/org/apollo/game/event/handler/impl/ClosedInterfaceEventHandler.java index 3d1e0330..13963945 100644 --- a/src/org/apollo/game/event/handler/impl/ClosedInterfaceEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/ClosedInterfaceEventHandler.java @@ -12,10 +12,10 @@ import org.apollo.game.model.entity.Player; */ public final class ClosedInterfaceEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ClosedInterfaceEvent event) { - System.out.println("closing interface"); - player.getInterfaceSet().interfaceClosed(); - } + @Override + public void handle(EventHandlerContext ctx, Player player, ClosedInterfaceEvent event) { + System.out.println("closing interface"); + player.getInterfaceSet().interfaceClosed(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/CommandEventHandler.java b/src/org/apollo/game/event/handler/impl/CommandEventHandler.java index 837c5c08..c629094e 100644 --- a/src/org/apollo/game/event/handler/impl/CommandEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/CommandEventHandler.java @@ -14,16 +14,16 @@ import org.apollo.game.model.entity.Player; */ public final class CommandEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, CommandEvent event) { - String[] components = event.getCommand().split(" "); - String name = components[0]; + @Override + public void handle(EventHandlerContext ctx, Player player, CommandEvent event) { + String[] components = event.getCommand().split(" "); + String name = components[0]; - String[] arguments = new String[components.length - 1]; - System.arraycopy(components, 1, arguments, 0, arguments.length); + String[] arguments = new String[components.length - 1]; + System.arraycopy(components, 1, arguments, 0, arguments.length); - Command command = new Command(name, arguments); - World.getWorld().getCommandDispatcher().dispatch(player, command); - } + Command command = new Command(name, arguments); + World.getWorld().getCommandDispatcher().dispatch(player, command); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/DialogueButtonHandler.java b/src/org/apollo/game/event/handler/impl/DialogueButtonHandler.java index d7d56324..d924984b 100644 --- a/src/org/apollo/game/event/handler/impl/DialogueButtonHandler.java +++ b/src/org/apollo/game/event/handler/impl/DialogueButtonHandler.java @@ -13,15 +13,15 @@ import org.apollo.game.model.inter.InterfaceType; */ public final class DialogueButtonHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ButtonEvent event) { - if (player.getInterfaceSet().contains(InterfaceType.DIALOGUE)) { - boolean breakChain = player.getInterfaceSet().buttonClicked(event.getWidgetId()); + @Override + public void handle(EventHandlerContext ctx, Player player, ButtonEvent event) { + if (player.getInterfaceSet().contains(InterfaceType.DIALOGUE)) { + boolean breakChain = player.getInterfaceSet().buttonClicked(event.getWidgetId()); - if (breakChain) { - ctx.breakHandlerChain(); - } - } + if (breakChain) { + ctx.breakHandlerChain(); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/DialogueContinueEventHandler.java b/src/org/apollo/game/event/handler/impl/DialogueContinueEventHandler.java index 804cae2a..2261125e 100644 --- a/src/org/apollo/game/event/handler/impl/DialogueContinueEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/DialogueContinueEventHandler.java @@ -13,11 +13,11 @@ import org.apollo.game.model.inter.InterfaceType; */ public final class DialogueContinueEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, DialogueContinueEvent event) { - if (player.getInterfaceSet().contains(InterfaceType.DIALOGUE)) { - player.getInterfaceSet().continueRequested(); - } + @Override + public void handle(EventHandlerContext ctx, Player player, DialogueContinueEvent event) { + if (player.getInterfaceSet().contains(InterfaceType.DIALOGUE)) { + player.getInterfaceSet().continueRequested(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/EnteredAmountEventHandler.java b/src/org/apollo/game/event/handler/impl/EnteredAmountEventHandler.java index 5984f483..24224f6f 100644 --- a/src/org/apollo/game/event/handler/impl/EnteredAmountEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/EnteredAmountEventHandler.java @@ -12,9 +12,9 @@ import org.apollo.game.model.entity.Player; */ public final class EnteredAmountEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, EnteredAmountEvent event) { - player.getInterfaceSet().enteredAmount(event.getAmount()); - } + @Override + public void handle(EventHandlerContext ctx, Player player, EnteredAmountEvent event) { + player.getInterfaceSet().enteredAmount(event.getAmount()); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/EquipEventHandler.java b/src/org/apollo/game/event/handler/impl/EquipEventHandler.java index 3a3d93af..7a6d8eff 100644 --- a/src/org/apollo/game/event/handler/impl/EquipEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/EquipEventHandler.java @@ -20,81 +20,81 @@ import org.apollo.util.LanguageUtil; */ public final class EquipEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ItemOptionEvent event) { - if (event.getOption() != 2 || event.getInterfaceId() != SynchronizationInventoryListener.INVENTORY_ID) { - return; - } - - int inventorySlot = event.getSlot(); - Item equipping = player.getInventory().get(inventorySlot); - int equippingId = equipping.getId(); - EquipmentDefinition definition = EquipmentDefinition.lookup(equippingId); - - if (definition == null) { - // We don't break the chain here or any item option events won't work! - return; - } - - for (int id = 0; id < 5; id++) { - int requirement = definition.getLevel(id); - - if (player.getSkillSet().getSkill(id).getMaximumLevel() < requirement) { - String skillName = Skill.getName(id); - String article = LanguageUtil.getIndefiniteArticle(skillName); - - player.sendMessage("You need " + article + " " + skillName + " level of " + requirement - + " to equip this item."); - ctx.breakHandlerChain(); - return; - } - } - - Inventory inventory = player.getInventory(); - Inventory equipment = player.getEquipment(); - - int equipmentSlot = definition.getSlot(); - Item currentlyEquipped = equipment.get(equipmentSlot); - - if (equipping.getDefinition().isStackable() - && (currentlyEquipped == null || currentlyEquipped.getId() == equippingId)) { - equipment.set(definition.getSlot(), equipping); - inventory.reset(inventorySlot); - return; - } - - Item weapon = equipment.get(EquipmentConstants.WEAPON); - Item shield = equipment.get(EquipmentConstants.SHIELD); - - if (definition.isTwoHanded()) { - int slotsRequired = weapon != null ? shield != null ? 1 : 0 : 0; - if (inventory.freeSlots() < slotsRequired) { - ctx.breakHandlerChain(); - return; - } - - equipment.reset(EquipmentConstants.WEAPON); - equipment.reset(EquipmentConstants.SHIELD); - equipment.set(EquipmentConstants.WEAPON, inventory.reset(inventorySlot)); - - if (shield != null) { - inventory.add(shield); - } - if (weapon != null) { - inventory.add(weapon); - } - } else if (definition.getSlot() == EquipmentConstants.SHIELD && weapon != null - && EquipmentDefinition.lookup(weapon.getId()).isTwoHanded()) { - equipment.set(EquipmentConstants.SHIELD, inventory.reset(inventorySlot)); - inventory.add(equipment.reset(EquipmentConstants.WEAPON)); - } else { - Item previous = equipment.reset(equipmentSlot); - inventory.remove(equipping); // no need for fancy stuff here as we know the item isn't stackable. - equipment.set(equipmentSlot, equipping); - if (previous != null) { - inventory.add(previous); - } - } + @Override + public void handle(EventHandlerContext ctx, Player player, ItemOptionEvent event) { + if (event.getOption() != 2 || event.getInterfaceId() != SynchronizationInventoryListener.INVENTORY_ID) { + return; } + int inventorySlot = event.getSlot(); + Item equipping = player.getInventory().get(inventorySlot); + int equippingId = equipping.getId(); + EquipmentDefinition definition = EquipmentDefinition.lookup(equippingId); + + if (definition == null) { + // We don't break the chain here or any item option events won't work! + return; + } + + for (int id = 0; id < 5; id++) { + int requirement = definition.getLevel(id); + + if (player.getSkillSet().getSkill(id).getMaximumLevel() < requirement) { + String skillName = Skill.getName(id); + String article = LanguageUtil.getIndefiniteArticle(skillName); + + player.sendMessage("You need " + article + " " + skillName + " level of " + requirement + + " to equip this item."); + ctx.breakHandlerChain(); + return; + } + } + + Inventory inventory = player.getInventory(); + Inventory equipment = player.getEquipment(); + + int equipmentSlot = definition.getSlot(); + Item currentlyEquipped = equipment.get(equipmentSlot); + + if (equipping.getDefinition().isStackable() + && (currentlyEquipped == null || currentlyEquipped.getId() == equippingId)) { + equipment.set(definition.getSlot(), equipping); + inventory.reset(inventorySlot); + return; + } + + Item weapon = equipment.get(EquipmentConstants.WEAPON); + Item shield = equipment.get(EquipmentConstants.SHIELD); + + if (definition.isTwoHanded()) { + int slotsRequired = weapon != null ? shield != null ? 1 : 0 : 0; + if (inventory.freeSlots() < slotsRequired) { + ctx.breakHandlerChain(); + return; + } + + equipment.reset(EquipmentConstants.WEAPON); + equipment.reset(EquipmentConstants.SHIELD); + equipment.set(EquipmentConstants.WEAPON, inventory.reset(inventorySlot)); + + if (shield != null) { + inventory.add(shield); + } + if (weapon != null) { + inventory.add(weapon); + } + } else if (definition.getSlot() == EquipmentConstants.SHIELD && weapon != null + && EquipmentDefinition.lookup(weapon.getId()).isTwoHanded()) { + equipment.set(EquipmentConstants.SHIELD, inventory.reset(inventorySlot)); + inventory.add(equipment.reset(EquipmentConstants.WEAPON)); + } else { + Item previous = equipment.reset(equipmentSlot); + inventory.remove(equipping); // no need for fancy stuff here as we know the item isn't stackable. + equipment.set(equipmentSlot, equipping); + if (previous != null) { + inventory.add(previous); + } + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java b/src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java index 13d620a2..97dc0197 100644 --- a/src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java @@ -16,36 +16,36 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class ItemOnItemVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) { - Inventory inventory; + @Override + public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) { + Inventory inventory; - switch (event.getInterfaceId()) { - case SynchronizationInventoryListener.INVENTORY_ID: - case BankConstants.SIDEBAR_INVENTORY_ID: - inventory = player.getInventory(); - break; - case SynchronizationInventoryListener.EQUIPMENT_ID: - inventory = player.getEquipment(); - break; - case BankConstants.BANK_INVENTORY_ID: - inventory = player.getBank(); - break; - default: - ctx.breakHandlerChain(); - return; - } - - int slot = event.getTargetSlot(); - if (slot < 0 || slot >= inventory.capacity()) { - ctx.breakHandlerChain(); - return; - } - - Item item = inventory.get(slot); - if (item == null || item.getId() != event.getTargetId()) { - ctx.breakHandlerChain(); - } + switch (event.getInterfaceId()) { + case SynchronizationInventoryListener.INVENTORY_ID: + case BankConstants.SIDEBAR_INVENTORY_ID: + inventory = player.getInventory(); + break; + case SynchronizationInventoryListener.EQUIPMENT_ID: + inventory = player.getEquipment(); + break; + case BankConstants.BANK_INVENTORY_ID: + inventory = player.getBank(); + break; + default: + ctx.breakHandlerChain(); + return; } + int slot = event.getTargetSlot(); + if (slot < 0 || slot >= inventory.capacity()) { + ctx.breakHandlerChain(); + return; + } + + Item item = inventory.get(slot); + if (item == null || item.getId() != event.getTargetId()) { + ctx.breakHandlerChain(); + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ItemOnObjectVerificationHandler.java b/src/org/apollo/game/event/handler/impl/ItemOnObjectVerificationHandler.java index 0f7470ae..cc33c79e 100644 --- a/src/org/apollo/game/event/handler/impl/ItemOnObjectVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/ItemOnObjectVerificationHandler.java @@ -16,27 +16,27 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class ItemOnObjectVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ItemOnObjectEvent event) { - if (event.getInterfaceId() != SynchronizationInventoryListener.INVENTORY_ID - && event.getInterfaceId() != BankConstants.SIDEBAR_INVENTORY_ID) { - ctx.breakHandlerChain(); - return; - } - - Inventory inventory = player.getInventory(); - - int slot = event.getSlot(); - if (slot < 0 || slot >= inventory.capacity()) { - ctx.breakHandlerChain(); - return; - } - - Item item = inventory.get(slot); - if (item == null || item.getId() != event.getId()) { - ctx.breakHandlerChain(); - return; - } + @Override + public void handle(EventHandlerContext ctx, Player player, ItemOnObjectEvent event) { + if (event.getInterfaceId() != SynchronizationInventoryListener.INVENTORY_ID + && event.getInterfaceId() != BankConstants.SIDEBAR_INVENTORY_ID) { + ctx.breakHandlerChain(); + return; } + Inventory inventory = player.getInventory(); + + int slot = event.getSlot(); + if (slot < 0 || slot >= inventory.capacity()) { + ctx.breakHandlerChain(); + return; + } + + Item item = inventory.get(slot); + if (item == null || item.getId() != event.getId()) { + ctx.breakHandlerChain(); + return; + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/ItemVerificationHandler.java b/src/org/apollo/game/event/handler/impl/ItemVerificationHandler.java index cee919b8..6b993462 100644 --- a/src/org/apollo/game/event/handler/impl/ItemVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/ItemVerificationHandler.java @@ -16,36 +16,36 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class ItemVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, InventoryItemEvent event) { - Inventory inventory; + @Override + public void handle(EventHandlerContext ctx, Player player, InventoryItemEvent event) { + Inventory inventory; - switch (event.getInterfaceId()) { - case SynchronizationInventoryListener.INVENTORY_ID: - case BankConstants.SIDEBAR_INVENTORY_ID: - inventory = player.getInventory(); - break; - case SynchronizationInventoryListener.EQUIPMENT_ID: - inventory = player.getEquipment(); - break; - case BankConstants.BANK_INVENTORY_ID: - inventory = player.getBank(); - break; - default: - ctx.breakHandlerChain(); - return; - } - - int slot = event.getSlot(); - if (slot < 0 || slot >= inventory.capacity()) { - ctx.breakHandlerChain(); - return; - } - - Item item = inventory.get(slot); - if (item == null || item.getId() != event.getId()) { - ctx.breakHandlerChain(); - } + switch (event.getInterfaceId()) { + case SynchronizationInventoryListener.INVENTORY_ID: + case BankConstants.SIDEBAR_INVENTORY_ID: + inventory = player.getInventory(); + break; + case SynchronizationInventoryListener.EQUIPMENT_ID: + inventory = player.getEquipment(); + break; + case BankConstants.BANK_INVENTORY_ID: + inventory = player.getBank(); + break; + default: + ctx.breakHandlerChain(); + return; } + int slot = event.getSlot(); + if (slot < 0 || slot >= inventory.capacity()) { + ctx.breakHandlerChain(); + return; + } + + Item item = inventory.get(slot); + if (item == null || item.getId() != event.getId()) { + ctx.breakHandlerChain(); + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/NpcActionVerificationHandler.java b/src/org/apollo/game/event/handler/impl/NpcActionVerificationHandler.java index 5b57d505..8c53aba7 100644 --- a/src/org/apollo/game/event/handler/impl/NpcActionVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/NpcActionVerificationHandler.java @@ -15,18 +15,18 @@ import org.apollo.game.model.entity.Player; */ public final class NpcActionVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, NpcActionEvent event) { - if (event.getIndex() < 0 || event.getIndex() >= WorldConstants.MAXIMUM_NPCS) { - ctx.breakHandlerChain(); - return; - } - - Npc npc = World.getWorld().getNpcRepository().get(event.getIndex()); - - if (npc == null || !player.getPosition().isWithinDistance(npc.getPosition(), 15)) { - ctx.breakHandlerChain(); - } + @Override + public void handle(EventHandlerContext ctx, Player player, NpcActionEvent event) { + if (event.getIndex() < 0 || event.getIndex() >= WorldConstants.MAXIMUM_NPCS) { + ctx.breakHandlerChain(); + return; } + Npc npc = World.getWorld().getNpcRepository().get(event.getIndex()); + + if (npc == null || !player.getPosition().isWithinDistance(npc.getPosition(), 15)) { + ctx.breakHandlerChain(); + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/PlayerDesignEventHandler.java b/src/org/apollo/game/event/handler/impl/PlayerDesignEventHandler.java index 8ded34b0..06fe358e 100644 --- a/src/org/apollo/game/event/handler/impl/PlayerDesignEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/PlayerDesignEventHandler.java @@ -13,11 +13,11 @@ import org.apollo.game.model.entity.Player; */ public final class PlayerDesignEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, PlayerDesignEvent event) { - player.setAppearance(event.getAppearance()); - player.setNew(true); - player.send(new CloseInterfaceEvent()); - } + @Override + public void handle(EventHandlerContext ctx, Player player, PlayerDesignEvent event) { + player.setAppearance(event.getAppearance()); + player.setNew(true); + player.send(new CloseInterfaceEvent()); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/PlayerDesignVerificationHandler.java b/src/org/apollo/game/event/handler/impl/PlayerDesignVerificationHandler.java index 9c44f1a7..6282076a 100644 --- a/src/org/apollo/game/event/handler/impl/PlayerDesignVerificationHandler.java +++ b/src/org/apollo/game/event/handler/impl/PlayerDesignVerificationHandler.java @@ -14,71 +14,71 @@ import org.apollo.game.model.settings.Gender; */ public final class PlayerDesignVerificationHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, PlayerDesignEvent event) { - if (!valid(event.getAppearance())) { - ctx.breakHandlerChain(); - } + @Override + public void handle(EventHandlerContext ctx, Player player, PlayerDesignEvent event) { + if (!valid(event.getAppearance())) { + ctx.breakHandlerChain(); + } + } + + /** + * Checks if an appearance combination is valid. + * + * @param appearance The appearance combination. + * @return {@code true} if so, {@code false} if not. + */ + private boolean valid(Appearance appearance) { + int[] colors = appearance.getColors(); + int[] maxColors = new int[] { 11, 15, 15, 5, 7 }; + for (int i = 0; i < colors.length; i++) { + if (colors[i] < 0 || colors[i] > maxColors[i]) { + return false; + } } - /** - * Checks if an appearance combination is valid. - * - * @param appearance The appearance combination. - * @return {@code true} if so, {@code false} if not. - */ - private boolean valid(Appearance appearance) { - int[] colors = appearance.getColors(); - int[] maxColors = new int[] { 11, 15, 15, 5, 7 }; - for (int i = 0; i < colors.length; i++) { - if (colors[i] < 0 || colors[i] > maxColors[i]) { - return false; - } - } - - Gender gender = appearance.getGender(); - if (gender == Gender.MALE) { - return validMaleStyle(appearance); - } else if (gender == Gender.FEMALE) { - return validFemaleStyle(appearance); - } - throw new IllegalArgumentException("Player can only be either male or female."); + Gender gender = appearance.getGender(); + if (gender == Gender.MALE) { + return validMaleStyle(appearance); + } else if (gender == Gender.FEMALE) { + return validFemaleStyle(appearance); } + throw new IllegalArgumentException("Player can only be either male or female."); + } - /** - * Checks if a {@link Gender#FEMALE} style combination is valid. - * - * @param appearance The appearance combination. - * @return {@code true} if so, {@code false} if not. - */ - private boolean validFemaleStyle(Appearance appearance) { - int[] styles = appearance.getStyle(); - int[] minStyles = new int[] { 45, 255, 56, 61, 67, 70, 79 }; - int[] maxStyles = new int[] { 54, 255, 60, 65, 68, 77, 80 }; - for (int i = 0; i < styles.length; i++) { - if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { - return false; - } - } - return true; + /** + * Checks if a {@link Gender#FEMALE} style combination is valid. + * + * @param appearance The appearance combination. + * @return {@code true} if so, {@code false} if not. + */ + private boolean validFemaleStyle(Appearance appearance) { + int[] styles = appearance.getStyle(); + int[] minStyles = new int[] { 45, 255, 56, 61, 67, 70, 79 }; + int[] maxStyles = new int[] { 54, 255, 60, 65, 68, 77, 80 }; + for (int i = 0; i < styles.length; i++) { + if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { + return false; + } } + return true; + } - /** - * Checks if a {@link Gender#MALE} style combination is valid. - * - * @param appearance The appearance combination. - * @return {@code true} if so, {@code false} if not. - */ - private boolean validMaleStyle(Appearance appearance) { - int[] styles = appearance.getStyle(); - int[] minStyles = new int[] { 0, 10, 18, 26, 33, 36, 42 }; - int[] maxStyles = new int[] { 8, 17, 25, 31, 34, 40, 43 }; - for (int i = 0; i < styles.length; i++) { - if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { - return false; - } - } - return true; + /** + * Checks if a {@link Gender#MALE} style combination is valid. + * + * @param appearance The appearance combination. + * @return {@code true} if so, {@code false} if not. + */ + private boolean validMaleStyle(Appearance appearance) { + int[] styles = appearance.getStyle(); + int[] minStyles = new int[] { 0, 10, 18, 26, 33, 36, 42 }; + int[] maxStyles = new int[] { 8, 17, 25, 31, 34, 40, 43 }; + for (int i = 0; i < styles.length; i++) { + if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { + return false; + } } + return true; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/RemoveEventHandler.java b/src/org/apollo/game/event/handler/impl/RemoveEventHandler.java index c08d270f..42195f8c 100644 --- a/src/org/apollo/game/event/handler/impl/RemoveEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/RemoveEventHandler.java @@ -16,43 +16,43 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class RemoveEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, ItemActionEvent event) { - if (event.getOption() == 1 && event.getInterfaceId() == SynchronizationInventoryListener.EQUIPMENT_ID) { - Inventory inventory = player.getInventory(); - Inventory equipment = player.getEquipment(); + @Override + public void handle(EventHandlerContext ctx, Player player, ItemActionEvent event) { + if (event.getOption() == 1 && event.getInterfaceId() == SynchronizationInventoryListener.EQUIPMENT_ID) { + Inventory inventory = player.getInventory(); + Inventory equipment = player.getEquipment(); - int slot = event.getSlot(); - Item item = equipment.get(slot); - int id = item.getId(); + int slot = event.getSlot(); + Item item = equipment.get(slot); + int id = item.getId(); - if (inventory.freeSlots() == 0 && !item.getDefinition().isStackable()) { - inventory.forceCapacityExceeded(); - ctx.breakHandlerChain(); - return; - } + if (inventory.freeSlots() == 0 && !item.getDefinition().isStackable()) { + inventory.forceCapacityExceeded(); + ctx.breakHandlerChain(); + return; + } - boolean removed = true; + boolean removed = true; - inventory.stopFiringEvents(); - equipment.stopFiringEvents(); + inventory.stopFiringEvents(); + equipment.stopFiringEvents(); - try { - int remaining = inventory.add(id, item.getAmount()); - removed = remaining == 0; - equipment.set(slot, removed ? null : new Item(id, remaining)); - } finally { - inventory.startFiringEvents(); - equipment.startFiringEvents(); - } + try { + int remaining = inventory.add(id, item.getAmount()); + removed = remaining == 0; + equipment.set(slot, removed ? null : new Item(id, remaining)); + } finally { + inventory.startFiringEvents(); + equipment.startFiringEvents(); + } - if (removed) { - inventory.forceRefresh(); - equipment.forceRefresh(slot); - } else { - inventory.forceCapacityExceeded(); - } - } + if (removed) { + inventory.forceRefresh(); + equipment.forceRefresh(slot); + } else { + inventory.forceCapacityExceeded(); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/SwitchItemEventHandler.java b/src/org/apollo/game/event/handler/impl/SwitchItemEventHandler.java index 56ec674c..9db40393 100644 --- a/src/org/apollo/game/event/handler/impl/SwitchItemEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/SwitchItemEventHandler.java @@ -16,32 +16,32 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class SwitchItemEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, SwitchItemEvent event) { - Inventory inventory; - boolean insertPermitted = false; + @Override + public void handle(EventHandlerContext ctx, Player player, SwitchItemEvent event) { + Inventory inventory; + boolean insertPermitted = false; - switch (event.getInterfaceId()) { - case SynchronizationInventoryListener.INVENTORY_ID: - case BankConstants.SIDEBAR_INVENTORY_ID: - inventory = player.getInventory(); - break; - case SynchronizationInventoryListener.EQUIPMENT_ID: - inventory = player.getEquipment(); - break; - case BankConstants.BANK_INVENTORY_ID: - inventory = player.getBank(); - insertPermitted = true; - break; - default: - return; // not a known inventory, ignore - } - - if (event.getOldSlot() >= 0 && event.getNewSlot() >= 0 && event.getOldSlot() < inventory.capacity() - && event.getNewSlot() < inventory.capacity()) { - // events must be fired for it to work if a sidebar inventory overlay is used - inventory.swap(insertPermitted ? event.isInserting() : false, event.getOldSlot(), event.getNewSlot()); - } + switch (event.getInterfaceId()) { + case SynchronizationInventoryListener.INVENTORY_ID: + case BankConstants.SIDEBAR_INVENTORY_ID: + inventory = player.getInventory(); + break; + case SynchronizationInventoryListener.EQUIPMENT_ID: + inventory = player.getEquipment(); + break; + case BankConstants.BANK_INVENTORY_ID: + inventory = player.getBank(); + insertPermitted = true; + break; + default: + return; // not a known inventory, ignore } + if (event.getOldSlot() >= 0 && event.getNewSlot() >= 0 && event.getOldSlot() < inventory.capacity() + && event.getNewSlot() < inventory.capacity()) { + // events must be fired for it to work if a sidebar inventory overlay is used + inventory.swap(insertPermitted ? event.isInserting() : false, event.getOldSlot(), event.getNewSlot()); + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/handler/impl/WalkEventHandler.java b/src/org/apollo/game/event/handler/impl/WalkEventHandler.java index ee7e5182..1edc71a1 100644 --- a/src/org/apollo/game/event/handler/impl/WalkEventHandler.java +++ b/src/org/apollo/game/event/handler/impl/WalkEventHandler.java @@ -14,28 +14,28 @@ import org.apollo.game.model.entity.WalkingQueue; */ public final class WalkEventHandler extends EventHandler { - @Override - public void handle(EventHandlerContext ctx, Player player, WalkEvent event) { - WalkingQueue queue = player.getWalkingQueue(); + @Override + public void handle(EventHandlerContext ctx, Player player, WalkEvent event) { + WalkingQueue queue = player.getWalkingQueue(); - Position[] steps = event.getSteps(); - for (int i = 0; i < steps.length; i++) { - Position step = steps[i]; - if (i == 0) { - if (!queue.addFirstStep(step)) { - return; // ignore packet - } - } else { - queue.addStep(step); - } + Position[] steps = event.getSteps(); + for (int i = 0; i < steps.length; i++) { + Position step = steps[i]; + if (i == 0) { + if (!queue.addFirstStep(step)) { + return; // ignore packet } - - queue.setRunningQueue(event.isRunning() || player.isRunning()); - - if (queue.size() > 0) { - player.stopAction(); - } - player.getInterfaceSet().close(); + } else { + queue.addStep(step); + } } + queue.setRunningQueue(event.isRunning() || player.isRunning()); + + if (queue.size() > 0) { + player.stopAction(); + } + player.getInterfaceSet().close(); + } + } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/AddFriendEvent.java b/src/org/apollo/game/event/impl/AddFriendEvent.java index ce442241..09c692bf 100644 --- a/src/org/apollo/game/event/impl/AddFriendEvent.java +++ b/src/org/apollo/game/event/impl/AddFriendEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class AddFriendEvent extends Event { - /** - * The username of the befriended player. - */ - private final String username; + /** + * The username of the befriended player. + */ + private final String username; - /** - * Creates a new befriend user event. - * - * @param username The befriended player's username. - */ - public AddFriendEvent(String username) { - this.username = username; - } + /** + * Creates a new befriend user event. + * + * @param username The befriended player's username. + */ + public AddFriendEvent(String username) { + this.username = username; + } - /** - * Gets the username of the befriended player. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the befriended player. + * + * @return The username. + */ + public String getUsername() { + return username; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/AddGlobalTileItemEvent.java b/src/org/apollo/game/event/impl/AddGlobalTileItemEvent.java index 8f5b73d4..e8224e0e 100644 --- a/src/org/apollo/game/event/impl/AddGlobalTileItemEvent.java +++ b/src/org/apollo/game/event/impl/AddGlobalTileItemEvent.java @@ -5,78 +5,78 @@ import org.apollo.game.model.Item; public final class AddGlobalTileItemEvent extends Event { - /** - * The item to add to the tile. - */ - private final Item item; + /** + * The item to add to the tile. + */ + private final Item item; - /** - * The position offset - */ - private final int positionOffset; + /** + * The position offset + */ + private final int positionOffset; - /** - * The index of the player who dropped the item. - */ - private final int index; + /** + * The index of the player who dropped the item. + */ + private final int index; - /** - * Creates the add global tile item event. - * - * @param item The item to add to the tile. - * @param index The index of the player who dropped the item. - */ - public AddGlobalTileItemEvent(Item item, int index) { - this(item, index, 0); - } + /** + * Creates the add global tile item event. + * + * @param item The item to add to the tile. + * @param index The index of the player who dropped the item. + */ + public AddGlobalTileItemEvent(Item item, int index) { + this(item, index, 0); + } - /** - * Creates the add global tile item event. - * - * @param item The item to add to the tile. - * @param index The index of the player who dropped the item. - * @param positionOffset The offset from the 'base' position. - */ - public AddGlobalTileItemEvent(Item item, int index, int positionOffset) { - this.item = item; - this.index = index; - this.positionOffset = positionOffset; - } + /** + * Creates the add global tile item event. + * + * @param item The item to add to the tile. + * @param index The index of the player who dropped the item. + * @param positionOffset The offset from the 'base' position. + */ + public AddGlobalTileItemEvent(Item item, int index, int positionOffset) { + this.item = item; + this.index = index; + this.positionOffset = positionOffset; + } - /** - * Gets the id of the item. - * - * @return The id. - */ - public int getId() { - return item.getId(); - } + /** + * Gets the id of the item. + * + * @return The id. + */ + public int getId() { + return item.getId(); + } - /** - * Gets the amount of the item. - * - * @return The amount. - */ - public int getAmount() { - return item.getAmount(); - } + /** + * Gets the amount of the item. + * + * @return The amount. + */ + public int getAmount() { + return item.getAmount(); + } - /** - * Gets the index of the player who dropped the item. - * - * @return The index. - */ - public int getIndex() { - return index; - } + /** + * Gets the index of the player who dropped the item. + * + * @return The index. + */ + public int getIndex() { + return index; + } - /** - * Gets the offset from the 'base' position. - * - * @return The offset. - */ - public int getPositionOffset() { - return positionOffset; - } + /** + * Gets the offset from the 'base' position. + * + * @return The offset. + */ + public int getPositionOffset() { + return positionOffset; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/AddIgnoreEvent.java b/src/org/apollo/game/event/impl/AddIgnoreEvent.java index fff53923..7b4490aa 100644 --- a/src/org/apollo/game/event/impl/AddIgnoreEvent.java +++ b/src/org/apollo/game/event/impl/AddIgnoreEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class AddIgnoreEvent extends Event { - /** - * The username of the ignored player. - */ - private final String username; + /** + * The username of the ignored player. + */ + private final String username; - /** - * Creates a new ignore player event. - * - * @param username The ignored player's username. - */ - public AddIgnoreEvent(String username) { - this.username = username; - } + /** + * Creates a new ignore player event. + * + * @param username The ignored player's username. + */ + public AddIgnoreEvent(String username) { + this.username = username; + } - /** - * Gets the username of the ignored player. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the ignored player. + * + * @return The username. + */ + public String getUsername() { + return username; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/AddTileItemEvent.java b/src/org/apollo/game/event/impl/AddTileItemEvent.java index 87621c8c..79e04c53 100644 --- a/src/org/apollo/game/event/impl/AddTileItemEvent.java +++ b/src/org/apollo/game/event/impl/AddTileItemEvent.java @@ -10,61 +10,61 @@ import org.apollo.game.model.Item; */ public final class AddTileItemEvent extends Event { - /** - * The item to add to the tile. - */ - private final Item item; + /** + * The item to add to the tile. + */ + private final Item item; - /** - * The position offset - */ - private final int positionOffset; + /** + * The position offset + */ + private final int positionOffset; - /** - * Creates an add tile item event. - * - * @param item The item to add to the tile. - */ - public AddTileItemEvent(Item item) { - this(item, 0); - } + /** + * Creates an add tile item event. + * + * @param item The item to add to the tile. + */ + public AddTileItemEvent(Item item) { + this(item, 0); + } - /** - * Creates an add tile item event. - * - * @param item The item to add to the tile. - * @param positionOffset The offset from the 'base' position. - */ - public AddTileItemEvent(Item item, int positionOffset) { - this.item = item; - this.positionOffset = positionOffset; - } + /** + * Creates an add tile item event. + * + * @param item The item to add to the tile. + * @param positionOffset The offset from the 'base' position. + */ + public AddTileItemEvent(Item item, int positionOffset) { + this.item = item; + this.positionOffset = positionOffset; + } - /** - * Gets the id of the item. - * - * @return The id. - */ - public int getId() { - return item.getId(); - } + /** + * Gets the id of the item. + * + * @return The id. + */ + public int getId() { + return item.getId(); + } - /** - * Gets the amount of the item. - * - * @return The amount. - */ - public int getAmount() { - return item.getAmount(); - } + /** + * Gets the amount of the item. + * + * @return The amount. + */ + public int getAmount() { + return item.getAmount(); + } - /** - * Gets the offset from the 'base' position. - * - * @return The offset. - */ - public int getPositionOffset() { - return positionOffset; - } + /** + * Gets the offset from the 'base' position. + * + * @return The offset. + */ + public int getPositionOffset() { + return positionOffset; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ArrowKeyEvent.java b/src/org/apollo/game/event/impl/ArrowKeyEvent.java index 3b5ebe33..65cf64ff 100644 --- a/src/org/apollo/game/event/impl/ArrowKeyEvent.java +++ b/src/org/apollo/game/event/impl/ArrowKeyEvent.java @@ -9,40 +9,40 @@ import org.apollo.game.event.Event; */ public final class ArrowKeyEvent extends Event { - /** - * The camera roll. - */ - private final int roll; + /** + * The camera roll. + */ + private final int roll; - /** - * The camera yaw. - */ - private final int yaw; + /** + * The camera yaw. + */ + private final int yaw; - /** - * Creates a new arrow key event. - */ - public ArrowKeyEvent(int roll, int yaw) { - this.roll = roll; - this.yaw = yaw; - } + /** + * Creates a new arrow key event. + */ + public ArrowKeyEvent(int roll, int yaw) { + this.roll = roll; + this.yaw = yaw; + } - /** - * Gets the roll of the camera. - * - * @return The roll. - */ - public int getRoll() { - return roll; - } + /** + * Gets the roll of the camera. + * + * @return The roll. + */ + public int getRoll() { + return roll; + } - /** - * Gets the yaw of the camera. - * - * @return The yaw. - */ - public int getYaw() { - return yaw; - } + /** + * Gets the yaw of the camera. + * + * @return The yaw. + */ + public int getYaw() { + return yaw; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ButtonEvent.java b/src/org/apollo/game/event/impl/ButtonEvent.java index a52744be..7fd7b954 100644 --- a/src/org/apollo/game/event/impl/ButtonEvent.java +++ b/src/org/apollo/game/event/impl/ButtonEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class ButtonEvent extends Event { - /** - * The widget id. - */ - private final int widgetId; + /** + * The widget id. + */ + private final int widgetId; - /** - * Creates the button event. - * - * @param widgetId The widget id. - */ - public ButtonEvent(int widgetId) { - this.widgetId = widgetId; - } + /** + * Creates the button event. + * + * @param widgetId The widget id. + */ + public ButtonEvent(int widgetId) { + this.widgetId = widgetId; + } - /** - * Gets the widget id. - * - * @return The widget id. - */ - public int getWidgetId() { - return widgetId; - } + /** + * Gets the widget id. + * + * @return The widget id. + */ + public int getWidgetId() { + return widgetId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ChatEvent.java b/src/org/apollo/game/event/impl/ChatEvent.java index f3565fd8..31811810 100644 --- a/src/org/apollo/game/event/impl/ChatEvent.java +++ b/src/org/apollo/game/event/impl/ChatEvent.java @@ -9,75 +9,75 @@ import org.apollo.game.event.Event; */ public final class ChatEvent extends Event { - /** - * The text color. - */ - private final int color; + /** + * The text color. + */ + private final int color; - /** - * The compressed message. - */ - private final byte[] compressedMessage; + /** + * The compressed message. + */ + private final byte[] compressedMessage; - /** - * The text effects. - */ - private final int effects; + /** + * The text effects. + */ + private final int effects; - /** - * The message. - */ - private final String message; + /** + * The message. + */ + private final String message; - /** - * Creates a new chat event. - * - * @param message The message. - * @param compressedMessage The compressed message. - * @param color The text color. - * @param effects The text effects. - */ - public ChatEvent(String message, byte[] compressedMessage, int color, int effects) { - this.message = message; - this.compressedMessage = compressedMessage; - this.color = color; - this.effects = effects; - } + /** + * Creates a new chat event. + * + * @param message The message. + * @param compressedMessage The compressed message. + * @param color The text color. + * @param effects The text effects. + */ + public ChatEvent(String message, byte[] compressedMessage, int color, int effects) { + this.message = message; + this.compressedMessage = compressedMessage; + this.color = color; + this.effects = effects; + } - /** - * Gets the compressed message. - * - * @return The compressed message. - */ - public byte[] getCompressedMessage() { - return compressedMessage; - } + /** + * Gets the compressed message. + * + * @return The compressed message. + */ + public byte[] getCompressedMessage() { + return compressedMessage; + } - /** - * Gets the message. - * - * @return The message. - */ - public String getMessage() { - return message; - } + /** + * Gets the message. + * + * @return The message. + */ + public String getMessage() { + return message; + } - /** - * Gets the text color. - * - * @return The text color. - */ - public int getTextColor() { - return color; - } + /** + * Gets the text color. + * + * @return The text color. + */ + public int getTextColor() { + return color; + } - /** - * Gets the text effects. - * - * @return The text effects. - */ - public int getTextEffects() { - return effects; - } + /** + * Gets the text effects. + * + * @return The text effects. + */ + public int getTextEffects() { + return effects; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/CommandEvent.java b/src/org/apollo/game/event/impl/CommandEvent.java index a0332197..7635524a 100644 --- a/src/org/apollo/game/event/impl/CommandEvent.java +++ b/src/org/apollo/game/event/impl/CommandEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class CommandEvent extends Event { - /** - * The command. - */ - private final String command; + /** + * The command. + */ + private final String command; - /** - * Creates the command event. - * - * @param command The command. - */ - public CommandEvent(String command) { - this.command = command; - } + /** + * Creates the command event. + * + * @param command The command. + */ + public CommandEvent(String command) { + this.command = command; + } - /** - * Gets the command. - * - * @return The command. - */ - public String getCommand() { - return command; - } + /** + * Gets the command. + * + * @return The command. + */ + public String getCommand() { + return command; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ConfigEvent.java b/src/org/apollo/game/event/impl/ConfigEvent.java index dae8caf4..0dde2b19 100644 --- a/src/org/apollo/game/event/impl/ConfigEvent.java +++ b/src/org/apollo/game/event/impl/ConfigEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class ConfigEvent extends Event { - /** - * The identifier. - */ - private final int id; + /** + * The identifier. + */ + private final int id; - /** - * The value. - */ - private final int value; + /** + * The value. + */ + private final int value; - /** - * Creates a new config event. - * - * @param id The config's identifier. - * @param value The value. - */ - public ConfigEvent(int id, int value) { - this.id = id; - this.value = value; - } + /** + * Creates a new config event. + * + * @param id The config's identifier. + * @param value The value. + */ + public ConfigEvent(int id, int value) { + this.id = id; + this.value = value; + } - /** - * Gets the config's identifier. - * - * @return The config id. - */ - public int getId() { - return id; - } + /** + * Gets the config's identifier. + * + * @return The config id. + */ + public int getId() { + return id; + } - /** - * Gets the config's value. - * - * @return The config value. - */ - public int getValue() { - return value; - } + /** + * Gets the config's value. + * + * @return The config value. + */ + public int getValue() { + return value; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/DialogueContinueEvent.java b/src/org/apollo/game/event/impl/DialogueContinueEvent.java index a1b10557..c3237751 100644 --- a/src/org/apollo/game/event/impl/DialogueContinueEvent.java +++ b/src/org/apollo/game/event/impl/DialogueContinueEvent.java @@ -10,27 +10,27 @@ import org.apollo.game.event.Event; */ public final class DialogueContinueEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * Creates a new dialogue continue event. - * - * @param interfaceId The interface id. - */ - public DialogueContinueEvent(int interfaceId) { - this.interfaceId = interfaceId; - } + /** + * Creates a new dialogue continue event. + * + * @param interfaceId The interface id. + */ + public DialogueContinueEvent(int interfaceId) { + this.interfaceId = interfaceId; + } - /** - * Gets the interface id of the button. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id of the button. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/DisplayCrossbonesEvent.java b/src/org/apollo/game/event/impl/DisplayCrossbonesEvent.java index a9344fe9..4c40b800 100644 --- a/src/org/apollo/game/event/impl/DisplayCrossbonesEvent.java +++ b/src/org/apollo/game/event/impl/DisplayCrossbonesEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class DisplayCrossbonesEvent extends Event { - /** - * Whether or not the crossbones should be displayed. - */ - private final boolean display; + /** + * Whether or not the crossbones should be displayed. + */ + private final boolean display; - /** - * Creates a display crossbones event. - * - * @param display Whether or not the crossbones should be displayed. - */ - public DisplayCrossbonesEvent(boolean display) { - this.display = display; - } + /** + * Creates a display crossbones event. + * + * @param display Whether or not the crossbones should be displayed. + */ + public DisplayCrossbonesEvent(boolean display) { + this.display = display; + } - /** - * Indicates whether the crossbones will be displayed. - * - * @return {@code true} if the crossbones will be displayed, otherwise {@code false}. - */ - public boolean isDisplayed() { - return display; - } + /** + * Indicates whether the crossbones will be displayed. + * + * @return {@code true} if the crossbones will be displayed, otherwise {@code false}. + */ + public boolean isDisplayed() { + return display; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/DisplayTabInterfaceEvent.java b/src/org/apollo/game/event/impl/DisplayTabInterfaceEvent.java index a4b284d8..b2dc2296 100644 --- a/src/org/apollo/game/event/impl/DisplayTabInterfaceEvent.java +++ b/src/org/apollo/game/event/impl/DisplayTabInterfaceEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class DisplayTabInterfaceEvent extends Event { - /** - * The tab index. - */ - private final int tab; + /** + * The tab index. + */ + private final int tab; - /** - * Creates a new display tab interface event. - * - * @param tab The index of the tab to display. - */ - public DisplayTabInterfaceEvent(int tab) { - this.tab = tab; - } + /** + * Creates a new display tab interface event. + * + * @param tab The index of the tab to display. + */ + public DisplayTabInterfaceEvent(int tab) { + this.tab = tab; + } - /** - * Gets the index of the tab to display. - * - * @return The tab index. - */ - public int getTab() { - return tab; - } + /** + * Gets the index of the tab to display. + * + * @return The tab index. + */ + public int getTab() { + return tab; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/EnteredAmountEvent.java b/src/org/apollo/game/event/impl/EnteredAmountEvent.java index 74930dcc..196638b0 100644 --- a/src/org/apollo/game/event/impl/EnteredAmountEvent.java +++ b/src/org/apollo/game/event/impl/EnteredAmountEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class EnteredAmountEvent extends Event { - /** - * The amount. - */ - private final int amount; + /** + * The amount. + */ + private final int amount; - /** - * Creates the entered amount event. - * - * @param amount The amount. - */ - public EnteredAmountEvent(int amount) { - this.amount = amount; - } + /** + * Creates the entered amount event. + * + * @param amount The amount. + */ + public EnteredAmountEvent(int amount) { + this.amount = amount; + } - /** - * Gets the amount. - * - * @return The amount. - */ - public int getAmount() { - return amount; - } + /** + * Gets the amount. + * + * @return The amount. + */ + public int getAmount() { + return amount; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FifthItemActionEvent.java b/src/org/apollo/game/event/impl/FifthItemActionEvent.java index 7895979d..98ae24d0 100644 --- a/src/org/apollo/game/event/impl/FifthItemActionEvent.java +++ b/src/org/apollo/game/event/impl/FifthItemActionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FifthItemActionEvent extends ItemActionEvent { - /** - * Creates the fifth item action event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - */ - public FifthItemActionEvent(int interfaceId, int id, int slot) { - super(5, interfaceId, id, slot); - } + /** + * Creates the fifth item action event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + */ + public FifthItemActionEvent(int interfaceId, int id, int slot) { + super(5, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FifthItemOptionEvent.java b/src/org/apollo/game/event/impl/FifthItemOptionEvent.java index bc7e6251..12c6bd91 100644 --- a/src/org/apollo/game/event/impl/FifthItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/FifthItemOptionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FifthItemOptionEvent extends ItemOptionEvent { - /** - * Creates the fifth item option event. - * - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public FifthItemOptionEvent(int interfaceId, int id, int slot) { - super(5, interfaceId, id, slot); - } + /** + * Creates the fifth item option event. + * + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public FifthItemOptionEvent(int interfaceId, int id, int slot) { + super(5, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FifthPlayerActionEvent.java b/src/org/apollo/game/event/impl/FifthPlayerActionEvent.java index 55a512c4..24306734 100644 --- a/src/org/apollo/game/event/impl/FifthPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/FifthPlayerActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class FifthPlayerActionEvent extends PlayerActionEvent { - /** - * Creates a fifth player action event. - * - * @param playerIndex The index of the clicked player. - */ - public FifthPlayerActionEvent(int playerIndex) { - super(5, playerIndex); - } + /** + * Creates a fifth player action event. + * + * @param playerIndex The index of the clicked player. + */ + public FifthPlayerActionEvent(int playerIndex) { + super(5, playerIndex); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FirstItemActionEvent.java b/src/org/apollo/game/event/impl/FirstItemActionEvent.java index c1cd0123..ef170450 100644 --- a/src/org/apollo/game/event/impl/FirstItemActionEvent.java +++ b/src/org/apollo/game/event/impl/FirstItemActionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FirstItemActionEvent extends ItemActionEvent { - /** - * Creates the first item action event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - */ - public FirstItemActionEvent(int interfaceId, int id, int slot) { - super(1, interfaceId, id, slot); - } + /** + * Creates the first item action event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + */ + public FirstItemActionEvent(int interfaceId, int id, int slot) { + super(1, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FirstItemOptionEvent.java b/src/org/apollo/game/event/impl/FirstItemOptionEvent.java index 0af5e860..557ee27b 100644 --- a/src/org/apollo/game/event/impl/FirstItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/FirstItemOptionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FirstItemOptionEvent extends ItemOptionEvent { - /** - * Creates the first item option event. - * - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public FirstItemOptionEvent(int interfaceId, int id, int slot) { - super(1, interfaceId, id, slot); - } + /** + * Creates the first item option event. + * + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public FirstItemOptionEvent(int interfaceId, int id, int slot) { + super(1, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FirstNpcActionEvent.java b/src/org/apollo/game/event/impl/FirstNpcActionEvent.java index 39124bdb..4c330262 100644 --- a/src/org/apollo/game/event/impl/FirstNpcActionEvent.java +++ b/src/org/apollo/game/event/impl/FirstNpcActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class FirstNpcActionEvent extends NpcActionEvent { - /** - * Creates a new first npc action event. - * - * @param index The index of the npc. - */ - public FirstNpcActionEvent(int index) { - super(1, index); - } + /** + * Creates a new first npc action event. + * + * @param index The index of the npc. + */ + public FirstNpcActionEvent(int index) { + super(1, index); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FirstObjectActionEvent.java b/src/org/apollo/game/event/impl/FirstObjectActionEvent.java index b51ddcaf..325487a7 100644 --- a/src/org/apollo/game/event/impl/FirstObjectActionEvent.java +++ b/src/org/apollo/game/event/impl/FirstObjectActionEvent.java @@ -9,14 +9,14 @@ import org.apollo.game.model.Position; */ public final class FirstObjectActionEvent extends ObjectActionEvent { - /** - * Creates the first object action event. - * - * @param id The id. - * @param position The position. - */ - public FirstObjectActionEvent(int id, Position position) { - super(1, id, position); - } + /** + * Creates the first object action event. + * + * @param id The id. + * @param position The position. + */ + public FirstObjectActionEvent(int id, Position position) { + super(1, id, position); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FirstPlayerActionEvent.java b/src/org/apollo/game/event/impl/FirstPlayerActionEvent.java index e920192e..9cd091ac 100644 --- a/src/org/apollo/game/event/impl/FirstPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/FirstPlayerActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class FirstPlayerActionEvent extends PlayerActionEvent { - /** - * Creates a first player action event. - * - * @param playerIndex The index of the clicked player. - */ - public FirstPlayerActionEvent(int playerIndex) { - super(1, playerIndex); - } + /** + * Creates a first player action event. + * + * @param playerIndex The index of the clicked player. + */ + public FirstPlayerActionEvent(int playerIndex) { + super(1, playerIndex); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FocusUpdateEvent.java b/src/org/apollo/game/event/impl/FocusUpdateEvent.java index ad4605d8..c9b0f4b2 100644 --- a/src/org/apollo/game/event/impl/FocusUpdateEvent.java +++ b/src/org/apollo/game/event/impl/FocusUpdateEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class FocusUpdateEvent extends Event { - /** - * Indicates whether the client is focused or not. - */ - private final boolean focused; + /** + * Indicates whether the client is focused or not. + */ + private final boolean focused; - /** - * Creates a new focus update event. - * - * @param update The data received. - */ - public FocusUpdateEvent(boolean focused) { - this.focused = focused; - } + /** + * Creates a new focus update event. + * + * @param update The data received. + */ + public FocusUpdateEvent(boolean focused) { + this.focused = focused; + } - /** - * Indicates whether or not the client is focused. - * - * @return {@code true} if the client is focused, otherwise {@code false}. - */ - public boolean isFocused() { - return focused; - } + /** + * Indicates whether or not the client is focused. + * + * @return {@code true} if the client is focused, otherwise {@code false}. + */ + public boolean isFocused() { + return focused; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ForwardPrivateMessageEvent.java b/src/org/apollo/game/event/impl/ForwardPrivateMessageEvent.java index 332abe28..84fa5587 100644 --- a/src/org/apollo/game/event/impl/ForwardPrivateMessageEvent.java +++ b/src/org/apollo/game/event/impl/ForwardPrivateMessageEvent.java @@ -10,58 +10,58 @@ import org.apollo.game.model.settings.PrivilegeLevel; */ public final class ForwardPrivateMessageEvent extends Event { - /** - * The username of the player sending the message. - */ - private final String username; + /** + * The username of the player sending the message. + */ + private final String username; - /** - * The privilege level of the player. - */ - private final PrivilegeLevel privilege; + /** + * The privilege level of the player. + */ + private final PrivilegeLevel privilege; - /** - * The message. - */ - private final byte[] message; + /** + * The message. + */ + private final byte[] message; - /** - * Creates a new forward private message event. - * - * @param sender The player sending the message. - * @param message The compressed message. - */ - public ForwardPrivateMessageEvent(String username, PrivilegeLevel level, byte[] message) { - this.username = username; - this.privilege = level; - this.message = message; - } + /** + * Creates a new forward private message event. + * + * @param sender The player sending the message. + * @param message The compressed message. + */ + public ForwardPrivateMessageEvent(String username, PrivilegeLevel level, byte[] message) { + this.username = username; + this.privilege = level; + this.message = message; + } - /** - * Gets the username of the sender. - * - * @return The username. - */ - public String getSenderUsername() { - return username; - } + /** + * Gets the username of the sender. + * + * @return The username. + */ + public String getSenderUsername() { + return username; + } - /** - * Gets the {@link PrivilegeLevel} of the sender. - * - * @return The privilege level. - */ - public PrivilegeLevel getSenderPrivilege() { - return privilege; - } + /** + * Gets the {@link PrivilegeLevel} of the sender. + * + * @return The privilege level. + */ + public PrivilegeLevel getSenderPrivilege() { + return privilege; + } - /** - * Gets the compressed message. - * - * @return The message. - */ - public byte[] getCompressedMessage() { - return message; - } + /** + * Gets the compressed message. + * + * @return The message. + */ + public byte[] getCompressedMessage() { + return message; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FourthItemActionEvent.java b/src/org/apollo/game/event/impl/FourthItemActionEvent.java index 21298adc..67408f28 100644 --- a/src/org/apollo/game/event/impl/FourthItemActionEvent.java +++ b/src/org/apollo/game/event/impl/FourthItemActionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FourthItemActionEvent extends ItemActionEvent { - /** - * Creates the fourth item action event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - */ - public FourthItemActionEvent(int interfaceId, int id, int slot) { - super(4, interfaceId, id, slot); - } + /** + * Creates the fourth item action event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + */ + public FourthItemActionEvent(int interfaceId, int id, int slot) { + super(4, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FourthItemOptionEvent.java b/src/org/apollo/game/event/impl/FourthItemOptionEvent.java index 5d9fa6e5..e8c63e66 100644 --- a/src/org/apollo/game/event/impl/FourthItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/FourthItemOptionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class FourthItemOptionEvent extends ItemOptionEvent { - /** - * Creates the fourth item option event. - * - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public FourthItemOptionEvent(int interfaceId, int id, int slot) { - super(4, interfaceId, id, slot); - } + /** + * Creates the fourth item option event. + * + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public FourthItemOptionEvent(int interfaceId, int id, int slot) { + super(4, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FourthPlayerActionEvent.java b/src/org/apollo/game/event/impl/FourthPlayerActionEvent.java index 5267c8a0..7ba06d01 100644 --- a/src/org/apollo/game/event/impl/FourthPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/FourthPlayerActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class FourthPlayerActionEvent extends PlayerActionEvent { - /** - * Creates a fourth player action event. - * - * @param playerIndex The index of the clicked player. - */ - public FourthPlayerActionEvent(int playerIndex) { - super(4, playerIndex); - } + /** + * Creates a fourth player action event. + * + * @param playerIndex The index of the clicked player. + */ + public FourthPlayerActionEvent(int playerIndex) { + super(4, playerIndex); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/FriendServerStatusEvent.java b/src/org/apollo/game/event/impl/FriendServerStatusEvent.java index 2b86d853..9f4be339 100644 --- a/src/org/apollo/game/event/impl/FriendServerStatusEvent.java +++ b/src/org/apollo/game/event/impl/FriendServerStatusEvent.java @@ -10,27 +10,27 @@ import org.apollo.game.model.settings.ServerStatus; */ public final class FriendServerStatusEvent extends Event { - /** - * The status code of the friend server. - */ - private final int status; + /** + * The status code of the friend server. + */ + private final int status; - /** - * Creates a new friend server status event. - * - * @param status The status. - */ - public FriendServerStatusEvent(ServerStatus status) { - this.status = status.getCode(); - } + /** + * Creates a new friend server status event. + * + * @param status The status. + */ + public FriendServerStatusEvent(ServerStatus status) { + this.status = status.getCode(); + } - /** - * Gets the status code of the friend server. - * - * @return The status code. - */ - public int getStatusCode() { - return status; - } + /** + * Gets the status code of the friend server. + * + * @return The status code. + */ + public int getStatusCode() { + return status; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/IdAssignmentEvent.java b/src/org/apollo/game/event/impl/IdAssignmentEvent.java index becbc728..7f19315d 100644 --- a/src/org/apollo/game/event/impl/IdAssignmentEvent.java +++ b/src/org/apollo/game/event/impl/IdAssignmentEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class IdAssignmentEvent extends Event { - /** - * The id of this player. - */ - private final int id; + /** + * The id of this player. + */ + private final int id; - /** - * The membership flag. - */ - private final boolean members; + /** + * The membership flag. + */ + private final boolean members; - /** - * Creates the local id event. - * - * @param id The id. - * @param members The membership flag. - */ - public IdAssignmentEvent(int id, boolean members) { - this.id = id; - this.members = members; - } + /** + * Creates the local id event. + * + * @param id The id. + * @param members The membership flag. + */ + public IdAssignmentEvent(int id, boolean members) { + this.id = id; + this.members = members; + } - /** - * Gets the id. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the id. + * + * @return The id. + */ + public int getId() { + return id; + } - /** - * Gets the membership flag. - * - * @return The membership flag. - */ - public boolean isMembers() { - return members; - } + /** + * Gets the membership flag. + * + * @return The membership flag. + */ + public boolean isMembers() { + return members; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/IgnoreListEvent.java b/src/org/apollo/game/event/impl/IgnoreListEvent.java index 58e69a22..82c667ea 100644 --- a/src/org/apollo/game/event/impl/IgnoreListEvent.java +++ b/src/org/apollo/game/event/impl/IgnoreListEvent.java @@ -11,27 +11,27 @@ import org.apollo.game.event.Event; */ public final class IgnoreListEvent extends Event { - /** - * The list of ignored player usernames. - */ - private final List usernames; + /** + * The list of ignored player usernames. + */ + private final List usernames; - /** - * Creates a new ignore list event. - * - * @param player The player. - */ - public IgnoreListEvent(List usernames) { - this.usernames = usernames; - } + /** + * Creates a new ignore list event. + * + * @param player The player. + */ + public IgnoreListEvent(List usernames) { + this.usernames = usernames; + } - /** - * Gets the list of ignored usernames. - * - * @return The usernames. - */ - public List getUsernames() { - return usernames; - } + /** + * Gets the list of ignored usernames. + * + * @return The usernames. + */ + public List getUsernames() { + return usernames; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/InventoryItemEvent.java b/src/org/apollo/game/event/impl/InventoryItemEvent.java index b3830027..9d310862 100644 --- a/src/org/apollo/game/event/impl/InventoryItemEvent.java +++ b/src/org/apollo/game/event/impl/InventoryItemEvent.java @@ -10,75 +10,75 @@ import org.apollo.game.event.Event; */ public abstract class InventoryItemEvent extends Event { - /** - * The item id. - */ - private final int id; + /** + * The item id. + */ + private final int id; - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The option number (1-5). - */ - private final int option; + /** + * The option number (1-5). + */ + private final int option; - /** - * The item's slot. - */ - private final int slot; + /** + * The item's slot. + */ + private final int slot; - /** - * Creates the item action event. - * - * @param option The option number. - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - protected InventoryItemEvent(int option, int interfaceId, int id, int slot) { - this.option = option; - this.interfaceId = interfaceId; - this.id = id; - this.slot = slot; - } + /** + * Creates the item action event. + * + * @param option The option number. + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + protected InventoryItemEvent(int option, int interfaceId, int id, int slot) { + this.option = option; + this.interfaceId = interfaceId; + this.id = id; + this.slot = slot; + } - /** - * Gets the item id. - * - * @return The item id. - */ - public final int getId() { - return id; - } + /** + * Gets the item id. + * + * @return The item id. + */ + public final int getId() { + return id; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public final int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public final int getInterfaceId() { + return interfaceId; + } - /** - * Gets the option number. - * - * @return The option number. - */ - public final int getOption() { - return option; - } + /** + * Gets the option number. + * + * @return The option number. + */ + public final int getOption() { + return option; + } - /** - * Gets the slot. - * - * @return The slot. - */ - public final int getSlot() { - return slot; - } + /** + * Gets the slot. + * + * @return The slot. + */ + public final int getSlot() { + return slot; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ItemActionEvent.java b/src/org/apollo/game/event/impl/ItemActionEvent.java index 7b2f9105..eafbd747 100644 --- a/src/org/apollo/game/event/impl/ItemActionEvent.java +++ b/src/org/apollo/game/event/impl/ItemActionEvent.java @@ -11,16 +11,16 @@ import org.apollo.game.event.Event; */ public abstract class ItemActionEvent extends InventoryItemEvent { - /** - * Creates the item action event. - * - * @param option The option number. - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public ItemActionEvent(int option, int interfaceId, int id, int slot) { - super(option, interfaceId, id, slot); - } + /** + * Creates the item action event. + * + * @param option The option number. + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public ItemActionEvent(int option, int interfaceId, int id, int slot) { + super(option, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ItemOnItemEvent.java b/src/org/apollo/game/event/impl/ItemOnItemEvent.java index 40c2c912..d6001542 100644 --- a/src/org/apollo/game/event/impl/ItemOnItemEvent.java +++ b/src/org/apollo/game/event/impl/ItemOnItemEvent.java @@ -7,64 +7,64 @@ package org.apollo.game.event.impl; */ public final class ItemOnItemEvent extends InventoryItemEvent { - /** - * The id of the target item. - */ - private final int targetId; + /** + * The id of the target item. + */ + private final int targetId; - /** - * The interface id of the target item. - */ - private final int targetInterface; + /** + * The interface id of the target item. + */ + private final int targetInterface; - /** - * The slot of the target item. - */ - private final int targetSlot; + /** + * The slot of the target item. + */ + private final int targetSlot; - /** - * Creates a new item-on-item event. - * - * @param usedInterface The interface id of the used item. - * @param usedId The id of the used item. - * @param usedSlot The slot of the target item. - * @param targetInterface The interface id of the target item. - * @param targetId The id of the target item. - * @param targetSlot The slot of the target item. - */ - public ItemOnItemEvent(int usedInterface, int usedId, int usedSlot, int targetInterface, int targetId, - int targetSlot) { - super(0, usedInterface, usedId, usedSlot); - this.targetInterface = targetInterface; - this.targetSlot = targetSlot; - this.targetId = targetId; - } + /** + * Creates a new item-on-item event. + * + * @param usedInterface The interface id of the used item. + * @param usedId The id of the used item. + * @param usedSlot The slot of the target item. + * @param targetInterface The interface id of the target item. + * @param targetId The id of the target item. + * @param targetSlot The slot of the target item. + */ + public ItemOnItemEvent(int usedInterface, int usedId, int usedSlot, int targetInterface, int targetId, + int targetSlot) { + super(0, usedInterface, usedId, usedSlot); + this.targetInterface = targetInterface; + this.targetSlot = targetSlot; + this.targetId = targetId; + } - /** - * Gets the id of the target item. - * - * @return The target item's interface id. - */ - public int getTargetId() { - return targetId; - } + /** + * Gets the id of the target item. + * + * @return The target item's interface id. + */ + public int getTargetId() { + return targetId; + } - /** - * Gets the interface id of the target item. - * - * @return The target item's interface id. - */ - public int getTargetInterfaceId() { - return targetInterface; - } + /** + * Gets the interface id of the target item. + * + * @return The target item's interface id. + */ + public int getTargetInterfaceId() { + return targetInterface; + } - /** - * Gets the slot of the target item. - * - * @return The slot of the target item. - */ - public int getTargetSlot() { - return targetSlot; - } + /** + * Gets the slot of the target item. + * + * @return The slot of the target item. + */ + public int getTargetSlot() { + return targetSlot; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ItemOnObjectEvent.java b/src/org/apollo/game/event/impl/ItemOnObjectEvent.java index 23ea81c1..dea33947 100644 --- a/src/org/apollo/game/event/impl/ItemOnObjectEvent.java +++ b/src/org/apollo/game/event/impl/ItemOnObjectEvent.java @@ -10,48 +10,48 @@ import org.apollo.game.model.Position; */ public final class ItemOnObjectEvent extends InventoryItemEvent { - /** - * The object id the item was used on. - */ - private final int objectId; + /** + * The object id the item was used on. + */ + private final int objectId; - /** - * The position of the object. - */ - private final Position position; + /** + * The position of the object. + */ + private final Position position; - /** - * Creates an item on object event. - * - * @param interfaceId The interface id. - * @param itemId The item id. - * @param itemSlot The slot the item is in. - * @param objectId The object id. - * @param x The x coordinate. - * @param y The y coordinate. - */ - public ItemOnObjectEvent(int interfaceId, int itemId, int itemSlot, int objectId, int x, int y) { - super(0, interfaceId, itemId, itemSlot); - this.objectId = objectId; - this.position = new Position(x, y); - } + /** + * Creates an item on object event. + * + * @param interfaceId The interface id. + * @param itemId The item id. + * @param itemSlot The slot the item is in. + * @param objectId The object id. + * @param x The x coordinate. + * @param y The y coordinate. + */ + public ItemOnObjectEvent(int interfaceId, int itemId, int itemSlot, int objectId, int x, int y) { + super(0, interfaceId, itemId, itemSlot); + this.objectId = objectId; + this.position = new Position(x, y); + } - /** - * Gets the object id. - * - * @return The object id. - */ - public int getObjectId() { - return objectId; - } + /** + * Gets the object id. + * + * @return The object id. + */ + public int getObjectId() { + return objectId; + } - /** - * Gets the position of the object. - * - * @return The position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position of the object. + * + * @return The position. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ItemOptionEvent.java b/src/org/apollo/game/event/impl/ItemOptionEvent.java index 44f5d5c7..62058570 100644 --- a/src/org/apollo/game/event/impl/ItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/ItemOptionEvent.java @@ -9,16 +9,16 @@ package org.apollo.game.event.impl; */ public abstract class ItemOptionEvent extends InventoryItemEvent { - /** - * Creates the item option event. - * - * @param option The option number. - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public ItemOptionEvent(int option, int interfaceId, int id, int slot) { - super(option, interfaceId, id, slot); - } + /** + * Creates the item option event. + * + * @param option The option number. + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public ItemOptionEvent(int option, int interfaceId, int id, int slot) { + super(option, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/KeepAliveEvent.java b/src/org/apollo/game/event/impl/KeepAliveEvent.java index 0876eb68..e9aaa0e7 100644 --- a/src/org/apollo/game/event/impl/KeepAliveEvent.java +++ b/src/org/apollo/game/event/impl/KeepAliveEvent.java @@ -9,25 +9,25 @@ import org.apollo.game.event.Event; */ public final class KeepAliveEvent extends Event { - /** - * The time this event was created. - */ - private final long createdAt; + /** + * The time this event was created. + */ + private final long createdAt; - /** - * Creates the keep alive event. - */ - public KeepAliveEvent() { - createdAt = System.currentTimeMillis(); - } + /** + * Creates the keep alive event. + */ + public KeepAliveEvent() { + createdAt = System.currentTimeMillis(); + } - /** - * Gets the time when this event was created. - * - * @return The time when this event was created. - */ - public long getCreatedAt() { - return createdAt; - } + /** + * Gets the time when this event was created. + * + * @return The time when this event was created. + */ + public long getCreatedAt() { + return createdAt; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/MagicOnItemEvent.java b/src/org/apollo/game/event/impl/MagicOnItemEvent.java index f6996972..00074b7c 100644 --- a/src/org/apollo/game/event/impl/MagicOnItemEvent.java +++ b/src/org/apollo/game/event/impl/MagicOnItemEvent.java @@ -7,31 +7,31 @@ package org.apollo.game.event.impl; */ public final class MagicOnItemEvent extends InventoryItemEvent { - /** - * The spell id. - */ - private final int spell; + /** + * The spell id. + */ + private final int spell; - /** - * Creates a new magic on item event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - * @param spell The spell id. - */ - public MagicOnItemEvent(int interfaceId, int id, int slot, int spell) { - super(0, interfaceId, id, slot); - this.spell = spell; - } + /** + * Creates a new magic on item event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + * @param spell The spell id. + */ + public MagicOnItemEvent(int interfaceId, int id, int slot, int spell) { + super(0, interfaceId, id, slot); + this.spell = spell; + } - /** - * Gets the spell id. - * - * @return The spell id. - */ - public int getSpellId() { - return spell; - } + /** + * Gets the spell id. + * + * @return The spell id. + */ + public int getSpellId() { + return spell; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/MouseClickEvent.java b/src/org/apollo/game/event/impl/MouseClickEvent.java index a034b634..d3929a9e 100644 --- a/src/org/apollo/game/event/impl/MouseClickEvent.java +++ b/src/org/apollo/game/event/impl/MouseClickEvent.java @@ -9,77 +9,77 @@ import org.apollo.game.event.Event; */ public final class MouseClickEvent extends Event { - /** - * The number of clicks on this point (i.e. the point ({@link #x}, {@link #y})). - */ - private final int clickCount; + /** + * The number of clicks on this point (i.e. the point ({@link #x}, {@link #y})). + */ + private final int clickCount; - /** - * The x coordinate of the mouse click. - */ - private final int x; + /** + * The x coordinate of the mouse click. + */ + private final int x; - /** - * The y coordinate of the mouse click. - */ - private final int y; + /** + * The y coordinate of the mouse click. + */ + private final int y; - /** - * Indicates whether the {@link #x} and {@link #y} values represent the deviation from the last click or an actual - * point. - */ - private final boolean delta; + /** + * Indicates whether the {@link #x} and {@link #y} values represent the deviation from the last click or an actual + * point. + */ + private final boolean delta; - /** - * Creates a new mouse click event. - * - * @param clickCount The number of clicks on this point. - * @param x The x coordinate of the mouse click. - * @param y The y coordinate of the mouse click. - * @param delta If the coordinates represent a change in x/y, rather than the values themselves. - */ - public MouseClickEvent(int clickCount, int x, int y, boolean delta) { - this.clickCount = clickCount; - this.x = x; - this.y = y; - this.delta = delta; - } + /** + * Creates a new mouse click event. + * + * @param clickCount The number of clicks on this point. + * @param x The x coordinate of the mouse click. + * @param y The y coordinate of the mouse click. + * @param delta If the coordinates represent a change in x/y, rather than the values themselves. + */ + public MouseClickEvent(int clickCount, int x, int y, boolean delta) { + this.clickCount = clickCount; + this.x = x; + this.y = y; + this.delta = delta; + } - /** - * Gets the number of clicks on this point - maximum value of 2047. - * - * @return The number of clicks. - */ - public int getClickCount() { - return clickCount; - } + /** + * Gets the number of clicks on this point - maximum value of 2047. + * + * @return The number of clicks. + */ + public int getClickCount() { + return clickCount; + } - /** - * The x coordinate of the click. - * - * @return The x coordinate. - */ - public int getX() { - return x; - } + /** + * The x coordinate of the click. + * + * @return The x coordinate. + */ + public int getX() { + return x; + } - /** - * The y coordinate of the click. - * - * @return The y coordinate. - */ - public int getY() { - return y; - } + /** + * The y coordinate of the click. + * + * @return The y coordinate. + */ + public int getY() { + return y; + } - /** - * Gets the value indicating whether the {@link #x} and {@link #y} values represent the deviation from the last - * click or an actual point. - * - * @return The value. - */ - public boolean getDelta() { - return delta; - } + /** + * Gets the value indicating whether the {@link #x} and {@link #y} values represent the deviation from the last + * click or an actual point. + * + * @return The value. + */ + public boolean getDelta() { + return delta; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/NpcActionEvent.java b/src/org/apollo/game/event/impl/NpcActionEvent.java index 7cc247fc..62809018 100644 --- a/src/org/apollo/game/event/impl/NpcActionEvent.java +++ b/src/org/apollo/game/event/impl/NpcActionEvent.java @@ -11,43 +11,43 @@ import org.apollo.game.event.Event; */ public abstract class NpcActionEvent extends Event { - /** - * The option number. - */ - private final int option; + /** + * The option number. + */ + private final int option; - /** - * The index of the clicked npc. - */ - private final int index; + /** + * The index of the clicked npc. + */ + private final int index; - /** - * Creates an npc action event. - * - * @param option The option number. - * @param index The index of the npc. - */ - public NpcActionEvent(int option, int index) { - this.option = option; - this.index = index - 1; - } + /** + * Creates an npc action event. + * + * @param option The option number. + * @param index The index of the npc. + */ + public NpcActionEvent(int option, int index) { + this.option = option; + this.index = index - 1; + } - /** - * Gets the menu action number (i.e. the action event 'option') clicked. - * - * @return The option number. - */ - public int getOption() { - return option; - } + /** + * Gets the menu action number (i.e. the action event 'option') clicked. + * + * @return The option number. + */ + public int getOption() { + return option; + } - /** - * Gets the index of the npc clicked. - * - * @return The npc index. - */ - public int getIndex() { - return index; - } + /** + * Gets the index of the npc clicked. + * + * @return The npc index. + */ + public int getIndex() { + return index; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/NpcSynchronizationEvent.java b/src/org/apollo/game/event/impl/NpcSynchronizationEvent.java index 1f961234..cdcdafaa 100644 --- a/src/org/apollo/game/event/impl/NpcSynchronizationEvent.java +++ b/src/org/apollo/game/event/impl/NpcSynchronizationEvent.java @@ -14,59 +14,59 @@ import org.apollo.game.sync.seg.SynchronizationSegment; */ public final class NpcSynchronizationEvent extends Event { - /** - * The amount of local npcs. - */ - private final int localNpcs; + /** + * The amount of local npcs. + */ + private final int localNpcs; - /** - * The npc's position. - */ - private final Position position; + /** + * The npc's position. + */ + private final Position position; - /** - * A list of segments. - */ - private final List segments; + /** + * A list of segments. + */ + private final List segments; - /** - * Creates a new {@link NpcSynchronizationEvent}. - * - * @param position The position of the {@link Npc}. - * @param segments The list of segments. - * @param localNpcs The amount of local npcs. - */ - public NpcSynchronizationEvent(Position position, List segments, int localNpcs) { - this.position = position; - this.segments = segments; - this.localNpcs = localNpcs; - } + /** + * Creates a new {@link NpcSynchronizationEvent}. + * + * @param position The position of the {@link Npc}. + * @param segments The list of segments. + * @param localNpcs The amount of local npcs. + */ + public NpcSynchronizationEvent(Position position, List segments, int localNpcs) { + this.position = position; + this.segments = segments; + this.localNpcs = localNpcs; + } - /** - * Gets the number of local npcs. - * - * @return The number of local npcs. - */ - public int getLocalNpcCount() { - return localNpcs; - } + /** + * Gets the number of local npcs. + * + * @return The number of local npcs. + */ + public int getLocalNpcCount() { + return localNpcs; + } - /** - * Gets the npc's position. - * - * @return The npc's position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the npc's position. + * + * @return The npc's position. + */ + public Position getPosition() { + return position; + } - /** - * Gets the synchronization segments. - * - * @return The segments. - */ - public List getSegments() { - return segments; - } + /** + * Gets the synchronization segments. + * + * @return The segments. + */ + public List getSegments() { + return segments; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ObjectActionEvent.java b/src/org/apollo/game/event/impl/ObjectActionEvent.java index c4de0482..cbc6a102 100644 --- a/src/org/apollo/game/event/impl/ObjectActionEvent.java +++ b/src/org/apollo/game/event/impl/ObjectActionEvent.java @@ -12,59 +12,59 @@ import org.apollo.game.model.Position; */ public abstract class ObjectActionEvent extends Event { - /** - * The object's id. - */ - private final int id; + /** + * The object's id. + */ + private final int id; - /** - * The option number (1-3). - */ - private final int option; + /** + * The option number (1-3). + */ + private final int option; - /** - * The object's position. - */ - private final Position position; + /** + * The object's position. + */ + private final Position position; - /** - * Creates a new object action event. - * - * @param option The option number. - * @param id The id of the object. - * @param position The position of the object. - */ - public ObjectActionEvent(int option, int id, Position position) { - this.option = option; - this.id = id; - this.position = position; - } + /** + * Creates a new object action event. + * + * @param option The option number. + * @param id The id of the object. + * @param position The position of the object. + */ + public ObjectActionEvent(int option, int id, Position position) { + this.option = option; + this.id = id; + this.position = position; + } - /** - * Gets the id of the object. - * - * @return The id of the object. - */ - public int getId() { - return id; - } + /** + * Gets the id of the object. + * + * @return The id of the object. + */ + public int getId() { + return id; + } - /** - * Gets the option number. - * - * @return The option number. - */ - public int getOption() { - return option; - } + /** + * Gets the option number. + * + * @return The option number. + */ + public int getOption() { + return option; + } - /** - * Gets the position of the object. - * - * @return The position of the object. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position of the object. + * + * @return The position of the object. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/OpenDialogueInterfaceEvent.java b/src/org/apollo/game/event/impl/OpenDialogueInterfaceEvent.java index 7cf87c24..84b2d435 100644 --- a/src/org/apollo/game/event/impl/OpenDialogueInterfaceEvent.java +++ b/src/org/apollo/game/event/impl/OpenDialogueInterfaceEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class OpenDialogueInterfaceEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * Creates a new event with the specified interface id. - * - * @param interfaceId The interface id. - */ - public OpenDialogueInterfaceEvent(int interfaceId) { - this.interfaceId = interfaceId; - } + /** + * Creates a new event with the specified interface id. + * + * @param interfaceId The interface id. + */ + public OpenDialogueInterfaceEvent(int interfaceId) { + this.interfaceId = interfaceId; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/OpenInterfaceEvent.java b/src/org/apollo/game/event/impl/OpenInterfaceEvent.java index 368b958b..8d666746 100644 --- a/src/org/apollo/game/event/impl/OpenInterfaceEvent.java +++ b/src/org/apollo/game/event/impl/OpenInterfaceEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class OpenInterfaceEvent extends Event { - /** - * The interface id. - */ - private final int id; + /** + * The interface id. + */ + private final int id; - /** - * Creates the event with the specified interface id. - * - * @param id The interface id. - */ - public OpenInterfaceEvent(int id) { - this.id = id; - } + /** + * Creates the event with the specified interface id. + * + * @param id The interface id. + */ + public OpenInterfaceEvent(int id) { + this.id = id; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getId() { - return id; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getId() { + return id; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/OpenInterfaceSidebarEvent.java b/src/org/apollo/game/event/impl/OpenInterfaceSidebarEvent.java index b7990691..170e48c0 100644 --- a/src/org/apollo/game/event/impl/OpenInterfaceSidebarEvent.java +++ b/src/org/apollo/game/event/impl/OpenInterfaceSidebarEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class OpenInterfaceSidebarEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The sidebar id. - */ - private final int sidebarId; + /** + * The sidebar id. + */ + private final int sidebarId; - /** - * Creates the open interface sidebar event. - * - * @param interfaceId The interface id. - * @param sidebarId The sidebar id. - */ - public OpenInterfaceSidebarEvent(int interfaceId, int sidebarId) { - this.interfaceId = interfaceId; - this.sidebarId = sidebarId; - } + /** + * Creates the open interface sidebar event. + * + * @param interfaceId The interface id. + * @param sidebarId The sidebar id. + */ + public OpenInterfaceSidebarEvent(int interfaceId, int sidebarId) { + this.interfaceId = interfaceId; + this.sidebarId = sidebarId; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the sidebar id. - * - * @return The sidebar id. - */ - public int getSidebarId() { - return sidebarId; - } + /** + * Gets the sidebar id. + * + * @return The sidebar id. + */ + public int getSidebarId() { + return sidebarId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PlayerActionEvent.java b/src/org/apollo/game/event/impl/PlayerActionEvent.java index 54ca3567..1f9663a2 100644 --- a/src/org/apollo/game/event/impl/PlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/PlayerActionEvent.java @@ -11,43 +11,43 @@ import org.apollo.game.event.Event; */ public abstract class PlayerActionEvent extends Event { - /** - * The option number. - */ - private final int option; + /** + * The option number. + */ + private final int option; - /** - * The index of the clicked player. - */ - private final int index; + /** + * The index of the clicked player. + */ + private final int index; - /** - * Creates a player action event. - * - * @param option The option number. - * @param playerIndex The index of the player. - */ - public PlayerActionEvent(int option, int playerIndex) { - this.option = option; - this.index = playerIndex; - } + /** + * Creates a player action event. + * + * @param option The option number. + * @param playerIndex The index of the player. + */ + public PlayerActionEvent(int option, int playerIndex) { + this.option = option; + this.index = playerIndex; + } - /** - * Gets the menu action number (i.e. the action event 'option') clicked. - * - * @return The option number. - */ - public int getOption() { - return option; - } + /** + * Gets the menu action number (i.e. the action event 'option') clicked. + * + * @return The option number. + */ + public int getOption() { + return option; + } - /** - * Gets the index of the clicked player. - * - * @return The index. - */ - public int getIndex() { - return index; - } + /** + * Gets the index of the clicked player. + * + * @return The index. + */ + public int getIndex() { + return index; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PlayerDesignEvent.java b/src/org/apollo/game/event/impl/PlayerDesignEvent.java index a8396703..850c62ab 100644 --- a/src/org/apollo/game/event/impl/PlayerDesignEvent.java +++ b/src/org/apollo/game/event/impl/PlayerDesignEvent.java @@ -10,27 +10,27 @@ import org.apollo.game.model.Appearance; */ public final class PlayerDesignEvent extends Event { - /** - * The appearance. - */ - private final Appearance appearance; + /** + * The appearance. + */ + private final Appearance appearance; - /** - * Creates the player design event. - * - * @param appearance The appearance. - */ - public PlayerDesignEvent(Appearance appearance) { - this.appearance = appearance; - } + /** + * Creates the player design event. + * + * @param appearance The appearance. + */ + public PlayerDesignEvent(Appearance appearance) { + this.appearance = appearance; + } - /** - * Gets the appearance. - * - * @return The appearance. - */ - public Appearance getAppearance() { - return appearance; - } + /** + * Gets the appearance. + * + * @return The appearance. + */ + public Appearance getAppearance() { + return appearance; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PlayerSynchronizationEvent.java b/src/org/apollo/game/event/impl/PlayerSynchronizationEvent.java index c69d3f3b..07c80f43 100644 --- a/src/org/apollo/game/event/impl/PlayerSynchronizationEvent.java +++ b/src/org/apollo/game/event/impl/PlayerSynchronizationEvent.java @@ -13,108 +13,108 @@ import org.apollo.game.sync.seg.SynchronizationSegment; */ public final class PlayerSynchronizationEvent extends Event { - /** - * The last known region. - */ - private final Position lastKnownRegion; + /** + * The last known region. + */ + private final Position lastKnownRegion; - /** - * The number of local players. - */ - private final int localPlayers; + /** + * The number of local players. + */ + private final int localPlayers; - /** - * The player's position. - */ - private final Position position; + /** + * The player's position. + */ + private final Position position; - /** - * A flag indicating if the region has changed. - */ - private final boolean regionChanged; + /** + * A flag indicating if the region has changed. + */ + private final boolean regionChanged; - /** - * The current player's synchronization segment. - */ - private final SynchronizationSegment segment; + /** + * The current player's synchronization segment. + */ + private final SynchronizationSegment segment; - /** - * A list of segments. - */ - private final List segments; + /** + * A list of segments. + */ + private final List segments; - /** - * Creates the player synchronization event. - * - * @param lastKnownRegion The last known region. - * @param position The player's current position. - * @param regionChanged A flag indicating if the region has changed. - * @param segment The current player's synchronization segment. - * @param localPlayers The number of local players. - * @param segments A list of segments. - */ - public PlayerSynchronizationEvent(Position lastKnownRegion, Position position, boolean regionChanged, - SynchronizationSegment segment, int localPlayers, List segments) { - this.lastKnownRegion = lastKnownRegion; - this.position = position; - this.regionChanged = regionChanged; - this.segment = segment; - this.localPlayers = localPlayers; - this.segments = segments; - } + /** + * Creates the player synchronization event. + * + * @param lastKnownRegion The last known region. + * @param position The player's current position. + * @param regionChanged A flag indicating if the region has changed. + * @param segment The current player's synchronization segment. + * @param localPlayers The number of local players. + * @param segments A list of segments. + */ + public PlayerSynchronizationEvent(Position lastKnownRegion, Position position, boolean regionChanged, + SynchronizationSegment segment, int localPlayers, List segments) { + this.lastKnownRegion = lastKnownRegion; + this.position = position; + this.regionChanged = regionChanged; + this.segment = segment; + this.localPlayers = localPlayers; + this.segments = segments; + } - /** - * Gets the last known region. - * - * @return The last known region. - */ - public Position getLastKnownRegion() { - return lastKnownRegion; - } + /** + * Gets the last known region. + * + * @return The last known region. + */ + public Position getLastKnownRegion() { + return lastKnownRegion; + } - /** - * Gets the number of local players. - * - * @return The number of local players. - */ - public int getLocalPlayers() { - return localPlayers; - } + /** + * Gets the number of local players. + * + * @return The number of local players. + */ + public int getLocalPlayers() { + return localPlayers; + } - /** - * Gets the player's position. - * - * @return The player's position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the player's position. + * + * @return The player's position. + */ + public Position getPosition() { + return position; + } - /** - * Gets the current player's segment. - * - * @return The current player's segment. - */ - public SynchronizationSegment getSegment() { - return segment; - } + /** + * Gets the current player's segment. + * + * @return The current player's segment. + */ + public SynchronizationSegment getSegment() { + return segment; + } - /** - * Gets the synchronization segments. - * - * @return The segments. - */ - public List getSegments() { - return segments; - } + /** + * Gets the synchronization segments. + * + * @return The segments. + */ + public List getSegments() { + return segments; + } - /** - * Checks if the region has changed. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasRegionChanged() { - return regionChanged; - } + /** + * Checks if the region has changed. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasRegionChanged() { + return regionChanged; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PositionEvent.java b/src/org/apollo/game/event/impl/PositionEvent.java index b059e1b0..c9b8921f 100644 --- a/src/org/apollo/game/event/impl/PositionEvent.java +++ b/src/org/apollo/game/event/impl/PositionEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.model.Position; */ public final class PositionEvent extends Event { - /** - * The base position. - */ - private final Position base; + /** + * The base position. + */ + private final Position base; - /** - * The target position. - */ - private final Position position; + /** + * The target position. + */ + private final Position position; - /** - * Creates a new position event. - * - * @param base The base from which the position is being focused on. - * @param position The position to focus on. - */ - public PositionEvent(Position base, Position position) { - this.base = base; - this.position = position; - } + /** + * Creates a new position event. + * + * @param base The base from which the position is being focused on. + * @param position The position to focus on. + */ + public PositionEvent(Position base, Position position) { + this.base = base; + this.position = position; + } - /** - * Gets the base position. - * - * @return The position. - */ - public Position getBase() { - return base; - } + /** + * Gets the base position. + * + * @return The position. + */ + public Position getBase() { + return base; + } - /** - * Gets the position to focus on. - * - * @return The target position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position to focus on. + * + * @return The target position. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PrivacyOptionEvent.java b/src/org/apollo/game/event/impl/PrivacyOptionEvent.java index 7fa2198e..93ca6e72 100644 --- a/src/org/apollo/game/event/impl/PrivacyOptionEvent.java +++ b/src/org/apollo/game/event/impl/PrivacyOptionEvent.java @@ -12,59 +12,59 @@ import org.apollo.game.model.settings.PrivacyState; */ public final class PrivacyOptionEvent extends Event { - /** - * The privacy state of the player's chat. - */ - private final PrivacyState chatPrivacy; + /** + * The privacy state of the player's chat. + */ + private final PrivacyState chatPrivacy; - /** - * The privacy state of the player's friend chat. - */ - private final PrivacyState friendPrivacy; + /** + * The privacy state of the player's friend chat. + */ + private final PrivacyState friendPrivacy; - /** - * The privacy state of the player's trade chat. - */ - private final PrivacyState tradePrivacy; + /** + * The privacy state of the player's trade chat. + */ + private final PrivacyState tradePrivacy; - /** - * Creates a privacy option event. - * - * @param chatPrivacy The privacy state of the player's chat. - * @param friendPrivacy The privacy state of the player's friend chat. - * @param tradePrivacy The privacy state of the player's trade chat. - */ - public PrivacyOptionEvent(int chatPrivacy, int friendPrivacy, int tradePrivacy) { - this.chatPrivacy = PrivacyState.valueOf(chatPrivacy, true); - this.friendPrivacy = PrivacyState.valueOf(friendPrivacy, false); - this.tradePrivacy = PrivacyState.valueOf(tradePrivacy, false); - } + /** + * Creates a privacy option event. + * + * @param chatPrivacy The privacy state of the player's chat. + * @param friendPrivacy The privacy state of the player's friend chat. + * @param tradePrivacy The privacy state of the player's trade chat. + */ + public PrivacyOptionEvent(int chatPrivacy, int friendPrivacy, int tradePrivacy) { + this.chatPrivacy = PrivacyState.valueOf(chatPrivacy, true); + this.friendPrivacy = PrivacyState.valueOf(friendPrivacy, false); + this.tradePrivacy = PrivacyState.valueOf(tradePrivacy, false); + } - /** - * Gets the chat {@link PrivacyState}. - * - * @return The privacy state. - */ - public PrivacyState getChatPrivacy() { - return chatPrivacy; - } + /** + * Gets the chat {@link PrivacyState}. + * + * @return The privacy state. + */ + public PrivacyState getChatPrivacy() { + return chatPrivacy; + } - /** - * Gets the friend {@link PrivacyState}. - * - * @return The privacy state. - */ - public PrivacyState getFriendPrivacy() { - return friendPrivacy; - } + /** + * Gets the friend {@link PrivacyState}. + * + * @return The privacy state. + */ + public PrivacyState getFriendPrivacy() { + return friendPrivacy; + } - /** - * Gets the trade {@link PrivacyState}. - * - * @return The privacy state. - */ - public PrivacyState getTradePrivacy() { - return tradePrivacy; - } + /** + * Gets the trade {@link PrivacyState}. + * + * @return The privacy state. + */ + public PrivacyState getTradePrivacy() { + return tradePrivacy; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/PrivateMessageEvent.java b/src/org/apollo/game/event/impl/PrivateMessageEvent.java index 3e00d021..6deef9b0 100644 --- a/src/org/apollo/game/event/impl/PrivateMessageEvent.java +++ b/src/org/apollo/game/event/impl/PrivateMessageEvent.java @@ -9,59 +9,59 @@ import org.apollo.game.event.Event; */ public final class PrivateMessageEvent extends Event { - /** - * The username this message is being sent to. - */ - private final String username; + /** + * The username this message is being sent to. + */ + private final String username; - /** - * The message being sent. - */ - private final String message; + /** + * The message being sent. + */ + private final String message; - /** - * The compressed message. - */ - private final byte[] compressedMessage; + /** + * The compressed message. + */ + private final byte[] compressedMessage; - /** - * Creates a new private message event. - * - * @param username The username of the player the message is being sent to. - * @param message The message. - * @param compressedMessage The message, in a compressed form. - */ - public PrivateMessageEvent(String username, String message, byte[] compressedMessage) { - this.username = username; - this.message = message; - this.compressedMessage = compressedMessage; - } + /** + * Creates a new private message event. + * + * @param username The username of the player the message is being sent to. + * @param message The message. + * @param compressedMessage The message, in a compressed form. + */ + public PrivateMessageEvent(String username, String message, byte[] compressedMessage) { + this.username = username; + this.message = message; + this.compressedMessage = compressedMessage; + } - /** - * Gets the username of the player the message is being sent to. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the player the message is being sent to. + * + * @return The username. + */ + public String getUsername() { + return username; + } - /** - * Gets the message being sent. - * - * @return The message. - */ - public String getMessage() { - return message; - } + /** + * Gets the message being sent. + * + * @return The message. + */ + public String getMessage() { + return message; + } - /** - * Gets the compressed message. - * - * @return The compressed message. - */ - public byte[] getCompressedMessage() { - return compressedMessage; - } + /** + * Gets the compressed message. + * + * @return The compressed message. + */ + public byte[] getCompressedMessage() { + return compressedMessage; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/RegionChangeEvent.java b/src/org/apollo/game/event/impl/RegionChangeEvent.java index ab818a1a..07f179cf 100644 --- a/src/org/apollo/game/event/impl/RegionChangeEvent.java +++ b/src/org/apollo/game/event/impl/RegionChangeEvent.java @@ -10,27 +10,27 @@ import org.apollo.game.model.Position; */ public final class RegionChangeEvent extends Event { - /** - * The position of the region to load. - */ - private final Position position; + /** + * The position of the region to load. + */ + private final Position position; - /** - * Creates the region changed event. - * - * @param position The position of the region. - */ - public RegionChangeEvent(Position position) { - this.position = position; - } + /** + * Creates the region changed event. + * + * @param position The position of the region. + */ + public RegionChangeEvent(Position position) { + this.position = position; + } - /** - * Gets the position of the region to load. - * - * @return The position of the region to load. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position of the region to load. + * + * @return The position of the region to load. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/RemoveFriendEvent.java b/src/org/apollo/game/event/impl/RemoveFriendEvent.java index 7008c0c9..2919f6fc 100644 --- a/src/org/apollo/game/event/impl/RemoveFriendEvent.java +++ b/src/org/apollo/game/event/impl/RemoveFriendEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class RemoveFriendEvent extends Event { - /** - * The username of the defriended player. - */ - private final String username; + /** + * The username of the defriended player. + */ + private final String username; - /** - * Creates a new defriend user event. - * - * @param username The defriended player's username. - */ - public RemoveFriendEvent(String username) { - this.username = username; - } + /** + * Creates a new defriend user event. + * + * @param username The defriended player's username. + */ + public RemoveFriendEvent(String username) { + this.username = username; + } - /** - * Gets the username of the defriended player. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the defriended player. + * + * @return The username. + */ + public String getUsername() { + return username; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/RemoveIgnoreEvent.java b/src/org/apollo/game/event/impl/RemoveIgnoreEvent.java index a5316fe0..1ddf98a7 100644 --- a/src/org/apollo/game/event/impl/RemoveIgnoreEvent.java +++ b/src/org/apollo/game/event/impl/RemoveIgnoreEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class RemoveIgnoreEvent extends Event { - /** - * The username of the unignored player. - */ - private final String username; + /** + * The username of the unignored player. + */ + private final String username; - /** - * Creates a new unignore player event. - * - * @param username The unignored player's username. - */ - public RemoveIgnoreEvent(String username) { - this.username = username; - } + /** + * Creates a new unignore player event. + * + * @param username The unignored player's username. + */ + public RemoveIgnoreEvent(String username) { + this.username = username; + } - /** - * Gets the username of the unignored player. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the unignored player. + * + * @return The username. + */ + public String getUsername() { + return username; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/RemoveTileItemEvent.java b/src/org/apollo/game/event/impl/RemoveTileItemEvent.java index 82a8a1d5..e65f5b06 100644 --- a/src/org/apollo/game/event/impl/RemoveTileItemEvent.java +++ b/src/org/apollo/game/event/impl/RemoveTileItemEvent.java @@ -9,52 +9,52 @@ import org.apollo.game.event.Event; */ public final class RemoveTileItemEvent extends Event { - /** - * The item. - */ - private final int id; + /** + * The item. + */ + private final int id; - /** - * The offset from the client's base position. - */ - private final int positionOffset; + /** + * The offset from the client's base position. + */ + private final int positionOffset; - /** - * Creates a remove tile item event. - * - * @param id The id of the item to remove. - */ - public RemoveTileItemEvent(int id) { - this(id, 0); - } + /** + * Creates a remove tile item event. + * + * @param id The id of the item to remove. + */ + public RemoveTileItemEvent(int id) { + this(id, 0); + } - /** - * Creates a remove tile item event. - * - * @param id The id of the item to remove. - * @param positionOffset The offset from the 'base' position. - */ - public RemoveTileItemEvent(int id, int positionOffset) { - this.id = id; - this.positionOffset = positionOffset; - } + /** + * Creates a remove tile item event. + * + * @param id The id of the item to remove. + * @param positionOffset The offset from the 'base' position. + */ + public RemoveTileItemEvent(int id, int positionOffset) { + this.id = id; + this.positionOffset = positionOffset; + } - /** - * Gets the id of the item to remove. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the id of the item to remove. + * + * @return The id. + */ + public int getId() { + return id; + } - /** - * Gets the offset from the 'base' position. - * - * @return The offset. - */ - public int getPositionOffset() { - return positionOffset; - } + /** + * Gets the offset from the 'base' position. + * + * @return The offset. + */ + public int getPositionOffset() { + return positionOffset; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SecondItemActionEvent.java b/src/org/apollo/game/event/impl/SecondItemActionEvent.java index dee318fc..178b4bca 100644 --- a/src/org/apollo/game/event/impl/SecondItemActionEvent.java +++ b/src/org/apollo/game/event/impl/SecondItemActionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class SecondItemActionEvent extends ItemActionEvent { - /** - * Creates the second item action event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - */ - public SecondItemActionEvent(int interfaceId, int id, int slot) { - super(2, interfaceId, id, slot); - } + /** + * Creates the second item action event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + */ + public SecondItemActionEvent(int interfaceId, int id, int slot) { + super(2, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SecondItemOptionEvent.java b/src/org/apollo/game/event/impl/SecondItemOptionEvent.java index db4c6e22..6fbd4448 100644 --- a/src/org/apollo/game/event/impl/SecondItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/SecondItemOptionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class SecondItemOptionEvent extends ItemOptionEvent { - /** - * Creates the second item option event. - * - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public SecondItemOptionEvent(int interfaceId, int id, int slot) { - super(2, interfaceId, id, slot); - } + /** + * Creates the second item option event. + * + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public SecondItemOptionEvent(int interfaceId, int id, int slot) { + super(2, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SecondNpcActionEvent.java b/src/org/apollo/game/event/impl/SecondNpcActionEvent.java index 1b2b1703..c031e31e 100644 --- a/src/org/apollo/game/event/impl/SecondNpcActionEvent.java +++ b/src/org/apollo/game/event/impl/SecondNpcActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class SecondNpcActionEvent extends NpcActionEvent { - /** - * Creates a new second npc action event. - * - * @param index The index of the npc. - */ - public SecondNpcActionEvent(int index) { - super(2, index); - } + /** + * Creates a new second npc action event. + * + * @param index The index of the npc. + */ + public SecondNpcActionEvent(int index) { + super(2, index); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SecondObjectActionEvent.java b/src/org/apollo/game/event/impl/SecondObjectActionEvent.java index 85444d9c..138017e7 100644 --- a/src/org/apollo/game/event/impl/SecondObjectActionEvent.java +++ b/src/org/apollo/game/event/impl/SecondObjectActionEvent.java @@ -9,14 +9,14 @@ import org.apollo.game.model.Position; */ public final class SecondObjectActionEvent extends ObjectActionEvent { - /** - * Creates the second object action event. - * - * @param id The id. - * @param position The position. - */ - public SecondObjectActionEvent(int id, Position position) { - super(2, id, position); - } + /** + * Creates the second object action event. + * + * @param id The id. + * @param position The position. + */ + public SecondObjectActionEvent(int id, Position position) { + super(2, id, position); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SecondPlayerActionEvent.java b/src/org/apollo/game/event/impl/SecondPlayerActionEvent.java index 2f481544..33c329c5 100644 --- a/src/org/apollo/game/event/impl/SecondPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/SecondPlayerActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class SecondPlayerActionEvent extends PlayerActionEvent { - /** - * Creates a second player action event. - * - * @param playerIndex The index of the clicked player. - */ - public SecondPlayerActionEvent(int playerIndex) { - super(2, playerIndex); - } + /** + * Creates a second player action event. + * + * @param playerIndex The index of the clicked player. + */ + public SecondPlayerActionEvent(int playerIndex) { + super(2, playerIndex); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SendFriendEvent.java b/src/org/apollo/game/event/impl/SendFriendEvent.java index 8eb886c3..ef27e175 100644 --- a/src/org/apollo/game/event/impl/SendFriendEvent.java +++ b/src/org/apollo/game/event/impl/SendFriendEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class SendFriendEvent extends Event { - /** - * The username of the friend. - */ - private final String username; + /** + * The username of the friend. + */ + private final String username; - /** - * The world id the friend is in. - */ - private final int world; + /** + * The world id the friend is in. + */ + private final int world; - /** - * Creates a new send friend event. - * - * @param username The username of the friend. - * @param world The world the friend is in. - */ - public SendFriendEvent(String username, int world) { - this.username = username; - this.world = world == 0 ? 0 : world + 9; - } + /** + * Creates a new send friend event. + * + * @param username The username of the friend. + * @param world The world the friend is in. + */ + public SendFriendEvent(String username, int world) { + this.username = username; + this.world = world == 0 ? 0 : world + 9; + } - /** - * Gets the username of the friend. - * - * @return The username. - */ - public String getUsername() { - return username; - } + /** + * Gets the username of the friend. + * + * @return The username. + */ + public String getUsername() { + return username; + } - /** - * Gets the world id the friend is in. - * - * @return The world id. - */ - public int getWorld() { - return world; - } + /** + * Gets the world id the friend is in. + * + * @return The world id. + */ + public int getWorld() { + return world; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ServerMessageEvent.java b/src/org/apollo/game/event/impl/ServerMessageEvent.java index 544eb3eb..8e4c75a5 100644 --- a/src/org/apollo/game/event/impl/ServerMessageEvent.java +++ b/src/org/apollo/game/event/impl/ServerMessageEvent.java @@ -9,37 +9,37 @@ import org.apollo.game.event.Event; */ public final class ServerMessageEvent extends Event { - /** - * The message. - */ - private final String message; + /** + * The message. + */ + private final String message; - /** - * Creates a server message event. - * - * @param message The message. - */ - public ServerMessageEvent(String message) { - this(message, false); - } + /** + * Creates a server message event. + * + * @param message The message. + */ + public ServerMessageEvent(String message) { + this(message, false); + } - /** - * Creates a server message event. - * - * @param message The message. - * @param filterable If the message can be filtered. - */ - public ServerMessageEvent(String message, boolean filterable) { - this.message = message + (filterable ? ":filterable:" : ""); - } + /** + * Creates a server message event. + * + * @param message The message. + * @param filterable If the message can be filtered. + */ + public ServerMessageEvent(String message, boolean filterable) { + this.message = message + (filterable ? ":filterable:" : ""); + } - /** - * Gets the message. - * - * @return The message. - */ - public String getMessage() { - return message; - } + /** + * Gets the message. + * + * @return The message. + */ + public String getMessage() { + return message; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetPlayerActionEvent.java b/src/org/apollo/game/event/impl/SetPlayerActionEvent.java index 915a566d..6dad5fd8 100644 --- a/src/org/apollo/game/event/impl/SetPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/SetPlayerActionEvent.java @@ -9,70 +9,70 @@ import org.apollo.game.event.Event; */ public final class SetPlayerActionEvent extends Event { - /** - * This action's text (e.g. "Follow"). - */ - private final String text; + /** + * This action's text (e.g. "Follow"). + */ + private final String text; - /** - * The menu slot this action will occupy. - */ - private final int slot; + /** + * The menu slot this action will occupy. + */ + private final int slot; - /** - * Whether or not this action is the primary action. - */ - private final boolean primaryAction; + /** + * Whether or not this action is the primary action. + */ + private final boolean primaryAction; - /** - * Creates the set player action event. - * - * @param text The action text. - * @param slot The menu slot. - */ - public SetPlayerActionEvent(String text, int slot) { - this(text, slot, false); - } + /** + * Creates the set player action event. + * + * @param text The action text. + * @param slot The menu slot. + */ + public SetPlayerActionEvent(String text, int slot) { + this(text, slot, false); + } - /** - * Creates the set player action event. - * - * @param text The action text. - * @param slot The menu slot. - * @param primaryInteraction Whether or not the action is the primary action. - */ - public SetPlayerActionEvent(String text, int slot, boolean primaryInteraction) { - this.text = text; - this.slot = slot; - this.primaryAction = primaryInteraction; - } + /** + * Creates the set player action event. + * + * @param text The action text. + * @param slot The menu slot. + * @param primaryInteraction Whether or not the action is the primary action. + */ + public SetPlayerActionEvent(String text, int slot, boolean primaryInteraction) { + this.text = text; + this.slot = slot; + this.primaryAction = primaryInteraction; + } - /** - * Gets the action text. - * - * @return The text. - */ - public String getText() { - return text; - } + /** + * Gets the action text. + * + * @return The text. + */ + public String getText() { + return text; + } - /** - * Gets the menu slot this action occupies. - * - * @return The slot. - */ - public int getSlot() { - return slot; - } + /** + * Gets the menu slot this action occupies. + * + * @return The slot. + */ + public int getSlot() { + return slot; + } - /** - * Whether or not this action is the primary one (i.e. should be displayed when the player hovers over the other - * player). - * - * @return {@code true} if this action is the primary action, {@code false} if not. - */ - public boolean isPrimaryAction() { - return primaryAction; - } + /** + * Whether or not this action is the primary one (i.e. should be displayed when the player hovers over the other + * player). + * + * @return {@code true} if this action is the primary action, {@code false} if not. + */ + public boolean isPrimaryAction() { + return primaryAction; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetItemModelEvent.java b/src/org/apollo/game/event/impl/SetWidgetItemModelEvent.java index 1cff80c9..a72312b8 100644 --- a/src/org/apollo/game/event/impl/SetWidgetItemModelEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetItemModelEvent.java @@ -9,59 +9,59 @@ import org.apollo.game.event.Event; */ public final class SetWidgetItemModelEvent extends Event { - /** - * The interface's id. - */ - private final int interfaceId; + /** + * The interface's id. + */ + private final int interfaceId; - /** - * The model's (item) id. - */ - private final int modelId; + /** + * The model's (item) id. + */ + private final int modelId; - /** - * The zoom level. - */ - private final int zoom; + /** + * The zoom level. + */ + private final int zoom; - /** - * Creates a new set interface item model event. - * - * @param interfaceId The interface's id. - * @param modelId The model's (item) id. - * @param zoom The zoom level. - */ - public SetWidgetItemModelEvent(int interfaceId, int modelId, int zoom) { - this.interfaceId = interfaceId; - this.modelId = modelId; - this.zoom = zoom; - } + /** + * Creates a new set interface item model event. + * + * @param interfaceId The interface's id. + * @param modelId The model's (item) id. + * @param zoom The zoom level. + */ + public SetWidgetItemModelEvent(int interfaceId, int modelId, int zoom) { + this.interfaceId = interfaceId; + this.modelId = modelId; + this.zoom = zoom; + } - /** - * Gets the interface's id. - * - * @return The id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface's id. + * + * @return The id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the model's (item) id. - * - * @return The id. - */ - public int getModelId() { - return modelId; - } + /** + * Gets the model's (item) id. + * + * @return The id. + */ + public int getModelId() { + return modelId; + } - /** - * Gets the zoom level. - * - * @return The zoom. - */ - public int getZoom() { - return zoom; - } + /** + * Gets the zoom level. + * + * @return The zoom. + */ + public int getZoom() { + return zoom; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetModelAnimationEvent.java b/src/org/apollo/game/event/impl/SetWidgetModelAnimationEvent.java index de6e1a7c..aae8342a 100644 --- a/src/org/apollo/game/event/impl/SetWidgetModelAnimationEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetModelAnimationEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class SetWidgetModelAnimationEvent extends Event { - /** - * The model's animation id. - */ - private final int animation; + /** + * The model's animation id. + */ + private final int animation; - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * Creates a new set interface npc model's animation event. - * - * @param interfaceId The interface id. - * @param animation The model's animation id. - */ - public SetWidgetModelAnimationEvent(int interfaceId, int animation) { - this.interfaceId = interfaceId; - this.animation = animation; - } + /** + * Creates a new set interface npc model's animation event. + * + * @param interfaceId The interface id. + * @param animation The model's animation id. + */ + public SetWidgetModelAnimationEvent(int interfaceId, int animation) { + this.interfaceId = interfaceId; + this.animation = animation; + } - /** - * Gets the model's mood id. - * - * @return The model's mood id. - */ - public int getAnimation() { - return animation; - } + /** + * Gets the model's mood id. + * + * @return The model's mood id. + */ + public int getAnimation() { + return animation; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetNpcModelEvent.java b/src/org/apollo/game/event/impl/SetWidgetNpcModelEvent.java index 0b36069f..f4f0bd62 100644 --- a/src/org/apollo/game/event/impl/SetWidgetNpcModelEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetNpcModelEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class SetWidgetNpcModelEvent extends Event { - /** - * The interface's id. - */ - private final int interfaceId; + /** + * The interface's id. + */ + private final int interfaceId; - /** - * The model's (NPC) id. - */ - private final int modelId; + /** + * The model's (NPC) id. + */ + private final int modelId; - /** - * Creates a new set interface NPC model event. - * - * @param interfaceId The interface's id. - * @param modelId The model's (NPC) id. - */ - public SetWidgetNpcModelEvent(int interfaceId, int modelId) { - this.interfaceId = interfaceId; - this.modelId = modelId; - } + /** + * Creates a new set interface NPC model event. + * + * @param interfaceId The interface's id. + * @param modelId The model's (NPC) id. + */ + public SetWidgetNpcModelEvent(int interfaceId, int modelId) { + this.interfaceId = interfaceId; + this.modelId = modelId; + } - /** - * Gets the interface's id. - * - * @return The id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface's id. + * + * @return The id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the model's (NPC) id. - * - * @return The id. - */ - public int getModelId() { - return modelId; - } + /** + * Gets the model's (NPC) id. + * + * @return The id. + */ + public int getModelId() { + return modelId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetPlayerModelEvent.java b/src/org/apollo/game/event/impl/SetWidgetPlayerModelEvent.java index 4d12a771..bcab4a92 100644 --- a/src/org/apollo/game/event/impl/SetWidgetPlayerModelEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetPlayerModelEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class SetWidgetPlayerModelEvent extends Event { - /** - * The interface's id. - */ - private final int interfaceId; + /** + * The interface's id. + */ + private final int interfaceId; - /** - * Creates a new set interface player model event. - * - * @param interfaceId The interface's id. - */ - public SetWidgetPlayerModelEvent(int interfaceId) { - this.interfaceId = interfaceId; - } + /** + * Creates a new set interface player model event. + * + * @param interfaceId The interface's id. + */ + public SetWidgetPlayerModelEvent(int interfaceId) { + this.interfaceId = interfaceId; + } - /** - * Gets the interface's id. - * - * @return The id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface's id. + * + * @return The id. + */ + public int getInterfaceId() { + return interfaceId; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetTextEvent.java b/src/org/apollo/game/event/impl/SetWidgetTextEvent.java index 33f5027c..4f77ac24 100644 --- a/src/org/apollo/game/event/impl/SetWidgetTextEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetTextEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class SetWidgetTextEvent extends Event { - /** - * The interface's id. - */ - private final int interfaceId; + /** + * The interface's id. + */ + private final int interfaceId; - /** - * The text. - */ - private final String text; + /** + * The text. + */ + private final String text; - /** - * Creates the set interface text event. - * - * @param interfaceId The interface's id. - * @param text The interface's text. - */ - public SetWidgetTextEvent(int interfaceId, String text) { - this.interfaceId = interfaceId; - this.text = text; - } + /** + * Creates the set interface text event. + * + * @param interfaceId The interface's id. + * @param text The interface's text. + */ + public SetWidgetTextEvent(int interfaceId, String text) { + this.interfaceId = interfaceId; + this.text = text; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the interface's text. - * - * @return The interface's text. - */ - public String getText() { - return text; - } + /** + * Gets the interface's text. + * + * @return The interface's text. + */ + public String getText() { + return text; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SetWidgetVisibilityEvent.java b/src/org/apollo/game/event/impl/SetWidgetVisibilityEvent.java index 8889a9f7..3f6a172a 100644 --- a/src/org/apollo/game/event/impl/SetWidgetVisibilityEvent.java +++ b/src/org/apollo/game/event/impl/SetWidgetVisibilityEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.event.Event; */ public final class SetWidgetVisibilityEvent extends Event { - /** - * The component id. - */ - private final int component; + /** + * The component id. + */ + private final int component; - /** - * Visible flag. - */ - private final boolean visible; + /** + * Visible flag. + */ + private final boolean visible; - /** - * Creates the interface component state event. - * - * @param component The compononent id. - * @param visible The flag for showing or hiding the component. - */ - public SetWidgetVisibilityEvent(int component, boolean visible) { - this.component = component; - this.visible = visible; - } + /** + * Creates the interface component state event. + * + * @param component The compononent id. + * @param visible The flag for showing or hiding the component. + */ + public SetWidgetVisibilityEvent(int component, boolean visible) { + this.component = component; + this.visible = visible; + } - /** - * Gets the id of the interface component. - * - * @return The component id. - */ - public int getWidgetId() { - return component; - } + /** + * Gets the id of the interface component. + * + * @return The component id. + */ + public int getWidgetId() { + return component; + } - /** - * Gets the visible flag. - * - * @return {@code true} if the component has been set to visible, {@code false} if not. - */ - public boolean isVisible() { - return visible; - } + /** + * Gets the visible flag. + * + * @return {@code true} if the component has been set to visible, {@code false} if not. + */ + public boolean isVisible() { + return visible; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SpamPacketEvent.java b/src/org/apollo/game/event/impl/SpamPacketEvent.java index 84e1cdd7..892cbfb7 100644 --- a/src/org/apollo/game/event/impl/SpamPacketEvent.java +++ b/src/org/apollo/game/event/impl/SpamPacketEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class SpamPacketEvent extends Event { - /** - * Data sent by the spam packet. - */ - private final byte[] data; + /** + * Data sent by the spam packet. + */ + private final byte[] data; - /** - * Creates a new spam packet event. - * - * @param data The data sent. - */ - public SpamPacketEvent(byte[] data) { - this.data = data; - } + /** + * Creates a new spam packet event. + * + * @param data The data sent. + */ + public SpamPacketEvent(byte[] data) { + this.data = data; + } - /** - * Gets the data sent. - * - * @return The data. - */ - public byte[] getData() { - return data; - } + /** + * Gets the data sent. + * + * @return The data. + */ + public byte[] getData() { + return data; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SwitchItemEvent.java b/src/org/apollo/game/event/impl/SwitchItemEvent.java index 7b8d991e..ddb63491 100644 --- a/src/org/apollo/game/event/impl/SwitchItemEvent.java +++ b/src/org/apollo/game/event/impl/SwitchItemEvent.java @@ -9,84 +9,84 @@ import org.apollo.game.event.Event; */ public final class SwitchItemEvent extends Event { - /** - * A flag indicating if insertion mode is enabled. - */ - private final boolean inserting; + /** + * A flag indicating if insertion mode is enabled. + */ + private final boolean inserting; - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The new slot. - */ - private final int newSlot; + /** + * The new slot. + */ + private final int newSlot; - /** - * The old slot. - */ - private final int oldSlot; + /** + * The old slot. + */ + private final int oldSlot; - /** - * Creates a new switch item event. - * - * @param interfaceId The interface id. - * @param inserting A flag indicating if the interface is in 'insert' mode instead of swap mode. - * @param oldSlot The old slot. - * @param newSlot The new slot. - */ - public SwitchItemEvent(int interfaceId, boolean inserting, int oldSlot, int newSlot) { - this.interfaceId = interfaceId; - this.inserting = inserting; - this.oldSlot = oldSlot; - this.newSlot = newSlot; - } + /** + * Creates a new switch item event. + * + * @param interfaceId The interface id. + * @param inserting A flag indicating if the interface is in 'insert' mode instead of swap mode. + * @param oldSlot The old slot. + * @param newSlot The new slot. + */ + public SwitchItemEvent(int interfaceId, boolean inserting, int oldSlot, int newSlot) { + this.interfaceId = interfaceId; + this.inserting = inserting; + this.oldSlot = oldSlot; + this.newSlot = newSlot; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the new slot. - * - * @return The new slot. - */ - public int getNewSlot() { - return newSlot; - } + /** + * Gets the new slot. + * + * @return The new slot. + */ + public int getNewSlot() { + return newSlot; + } - /** - * Gets the old slot. - * - * @return The old slot. - */ - public int getOldSlot() { - return oldSlot; - } + /** + * Gets the old slot. + * + * @return The old slot. + */ + public int getOldSlot() { + return oldSlot; + } - /** - * Checks if this event is in insertion mode. - * - * @return The insertion flag. - */ - public boolean isInserting() { - return inserting; - } + /** + * Checks if this event is in insertion mode. + * + * @return The insertion flag. + */ + public boolean isInserting() { + return inserting; + } - /** - * Checks if this event is in swap mode. - * - * @return The swap flag. - */ - public boolean isSwapping() { - return !inserting; - } + /** + * Checks if this event is in swap mode. + * + * @return The swap flag. + */ + public boolean isSwapping() { + return !inserting; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/SwitchTabInterfaceEvent.java b/src/org/apollo/game/event/impl/SwitchTabInterfaceEvent.java index 9801a5e7..7ae393a2 100644 --- a/src/org/apollo/game/event/impl/SwitchTabInterfaceEvent.java +++ b/src/org/apollo/game/event/impl/SwitchTabInterfaceEvent.java @@ -9,43 +9,43 @@ import org.apollo.game.event.Event; */ public final class SwitchTabInterfaceEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The tab id. - */ - private final int tab; + /** + * The tab id. + */ + private final int tab; - /** - * Creates the switch interface event. - * - * @param tab The tab id. - * @param interfaceId The interface id. - */ - public SwitchTabInterfaceEvent(int tab, int interfaceId) { - this.tab = tab; - this.interfaceId = interfaceId; - } + /** + * Creates the switch interface event. + * + * @param tab The tab id. + * @param interfaceId The interface id. + */ + public SwitchTabInterfaceEvent(int tab, int interfaceId) { + this.tab = tab; + this.interfaceId = interfaceId; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the tab id. - * - * @return The tab id. - */ - public int getTabId() { - return tab; - } + /** + * Gets the tab id. + * + * @return The tab id. + */ + public int getTabId() { + return tab; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/TakeTileItemEvent.java b/src/org/apollo/game/event/impl/TakeTileItemEvent.java index 7643e13d..bb00ad7d 100644 --- a/src/org/apollo/game/event/impl/TakeTileItemEvent.java +++ b/src/org/apollo/game/event/impl/TakeTileItemEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.model.Position; */ public final class TakeTileItemEvent extends Event { - /** - * The id of the item. - */ - private final int id; + /** + * The id of the item. + */ + private final int id; - /** - * The position of the tile. - */ - private final Position position; + /** + * The position of the tile. + */ + private final Position position; - /** - * Creates a new take tile item event. - * - * @param id The id of the item. - * @param position The position of the tile. - */ - public TakeTileItemEvent(int id, Position position) { - this.id = id; - this.position = position; - } + /** + * Creates a new take tile item event. + * + * @param id The id of the item. + * @param position The position of the tile. + */ + public TakeTileItemEvent(int id, Position position) { + this.id = id; + this.position = position; + } - /** - * Gets the id of the item. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the id of the item. + * + * @return The id. + */ + public int getId() { + return id; + } - /** - * Gets the position of the tile. - * - * @return The position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position of the tile. + * + * @return The position. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ThirdItemActionEvent.java b/src/org/apollo/game/event/impl/ThirdItemActionEvent.java index f04e6138..d5e8a6c4 100644 --- a/src/org/apollo/game/event/impl/ThirdItemActionEvent.java +++ b/src/org/apollo/game/event/impl/ThirdItemActionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class ThirdItemActionEvent extends ItemActionEvent { - /** - * Creates the third item action event. - * - * @param interfaceId The interface id. - * @param id The item id. - * @param slot The item slot. - */ - public ThirdItemActionEvent(int interfaceId, int id, int slot) { - super(3, interfaceId, id, slot); - } + /** + * Creates the third item action event. + * + * @param interfaceId The interface id. + * @param id The item id. + * @param slot The item slot. + */ + public ThirdItemActionEvent(int interfaceId, int id, int slot) { + super(3, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ThirdItemOptionEvent.java b/src/org/apollo/game/event/impl/ThirdItemOptionEvent.java index f474ca27..97674f45 100644 --- a/src/org/apollo/game/event/impl/ThirdItemOptionEvent.java +++ b/src/org/apollo/game/event/impl/ThirdItemOptionEvent.java @@ -7,15 +7,15 @@ package org.apollo.game.event.impl; */ public final class ThirdItemOptionEvent extends ItemOptionEvent { - /** - * Creates the third item option event. - * - * @param interfaceId The interface id. - * @param id The id. - * @param slot The slot. - */ - public ThirdItemOptionEvent(int interfaceId, int id, int slot) { - super(3, interfaceId, id, slot); - } + /** + * Creates the third item option event. + * + * @param interfaceId The interface id. + * @param id The id. + * @param slot The slot. + */ + public ThirdItemOptionEvent(int interfaceId, int id, int slot) { + super(3, interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ThirdNpcActionEvent.java b/src/org/apollo/game/event/impl/ThirdNpcActionEvent.java index 27c7f93d..401ed109 100644 --- a/src/org/apollo/game/event/impl/ThirdNpcActionEvent.java +++ b/src/org/apollo/game/event/impl/ThirdNpcActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class ThirdNpcActionEvent extends NpcActionEvent { - /** - * Creates a new third npc action event. - * - * @param index The index of the npc. - */ - public ThirdNpcActionEvent(int index) { - super(3, index); - } + /** + * Creates a new third npc action event. + * + * @param index The index of the npc. + */ + public ThirdNpcActionEvent(int index) { + super(3, index); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ThirdObjectActionEvent.java b/src/org/apollo/game/event/impl/ThirdObjectActionEvent.java index c759aa50..742a2f2e 100644 --- a/src/org/apollo/game/event/impl/ThirdObjectActionEvent.java +++ b/src/org/apollo/game/event/impl/ThirdObjectActionEvent.java @@ -9,14 +9,14 @@ import org.apollo.game.model.Position; */ public final class ThirdObjectActionEvent extends ObjectActionEvent { - /** - * Creates the third object action event. - * - * @param id The id. - * @param position The position. - */ - public ThirdObjectActionEvent(int id, Position position) { - super(3, id, position); - } + /** + * Creates the third object action event. + * + * @param id The id. + * @param position The position. + */ + public ThirdObjectActionEvent(int id, Position position) { + super(3, id, position); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/ThirdPlayerActionEvent.java b/src/org/apollo/game/event/impl/ThirdPlayerActionEvent.java index b68ace5e..d5ee620a 100644 --- a/src/org/apollo/game/event/impl/ThirdPlayerActionEvent.java +++ b/src/org/apollo/game/event/impl/ThirdPlayerActionEvent.java @@ -7,13 +7,13 @@ package org.apollo.game.event.impl; */ public final class ThirdPlayerActionEvent extends PlayerActionEvent { - /** - * Creates a third player action event. - * - * @param playerIndex The index of the clicked player. - */ - public ThirdPlayerActionEvent(int playerIndex) { - super(3, playerIndex); - } + /** + * Creates a third player action event. + * + * @param playerIndex The index of the clicked player. + */ + public ThirdPlayerActionEvent(int playerIndex) { + super(3, playerIndex); + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateItemsEvent.java b/src/org/apollo/game/event/impl/UpdateItemsEvent.java index fe18b877..24b5b4e6 100644 --- a/src/org/apollo/game/event/impl/UpdateItemsEvent.java +++ b/src/org/apollo/game/event/impl/UpdateItemsEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.model.Item; */ public final class UpdateItemsEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The items. - */ - private final Item[] items; + /** + * The items. + */ + private final Item[] items; - /** - * Creates the update inventory interface event. - * - * @param interfaceId The interface id. - * @param items The items. - */ - public UpdateItemsEvent(int interfaceId, Item[] items) { - this.interfaceId = interfaceId; - this.items = items; - } + /** + * Creates the update inventory interface event. + * + * @param interfaceId The interface id. + * @param items The items. + */ + public UpdateItemsEvent(int interfaceId, Item[] items) { + this.interfaceId = interfaceId; + this.items = items; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets the items. - * - * @return The items. - */ - public Item[] getItems() { - return items; - } + /** + * Gets the items. + * + * @return The items. + */ + public Item[] getItems() { + return items; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateRunEnergyEvent.java b/src/org/apollo/game/event/impl/UpdateRunEnergyEvent.java index ea5187e2..9784fd4d 100644 --- a/src/org/apollo/game/event/impl/UpdateRunEnergyEvent.java +++ b/src/org/apollo/game/event/impl/UpdateRunEnergyEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class UpdateRunEnergyEvent extends Event { - /** - * The run energy. - */ - private final int energy; + /** + * The run energy. + */ + private final int energy; - /** - * Creates a new update run energy event. - * - * @param energy The energy. - */ - public UpdateRunEnergyEvent(int energy) { - this.energy = energy; - } + /** + * Creates a new update run energy event. + * + * @param energy The energy. + */ + public UpdateRunEnergyEvent(int energy) { + this.energy = energy; + } - /** - * Gets the amount of run energy. - * - * @return The energy. - */ - public int getEnergy() { - return energy; - } + /** + * Gets the amount of run energy. + * + * @return The energy. + */ + public int getEnergy() { + return energy; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateSkillEvent.java b/src/org/apollo/game/event/impl/UpdateSkillEvent.java index e4d2e249..5349bf86 100644 --- a/src/org/apollo/game/event/impl/UpdateSkillEvent.java +++ b/src/org/apollo/game/event/impl/UpdateSkillEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.model.entity.Skill; */ public final class UpdateSkillEvent extends Event { - /** - * The skill's id. - */ - private final int id; + /** + * The skill's id. + */ + private final int id; - /** - * The skill. - */ - private final Skill skill; + /** + * The skill. + */ + private final Skill skill; - /** - * Creates an update skill event. - * - * @param id The id. - * @param skill The skill. - */ - public UpdateSkillEvent(int id, Skill skill) { - this.id = id; - this.skill = skill; - } + /** + * Creates an update skill event. + * + * @param id The id. + * @param skill The skill. + */ + public UpdateSkillEvent(int id, Skill skill) { + this.id = id; + this.skill = skill; + } - /** - * Gets the skill's id. - * - * @return The skill's id. - */ - public int getId() { - return id; - } + /** + * Gets the skill's id. + * + * @return The skill's id. + */ + public int getId() { + return id; + } - /** - * Gets the skill. - * - * @return The skill. - */ - public Skill getSkill() { - return skill; - } + /** + * Gets the skill. + * + * @return The skill. + */ + public Skill getSkill() { + return skill; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateSlottedItemsEvent.java b/src/org/apollo/game/event/impl/UpdateSlottedItemsEvent.java index 49554791..62699bcf 100644 --- a/src/org/apollo/game/event/impl/UpdateSlottedItemsEvent.java +++ b/src/org/apollo/game/event/impl/UpdateSlottedItemsEvent.java @@ -10,43 +10,43 @@ import org.apollo.game.model.inv.SlottedItem; */ public final class UpdateSlottedItemsEvent extends Event { - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The slotted items. - */ - private final SlottedItem[] items; + /** + * The slotted items. + */ + private final SlottedItem[] items; - /** - * Creates the update item in interface event. - * - * @param interfaceId The interface id. - * @param items The slotted items. - */ - public UpdateSlottedItemsEvent(int interfaceId, SlottedItem... items) { - this.interfaceId = interfaceId; - this.items = items; - } + /** + * Creates the update item in interface event. + * + * @param interfaceId The interface id. + * @param items The slotted items. + */ + public UpdateSlottedItemsEvent(int interfaceId, SlottedItem... items) { + this.interfaceId = interfaceId; + this.items = items; + } - /** - * Gets the interface id. - * - * @return The interface id. - */ - public int getInterfaceId() { - return interfaceId; - } + /** + * Gets the interface id. + * + * @return The interface id. + */ + public int getInterfaceId() { + return interfaceId; + } - /** - * Gets an array of slotted items. - * - * @return The slotted items. - */ - public SlottedItem[] getSlottedItems() { - return items; - } + /** + * Gets an array of slotted items. + * + * @return The slotted items. + */ + public SlottedItem[] getSlottedItems() { + return items; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateTileItemEvent.java b/src/org/apollo/game/event/impl/UpdateTileItemEvent.java index 574a9103..022105cb 100644 --- a/src/org/apollo/game/event/impl/UpdateTileItemEvent.java +++ b/src/org/apollo/game/event/impl/UpdateTileItemEvent.java @@ -10,78 +10,78 @@ import org.apollo.game.model.Item; */ public final class UpdateTileItemEvent extends Event { - /** - * The {@link Item}. - */ - private final Item item; + /** + * The {@link Item}. + */ + private final Item item; - /** - * The offset from the client's base position. - */ - private final int positionOffset; + /** + * The offset from the client's base position. + */ + private final int positionOffset; - /** - * The previous amount of the item (if it is being updated). - */ - private final int previousAmount; + /** + * The previous amount of the item (if it is being updated). + */ + private final int previousAmount; - /** - * Creates a new event that updates the previous amount of the item. - * - * @param id The item to be placed. - * @param previousAmount The previous amount of the item. - */ - public UpdateTileItemEvent(Item item, int previousAmount) { - this(item, previousAmount, 0); - } + /** + * Creates a new event that updates the previous amount of the item. + * + * @param id The item to be placed. + * @param previousAmount The previous amount of the item. + */ + public UpdateTileItemEvent(Item item, int previousAmount) { + this(item, previousAmount, 0); + } - /** - * Creates a new set tile item event. - * - * @param id The item to be placed. - * @param previousAmount The previous amount of the item. - * @param positionOffset The offset from the client's base position. - */ - public UpdateTileItemEvent(Item item, int previousAmount, int positionOffset) { - this.item = item; - this.previousAmount = previousAmount; - this.positionOffset = positionOffset; - } + /** + * Creates a new set tile item event. + * + * @param id The item to be placed. + * @param previousAmount The previous amount of the item. + * @param positionOffset The offset from the client's base position. + */ + public UpdateTileItemEvent(Item item, int previousAmount, int positionOffset) { + this.item = item; + this.previousAmount = previousAmount; + this.positionOffset = positionOffset; + } - /** - * Gets the amount of the item. - * - * @return The amount. - */ - public int getAmount() { - return item.getAmount(); - } + /** + * Gets the amount of the item. + * + * @return The amount. + */ + public int getAmount() { + return item.getAmount(); + } - /** - * Gets the id of the item. - * - * @return The item. - */ - public int getId() { - return item.getId(); - } + /** + * Gets the id of the item. + * + * @return The item. + */ + public int getId() { + return item.getId(); + } - /** - * Gets the offset from the client's base position. - * - * @return The offset. - */ - public int getPositionOffset() { - return positionOffset; - } + /** + * Gets the offset from the client's base position. + * + * @return The offset. + */ + public int getPositionOffset() { + return positionOffset; + } - /** - * Gets the previous amount of the item. - * - * @return The previous amount. - */ - public int getPreviousAmount() { - return previousAmount; - } + /** + * Gets the previous amount of the item. + * + * @return The previous amount. + */ + public int getPreviousAmount() { + return previousAmount; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/UpdateWeightEvent.java b/src/org/apollo/game/event/impl/UpdateWeightEvent.java index cdec011e..d5397986 100644 --- a/src/org/apollo/game/event/impl/UpdateWeightEvent.java +++ b/src/org/apollo/game/event/impl/UpdateWeightEvent.java @@ -9,27 +9,27 @@ import org.apollo.game.event.Event; */ public final class UpdateWeightEvent extends Event { - /** - * The weight of the player - */ - private final int weight; + /** + * The weight of the player + */ + private final int weight; - /** - * Creates the update weight event. - * - * @param weight The weight of the player. - */ - public UpdateWeightEvent(int weight) { - this.weight = weight; - } + /** + * Creates the update weight event. + * + * @param weight The weight of the player. + */ + public UpdateWeightEvent(int weight) { + this.weight = weight; + } - /** - * Gets the weight of the player. - * - * @return The weight. - */ - public int getWeight() { - return weight; - } + /** + * Gets the weight of the player. + * + * @return The weight. + */ + public int getWeight() { + return weight; + } } \ No newline at end of file diff --git a/src/org/apollo/game/event/impl/WalkEvent.java b/src/org/apollo/game/event/impl/WalkEvent.java index 1055d2b6..378334ee 100644 --- a/src/org/apollo/game/event/impl/WalkEvent.java +++ b/src/org/apollo/game/event/impl/WalkEvent.java @@ -10,46 +10,46 @@ import org.apollo.game.model.Position; */ public final class WalkEvent extends Event { - /** - * The running flag. - */ - private boolean run; + /** + * The running flag. + */ + private boolean run; - /** - * The steps. - */ - private final Position[] steps; + /** + * The steps. + */ + private final Position[] steps; - /** - * Creates the event. - * - * @param steps The steps array. - * @param run The run flag. - */ - public WalkEvent(Position[] steps, boolean run) { - if (steps.length < 0) { - throw new IllegalArgumentException("Number of steps must not be negative."); - } - this.steps = steps; - this.run = run; + /** + * Creates the event. + * + * @param steps The steps array. + * @param run The run flag. + */ + public WalkEvent(Position[] steps, boolean run) { + if (steps.length < 0) { + throw new IllegalArgumentException("Number of steps must not be negative."); } + this.steps = steps; + this.run = run; + } - /** - * Gets the steps array. - * - * @return An array of steps. - */ - public Position[] getSteps() { - return steps; - } + /** + * Gets the steps array. + * + * @return An array of steps. + */ + public Position[] getSteps() { + return steps; + } - /** - * Checks if the steps should be ran (ctrl+click). - * - * @return {@code true} if so, {@code false} otherwise. - */ - public boolean isRunning() { - return run; - } + /** + * Checks if the steps should be ran (ctrl+click). + * + * @return {@code true} if so, {@code false} otherwise. + */ + public boolean isRunning() { + return run; + } } \ No newline at end of file diff --git a/src/org/apollo/game/login/LoginDispatcher.java b/src/org/apollo/game/login/LoginDispatcher.java index 878fd9c8..7b9e1a52 100644 --- a/src/org/apollo/game/login/LoginDispatcher.java +++ b/src/org/apollo/game/login/LoginDispatcher.java @@ -12,29 +12,29 @@ import org.apollo.game.model.entity.Player; */ public final class LoginDispatcher { - /** - * A {@link List} of login listeners. - */ - private List listeners = new ArrayList<>(); + /** + * A {@link List} of login listeners. + */ + private List listeners = new ArrayList<>(); - /** - * Dispatches a player to the appropriate login listener. - * - * @param player The player. - */ - public void dispatch(Player player) { - for (LoginListener listener : listeners) { - listener.execute(player); - } + /** + * Dispatches a player to the appropriate login listener. + * + * @param player The player. + */ + public void dispatch(Player player) { + for (LoginListener listener : listeners) { + listener.execute(player); } + } - /** - * Registers a listener with this dispatcher. - * - * @param listener The listener. - */ - public void register(LoginListener listener) { - listeners.add(listener); - } + /** + * Registers a listener with this dispatcher. + * + * @param listener The listener. + */ + public void register(LoginListener listener) { + listeners.add(listener); + } } \ No newline at end of file diff --git a/src/org/apollo/game/login/LoginListener.java b/src/org/apollo/game/login/LoginListener.java index 5fcc2ea4..de21d06f 100644 --- a/src/org/apollo/game/login/LoginListener.java +++ b/src/org/apollo/game/login/LoginListener.java @@ -10,11 +10,11 @@ import org.apollo.game.model.entity.Player; @FunctionalInterface public interface LoginListener { - /** - * Executes the action for this listener. - * - * @param player The player. - */ - public abstract void execute(Player player); + /** + * Executes the action for this listener. + * + * @param player The player. + */ + public abstract void execute(Player player); } \ No newline at end of file diff --git a/src/org/apollo/game/login/LogoutDispatcher.java b/src/org/apollo/game/login/LogoutDispatcher.java index c7a5e3f8..4e6edf6a 100644 --- a/src/org/apollo/game/login/LogoutDispatcher.java +++ b/src/org/apollo/game/login/LogoutDispatcher.java @@ -12,29 +12,29 @@ import org.apollo.game.model.entity.Player; */ public final class LogoutDispatcher { - /** - * A {@link List} of logout listeners. - */ - private List listeners = new ArrayList<>(); + /** + * A {@link List} of logout listeners. + */ + private List listeners = new ArrayList<>(); - /** - * Dispatches a player to the appropriate logout listener. - * - * @param player The player. - */ - public void dispatch(Player player) { - for (LogoutListener listen : listeners) { - listen.execute(player); - } + /** + * Dispatches a player to the appropriate logout listener. + * + * @param player The player. + */ + public void dispatch(Player player) { + for (LogoutListener listen : listeners) { + listen.execute(player); } + } - /** - * Registers a listener with this dispatcher. - * - * @param listener The listener. - */ - public void register(LogoutListener listener) { - listeners.add(listener); - } + /** + * Registers a listener with this dispatcher. + * + * @param listener The listener. + */ + public void register(LogoutListener listener) { + listeners.add(listener); + } } diff --git a/src/org/apollo/game/login/LogoutListener.java b/src/org/apollo/game/login/LogoutListener.java index 8a67f5ee..6b7414be 100644 --- a/src/org/apollo/game/login/LogoutListener.java +++ b/src/org/apollo/game/login/LogoutListener.java @@ -10,11 +10,11 @@ import org.apollo.game.model.entity.Player; @FunctionalInterface public interface LogoutListener { - /** - * Executes the action for this listener. - * - * @param player The player. - */ - public abstract void execute(Player player); + /** + * Executes the action for this listener. + * + * @param player The player. + */ + public abstract void execute(Player player); } \ No newline at end of file diff --git a/src/org/apollo/game/model/Animation.java b/src/org/apollo/game/model/Animation.java index a648d93b..177dcfcd 100644 --- a/src/org/apollo/game/model/Animation.java +++ b/src/org/apollo/game/model/Animation.java @@ -7,197 +7,197 @@ package org.apollo.game.model; */ public final class Animation { - /** - * The angry animation. - */ - public static final Animation ANGRY = new Animation(859); + /** + * The angry animation. + */ + public static final Animation ANGRY = new Animation(859); - /** - * The beckon animation. - */ - public static final Animation BECKON = new Animation(864); + /** + * The beckon animation. + */ + public static final Animation BECKON = new Animation(864); - /** - * The blow kiss animation. - */ - public static final Animation BLOW_KISS = new Animation(1368); + /** + * The blow kiss animation. + */ + public static final Animation BLOW_KISS = new Animation(1368); - /** - * The bow animation. - */ - public static final Animation BOW = new Animation(858); + /** + * The bow animation. + */ + public static final Animation BOW = new Animation(858); - /** - * The cheer animation. - */ - public static final Animation CHEER = new Animation(862); + /** + * The cheer animation. + */ + public static final Animation CHEER = new Animation(862); - /** - * The clap animation. - */ - public static final Animation CLAP = new Animation(865); + /** + * The clap animation. + */ + public static final Animation CLAP = new Animation(865); - /** - * The climb rope animation. - */ - public static final Animation CLIMB_ROPE = new Animation(1130); + /** + * The climb rope animation. + */ + public static final Animation CLIMB_ROPE = new Animation(1130); - /** - * The cry animation. - */ - public static final Animation CRY = new Animation(860); + /** + * The cry animation. + */ + public static final Animation CRY = new Animation(860); - /** - * The dance animation. - */ - public static final Animation DANCE = new Animation(866); + /** + * The dance animation. + */ + public static final Animation DANCE = new Animation(866); - /** - * The glass box animation. - */ - public static final Animation GLASS_BOX = new Animation(1131); + /** + * The glass box animation. + */ + public static final Animation GLASS_BOX = new Animation(1131); - /** - * The glass wall animation. - */ - public static final Animation GLASS_WALL = new Animation(1128); + /** + * The glass wall animation. + */ + public static final Animation GLASS_WALL = new Animation(1128); - /** - * The goblin bow animation. - */ - public static final Animation GOBLIN_BOW = new Animation(2127); + /** + * The goblin bow animation. + */ + public static final Animation GOBLIN_BOW = new Animation(2127); - /** - * The goblin dance animation. - */ - public static final Animation GOBLIN_DANCE = new Animation(2128); + /** + * The goblin dance animation. + */ + public static final Animation GOBLIN_DANCE = new Animation(2128); - /** - * The head bang animation. - */ - public static final Animation HEAD_BANG = new Animation(2108); + /** + * The head bang animation. + */ + public static final Animation HEAD_BANG = new Animation(2108); - /** - * The jig animation. - */ - public static final Animation JIG = new Animation(2106); + /** + * The jig animation. + */ + public static final Animation JIG = new Animation(2106); - /** - * The joy jump animation. - */ - public static final Animation JOY_JUMP = new Animation(2109); + /** + * The joy jump animation. + */ + public static final Animation JOY_JUMP = new Animation(2109); - /** - * The laugh animation. - */ - public static final Animation LAUGH = new Animation(861); + /** + * The laugh animation. + */ + public static final Animation LAUGH = new Animation(861); - /** - * The lean animation. - */ - public static final Animation LEAN = new Animation(1129); + /** + * The lean animation. + */ + public static final Animation LEAN = new Animation(1129); - /** - * The no animation. - */ - public static final Animation NO = new Animation(856); + /** + * The no animation. + */ + public static final Animation NO = new Animation(856); - /** - * The panic animation. - */ - public static final Animation PANIC = new Animation(2105); + /** + * The panic animation. + */ + public static final Animation PANIC = new Animation(2105); - /** - * The raspberry animation. - */ - public static final Animation RASPBERRY = new Animation(2110); + /** + * The raspberry animation. + */ + public static final Animation RASPBERRY = new Animation(2110); - /** - * The salute animation. - */ - public static final Animation SALUTE = new Animation(2112); + /** + * The salute animation. + */ + public static final Animation SALUTE = new Animation(2112); - /** - * The shrug animation. - */ - public static final Animation SHRUG = new Animation(2113); + /** + * The shrug animation. + */ + public static final Animation SHRUG = new Animation(2113); - /** - * The spin animation. - */ - public static final Animation SPIN = new Animation(2107); + /** + * The spin animation. + */ + public static final Animation SPIN = new Animation(2107); - /** - * A special animation which stops the current animation. - */ - public static final Animation STOP_ANIMATION = new Animation(-1); + /** + * A special animation which stops the current animation. + */ + public static final Animation STOP_ANIMATION = new Animation(-1); - /** - * The thinking animation. - */ - public static final Animation THINKING = new Animation(857); + /** + * The thinking animation. + */ + public static final Animation THINKING = new Animation(857); - /** - * The wave animation. - */ - public static final Animation WAVE = new Animation(863); + /** + * The wave animation. + */ + public static final Animation WAVE = new Animation(863); - /** - * The yawn animation. - */ - public static final Animation YAWN = new Animation(2111); + /** + * The yawn animation. + */ + public static final Animation YAWN = new Animation(2111); - /** - * The yes animation. - */ - public static final Animation YES = new Animation(855); + /** + * The yes animation. + */ + public static final Animation YES = new Animation(855); - /** - * The delay. - */ - private final int delay; + /** + * The delay. + */ + private final int delay; - /** - * The id. - */ - private final int id; + /** + * The id. + */ + private final int id; - /** - * Creates a new animation with no delay. - * - * @param id The id. - */ - public Animation(int id) { - this(id, 0); - } + /** + * Creates a new animation with no delay. + * + * @param id The id. + */ + public Animation(int id) { + this(id, 0); + } - /** - * Creates a new animation. - * - * @param id The id. - * @param delay The delay. - */ - public Animation(int id, int delay) { - this.id = id; - this.delay = delay; - } + /** + * Creates a new animation. + * + * @param id The id. + * @param delay The delay. + */ + public Animation(int id, int delay) { + this.id = id; + this.delay = delay; + } - /** - * Gets the animation's delay. - * - * @return The animation's delay. - */ - public int getDelay() { - return delay; - } + /** + * Gets the animation's delay. + * + * @return The animation's delay. + */ + public int getDelay() { + return delay; + } - /** - * Gets the animation's id. - * - * @return The animation's id. - */ - public int getId() { - return id; - } + /** + * Gets the animation's id. + * + * @return The animation's id. + */ + public int getId() { + return id; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/Appearance.java b/src/org/apollo/game/model/Appearance.java index 4da322dd..7df7bdb6 100644 --- a/src/org/apollo/game/model/Appearance.java +++ b/src/org/apollo/game/model/Appearance.java @@ -9,91 +9,91 @@ import org.apollo.game.model.settings.Gender; */ public final class Appearance { - /** - * The default appearance. - */ - public static final Appearance DEFAULT_APPEARANCE = new Appearance(Gender.MALE, new int[] { 0, 10, 18, 26, 33, 36, - 42 }, new int[5]); + /** + * The default appearance. + */ + public static final Appearance DEFAULT_APPEARANCE = new Appearance(Gender.MALE, new int[] { 0, 10, 18, 26, 33, 36, + 42 }, new int[5]); - /** - * The array of clothing/skin colors. - */ - private final int[] colors; + /** + * The array of clothing/skin colors. + */ + private final int[] colors; - /** - * The player's gender. - */ - private final Gender gender; + /** + * The player's gender. + */ + private final Gender gender; - /** - * The array of clothing/characteristic styles. - */ - private final int[] style; + /** + * The array of clothing/characteristic styles. + */ + private final int[] style; - /** - * Creates the appearance with the specified gender, style and colors. - * - * @param gender The gender. - * @param style The style. - * @param colors The colors. - */ - public Appearance(Gender gender, int[] style, int[] colors) { - if (gender == null || style == null || colors == null) { - throw new NullPointerException("No arguments can be null."); - } else if (style.length != 7) { - throw new IllegalArgumentException("The style array must have 7 elements."); - } else if (colors.length != 5) { - throw new IllegalArgumentException("The colors array must have 5 elements."); - } - this.gender = gender; - this.style = style; - this.colors = colors; + /** + * Creates the appearance with the specified gender, style and colors. + * + * @param gender The gender. + * @param style The style. + * @param colors The colors. + */ + public Appearance(Gender gender, int[] style, int[] colors) { + if (gender == null || style == null || colors == null) { + throw new NullPointerException("No arguments can be null."); + } else if (style.length != 7) { + throw new IllegalArgumentException("The style array must have 7 elements."); + } else if (colors.length != 5) { + throw new IllegalArgumentException("The colors array must have 5 elements."); } + this.gender = gender; + this.style = style; + this.colors = colors; + } - /** - * Gets the player's colors. - * - * @return The player's colors. - */ - public int[] getColors() { - return colors; - } + /** + * Gets the player's colors. + * + * @return The player's colors. + */ + public int[] getColors() { + return colors; + } - /** - * Gets the gender of the player. - * - * @return The gender of the player. - */ - public Gender getGender() { - return gender; - } + /** + * Gets the gender of the player. + * + * @return The gender of the player. + */ + public Gender getGender() { + return gender; + } - /** - * Gets the player's styles. - * - * @return The player's styles. - */ - public int[] getStyle() { - // 0 = head 1 = chin/beard 2 = chest 3 = arms 4 = hands 5 = legs 6 = feet - return style; - } + /** + * Gets the player's styles. + * + * @return The player's styles. + */ + public int[] getStyle() { + // 0 = head 1 = chin/beard 2 = chest 3 = arms 4 = hands 5 = legs 6 = feet + return style; + } - /** - * Checks if the player is female. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isFemale() { - return gender == Gender.FEMALE; - } + /** + * Checks if the player is female. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isFemale() { + return gender == Gender.FEMALE; + } - /** - * Checks if the player is male. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isMale() { - return gender == Gender.MALE; - } + /** + * Checks if the player is male. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isMale() { + return gender == Gender.MALE; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/Direction.java b/src/org/apollo/game/model/Direction.java index f0096a7f..fbed89e1 100644 --- a/src/org/apollo/game/model/Direction.java +++ b/src/org/apollo/game/model/Direction.java @@ -7,121 +7,121 @@ package org.apollo.game.model; */ public enum Direction { - /** - * No movement. - */ - NONE(-1), + /** + * No movement. + */ + NONE(-1), - /** - * North west movement. - */ - NORTH_WEST(0), + /** + * North west movement. + */ + NORTH_WEST(0), - /** - * North movement. - */ - NORTH(1), + /** + * North movement. + */ + NORTH(1), - /** - * North east movement. - */ - NORTH_EAST(2), + /** + * North east movement. + */ + NORTH_EAST(2), - /** - * West movement. - */ - WEST(3), + /** + * West movement. + */ + WEST(3), - /** - * East movement. - */ - EAST(4), + /** + * East movement. + */ + EAST(4), - /** - * South west movement. - */ - SOUTH_WEST(5), + /** + * South west movement. + */ + SOUTH_WEST(5), - /** - * South movement. - */ - SOUTH(6), + /** + * South movement. + */ + SOUTH(6), - /** - * South east movement. - */ - SOUTH_EAST(7); + /** + * South east movement. + */ + SOUTH_EAST(7); - /** - * An empty direction array. - */ - public static final Direction[] EMPTY_DIRECTION_ARRAY = new Direction[0]; + /** + * An empty direction array. + */ + public static final Direction[] EMPTY_DIRECTION_ARRAY = new Direction[0]; - /** - * Creates a direction from the differences between X and Y. - * - * @param deltaX The difference between two X coordinates. - * @param deltaY The difference between two Y coordinates. - * @return The direction. - */ - public static Direction fromDeltas(int deltaX, int deltaY) { - if (deltaY == 1) { - if (deltaX == 1) { - return Direction.NORTH_EAST; - } else if (deltaX == 0) { - return Direction.NORTH; - } - return Direction.NORTH_WEST; - } else if (deltaY == -1) { - if (deltaX == 1) { - return Direction.SOUTH_EAST; - } else if (deltaX == 0) { - return Direction.SOUTH; - } - return Direction.SOUTH_WEST; - } else { - if (deltaX == 1) { - return Direction.EAST; - } else if (deltaX == -1) { - return Direction.WEST; - } - } - return Direction.NONE; + /** + * Creates a direction from the differences between X and Y. + * + * @param deltaX The difference between two X coordinates. + * @param deltaY The difference between two Y coordinates. + * @return The direction. + */ + public static Direction fromDeltas(int deltaX, int deltaY) { + if (deltaY == 1) { + if (deltaX == 1) { + return Direction.NORTH_EAST; + } else if (deltaX == 0) { + return Direction.NORTH; + } + return Direction.NORTH_WEST; + } else if (deltaY == -1) { + if (deltaX == 1) { + return Direction.SOUTH_EAST; + } else if (deltaX == 0) { + return Direction.SOUTH; + } + return Direction.SOUTH_WEST; + } else { + if (deltaX == 1) { + return Direction.EAST; + } else if (deltaX == -1) { + return Direction.WEST; + } } + return Direction.NONE; + } - /** - * Checks if the direction represented by the two delta values can connect two points together in a single - * direction. - * - * @param deltaX The difference in X coordinates. - * @param deltaY The difference in X coordinates. - * @return {@code true} if so, {@code false} if not. - */ - public static boolean isConnectable(int deltaX, int deltaY) { - return Math.abs(deltaX) == Math.abs(deltaY) || deltaX == 0 || deltaY == 0; - } + /** + * Checks if the direction represented by the two delta values can connect two points together in a single + * direction. + * + * @param deltaX The difference in X coordinates. + * @param deltaY The difference in X coordinates. + * @return {@code true} if so, {@code false} if not. + */ + public static boolean isConnectable(int deltaX, int deltaY) { + return Math.abs(deltaX) == Math.abs(deltaY) || deltaX == 0 || deltaY == 0; + } - /** - * The direction as an integer. - */ - private final int intValue; + /** + * The direction as an integer. + */ + private final int intValue; - /** - * Creates the direction. - * - * @param intValue The direction as an integer. - */ - private Direction(int intValue) { - this.intValue = intValue; - } + /** + * Creates the direction. + * + * @param intValue The direction as an integer. + */ + private Direction(int intValue) { + this.intValue = intValue; + } - /** - * Gets the direction as an integer which the client can understand. - * - * @return The movement as an integer. - */ - public int toInteger() { - return intValue; - } + /** + * Gets the direction as an integer which the client can understand. + * + * @return The movement as an integer. + */ + public int toInteger() { + return intValue; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/Graphic.java b/src/org/apollo/game/model/Graphic.java index fde393c3..5e6e494e 100644 --- a/src/org/apollo/game/model/Graphic.java +++ b/src/org/apollo/game/model/Graphic.java @@ -7,83 +7,83 @@ package org.apollo.game.model; */ public final class Graphic { - /** - * A special graphic which stops the current graphic. - */ - public static final Graphic STOP_GRAPHIC = new Graphic(-1); + /** + * A special graphic which stops the current graphic. + */ + public static final Graphic STOP_GRAPHIC = new Graphic(-1); - /** - * The delay. - */ - private final int delay; + /** + * The delay. + */ + private final int delay; - /** - * The height. - */ - private final int height; + /** + * The height. + */ + private final int height; - /** - * The id. - */ - private final int id; + /** + * The id. + */ + private final int id; - /** - * Creates a new graphic with no delay and a height of zero. - * - * @param id The id. - */ - public Graphic(int id) { - this(id, 0, 0); - } + /** + * Creates a new graphic with no delay and a height of zero. + * + * @param id The id. + */ + public Graphic(int id) { + this(id, 0, 0); + } - /** - * Creates a new graphic with a height of zero. - * - * @param id The id. - * @param delay The delay. - */ - public Graphic(int id, int delay) { - this(id, delay, 0); - } + /** + * Creates a new graphic with a height of zero. + * + * @param id The id. + * @param delay The delay. + */ + public Graphic(int id, int delay) { + this(id, delay, 0); + } - /** - * Creates a new graphic. - * - * @param id The id. - * @param delay The delay. - * @param height The height. - */ - public Graphic(int id, int delay, int height) { - this.id = id; - this.delay = delay; - this.height = height; - } + /** + * Creates a new graphic. + * + * @param id The id. + * @param delay The delay. + * @param height The height. + */ + public Graphic(int id, int delay, int height) { + this.id = id; + this.delay = delay; + this.height = height; + } - /** - * Gets the graphic's delay. - * - * @return The delay. - */ - public int getDelay() { - return delay; - } + /** + * Gets the graphic's delay. + * + * @return The delay. + */ + public int getDelay() { + return delay; + } - /** - * Gets the graphic's height. - * - * @return The height. - */ - public int getHeight() { - return height; - } + /** + * Gets the graphic's height. + * + * @return The height. + */ + public int getHeight() { + return height; + } - /** - * Gets the graphic's id. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the graphic's id. + * + * @return The id. + */ + public int getId() { + return id; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/Item.java b/src/org/apollo/game/model/Item.java index d969d43f..9fd48158 100644 --- a/src/org/apollo/game/model/Item.java +++ b/src/org/apollo/game/model/Item.java @@ -9,76 +9,76 @@ import org.apollo.game.model.def.ItemDefinition; */ public final class Item { - /** - * The amount of items in the stack. - */ - private final int amount; + /** + * The amount of items in the stack. + */ + private final int amount; - /** - * The item definition. - */ - private final ItemDefinition definition; + /** + * The item definition. + */ + private final ItemDefinition definition; - /** - * The item's id. - */ - private final int id; + /** + * The item's id. + */ + private final int id; - /** - * Creates an item with an amount of {@code 1}. - * - * @param id The item's id. - */ - public Item(int id) { - this(id, 1); + /** + * Creates an item with an amount of {@code 1}. + * + * @param id The item's id. + */ + public Item(int id) { + this(id, 1); + } + + /** + * Creates an item with the specified the amount. + * + * @param id The item's id. + * @param amount The amount. + * @throws IllegalArgumentException If the amount is negative. + */ + public Item(int id, int amount) { + if (amount < 0) { + throw new IllegalArgumentException("Negative amount."); } + this.id = id; + this.amount = amount; + this.definition = ItemDefinition.lookup(id); + } - /** - * Creates an item with the specified the amount. - * - * @param id The item's id. - * @param amount The amount. - * @throws IllegalArgumentException If the amount is negative. - */ - public Item(int id, int amount) { - if (amount < 0) { - throw new IllegalArgumentException("Negative amount."); - } - this.id = id; - this.amount = amount; - this.definition = ItemDefinition.lookup(id); - } + /** + * Gets the amount. + * + * @return The amount. + */ + public int getAmount() { + return amount; + } - /** - * Gets the amount. - * - * @return The amount. - */ - public int getAmount() { - return amount; - } + /** + * Gets the {@link ItemDefinition} that describes this item. + * + * @return The definition. + */ + public ItemDefinition getDefinition() { + return definition; + } - /** - * Gets the {@link ItemDefinition} that describes this item. - * - * @return The definition. - */ - public ItemDefinition getDefinition() { - return definition; - } + /** + * Gets the id. + * + * @return The id. + */ + public int getId() { + return id; + } - /** - * Gets the id. - * - * @return The id. - */ - public int getId() { - return id; - } - - @Override - public String toString() { - return Item.class.getName() + " [id=" + id + ", amount=" + amount + "]"; - } + @Override + public String toString() { + return Item.class.getName() + " [id=" + id + ", amount=" + amount + "]"; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/Position.java b/src/org/apollo/game/model/Position.java index 537946f0..74cac6f6 100644 --- a/src/org/apollo/game/model/Position.java +++ b/src/org/apollo/game/model/Position.java @@ -7,221 +7,221 @@ package org.apollo.game.model; */ public final class Position { - /** - * The number of height levels. - */ - public static final int HEIGHT_LEVELS = 4; + /** + * The number of height levels. + */ + public static final int HEIGHT_LEVELS = 4; - /** - * The maximum distance players/NPCs can 'see'. - */ - public static final int MAX_DISTANCE = 15; + /** + * The maximum distance players/NPCs can 'see'. + */ + public static final int MAX_DISTANCE = 15; - /** - * The height level. - */ - private final int height; + /** + * The height level. + */ + private final int height; - /** - * The x coordinate. - */ - private final int x; + /** + * The x coordinate. + */ + private final int x; - /** - * The y coordinate. - */ - private final int y; + /** + * The y coordinate. + */ + private final int y; - /** - * Creates a position at the default height. - * - * @param x The x coordinate. - * @param y The y coordinate. - */ - public Position(int x, int y) { - this(x, y, 0); + /** + * Creates a position at the default height. + * + * @param x The x coordinate. + * @param y The y coordinate. + */ + public Position(int x, int y) { + this(x, y, 0); + } + + /** + * Creates a position with the specified height. + * + * @param x The x coordinate. + * @param y The y coordinate. + * @param height The height. + */ + public Position(int x, int y, int height) { + if (height < 0 || height >= HEIGHT_LEVELS) { + throw new IllegalArgumentException("Height level out of bounds."); } + this.x = x; + this.y = y; + this.height = height; + } - /** - * Creates a position with the specified height. - * - * @param x The x coordinate. - * @param y The y coordinate. - * @param height The height. - */ - public Position(int x, int y, int height) { - if (height < 0 || height >= HEIGHT_LEVELS) { - throw new IllegalArgumentException("Height level out of bounds."); - } - this.x = x; - this.y = y; - this.height = height; + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; } + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + Position other = (Position) obj; + if (height != other.height || x != other.x || y != other.y) { + return false; + } + return true; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - Position other = (Position) obj; - if (height != other.height || x != other.x || y != other.y) { - return false; - } - return true; - } + /** + * Gets the x coordinate of the central sector. + * + * @return The x coordinate of the central sector. + */ + public int getCentralSectorX() { + return x / 8; + } - /** - * Gets the x coordinate of the central sector. - * - * @return The x coordinate of the central sector. - */ - public int getCentralSectorX() { - return x / 8; - } + /** + * Gets the y coordinate of the central sector. + * + * @return The y coordinate of the central sector. + */ + public int getCentralSectorY() { + return y / 8; + } - /** - * Gets the y coordinate of the central sector. - * - * @return The y coordinate of the central sector. - */ - public int getCentralSectorY() { - return y / 8; - } + /** + * Gets the distance between this position and another position. Only x and y are considered (i.e. 2 dimensions). + * + * @param other The other position. + * @return The distance. + */ + public int getDistance(Position other) { + int deltaX = x - other.x; + int deltaY = y - other.y; + return (int) Math.ceil(Math.sqrt(deltaX * deltaX + deltaY * deltaY)); + } - /** - * Gets the distance between this position and another position. Only x and y are considered (i.e. 2 dimensions). - * - * @param other The other position. - * @return The distance. - */ - public int getDistance(Position other) { - int deltaX = x - other.x; - int deltaY = y - other.y; - return (int) Math.ceil(Math.sqrt(deltaX * deltaX + deltaY * deltaY)); - } + /** + * Gets the height level. + * + * @return The height level. + */ + public int getHeight() { + return height; + } - /** - * Gets the height level. - * - * @return The height level. - */ - public int getHeight() { - return height; - } + /** + * Gets the x coordinate inside the sector of this position. + * + * @return The local x coordinate. + */ + public int getLocalX() { + return getLocalX(this); + } - /** - * Gets the x coordinate inside the sector of this position. - * - * @return The local x coordinate. - */ - public int getLocalX() { - return getLocalX(this); - } + /** + * Gets the local x coordinate inside the sector of the {@code base} position. + * + * @param base The base position. + * @return The local x coordinate. + */ + public int getLocalX(Position base) { + return x - base.getTopLeftSectorX() * 8; + } - /** - * Gets the local x coordinate inside the sector of the {@code base} position. - * - * @param base The base position. - * @return The local x coordinate. - */ - public int getLocalX(Position base) { - return x - base.getTopLeftSectorX() * 8; - } + /** + * Gets the y coordinate inside the sector of this position. + * + * @return The local y coordinate. + */ + public int getLocalY() { + return getLocalY(this); + } - /** - * Gets the y coordinate inside the sector of this position. - * - * @return The local y coordinate. - */ - public int getLocalY() { - return getLocalY(this); - } + /** + * Gets the local y coordinate inside the sector of the {@code base} position. + * + * @param base The base position. + * @return The local y coordinate. + */ + public int getLocalY(Position base) { + return y - base.getTopLeftSectorY() * 8; + } - /** - * Gets the local y coordinate inside the sector of the {@code base} position. - * - * @param base The base position. - * @return The local y coordinate. - */ - public int getLocalY(Position base) { - return y - base.getTopLeftSectorY() * 8; - } + /** + * Gets the longest horizontal or vertical delta between the two positions. + * + * @param other The other position. + * @return The longest horizontal or vertical delta. + */ + public int getLongestDelta(Position other) { + int deltaX = x - other.x; + int deltaY = y - other.y; + return Math.max(deltaX, deltaY); + } - /** - * Gets the longest horizontal or vertical delta between the two positions. - * - * @param other The other position. - * @return The longest horizontal or vertical delta. - */ - public int getLongestDelta(Position other) { - int deltaX = x - other.x; - int deltaY = y - other.y; - return Math.max(deltaX, deltaY); - } + /** + * Gets the x coordinate of the sector this position is in. + * + * @return The sector x coordinate. + */ + public int getTopLeftSectorX() { + return x / 8 - 6; + } - /** - * Gets the x coordinate of the sector this position is in. - * - * @return The sector x coordinate. - */ - public int getTopLeftSectorX() { - return x / 8 - 6; - } + /** + * Gets the y coordinate of the sector this position is in. + * + * @return The sector y coordinate. + */ + public int getTopLeftSectorY() { + return y / 8 - 6; + } - /** - * Gets the y coordinate of the sector this position is in. - * - * @return The sector y coordinate. - */ - public int getTopLeftSectorY() { - return y / 8 - 6; - } + /** + * Gets the x coordinate. + * + * @return The x coordinate. + */ + public int getX() { + return x; + } - /** - * Gets the x coordinate. - * - * @return The x coordinate. - */ - public int getX() { - return x; - } + /** + * Gets the y coordinate. + * + * @return The y coordinate. + */ + public int getY() { + return y; + } - /** - * Gets the y coordinate. - * - * @return The y coordinate. - */ - public int getY() { - return y; - } + @Override + public int hashCode() { + return height << 30 & 0xC0000000 | y << 15 & 0x3FFF8000 | x & 0x7FFF; + } - @Override - public int hashCode() { - return height << 30 & 0xC0000000 | y << 15 & 0x3FFF8000 | x & 0x7FFF; - } + /** + * Checks if the position is within distance of another. + * + * @param other The other position. + * @param distance The distance. + * @return {@code true} if so, {@code false} if not. + */ + public boolean isWithinDistance(Position other, int distance) { + int deltaX = Math.abs(x - other.x); + int deltaY = Math.abs(y - other.y); + return deltaX <= distance && deltaY <= distance; + } - /** - * Checks if the position is within distance of another. - * - * @param other The other position. - * @param distance The distance. - * @return {@code true} if so, {@code false} if not. - */ - public boolean isWithinDistance(Position other, int distance) { - int deltaX = Math.abs(x - other.x); - int deltaY = Math.abs(y - other.y); - return deltaX <= distance && deltaY <= distance; - } - - @Override - public String toString() { - return Position.class.getName() + " [x=" + x + ", y=" + y + ", height=" + height + "]"; - } + @Override + public String toString() { + return Position.class.getName() + " [x=" + x + ", y=" + y + ", height=" + height + "]"; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/World.java b/src/org/apollo/game/model/World.java index b578a20e..5e0dafed 100644 --- a/src/org/apollo/game/model/World.java +++ b/src/org/apollo/game/model/World.java @@ -44,349 +44,349 @@ import org.apollo.util.plugin.PluginManager; */ public final class World { + /** + * Represents the different status codes for registering a player. + * + * @author Graham + */ + public enum RegistrationStatus { + /** - * Represents the different status codes for registering a player. - * - * @author Graham + * Indicates that the player is already online. */ - public enum RegistrationStatus { + ALREADY_ONLINE, - /** - * Indicates that the player is already online. - */ - ALREADY_ONLINE, + /** + * Indicates that the player was registered successfully. + */ + OK, - /** - * Indicates that the player was registered successfully. - */ - OK, + /** + * Indicates the world is full. + */ + WORLD_FULL; - /** - * Indicates the world is full. - */ - WORLD_FULL; + } + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(World.class.getName()); + + /** + * The world. + */ + private static final World world = new World(); + + /** + * Gets the world. + * + * @return The world. + */ + public static World getWorld() { + return world; + } + + /** + * The command dispatcher. + */ + private final CommandDispatcher commandDispatcher = new CommandDispatcher(); + + /** + * The login dispatcher. + */ + private final LoginDispatcher loginDispatcher = new LoginDispatcher(); + + /** + * The logout dispatcher. + */ + private final LogoutDispatcher logoutDispatcher = new LogoutDispatcher(); + + /** + * The {@link MobRepository} of {@link Npc}s. + */ + private final MobRepository npcRepository = new MobRepository<>(WorldConstants.MAXIMUM_NPCS); + + /** + * The {@link MobRepository} of {@link Player}s. + */ + private final MobRepository playerRepository = new MobRepository<>(WorldConstants.MAXIMUM_PLAYERS); + + /** + * A {@link Map} of player usernames and the player objects. + */ + private final Map players = new HashMap<>(); + + /** + * The {@link PluginManager}. TODO: better place than here!! + */ + private PluginManager pluginManager; + + /** + * The release number (i.e. version) of this world. + */ + private int releaseNumber; + + /** + * The scheduler. + */ + private final Scheduler scheduler = new Scheduler(); + + /** + * This world's {@link SectorRepository}. + */ + private final SectorRepository sectorRepository = new SectorRepository(false); + + /** + * Creates the world. + */ + private World() { + + } + + /** + * Gets the command dispatcher. + * + * @return The command dispatcher. + */ + public CommandDispatcher getCommandDispatcher() { + return commandDispatcher; + } + + /** + * Gets the {@link LoginDispatcher}. + * + * @return The dispatcher. + */ + public LoginDispatcher getLoginDispatcher() { + return loginDispatcher; + } + + /** + * Gets the {@link LogoutDispatcher}. + * + * @return The dispatcher. + */ + public LogoutDispatcher getLogoutDispatcher() { + return logoutDispatcher; + } + + /** + * Gets the npc repository. + * + * @return The npc repository. + */ + public MobRepository getNpcRepository() { + return npcRepository; + } + + /** + * Gets the {@link Player} with the specified username. Note that this will return {@code null} if the player is + * offline. + * + * @param username The username. + * @return The player. + */ + public Player getPlayer(String username) { + return players.get(NameUtil.encodeBase37(username.toLowerCase())); + } + + /** + * Gets the player repository. + * + * @return The player repository. + */ + public MobRepository getPlayerRepository() { + return playerRepository; + } + + /** + * Gets the plugin manager. TODO should this be here? + * + * @return The plugin manager. + */ + public PluginManager getPluginManager() { + return pluginManager; + } + + /** + * Gets the release number of this world. + * + * @return The release number. + */ + public int getReleaseNumber() { + return releaseNumber; + } + + /** + * Gets this world's {@link SectorRepository}. + * + * @return The sector repository. + */ + public SectorRepository getSectorRepository() { + return sectorRepository; + } + + /** + * Initialises the world by loading definitions from the specified file system. + * + * @param release The release number. + * @param fs The file system. + * @param manager The plugin manager. TODO move this. + * @throws IOException If an I/O error occurs. + */ + public void init(int release, IndexedFileSystem fs, PluginManager manager) throws Exception { + this.releaseNumber = release; + + ItemDefinitionDecoder itemDefDecoder = new ItemDefinitionDecoder(fs); + ItemDefinition[] itemDefs = itemDefDecoder.decode(); + ItemDefinition.init(itemDefs); + logger.info("Loaded " + itemDefs.length + " item definitions."); + + try (InputStream is = new BufferedInputStream(new FileInputStream("data/equipment-" + release + ".dat"))) { + EquipmentDefinitionParser parser = new EquipmentDefinitionParser(is); + EquipmentDefinition[] defs = parser.parse(); + EquipmentDefinition.init(defs); + logger.info("Loaded " + defs.length + " equipment definitions."); } - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(World.class.getName()); + NpcDefinitionDecoder npcDecoder = new NpcDefinitionDecoder(fs); + NpcDefinition[] npcDefs = npcDecoder.decode(); + NpcDefinition.init(npcDefs); + logger.info("Loaded " + npcDefs.length + " npc definitions."); - /** - * The world. - */ - private static final World world = new World(); + ObjectDefinitionDecoder objectDecoder = new ObjectDefinitionDecoder(fs); + ObjectDefinition[] objDefs = objectDecoder.decode(); + ObjectDefinition.init(objDefs); + logger.info("Loaded " + objDefs.length + " object definitions."); - /** - * Gets the world. - * - * @return The world. - */ - public static World getWorld() { - return world; + StaticObjectDecoder staticDecoder = new StaticObjectDecoder(fs); + GameObject[] objects = staticDecoder.decode(); + placeEntities(objects); + logger.info("Loaded " + objects.length + " static objects."); + + manager.start(); + pluginManager = manager; // TODO move!! + } + + /** + * Checks if the {@link Player} with the specified name is online. + * + * @param username The name. + * @return {@code true} if the player is online, otherwise {@code false}. + */ + public boolean isPlayerOnline(String username) { + return players.get(NameUtil.encodeBase37(username.toLowerCase())) != null; + } + + /** + * Adds entities to sectors in the {@link SectorRepository}. + * + * @param entities The entities. + * @return {@code true} if all entities were added successfully, otherwise {@code false}. + */ + private boolean placeEntities(Entity... entities) { + boolean success = true; + + for (Entity entity : entities) { + Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(entity.getPosition())); + success &= sector.addEntity(entity); + } + return success; + } + + /** + * Pulses the world. + */ + public void pulse() { + scheduler.pulse(); + } + + /** + * Registers the specified npc. + * + * @param npc The npc. + * @return {@code true} if the npc registered successfully, otherwise {@code false}. + */ + public boolean register(final Npc npc) { + boolean success = npcRepository.add(npc); + + if (success) { + Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition())); + sector.addEntity(npc); + } else { + logger.warning("Failed to register npc, repository capacity reached: [count=" + npcRepository.size() + "]"); + } + return success; + } + + /** + * Registers the specified player. + * + * @param player The player. + * @return A {@link RegistrationStatus}. + */ + public RegistrationStatus register(final Player player) { + if (isPlayerOnline(player.getUsername())) { + return RegistrationStatus.ALREADY_ONLINE; } - /** - * The command dispatcher. - */ - private final CommandDispatcher commandDispatcher = new CommandDispatcher(); - - /** - * The login dispatcher. - */ - private final LoginDispatcher loginDispatcher = new LoginDispatcher(); - - /** - * The logout dispatcher. - */ - private final LogoutDispatcher logoutDispatcher = new LogoutDispatcher(); - - /** - * The {@link MobRepository} of {@link Npc}s. - */ - private final MobRepository npcRepository = new MobRepository<>(WorldConstants.MAXIMUM_NPCS); - - /** - * The {@link MobRepository} of {@link Player}s. - */ - private final MobRepository playerRepository = new MobRepository<>(WorldConstants.MAXIMUM_PLAYERS); - - /** - * A {@link Map} of player usernames and the player objects. - */ - private final Map players = new HashMap<>(); - - /** - * The {@link PluginManager}. TODO: better place than here!! - */ - private PluginManager pluginManager; - - /** - * The release number (i.e. version) of this world. - */ - private int releaseNumber; - - /** - * The scheduler. - */ - private final Scheduler scheduler = new Scheduler(); - - /** - * This world's {@link SectorRepository}. - */ - private final SectorRepository sectorRepository = new SectorRepository(false); - - /** - * Creates the world. - */ - private World() { + boolean success = playerRepository.add(player); + if (success) { + if (players.put(NameUtil.encodeBase37(player.getUsername().toLowerCase()), player) != null) { + logger.info("Error adding the player to the username map - someone with that name already exists."); + return RegistrationStatus.ALREADY_ONLINE; + } + logger.info("Registered player: " + player + " [count=" + playerRepository.size() + "]"); + Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition())); + sector.addEntity(player); + return RegistrationStatus.OK; } - /** - * Gets the command dispatcher. - * - * @return The command dispatcher. - */ - public CommandDispatcher getCommandDispatcher() { - return commandDispatcher; + logger.warning("Failed to register player: " + player + " [count=" + playerRepository.size() + "]"); + return RegistrationStatus.WORLD_FULL; + } + + /** + * Schedules a new task. + * + * @param task The {@link ScheduledTask}. + */ + public boolean schedule(ScheduledTask task) { + return scheduler.schedule(task); + } + + /** + * Unregisters the specified {@link Npc}. + * + * @param npc The npc. + */ + public void unregister(final Npc npc) { + if (npcRepository.remove(npc)) { + Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition())); + sector.removeEntity(npc); + } else { + logger.warning("Could not find npc " + npc + " to unregister!"); } + } - /** - * Gets the {@link LoginDispatcher}. - * - * @return The dispatcher. - */ - public LoginDispatcher getLoginDispatcher() { - return loginDispatcher; - } - - /** - * Gets the {@link LogoutDispatcher}. - * - * @return The dispatcher. - */ - public LogoutDispatcher getLogoutDispatcher() { - return logoutDispatcher; - } - - /** - * Gets the npc repository. - * - * @return The npc repository. - */ - public MobRepository getNpcRepository() { - return npcRepository; - } - - /** - * Gets the {@link Player} with the specified username. Note that this will return {@code null} if the player is - * offline. - * - * @param username The username. - * @return The player. - */ - public Player getPlayer(String username) { - return players.get(NameUtil.encodeBase37(username.toLowerCase())); - } - - /** - * Gets the player repository. - * - * @return The player repository. - */ - public MobRepository getPlayerRepository() { - return playerRepository; - } - - /** - * Gets the plugin manager. TODO should this be here? - * - * @return The plugin manager. - */ - public PluginManager getPluginManager() { - return pluginManager; - } - - /** - * Gets the release number of this world. - * - * @return The release number. - */ - public int getReleaseNumber() { - return releaseNumber; - } - - /** - * Gets this world's {@link SectorRepository}. - * - * @return The sector repository. - */ - public SectorRepository getSectorRepository() { - return sectorRepository; - } - - /** - * Initialises the world by loading definitions from the specified file system. - * - * @param release The release number. - * @param fs The file system. - * @param manager The plugin manager. TODO move this. - * @throws IOException If an I/O error occurs. - */ - public void init(int release, IndexedFileSystem fs, PluginManager manager) throws Exception { - this.releaseNumber = release; - - ItemDefinitionDecoder itemDefDecoder = new ItemDefinitionDecoder(fs); - ItemDefinition[] itemDefs = itemDefDecoder.decode(); - ItemDefinition.init(itemDefs); - logger.info("Loaded " + itemDefs.length + " item definitions."); - - try (InputStream is = new BufferedInputStream(new FileInputStream("data/equipment-" + release + ".dat"))) { - EquipmentDefinitionParser parser = new EquipmentDefinitionParser(is); - EquipmentDefinition[] defs = parser.parse(); - EquipmentDefinition.init(defs); - logger.info("Loaded " + defs.length + " equipment definitions."); - } - - NpcDefinitionDecoder npcDecoder = new NpcDefinitionDecoder(fs); - NpcDefinition[] npcDefs = npcDecoder.decode(); - NpcDefinition.init(npcDefs); - logger.info("Loaded " + npcDefs.length + " npc definitions."); - - ObjectDefinitionDecoder objectDecoder = new ObjectDefinitionDecoder(fs); - ObjectDefinition[] objDefs = objectDecoder.decode(); - ObjectDefinition.init(objDefs); - logger.info("Loaded " + objDefs.length + " object definitions."); - - StaticObjectDecoder staticDecoder = new StaticObjectDecoder(fs); - GameObject[] objects = staticDecoder.decode(); - placeEntities(objects); - logger.info("Loaded " + objects.length + " static objects."); - - manager.start(); - pluginManager = manager; // TODO move!! - } - - /** - * Checks if the {@link Player} with the specified name is online. - * - * @param username The name. - * @return {@code true} if the player is online, otherwise {@code false}. - */ - public boolean isPlayerOnline(String username) { - return players.get(NameUtil.encodeBase37(username.toLowerCase())) != null; - } - - /** - * Adds entities to sectors in the {@link SectorRepository}. - * - * @param entities The entities. - * @return {@code true} if all entities were added successfully, otherwise {@code false}. - */ - private boolean placeEntities(Entity... entities) { - boolean success = true; - - for (Entity entity : entities) { - Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(entity.getPosition())); - success &= sector.addEntity(entity); - } - return success; - } - - /** - * Pulses the world. - */ - public void pulse() { - scheduler.pulse(); - } - - /** - * Registers the specified npc. - * - * @param npc The npc. - * @return {@code true} if the npc registered successfully, otherwise {@code false}. - */ - public boolean register(final Npc npc) { - boolean success = npcRepository.add(npc); - - if (success) { - Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition())); - sector.addEntity(npc); - } else { - logger.warning("Failed to register npc, repository capacity reached: [count=" + npcRepository.size() + "]"); - } - return success; - } - - /** - * Registers the specified player. - * - * @param player The player. - * @return A {@link RegistrationStatus}. - */ - public RegistrationStatus register(final Player player) { - if (isPlayerOnline(player.getUsername())) { - return RegistrationStatus.ALREADY_ONLINE; - } - - boolean success = playerRepository.add(player); - if (success) { - if (players.put(NameUtil.encodeBase37(player.getUsername().toLowerCase()), player) != null) { - logger.info("Error adding the player to the username map - someone with that name already exists."); - return RegistrationStatus.ALREADY_ONLINE; - } - logger.info("Registered player: " + player + " [count=" + playerRepository.size() + "]"); - - Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition())); - sector.addEntity(player); - return RegistrationStatus.OK; - } - - logger.warning("Failed to register player: " + player + " [count=" + playerRepository.size() + "]"); - return RegistrationStatus.WORLD_FULL; - } - - /** - * Schedules a new task. - * - * @param task The {@link ScheduledTask}. - */ - public boolean schedule(ScheduledTask task) { - return scheduler.schedule(task); - } - - /** - * Unregisters the specified {@link Npc}. - * - * @param npc The npc. - */ - public void unregister(final Npc npc) { - if (npcRepository.remove(npc)) { - Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition())); - sector.removeEntity(npc); - } else { - logger.warning("Could not find npc " + npc + " to unregister!"); - } - } - - /** - * Unregisters the specified player. - * - * @param player The player. - */ - public void unregister(final Player player) { - if (playerRepository.remove(player) - & players.remove(NameUtil.encodeBase37(player.getUsername().toLowerCase())) == player) { - logger.info("Unregistered player: " + player + " [count=" + playerRepository.size() + "]"); - - Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition())); - sector.removeEntity(player); - logoutDispatcher.dispatch(player); - } else { - logger.warning("Could not find player " + player + " to unregister!"); - } + /** + * Unregisters the specified player. + * + * @param player The player. + */ + public void unregister(final Player player) { + if (playerRepository.remove(player) + & players.remove(NameUtil.encodeBase37(player.getUsername().toLowerCase())) == player) { + logger.info("Unregistered player: " + player + " [count=" + playerRepository.size() + "]"); + + Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition())); + sector.removeEntity(player); + logoutDispatcher.dispatch(player); + } else { + logger.warning("Could not find player " + player + " to unregister!"); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/WorldConstants.java b/src/org/apollo/game/model/WorldConstants.java index 24388fa5..12b2c90d 100644 --- a/src/org/apollo/game/model/WorldConstants.java +++ b/src/org/apollo/game/model/WorldConstants.java @@ -7,21 +7,21 @@ package org.apollo.game.model; */ public final class WorldConstants { - /** - * The maximum number of npcs. - */ - public static final int MAXIMUM_NPCS = 32768; + /** + * The maximum number of npcs. + */ + public static final int MAXIMUM_NPCS = 32768; - /** - * The maximum number of players. - */ - public static final int MAXIMUM_PLAYERS = 2000; + /** + * The maximum number of players. + */ + public static final int MAXIMUM_PLAYERS = 2000; - /** - * Default private constructor to prevent instantiation by other classes. - */ - private WorldConstants() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private WorldConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/area/Sector.java b/src/org/apollo/game/model/area/Sector.java index 68b0b0f8..eca5b86e 100644 --- a/src/org/apollo/game/model/area/Sector.java +++ b/src/org/apollo/game/model/area/Sector.java @@ -17,138 +17,138 @@ import org.apollo.game.model.entity.Entity.EntityType; */ public final class Sector { - /** - * The width and height of a sector, in tiles. - */ - public static final int SECTOR_SIZE = 8; + /** + * The width and height of a sector, in tiles. + */ + public static final int SECTOR_SIZE = 8; - /** - * The sector coordinates of this sector. - */ - private final SectorCoordinates coordinates; + /** + * The sector coordinates of this sector. + */ + private final SectorCoordinates coordinates; - /** - * A map of positions to entities in that position. - */ - private final Map> entities = new HashMap<>(); + /** + * A map of positions to entities in that position. + */ + private final Map> entities = new HashMap<>(); - /** - * A list of listeners registered to this sector. - */ - private final List listeners = new ArrayList<>(); + /** + * A list of listeners registered to this sector. + */ + private final List listeners = new ArrayList<>(); - /** - * Creates a new sector. - * - * @param x The x coordinate of the sector. - * @param y The y coordinate of the sector. - */ - public Sector(int x, int y) { - this(new SectorCoordinates(x, y)); + /** + * Creates a new sector. + * + * @param x The x coordinate of the sector. + * @param y The y coordinate of the sector. + */ + public Sector(int x, int y) { + this(new SectorCoordinates(x, y)); + } + + /** + * Creates a new sector with the specified {@link SectorCoordinates}. + * + * @param coordinates The coordinates. + */ + public Sector(SectorCoordinates coordinates) { + this.coordinates = coordinates; + } + + /** + * Adds a {@link Entity} from to sector. Note that this does not spawn the entity, or do any other action other than + * register it to this sector. The return value of this method should also be monitored - if this method fails (i.e. + * returns {@code false}), the entity should not be registered in the world. + * + * @param entity The entity. + * @return {@code true} if the entity was added successfully, otherwise {@code false}. + */ + public boolean addEntity(Entity entity) { + Position position = entity.getPosition(); + List entities = this.entities.get(position); + if (entities == null) { + entities = new ArrayList<>(); } - /** - * Creates a new sector with the specified {@link SectorCoordinates}. - * - * @param coordinates The coordinates. - */ - public Sector(SectorCoordinates coordinates) { - this.coordinates = coordinates; + if (entities.add(entity)) { + this.entities.put(position, entities); + notifyListeners(entity); + return true; + } + return false; + } + + /** + * Checks if this sector contains the specified entity. + * + * @param entity The entity. + * @return {@code true} if this sector contains the entity, otherwise {@code false}. + */ + public boolean contains(Entity entity) { + return entities.get(entity.getPosition()).contains(entity); + } + + /** + * Gets this sector's {@link SectorCoordinates}. + * + * @return The sector coordinates. + */ + public SectorCoordinates getCoordinates() { + return coordinates; + } + + /** + * Gets a copy of the {@link List} of {@link Entity}s. + * + * @param position The position containing the entities. + * @return The list. + */ + public List getEntities(Position position) { + return new ArrayList<>(entities.get(position)); + } + + /** + * Gets a copy of the {@link List} of {@link Entity}s with the specified {@link EntityType}. + * + * @param position The {@link Position} containing the entities. + * @param type The {@link EntityType}. + * @return The list of entities. + */ + @SuppressWarnings("unchecked") + public List getEntities(Position position, EntityType type) { + return (List) entities.get(position).stream().filter((e) -> e.getEntityType() == type) + .collect(Collectors.toList()); + } + + /** + * Notifies the listeners registered to this sector that an update has occurred. + * + * @param entity The entity that was updated. + */ + public void notifyListeners(Entity entity) { + listeners.forEach((l) -> l.execute(this, entity)); + } + + /** + * Removes a {@link Entity} from this sector. + * + * @param entity The entity. + * @return {@code true} if the entity was removed, otherwise {@code false}. + */ + public boolean removeEntity(Entity entity) { + Position position = entity.getPosition(); + List entities = this.entities.get(position); + if (entities == null) { + this.entities.put(position, new ArrayList<>()); + return false; } - /** - * Adds a {@link Entity} from to sector. Note that this does not spawn the entity, or do any other action other than - * register it to this sector. The return value of this method should also be monitored - if this method fails (i.e. - * returns {@code false}), the entity should not be registered in the world. - * - * @param entity The entity. - * @return {@code true} if the entity was added successfully, otherwise {@code false}. - */ - public boolean addEntity(Entity entity) { - Position position = entity.getPosition(); - List entities = this.entities.get(position); - if (entities == null) { - entities = new ArrayList<>(); - } - - if (entities.add(entity)) { - this.entities.put(position, entities); - notifyListeners(entity); - return true; - } - return false; - } - - /** - * Checks if this sector contains the specified entity. - * - * @param entity The entity. - * @return {@code true} if this sector contains the entity, otherwise {@code false}. - */ - public boolean contains(Entity entity) { - return entities.get(entity.getPosition()).contains(entity); - } - - /** - * Gets this sector's {@link SectorCoordinates}. - * - * @return The sector coordinates. - */ - public SectorCoordinates getCoordinates() { - return coordinates; - } - - /** - * Gets a copy of the {@link List} of {@link Entity}s. - * - * @param position The position containing the entities. - * @return The list. - */ - public List getEntities(Position position) { - return new ArrayList<>(entities.get(position)); - } - - /** - * Gets a copy of the {@link List} of {@link Entity}s with the specified {@link EntityType}. - * - * @param position The {@link Position} containing the entities. - * @param type The {@link EntityType}. - * @return The list of entities. - */ - @SuppressWarnings("unchecked") - public List getEntities(Position position, EntityType type) { - return (List) entities.get(position).stream().filter((e) -> e.getEntityType() == type) - .collect(Collectors.toList()); - } - - /** - * Notifies the listeners registered to this sector that an update has occurred. - * - * @param entity The entity that was updated. - */ - public void notifyListeners(Entity entity) { - listeners.forEach((l) -> l.execute(this, entity)); - } - - /** - * Removes a {@link Entity} from this sector. - * - * @param entity The entity. - * @return {@code true} if the entity was removed, otherwise {@code false}. - */ - public boolean removeEntity(Entity entity) { - Position position = entity.getPosition(); - List entities = this.entities.get(position); - if (entities == null) { - this.entities.put(position, new ArrayList<>()); - return false; - } - - if (entities.remove(entity)) { - notifyListeners(entity); - return true; - } - return false; + if (entities.remove(entity)) { + notifyListeners(entity); + return true; } + return false; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/area/SectorCoordinates.java b/src/org/apollo/game/model/area/SectorCoordinates.java index ca5203dd..7d922097 100644 --- a/src/org/apollo/game/model/area/SectorCoordinates.java +++ b/src/org/apollo/game/model/area/SectorCoordinates.java @@ -10,70 +10,70 @@ import org.apollo.game.model.Position; */ public final class SectorCoordinates { - /** - * Gets a pair of sector coordinates from a {@link Position}. - * - * @param position The position. - * @return The sector coordinates. - */ - public static SectorCoordinates fromPosition(Position position) { - return new SectorCoordinates(position.getTopLeftSectorX(), position.getTopLeftSectorY()); + /** + * Gets a pair of sector coordinates from a {@link Position}. + * + * @param position The position. + * @return The sector coordinates. + */ + public static SectorCoordinates fromPosition(Position position) { + return new SectorCoordinates(position.getTopLeftSectorX(), position.getTopLeftSectorY()); + } + + /** + * The x coordinate of this sector. + */ + private final int x; + + /** + * The y coordinate of this sector. + */ + private final int y; + + /** + * Creates the sector coordinates. + * + * @param x The x coordinate. + * @param y The y coordinate. + */ + public SectorCoordinates(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { + return false; } - - /** - * The x coordinate of this sector. - */ - private final int x; - - /** - * The y coordinate of this sector. - */ - private final int y; - - /** - * Creates the sector coordinates. - * - * @param x The x coordinate. - * @param y The y coordinate. - */ - public SectorCoordinates(int x, int y) { - this.x = x; - this.y = y; + final SectorCoordinates other = (SectorCoordinates) obj; + if (x != other.x || y != other.y) { + return false; } + return true; + } - @Override - public boolean equals(Object obj) { - if (obj == null || getClass() != obj.getClass()) { - return false; - } - final SectorCoordinates other = (SectorCoordinates) obj; - if (x != other.x || y != other.y) { - return false; - } - return true; - } + /** + * Gets the x coordinate (equivalent to the {@link Position#getTopLeftSectorX()} of a position within this sector). + * + * @return The x coordinate. + */ + public int getX() { + return x; + } - /** - * Gets the x coordinate (equivalent to the {@link Position#getTopLeftSectorX()} of a position within this sector). - * - * @return The x coordinate. - */ - public int getX() { - return x; - } + /** + * Gets the y coordinate (equivalent to the {@link Position#getTopLeftSectorY()} of a position within this sector). + * + * @return The y coordinate. + */ + public int getY() { + return y; + } - /** - * Gets the y coordinate (equivalent to the {@link Position#getTopLeftSectorY()} of a position within this sector). - * - * @return The y coordinate. - */ - public int getY() { - return y; - } - - @Override - public int hashCode() { - return 61 * (427 + x) + y; - } + @Override + public int hashCode() { + return 61 * (427 + x) + y; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/area/SectorListener.java b/src/org/apollo/game/model/area/SectorListener.java index c99d6433..5de1fd94 100644 --- a/src/org/apollo/game/model/area/SectorListener.java +++ b/src/org/apollo/game/model/area/SectorListener.java @@ -10,12 +10,12 @@ import org.apollo.game.model.entity.Entity; @FunctionalInterface public interface SectorListener { - /** - * Executes the action for this listener. - * - * @param The sector that was updated. - * @param entity The affected entity. - */ - public abstract void execute(Sector sector, Entity entity); + /** + * Executes the action for this listener. + * + * @param The sector that was updated. + * @param entity The affected entity. + */ + public abstract void execute(Sector sector, Entity entity); } \ No newline at end of file diff --git a/src/org/apollo/game/model/area/SectorRepository.java b/src/org/apollo/game/model/area/SectorRepository.java index 37d0a2e8..7b55180c 100644 --- a/src/org/apollo/game/model/area/SectorRepository.java +++ b/src/org/apollo/game/model/area/SectorRepository.java @@ -13,100 +13,100 @@ import java.util.Map; */ public final class SectorRepository { - /** - * Indicates whether sectors can be removed from this repository. - */ - private final boolean permitRemoval; + /** + * Indicates whether sectors can be removed from this repository. + */ + private final boolean permitRemoval; - /** - * A {@link Map} of {@link SectorCoordinates} that correspond to the appropriate {@link Sector}s. - */ - private final Map sectors = new HashMap<>(); + /** + * A {@link Map} of {@link SectorCoordinates} that correspond to the appropriate {@link Sector}s. + */ + private final Map sectors = new HashMap<>(); - /** - * Creates a new sector repository. - * - * @param permitRemoval If removal (of {@link Sector}s) from this repository should be permitted. - */ - public SectorRepository(boolean permitRemoval) { - this.permitRemoval = permitRemoval; + /** + * Creates a new sector repository. + * + * @param permitRemoval If removal (of {@link Sector}s) from this repository should be permitted. + */ + public SectorRepository(boolean permitRemoval) { + this.permitRemoval = permitRemoval; + } + + /** + * Adds a {@link Sector} to the repository. + * + * @param sector The sector. + * @throws IllegalArgumentException If the provided sector is null. + * @throws UnsupportedOperationException If the coordinates of the provided sector are already mapped (and hence the + * existing sector would be replaced), and removal of sectors is not permitted. + */ + public void add(Sector sector) { + if (sector == null) { + throw new IllegalArgumentException("Sector cannot be null."); + } else if (sectors.containsKey(sector.getCoordinates()) && !permitRemoval) { + throw new UnsupportedOperationException( + "Cannot add a sector with the same coordinates as an existing sector."); } + sectors.put(sector.getCoordinates(), sector); + } - /** - * Adds a {@link Sector} to the repository. - * - * @param sector The sector. - * @throws IllegalArgumentException If the provided sector is null. - * @throws UnsupportedOperationException If the coordinates of the provided sector are already mapped (and hence the - * existing sector would be replaced), and removal of sectors is not permitted. - */ - public void add(Sector sector) { - if (sector == null) { - throw new IllegalArgumentException("Sector cannot be null."); - } else if (sectors.containsKey(sector.getCoordinates()) && !permitRemoval) { - throw new UnsupportedOperationException( - "Cannot add a sector with the same coordinates as an existing sector."); - } - sectors.put(sector.getCoordinates(), sector); - } + /** + * Indicates whether the supplied value (i.e. the {@link Sector}) has a mapping. + * + * @param sector The sector. + * @return {@code true} if the value is mapped by a key (i.e. {@link SectorCoordinates}), otherwise {@code false}. + */ + public boolean contains(Sector sector) { + return sectors.containsValue(sector); + } - /** - * Indicates whether the supplied value (i.e. the {@link Sector}) has a mapping. - * - * @param sector The sector. - * @return {@code true} if the value is mapped by a key (i.e. {@link SectorCoordinates}), otherwise {@code false}. - */ - public boolean contains(Sector sector) { - return sectors.containsValue(sector); - } + /** + * Indicates whether the supplied key (i.e. the {@link SectorCoordinates}) has a mapping. + * + * @param coordinates The coordinates. + * @return {@code true} if the key is already mapped to a value (i.e. a {@link Sector}), otherwise {@code false}. + */ + public boolean contains(SectorCoordinates coordinates) { + return sectors.containsKey(coordinates); + } - /** - * Indicates whether the supplied key (i.e. the {@link SectorCoordinates}) has a mapping. - * - * @param coordinates The coordinates. - * @return {@code true} if the key is already mapped to a value (i.e. a {@link Sector}), otherwise {@code false}. - */ - public boolean contains(SectorCoordinates coordinates) { - return sectors.containsKey(coordinates); + /** + * Gets a {@link Sector} with the specified {@link SectorCoordinates}. If the sector does not exist (i.e. + * {@link #sectors}{@code .get()} returns {@code null}) then a new sector is created, submitted to the repository, + * and returned. + * + * @param coordinates The coordinates. + * @return The sector. + */ + public Sector get(SectorCoordinates coordinates) { + Sector sector = sectors.get(coordinates); + if (sector == null) { + sector = new Sector(coordinates); + add(sector); } + return sector; + } - /** - * Gets a {@link Sector} with the specified {@link SectorCoordinates}. If the sector does not exist (i.e. - * {@link #sectors}{@code .get()} returns {@code null}) then a new sector is created, submitted to the repository, - * and returned. - * - * @param coordinates The coordinates. - * @return The sector. - */ - public Sector get(SectorCoordinates coordinates) { - Sector sector = sectors.get(coordinates); - if (sector == null) { - sector = new Sector(coordinates); - add(sector); - } - return sector; - } + /** + * Gets the {@link List} of {@link Sector}s. + * + * @return The list. + */ + public List getSectors() { + return new ArrayList<>(sectors.values()); + } - /** - * Gets the {@link List} of {@link Sector}s. - * - * @return The list. - */ - public List getSectors() { - return new ArrayList<>(sectors.values()); - } - - /** - * Removes a {@link Sector} from the repository, if permitted. - * - * @param sector The sector to remove. - * @throws UnsupportedOperationException If this method is called on a repository that does not permit removal. - */ - public void remove(Sector sector) { - if (!permitRemoval) { - throw new UnsupportedOperationException("Cannot remove sectors from this repository."); - } - sectors.remove(sector.getCoordinates()); + /** + * Removes a {@link Sector} from the repository, if permitted. + * + * @param sector The sector to remove. + * @throws UnsupportedOperationException If this method is called on a repository that does not permit removal. + */ + public void remove(Sector sector) { + if (!permitRemoval) { + throw new UnsupportedOperationException("Cannot remove sectors from this repository."); } + sectors.remove(sector.getCoordinates()); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/def/EquipmentDefinition.java b/src/org/apollo/game/model/def/EquipmentDefinition.java index 16a16914..08c04f6c 100644 --- a/src/org/apollo/game/model/def/EquipmentDefinition.java +++ b/src/org/apollo/game/model/def/EquipmentDefinition.java @@ -13,268 +13,268 @@ import org.apollo.game.model.entity.Skill; */ public final class EquipmentDefinition { - /** - * The equipment definitions. - */ - private static final Map definitions = new HashMap(); + /** + * The equipment definitions. + */ + private static final Map definitions = new HashMap(); - /** - * Initialises the equipment definitions. - * - * @param definitions The definitions. - * @throws RuntimeException If there is an id mismatch. - */ - public static void init(EquipmentDefinition[] definitions) { - for (int id = 0; id < definitions.length; id++) { - EquipmentDefinition def = definitions[id]; - if (def != null) { - if (def.getId() != id) { - throw new RuntimeException("Equipment definition id mismatch."); - } - EquipmentDefinition.definitions.put(def.getId(), def); - } + /** + * Initialises the equipment definitions. + * + * @param definitions The definitions. + * @throws RuntimeException If there is an id mismatch. + */ + public static void init(EquipmentDefinition[] definitions) { + for (int id = 0; id < definitions.length; id++) { + EquipmentDefinition def = definitions[id]; + if (def != null) { + if (def.getId() != id) { + throw new RuntimeException("Equipment definition id mismatch."); } + EquipmentDefinition.definitions.put(def.getId(), def); + } } + } - /** - * Gets an equipment definition by its id. - * - * @param id The id. - * @return {@code null} if the item is not equipment, the definition otherwise. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public static EquipmentDefinition lookup(int id) { - if (id < 0 || id >= ItemDefinition.count()) { - throw new IndexOutOfBoundsException(EquipmentDefinition.class.getName() + " lookup index " + id - + " out of bounds."); - } - return definitions.get(id); + /** + * Gets an equipment definition by its id. + * + * @param id The id. + * @return {@code null} if the item is not equipment, the definition otherwise. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public static EquipmentDefinition lookup(int id) { + if (id < 0 || id >= ItemDefinition.count()) { + throw new IndexOutOfBoundsException(EquipmentDefinition.class.getName() + " lookup index " + id + + " out of bounds."); } + return definitions.get(id); + } - /** - * The item id. - */ - private final int id; + /** + * The item id. + */ + private final int id; - /** - * The array of skill requirement levels. - */ - private int[] levels = { 1, 1, 1, 1, 1, 1, 1 }; + /** + * The array of skill requirement levels. + */ + private int[] levels = { 1, 1, 1, 1, 1, 1, 1 }; - /** - * The slot this equipment goes into. - */ - private int slot; + /** + * The slot this equipment goes into. + */ + private int slot; - /** - * Various flags. - */ - private boolean twoHanded, fullBody, fullHat, fullMask; + /** + * Various flags. + */ + private boolean twoHanded, fullBody, fullHat, fullMask; - /** - * Creates a new equipment definition. - * - * @param id The id. - */ - public EquipmentDefinition(int id) { - this.id = id; + /** + * Creates a new equipment definition. + * + * @param id The id. + */ + public EquipmentDefinition(int id) { + this.id = id; + } + + /** + * Gets the total number of equipment definitions. + * + * @return The count. + */ + public int count() { + return definitions.size(); + } + + /** + * Gets the minimum attack level required to equip this item. + * + * @return The level. + */ + public int getAttackLevel() { + return levels[Skill.ATTACK]; + } + + /** + * Gets the minimum defence level required to equip this item. + * + * @return The level. + */ + public int getDefenceLevel() { + return levels[Skill.DEFENCE]; + } + + /** + * Gets the minimum hitpoints level required to equip this item. + * + * @return The level. + */ + public int getHitpointsLevel() { + return levels[Skill.HITPOINTS]; + } + + /** + * Gets the id. + * + * @return The id. + */ + public int getId() { + return id; + } + + /** + * Gets the minimum level required to equip this item for a specific skill. + * + * @param skill The skill id. + * @return The level. + */ + public int getLevel(int skill) { + if (skill < Skill.ATTACK || skill > Skill.MAGIC) { + throw new IllegalArgumentException("Skill id out of bounds."); } + return levels[skill]; + } - /** - * Gets the total number of equipment definitions. - * - * @return The count. - */ - public int count() { - return definitions.size(); - } + /** + * Gets the minimum magic level required to equip this item. + * + * @return The level. + */ + public int getMagicLevel() { + return levels[Skill.MAGIC]; + } - /** - * Gets the minimum attack level required to equip this item. - * - * @return The level. - */ - public int getAttackLevel() { - return levels[Skill.ATTACK]; - } + /** + * Gets the minimum prayer level required to equip this item. + * + * @return The level. + */ + public int getPrayerLevel() { + return levels[Skill.PRAYER]; + } - /** - * Gets the minimum defence level required to equip this item. - * - * @return The level. - */ - public int getDefenceLevel() { - return levels[Skill.DEFENCE]; - } + /** + * Gets the minimum ranged level required to equip this item. + * + * @return The level. + */ + public int getRangedLevel() { + return levels[Skill.RANGED]; + } - /** - * Gets the minimum hitpoints level required to equip this item. - * - * @return The level. - */ - public int getHitpointsLevel() { - return levels[Skill.HITPOINTS]; - } + /** + * Gets the target slot. + * + * @return The target slot. + */ + public int getSlot() { + return slot; + } - /** - * Gets the id. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the minimum strength level required to equip this item. + * + * @return The level. + */ + public int getStrengthLevel() { + return levels[Skill.STRENGTH]; + } - /** - * Gets the minimum level required to equip this item for a specific skill. - * - * @param skill The skill id. - * @return The level. - */ - public int getLevel(int skill) { - if (skill < Skill.ATTACK || skill > Skill.MAGIC) { - throw new IllegalArgumentException("Skill id out of bounds."); - } - return levels[skill]; - } + /** + * Checks if this equipment is a full body. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isFullBody() { + return fullBody; + } - /** - * Gets the minimum magic level required to equip this item. - * - * @return The level. - */ - public int getMagicLevel() { - return levels[Skill.MAGIC]; - } + /** + * Checks if this equipment is a full hat. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isFullHat() { + return fullHat; + } - /** - * Gets the minimum prayer level required to equip this item. - * - * @return The level. - */ - public int getPrayerLevel() { - return levels[Skill.PRAYER]; - } + /** + * Checks if this equipment is a full mask. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isFullMask() { + return fullMask; + } - /** - * Gets the minimum ranged level required to equip this item. - * - * @return The level. - */ - public int getRangedLevel() { - return levels[Skill.RANGED]; - } + /** + * Checks if this equipment is two-handed. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isTwoHanded() { + return twoHanded; + } - /** - * Gets the target slot. - * - * @return The target slot. - */ - public int getSlot() { - return slot; - } + /** + * Sets the flags. + * + * @param twoHanded The two handed flag. + * @param fullBody The full body flag. + * @param fullHat The full hat flag. + * @param fullMask The full mask flag. + */ + public void setFlags(boolean twoHanded, boolean fullBody, boolean fullHat, boolean fullMask) { + this.twoHanded = twoHanded; + this.fullBody = fullBody; + this.fullHat = fullHat; + this.fullMask = fullMask; + } - /** - * Gets the minimum strength level required to equip this item. - * - * @return The level. - */ - public int getStrengthLevel() { - return levels[Skill.STRENGTH]; - } + /** + * Sets the required levels. + * + * @param attack The required attack level. + * @param strength The required strength level. + * @param defence The required defence level. + * @param ranged The required ranged level. + * @param magic The required magic level. + */ + public void setLevels(int attack, int strength, int defence, int ranged, int magic) { + setLevels(attack, strength, defence, 1, ranged, 1, magic); + } - /** - * Checks if this equipment is a full body. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isFullBody() { - return fullBody; - } + /** + * Sets the required levels. + * + * @param attack The required attack level. + * @param strength The required strength level. + * @param defence The required defence level. + * @param hitpoints The required hitpoints level. + * @param ranged The required ranged level. + * @param prayer The required prayer level. + * @param magic The required magic level. + */ + public void setLevels(int attack, int strength, int defence, int hitpoints, int ranged, int prayer, int magic) { + levels[Skill.ATTACK] = attack; + levels[Skill.STRENGTH] = strength; + levels[Skill.DEFENCE] = defence; + levels[Skill.HITPOINTS] = hitpoints; + levels[Skill.RANGED] = ranged; + levels[Skill.PRAYER] = prayer; + levels[Skill.MAGIC] = magic; + } - /** - * Checks if this equipment is a full hat. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isFullHat() { - return fullHat; - } - - /** - * Checks if this equipment is a full mask. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isFullMask() { - return fullMask; - } - - /** - * Checks if this equipment is two-handed. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isTwoHanded() { - return twoHanded; - } - - /** - * Sets the flags. - * - * @param twoHanded The two handed flag. - * @param fullBody The full body flag. - * @param fullHat The full hat flag. - * @param fullMask The full mask flag. - */ - public void setFlags(boolean twoHanded, boolean fullBody, boolean fullHat, boolean fullMask) { - this.twoHanded = twoHanded; - this.fullBody = fullBody; - this.fullHat = fullHat; - this.fullMask = fullMask; - } - - /** - * Sets the required levels. - * - * @param attack The required attack level. - * @param strength The required strength level. - * @param defence The required defence level. - * @param ranged The required ranged level. - * @param magic The required magic level. - */ - public void setLevels(int attack, int strength, int defence, int ranged, int magic) { - setLevels(attack, strength, defence, 1, ranged, 1, magic); - } - - /** - * Sets the required levels. - * - * @param attack The required attack level. - * @param strength The required strength level. - * @param defence The required defence level. - * @param hitpoints The required hitpoints level. - * @param ranged The required ranged level. - * @param prayer The required prayer level. - * @param magic The required magic level. - */ - public void setLevels(int attack, int strength, int defence, int hitpoints, int ranged, int prayer, int magic) { - levels[Skill.ATTACK] = attack; - levels[Skill.STRENGTH] = strength; - levels[Skill.DEFENCE] = defence; - levels[Skill.HITPOINTS] = hitpoints; - levels[Skill.RANGED] = ranged; - levels[Skill.PRAYER] = prayer; - levels[Skill.MAGIC] = magic; - } - - /** - * Sets the target slot. - * - * @param slot The target slot. - */ - public void setSlot(int slot) { - this.slot = slot; - } + /** + * Sets the target slot. + * + * @param slot The target slot. + */ + public void setSlot(int slot) { + this.slot = slot; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/def/ItemDefinition.java b/src/org/apollo/game/model/def/ItemDefinition.java index 9d219793..e0dbd3d4 100644 --- a/src/org/apollo/game/model/def/ItemDefinition.java +++ b/src/org/apollo/game/model/def/ItemDefinition.java @@ -12,411 +12,411 @@ import com.google.common.collect.HashBiMap; */ public final class ItemDefinition { - /** - * The item definitions. - */ - private static ItemDefinition[] definitions; + /** + * The item definitions. + */ + private static ItemDefinition[] definitions; - /** - * A map of item ids to noted ids. - */ - private static final BiMap notes = HashBiMap.create(); + /** + * A map of item ids to noted ids. + */ + private static final BiMap notes = HashBiMap.create(); - /** - * A map of noted ids to item ids. - */ - private static final BiMap notesInverse = notes.inverse(); + /** + * A map of noted ids to item ids. + */ + private static final BiMap notesInverse = notes.inverse(); - /** - * Gets the total number of item definitions. - * - * @return The count. - */ - public static int count() { - return definitions.length; + /** + * Gets the total number of item definitions. + * + * @return The count. + */ + public static int count() { + return definitions.length; + } + + /** + * Gets the array of item definitions. + * + * @return The definitions. + */ + public static ItemDefinition[] getDefinitions() { + return definitions; + } + + /** + * Initialises the class with the specified set of definitions. + * + * @param definitions The definitions. + * @throws RuntimeException If there is an id mismatch. + */ + public static void init(ItemDefinition[] definitions) { + ItemDefinition.definitions = definitions; + for (int id = 0; id < definitions.length; id++) { + ItemDefinition def = definitions[id]; + if (def.getId() != id) { + throw new RuntimeException("Item definition id mismatch."); + } + if (def.isNote()) { + def.toNote(); + notes.put(def.getNoteInfoId(), def.getId()); + } } + } - /** - * Gets the array of item definitions. - * - * @return The definitions. - */ - public static ItemDefinition[] getDefinitions() { - return definitions; + /** + * Converts an item id to a noted id. + * + * @param id The item id. + * @return The noted id. + */ + public static int itemToNote(int id) { + Integer entry = notes.get(id); + if (entry == null) { + return id; } + return entry; + } - /** - * Initialises the class with the specified set of definitions. - * - * @param definitions The definitions. - * @throws RuntimeException If there is an id mismatch. - */ - public static void init(ItemDefinition[] definitions) { - ItemDefinition.definitions = definitions; - for (int id = 0; id < definitions.length; id++) { - ItemDefinition def = definitions[id]; - if (def.getId() != id) { - throw new RuntimeException("Item definition id mismatch."); - } - if (def.isNote()) { - def.toNote(); - notes.put(def.getNoteInfoId(), def.getId()); - } - } + /** + * Gets the item definition for the specified id. + * + * @param id The id. + * @return The definition. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public static ItemDefinition lookup(int id) { + if (id < 0 || id >= definitions.length) { + throw new IndexOutOfBoundsException(ItemDefinition.class.getName() + " lookup index " + id + + " out of bounds."); } + return definitions[id]; + } - /** - * Converts an item id to a noted id. - * - * @param id The item id. - * @return The noted id. - */ - public static int itemToNote(int id) { - Integer entry = notes.get(id); - if (entry == null) { - return id; - } - return entry; + /** + * Converts a noted id to the normal item id. + * + * @param id The note id. + * @return The item id. + */ + public static int noteToItem(int id) { + Integer entry = notesInverse.get(id); + if (entry == null) { + return id; } + return entry; + } - /** - * Gets the item definition for the specified id. - * - * @param id The id. - * @return The definition. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public static ItemDefinition lookup(int id) { - if (id < 0 || id >= definitions.length) { - throw new IndexOutOfBoundsException(ItemDefinition.class.getName() + " lookup index " + id - + " out of bounds."); - } - return definitions[id]; + /** + * The description of the item. + */ + private String description; + + /** + * The ground actions array. + */ + private String[] groundActions = new String[5]; + + /** + * The item's id. + */ + private final int id; + + /** + * The inventory actions array. + */ + private String[] inventoryActions = new String[5]; + + /** + * A flag indicating if this item is members only. + */ + private boolean members = false; + + /** + * The name of the item. + */ + private String name; + + /** + * The id of the item to copy note graphics from. + */ + private int noteGraphicId = -1; + + /** + * The id of the item to copy note info from. + */ + private int noteInfoId = -1; + + /** + * A flag indicating if this item is stackable. + */ + private boolean stackable; + + /** + * This item's team. + */ + private int team; + + /** + * The item's floor value. + */ + private int value = 1; + + /** + * Creates an item definition with the default values. + * + * @param id The item's id. + */ + public ItemDefinition(int id) { + this.id = id; + } + + /** + * Gets the description of this item. + * + * @return The item's description. + */ + public String getDescription() { + return description; + } + + /** + * Gets a ground action. + * + * @param id The id. + * @return The action. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public String getGroundAction(int id) { + if (id < 0 || id >= groundActions.length) { + throw new IndexOutOfBoundsException("Ground action id is out of bounds."); } + return groundActions[id]; + } - /** - * Converts a noted id to the normal item id. - * - * @param id The note id. - * @return The item id. - */ - public static int noteToItem(int id) { - Integer entry = notesInverse.get(id); - if (entry == null) { - return id; - } - return entry; + /** + * Gets this item's id. + * + * @return The id. + */ + public int getId() { + return id; + } + + /** + * Gets an inventory action. + * + * @param id The id. + * @return The action. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public String getInventoryAction(int id) { + if (id < 0 || id >= inventoryActions.length) { + throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); } + return inventoryActions[id]; + } - /** - * The description of the item. - */ - private String description; + /** + * Gets this item's name. + * + * @return The name. + */ + public String getName() { + return name; + } - /** - * The ground actions array. - */ - private String[] groundActions = new String[5]; + /** + * Gets this item's note graphic id. + * + * @return The note graphic id. + */ + public int getNoteGraphicId() { + return noteGraphicId; + } - /** - * The item's id. - */ - private final int id; + /** + * Gets this item's note info id. + * + * @return The note info id. + */ + public int getNoteInfoId() { + return noteInfoId; + } - /** - * The inventory actions array. - */ - private String[] inventoryActions = new String[5]; + /** + * Gets this item's team. + * + * @return The team. + */ + public int getTeam() { + return team; + } - /** - * A flag indicating if this item is members only. - */ - private boolean members = false; + /** + * Gets this item's value. + * + * @return The value. + */ + public int getValue() { + return value; + } - /** - * The name of the item. - */ - private String name; + /** + * Checks if this item is members only. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isMembersOnly() { + return members; + } - /** - * The id of the item to copy note graphics from. - */ - private int noteGraphicId = -1; + /** + * Checks if this item is a note. + * + * @return {@code true} if so, {@code false} otherwise. + */ + public boolean isNote() { + return noteGraphicId != -1 && noteInfoId != -1; + } - /** - * The id of the item to copy note info from. - */ - private int noteInfoId = -1; + /** + * Checks if the item specified by this definition is stackable. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isStackable() { + return stackable; + } - /** - * A flag indicating if this item is stackable. - */ - private boolean stackable; + /** + * Sets this item's description. + * + * @param description The description. + */ + public void setDescription(String description) { + this.description = description; + } - /** - * This item's team. - */ - private int team; - - /** - * The item's floor value. - */ - private int value = 1; - - /** - * Creates an item definition with the default values. - * - * @param id The item's id. - */ - public ItemDefinition(int id) { - this.id = id; + /** + * Sets a ground action. + * + * @param id The id. + * @param action The action. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public void setGroundAction(int id, String action) { + if (id < 0 || id >= groundActions.length) { + throw new IndexOutOfBoundsException("Ground action id is out of bounds."); } + groundActions[id] = action; + } - /** - * Gets the description of this item. - * - * @return The item's description. - */ - public String getDescription() { - return description; + /** + * Sets an inventory action. + * + * @param id The id. + * @param action The action. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public void setInventoryAction(int id, String action) { + if (id < 0 || id >= inventoryActions.length) { + throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); } + inventoryActions[id] = action; + } - /** - * Gets a ground action. - * - * @param id The id. - * @return The action. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public String getGroundAction(int id) { - if (id < 0 || id >= groundActions.length) { - throw new IndexOutOfBoundsException("Ground action id is out of bounds."); - } - return groundActions[id]; - } - - /** - * Gets this item's id. - * - * @return The id. - */ - public int getId() { - return id; - } - - /** - * Gets an inventory action. - * - * @param id The id. - * @return The action. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public String getInventoryAction(int id) { - if (id < 0 || id >= inventoryActions.length) { - throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); - } - return inventoryActions[id]; - } - - /** - * Gets this item's name. - * - * @return The name. - */ - public String getName() { - return name; - } - - /** - * Gets this item's note graphic id. - * - * @return The note graphic id. - */ - public int getNoteGraphicId() { - return noteGraphicId; - } - - /** - * Gets this item's note info id. - * - * @return The note info id. - */ - public int getNoteInfoId() { - return noteInfoId; - } - - /** - * Gets this item's team. - * - * @return The team. - */ - public int getTeam() { - return team; - } - - /** - * Gets this item's value. - * - * @return The value. - */ - public int getValue() { - return value; - } - - /** - * Checks if this item is members only. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isMembersOnly() { - return members; - } - - /** - * Checks if this item is a note. - * - * @return {@code true} if so, {@code false} otherwise. - */ - public boolean isNote() { - return noteGraphicId != -1 && noteInfoId != -1; - } - - /** - * Checks if the item specified by this definition is stackable. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isStackable() { - return stackable; - } - - /** - * Sets this item's description. - * - * @param description The description. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets a ground action. - * - * @param id The id. - * @param action The action. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public void setGroundAction(int id, String action) { - if (id < 0 || id >= groundActions.length) { - throw new IndexOutOfBoundsException("Ground action id is out of bounds."); - } - groundActions[id] = action; - } - - /** - * Sets an inventory action. - * - * @param id The id. - * @param action The action. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public void setInventoryAction(int id, String action) { - if (id < 0 || id >= inventoryActions.length) { - throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); - } - inventoryActions[id] = action; - } - - /** - * Sets this item's members only flag. - * - * @param members The flag. - */ - public void setMembersOnly(boolean members) { - this.members = members; - } - - /** - * Sets this item's name. - * - * @param name The name. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Sets this item's note graphic id. - * - * @param noteGraphicId The note graphic id. - */ - public void setNoteGraphicId(int noteGraphicId) { - this.noteGraphicId = noteGraphicId; - } - - /** - * Sets this item's note info id. - * - * @param noteInfoId The note info id. - */ - public void setNoteInfoId(int noteInfoId) { - this.noteInfoId = noteInfoId; - } - - /** - * Sets this item's stackable flag. - * - * @param stackable The stackable flag. - */ - public void setStackable(boolean stackable) { - this.stackable = stackable; - } - - /** - * Sets this item's team. - * - * @param team The team. - */ - public void setTeam(int team) { - this.team = team; - } - - /** - * sets this item's value. - * - * @param value The value. - */ - public void setValue(int value) { - this.value = value; - } - - /** - * Converts this item to a note, if possible. - * - * @throws IllegalStateException If {@link ItemDefinition#isNote()} returns {@code false}. - */ - public void toNote() { - if (isNote()) { - if (description != null && description.startsWith("Swap this note at any bank for ")) { - return; // already converted TODO better way of checking? - } - - ItemDefinition infoDef = lookup(noteInfoId); - name = infoDef.name; - members = infoDef.members; - - String prefix = "a"; - char firstChar = name == null ? 'n' : name.charAt(0); - - if (firstChar == 'A' || firstChar == 'E' || firstChar == 'I' || firstChar == 'O' || firstChar == 'U') { - prefix = "an"; - } - - description = "Swap this note at any bank for " + prefix + " " + name + "."; - stackable = true; - } else { - throw new IllegalStateException("Item cannot be noted."); - } + /** + * Sets this item's members only flag. + * + * @param members The flag. + */ + public void setMembersOnly(boolean members) { + this.members = members; + } + + /** + * Sets this item's name. + * + * @param name The name. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets this item's note graphic id. + * + * @param noteGraphicId The note graphic id. + */ + public void setNoteGraphicId(int noteGraphicId) { + this.noteGraphicId = noteGraphicId; + } + + /** + * Sets this item's note info id. + * + * @param noteInfoId The note info id. + */ + public void setNoteInfoId(int noteInfoId) { + this.noteInfoId = noteInfoId; + } + + /** + * Sets this item's stackable flag. + * + * @param stackable The stackable flag. + */ + public void setStackable(boolean stackable) { + this.stackable = stackable; + } + + /** + * Sets this item's team. + * + * @param team The team. + */ + public void setTeam(int team) { + this.team = team; + } + + /** + * sets this item's value. + * + * @param value The value. + */ + public void setValue(int value) { + this.value = value; + } + + /** + * Converts this item to a note, if possible. + * + * @throws IllegalStateException If {@link ItemDefinition#isNote()} returns {@code false}. + */ + public void toNote() { + if (isNote()) { + if (description != null && description.startsWith("Swap this note at any bank for ")) { + return; // already converted TODO better way of checking? + } + + ItemDefinition infoDef = lookup(noteInfoId); + name = infoDef.name; + members = infoDef.members; + + String prefix = "a"; + char firstChar = name == null ? 'n' : name.charAt(0); + + if (firstChar == 'A' || firstChar == 'E' || firstChar == 'I' || firstChar == 'O' || firstChar == 'U') { + prefix = "an"; + } + + description = "Swap this note at any bank for " + prefix + " " + name + "."; + stackable = true; + } else { + throw new IllegalStateException("Item cannot be noted."); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/def/NpcDefinition.java b/src/org/apollo/game/model/def/NpcDefinition.java index 13c05b3b..b04500d5 100644 --- a/src/org/apollo/game/model/def/NpcDefinition.java +++ b/src/org/apollo/game/model/def/NpcDefinition.java @@ -9,366 +9,366 @@ import org.apollo.game.model.entity.Npc; */ public final class NpcDefinition { - /** - * The NPC definitions. - */ - private static NpcDefinition[] definitions; + /** + * The NPC definitions. + */ + private static NpcDefinition[] definitions; - /** - * Gets the total number of npc definitions. - * - * @return The count. - */ - public static int count() { - return definitions.length; + /** + * Gets the total number of npc definitions. + * + * @return The count. + */ + public static int count() { + return definitions.length; + } + + /** + * Gets the array of npc definitions. + * + * @return The definitions. + */ + public static NpcDefinition[] getDefinitions() { + return definitions; + } + + /** + * Initialises the class with the specified set of definitions. + * + * @param definitions The definitions. + * @throws RuntimeException If there is an id mismatch. + */ + public static void init(NpcDefinition[] definitions) { + NpcDefinition.definitions = definitions; + for (int id = 0; id < definitions.length; id++) { + NpcDefinition def = definitions[id]; + if (def.getId() != id) { + throw new RuntimeException("Npc definition id mismatch."); + } } + } - /** - * Gets the array of npc definitions. - * - * @return The definitions. - */ - public static NpcDefinition[] getDefinitions() { - return definitions; + /** + * Gets the NPC definition for the specified id. + * + * @param The id. + * @return The definition. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public static NpcDefinition lookup(int id) { + if (id < 0 || id >= definitions.length) { + throw new IndexOutOfBoundsException(NpcDefinition.class.getName() + " lookup index " + id + + " out of bounds."); } + return definitions[id]; + } - /** - * Initialises the class with the specified set of definitions. - * - * @param definitions The definitions. - * @throws RuntimeException If there is an id mismatch. - */ - public static void init(NpcDefinition[] definitions) { - NpcDefinition.definitions = definitions; - for (int id = 0; id < definitions.length; id++) { - NpcDefinition def = definitions[id]; - if (def.getId() != id) { - throw new RuntimeException("Npc definition id mismatch."); - } - } + /** + * The combat level of the NPC. + */ + private int combatLevel = -1; + + /** + * The description of the NPC. + */ + private String description; + + /** + * The NPC id. + */ + private final int id; + + /** + * An array of interaction options. + */ + private String[] interactions = new String[5]; + + /** + * The name of the NPC. + */ + private String name; + + /** + * The NPC's size, in tiles. + */ + private int size = 1; + + /** + * The various animation ids. + */ + private int standAnim = -1, walkAnim = -1, walkBackAnim = -1, walkLeftAnim = -1, walkRightAnim = -1; + + /** + * Creates a new NPC definition. + * + * @param id The NPC id. + */ + public NpcDefinition(int id) { + this.id = id; + } + + /** + * Gets the NPC's combat level. + * + * @return The combat level, or -1 if it doesn't have one. + */ + public int getCombatLevel() { + return combatLevel; + } + + /** + * Gets the description of the NPC. + * + * @return The description. + */ + public String getDescription() { + return description; + } + + /** + * Gets the NPC id. + * + * @return The NPC id. + */ + public int getId() { + return id; + } + + /** + * Gets an interaction option. + * + * @param slot The slot of the option. + * @return The option, or {@code null} if there isn't any at the specified slot. + * @throws IndexOutOfBoundsException If the slot is out of bounds. + */ + public String getInteraction(int slot) { + if (slot < 0 || slot >= interactions.length) { + throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); } + return interactions[slot]; + } - /** - * Gets the NPC definition for the specified id. - * - * @param The id. - * @return The definition. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public static NpcDefinition lookup(int id) { - if (id < 0 || id >= definitions.length) { - throw new IndexOutOfBoundsException(NpcDefinition.class.getName() + " lookup index " + id - + " out of bounds."); - } - return definitions[id]; + /** + * Gets the array of interaction options. + * + * @return The interaction options. + */ + public String[] getInteractions() { + return interactions; + } + + /** + * Gets the name of the NPC. + * + * @return The name of the NPC. + */ + public String getName() { + return name; + } + + /** + * Gets the NPC's size, in tiles. + * + * @return The size. + */ + public int getSize() { + return size; + } + + /** + * Gets the id of the NPC's standing animation. + * + * @return The stand animation id, or -1 if it doesn't have one. + */ + public int getStandAnimation() { + return standAnim; + } + + /** + * Gets the walking animation of the NPC. + * + * @return The walking animation. + */ + public int getWalkAnimation() { + return walkAnim; + } + + /** + * Gets the walk-back animation of the NPC. + * + * @return The walk-back animation. + */ + public int getWalkBackAnimation() { + return walkBackAnim; + } + + /** + * Gets the walk-left animation of the NPC. + * + * @return The walk-left animation. + */ + public int getWalkLeftAnimation() { + return walkLeftAnim; + } + + /** + * Gets the walk-right animation of the NPC. + * + * @return The walk-right animation. + */ + public int getWalkRightAnimation() { + return walkRightAnim; + } + + /** + * Checks if the NPC has a combat level. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasCombatLevel() { + return combatLevel != -1; + } + + /** + * Checks if there is an interaction option present. + * + * @param slot The slot to check. + * @return {@code true} if so, {@code false} if not. + * @throws IndexOutOfBoundsException If the slot is out of bounds. + */ + public boolean hasInteraction(int slot) { + if (slot < 0 || slot >= interactions.length) { + throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); } + return interactions[slot] != null; + } - /** - * The combat level of the NPC. - */ - private int combatLevel = -1; + /** + * Checks if the NPC has a standing animation id. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasStandAnimation() { + return standAnim != -1; + } - /** - * The description of the NPC. - */ - private String description; + /** + * Checks if the NPC has a walking animation. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasWalkAnimation() { + return walkAnim != -1; + } - /** - * The NPC id. - */ - private final int id; + /** + * Checks if the NPC has a walk-back animation. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasWalkBackAnimation() { + return walkBackAnim != -1; + } - /** - * An array of interaction options. - */ - private String[] interactions = new String[5]; + /** + * Checks if the NPC has a walk-left animation. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasWalkLeftAnimation() { + return walkLeftAnim != -1; + } - /** - * The name of the NPC. - */ - private String name; + /** + * Checks if the NPC has a walk-right animation. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasWalkRightAnimation() { + return walkRightAnim != -1; + } - /** - * The NPC's size, in tiles. - */ - private int size = 1; + /** + * Sets the NPC's combat level. + * + * @param combatLevel The combat level. + */ + public void setCombatLevel(int combatLevel) { + this.combatLevel = combatLevel; + } - /** - * The various animation ids. - */ - private int standAnim = -1, walkAnim = -1, walkBackAnim = -1, walkLeftAnim = -1, walkRightAnim = -1; + /** + * Sets the description of the NPC. + * + * @param description The description. + */ + public void setDescription(String description) { + this.description = description; + } - /** - * Creates a new NPC definition. - * - * @param id The NPC id. - */ - public NpcDefinition(int id) { - this.id = id; + /** + * Sets an interaction option. + * + * @param slot The slot of the option. + * @param interaction The interaction options. + * @throws IndexOutOfBoundsException If the slot is out of bounds. + */ + public void setInteraction(int slot, String interaction) { + if (slot < 0 || slot >= interactions.length) { + throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); } + interactions[slot] = interaction; + } - /** - * Gets the NPC's combat level. - * - * @return The combat level, or -1 if it doesn't have one. - */ - public int getCombatLevel() { - return combatLevel; - } + /** + * Sets the name of the NPC. + * + * @param name The name. + */ + public void setName(String name) { + this.name = name; + } - /** - * Gets the description of the NPC. - * - * @return The description. - */ - public String getDescription() { - return description; - } + /** + * Sets the size of the NPC, in tiles. + * + * @param size The size. + */ + public void setSize(int size) { + this.size = size; + } - /** - * Gets the NPC id. - * - * @return The NPC id. - */ - public int getId() { - return id; - } + /** + * Sets the id of the NPC's standing animation. + * + * @param standAnim The stand animation id. + */ + public void setStandAnimation(int standAnim) { + this.standAnim = standAnim; + } - /** - * Gets an interaction option. - * - * @param slot The slot of the option. - * @return The option, or {@code null} if there isn't any at the specified slot. - * @throws IndexOutOfBoundsException If the slot is out of bounds. - */ - public String getInteraction(int slot) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } - return interactions[slot]; - } + /** + * Sets the walking animation of the NPC. + * + * @param walkAnim The walking animation. + */ + public void setWalkAnimation(int walkAnim) { + this.walkAnim = walkAnim; + } - /** - * Gets the array of interaction options. - * - * @return The interaction options. - */ - public String[] getInteractions() { - return interactions; - } - - /** - * Gets the name of the NPC. - * - * @return The name of the NPC. - */ - public String getName() { - return name; - } - - /** - * Gets the NPC's size, in tiles. - * - * @return The size. - */ - public int getSize() { - return size; - } - - /** - * Gets the id of the NPC's standing animation. - * - * @return The stand animation id, or -1 if it doesn't have one. - */ - public int getStandAnimation() { - return standAnim; - } - - /** - * Gets the walking animation of the NPC. - * - * @return The walking animation. - */ - public int getWalkAnimation() { - return walkAnim; - } - - /** - * Gets the walk-back animation of the NPC. - * - * @return The walk-back animation. - */ - public int getWalkBackAnimation() { - return walkBackAnim; - } - - /** - * Gets the walk-left animation of the NPC. - * - * @return The walk-left animation. - */ - public int getWalkLeftAnimation() { - return walkLeftAnim; - } - - /** - * Gets the walk-right animation of the NPC. - * - * @return The walk-right animation. - */ - public int getWalkRightAnimation() { - return walkRightAnim; - } - - /** - * Checks if the NPC has a combat level. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasCombatLevel() { - return combatLevel != -1; - } - - /** - * Checks if there is an interaction option present. - * - * @param slot The slot to check. - * @return {@code true} if so, {@code false} if not. - * @throws IndexOutOfBoundsException If the slot is out of bounds. - */ - public boolean hasInteraction(int slot) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } - return interactions[slot] != null; - } - - /** - * Checks if the NPC has a standing animation id. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasStandAnimation() { - return standAnim != -1; - } - - /** - * Checks if the NPC has a walking animation. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasWalkAnimation() { - return walkAnim != -1; - } - - /** - * Checks if the NPC has a walk-back animation. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasWalkBackAnimation() { - return walkBackAnim != -1; - } - - /** - * Checks if the NPC has a walk-left animation. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasWalkLeftAnimation() { - return walkLeftAnim != -1; - } - - /** - * Checks if the NPC has a walk-right animation. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasWalkRightAnimation() { - return walkRightAnim != -1; - } - - /** - * Sets the NPC's combat level. - * - * @param combatLevel The combat level. - */ - public void setCombatLevel(int combatLevel) { - this.combatLevel = combatLevel; - } - - /** - * Sets the description of the NPC. - * - * @param description The description. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets an interaction option. - * - * @param slot The slot of the option. - * @param interaction The interaction options. - * @throws IndexOutOfBoundsException If the slot is out of bounds. - */ - public void setInteraction(int slot, String interaction) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } - interactions[slot] = interaction; - } - - /** - * Sets the name of the NPC. - * - * @param name The name. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Sets the size of the NPC, in tiles. - * - * @param size The size. - */ - public void setSize(int size) { - this.size = size; - } - - /** - * Sets the id of the NPC's standing animation. - * - * @param standAnim The stand animation id. - */ - public void setStandAnimation(int standAnim) { - this.standAnim = standAnim; - } - - /** - * Sets the walking animation of the NPC. - * - * @param walkAnim The walking animation. - */ - public void setWalkAnimation(int walkAnim) { - this.walkAnim = walkAnim; - } - - /** - * Sets the various walking animations of the NPC. - * - * @param walkAnim The walking animation. - * @param walkBackAnim The walk-back animation. - * @param walkLeftAnim The walk-left animation. - * @param walkRightAnim The walk-right animation. - */ - public void setWalkAnimations(int walkAnim, int walkBackAnim, int walkLeftAnim, int walkRightAnim) { - this.walkAnim = walkAnim; - this.walkBackAnim = walkBackAnim; - this.walkLeftAnim = walkLeftAnim; - this.walkRightAnim = walkRightAnim; - } + /** + * Sets the various walking animations of the NPC. + * + * @param walkAnim The walking animation. + * @param walkBackAnim The walk-back animation. + * @param walkLeftAnim The walk-left animation. + * @param walkRightAnim The walk-right animation. + */ + public void setWalkAnimations(int walkAnim, int walkBackAnim, int walkLeftAnim, int walkRightAnim) { + this.walkAnim = walkAnim; + this.walkBackAnim = walkBackAnim; + this.walkLeftAnim = walkLeftAnim; + this.walkRightAnim = walkRightAnim; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/def/ObjectDefinition.java b/src/org/apollo/game/model/def/ObjectDefinition.java index 8d11be98..09efe247 100644 --- a/src/org/apollo/game/model/def/ObjectDefinition.java +++ b/src/org/apollo/game/model/def/ObjectDefinition.java @@ -9,265 +9,265 @@ import org.apollo.game.model.obj.GameObject; */ public final class ObjectDefinition { - /** - * The array of game object definitions. - */ - private static ObjectDefinition[] definitions; + /** + * The array of game object definitions. + */ + private static ObjectDefinition[] definitions; - /** - * Gets the total number of object definitions. - * - * @return The count. - */ - public static int count() { - return definitions.length; + /** + * Gets the total number of object definitions. + * + * @return The count. + */ + public static int count() { + return definitions.length; + } + + /** + * Gets the array of object definitions. + * + * @return The definitions. + */ + public static ObjectDefinition[] getDefinitions() { + return definitions; + } + + /** + * Initialises the object definitions. + * + * @param definitions The decoded definitions. + * @throws RuntimeException If there is an id mismatch. + */ + public static void init(ObjectDefinition[] definitions) { + ObjectDefinition.definitions = definitions; + for (int id = 0; id < definitions.length; id++) { + ObjectDefinition def = definitions[id]; + if (def.getId() != id) { + throw new RuntimeException("Item definition id mismatch."); + } } + } - /** - * Gets the array of object definitions. - * - * @return The definitions. - */ - public static ObjectDefinition[] getDefinitions() { - return definitions; + /** + * Gets the object definition for the specified id. + * + * @param id The id of the object. + * @return The definition. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + public static ObjectDefinition lookup(int id) { + if (id < 0 || id > definitions.length) { + throw new IndexOutOfBoundsException(ObjectDefinition.class.getName() + " lookup index " + id + + " out of bounds."); } + return definitions[id]; + } - /** - * Initialises the object definitions. - * - * @param definitions The decoded definitions. - * @throws RuntimeException If there is an id mismatch. - */ - public static void init(ObjectDefinition[] definitions) { - ObjectDefinition.definitions = definitions; - for (int id = 0; id < definitions.length; id++) { - ObjectDefinition def = definitions[id]; - if (def.getId() != id) { - throw new RuntimeException("Item definition id mismatch."); - } - } - } + /** + * The object's description. + */ + private String description; - /** - * Gets the object definition for the specified id. - * - * @param id The id of the object. - * @return The definition. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - public static ObjectDefinition lookup(int id) { - if (id < 0 || id > definitions.length) { - throw new IndexOutOfBoundsException(ObjectDefinition.class.getName() + " lookup index " + id - + " out of bounds."); - } - return definitions[id]; - } + /** + * This object's height. + */ + private int height; - /** - * The object's description. - */ - private String description; + /** + * The object's id. + */ + private final int id; - /** - * This object's height. - */ - private int height; + /** + * Denotes whether this object is impenetrable or not. + */ + private boolean impenetrable; - /** - * The object's id. - */ - private final int id; + /** + * Denotes whether this object has actions associated with it or not. + */ + private boolean interactive; - /** - * Denotes whether this object is impenetrable or not. - */ - private boolean impenetrable; + /** + * The object's menu actions. + */ + private String[] menuActions; - /** - * Denotes whether this object has actions associated with it or not. - */ - private boolean interactive; + /** + * The object's name. + */ + private String name; - /** - * The object's menu actions. - */ - private String[] menuActions; + /** + * Denotes whether the object can be walked over or not. + */ + private boolean solid; - /** - * The object's name. - */ - private String name; + /** + * This object's width. + */ + private int width; - /** - * Denotes whether the object can be walked over or not. - */ - private boolean solid; + /** + * Creates a new object definition. + * + * @param id The id of the object. + */ + public ObjectDefinition(int id) { + this.id = id; + } - /** - * This object's width. - */ - private int width; + /** + * Gets the description of this object. + * + * @return The description. + */ + public String getDescription() { + return description; + } - /** - * Creates a new object definition. - * - * @param id The id of the object. - */ - public ObjectDefinition(int id) { - this.id = id; - } + /** + * Gets the height of this object. + * + * @return The height. + */ + public int getHeight() { + return width; + } - /** - * Gets the description of this object. - * - * @return The description. - */ - public String getDescription() { - return description; - } + /** + * Gets the id of this object. + * + * @return The id. + */ + public int getId() { + return id; + } - /** - * Gets the height of this object. - * - * @return The height. - */ - public int getHeight() { - return width; - } + /** + * Gets the menu actions of this object. + * + * @return The menu actions. + */ + public String[] getMenuActions() { + return menuActions; + } - /** - * Gets the id of this object. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the name of this object. + * + * @return The name. + */ + public String getName() { + return name; + } - /** - * Gets the menu actions of this object. - * - * @return The menu actions. - */ - public String[] getMenuActions() { - return menuActions; - } + /** + * Gets the with of this object. + * + * @return The width. + */ + public int getWidth() { + return height; + } - /** - * Gets the name of this object. - * - * @return The name. - */ - public String getName() { - return name; - } + /** + * Indicates the impenetrability of this object. + * + * @return {@code true} if this object is impenetrable, otherwise {@code false}. + */ + public boolean isImpenetrable() { + return impenetrable; + } - /** - * Gets the with of this object. - * - * @return The width. - */ - public int getWidth() { - return height; - } + /** + * Indicates the interactivity of this object. + * + * @return {@code true} if the object is interactive, otherwise {@code false}. + */ + public boolean isInteractive() { + return interactive; + } - /** - * Indicates the impenetrability of this object. - * - * @return {@code true} if this object is impenetrable, otherwise {@code false}. - */ - public boolean isImpenetrable() { - return impenetrable; - } + /** + * Indicates the solidity of this object. + * + * @return {@code true} if this object is solid, otherwise {@code false}. + */ + public boolean isSolid() { + return solid; + } - /** - * Indicates the interactivity of this object. - * - * @return {@code true} if the object is interactive, otherwise {@code false}. - */ - public boolean isInteractive() { - return interactive; - } + /** + * Sets the description of this object. + * + * @param description The description. + */ + public void setDescription(String description) { + this.description = description; + } - /** - * Indicates the solidity of this object. - * - * @return {@code true} if this object is solid, otherwise {@code false}. - */ - public boolean isSolid() { - return solid; - } + /** + * Sets the height of this object. + * + * @param height The height. + */ + public void setHeight(int height) { + this.height = height; + } - /** - * Sets the description of this object. - * - * @param description The description. - */ - public void setDescription(String description) { - this.description = description; - } + /** + * Sets the impenetrability of this object. + * + * @param impenetrable The impenetrability. + */ + public void setImpenetrable(boolean impenetrable) { + this.impenetrable = impenetrable; + } - /** - * Sets the height of this object. - * - * @param height The height. - */ - public void setHeight(int height) { - this.height = height; - } + /** + * Sets the interactivity of this object. + * + * @param interactive The interactivity. + */ + public void setInteractive(boolean interactive) { + this.interactive = interactive; + } - /** - * Sets the impenetrability of this object. - * - * @param impenetrable The impenetrability. - */ - public void setImpenetrable(boolean impenetrable) { - this.impenetrable = impenetrable; - } + /** + * Sets the menu actions of this object. + * + * @param menuActions The menu actions. + */ + public void setMenuActions(String[] menuActions) { + this.menuActions = menuActions; + } - /** - * Sets the interactivity of this object. - * - * @param interactive The interactivity. - */ - public void setInteractive(boolean interactive) { - this.interactive = interactive; - } + /** + * Sets the name of this object. + * + * @param name The name. + */ + public void setName(String name) { + this.name = name; + } - /** - * Sets the menu actions of this object. - * - * @param menuActions The menu actions. - */ - public void setMenuActions(String[] menuActions) { - this.menuActions = menuActions; - } + /** + * Sets the solidity of this object. + * + * @param solid The solidity. + */ + public void setSolid(boolean solid) { + this.solid = solid; + } - /** - * Sets the name of this object. - * - * @param name The name. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Sets the solidity of this object. - * - * @param solid The solidity. - */ - public void setSolid(boolean solid) { - this.solid = solid; - } - - /** - * Sets the width of this object. - * - * @param width The width. - */ - public void setWidth(int width) { - this.width = width; - } + /** + * Sets the width of this object. + * + * @param width The width. + */ + public void setWidth(int width) { + this.width = width; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/Entity.java b/src/org/apollo/game/model/entity/Entity.java index 5e4e3dee..8faeea80 100644 --- a/src/org/apollo/game/model/entity/Entity.java +++ b/src/org/apollo/game/model/entity/Entity.java @@ -14,102 +14,102 @@ import org.apollo.game.model.Position; */ public abstract class Entity { - /** - * Represents a type of {@link Entity}. - * - * @author Major - */ - public enum EntityType { - - /** - * An item that has been dropped on the ground. - */ - DROPPED_ITEM, - - /** - * An object appearing in the game world. - */ - GAME_OBJECT, - - /** - * An npc. - */ - NPC, - - /** - * A player. - */ - PLAYER, - - /** - * A projectile (e.g. an arrow). - */ - PROJECTILE; - - } + /** + * Represents a type of {@link Entity}. + * + * @author Major + */ + public enum EntityType { /** - * A map of attribute names to attributes. + * An item that has been dropped on the ground. */ - protected final Map attributes = new HashMap<>(5); + DROPPED_ITEM, /** - * The position of this entity. + * An object appearing in the game world. */ - protected Position position; + GAME_OBJECT, /** - * Creates a new entity with the specified position. - * - * @param position The position. + * An npc. */ - public Entity(Position position) { - this.position = position; - } + NPC, /** - * Gets the value of the attribute with the specified name. - * - * @param name The name of the attribute. - * @return The value of the attribute. + * A player. */ - public final Object getAttribute(String name) { - return attributes.get(name); - } + PLAYER, /** - * Gets all of the attributes of this entity, as a {@link Set} of {@link Entry} objects. - * - * @return The set of attributes. + * A projectile (e.g. an arrow). */ - public final Set> getAttributes() { - return attributes.entrySet(); - } + PROJECTILE; - /** - * Gets the {@link EntityType} of this entity. - * - * @return The entity type. - */ - public abstract EntityType getEntityType(); + } - /** - * Gets the {@link Position} of this entity. - * - * @return The position. - */ - public Position getPosition() { - return position; - } + /** + * A map of attribute names to attributes. + */ + protected final Map attributes = new HashMap<>(5); - /** - * Sets the value of the attribute with the specified name. - * - * @param name The name of the attribute. - * @param value The value of the attribute. - */ - public final void setAttribute(String name, Object value) { - attributes.put(name, value); - } + /** + * The position of this entity. + */ + protected Position position; + + /** + * Creates a new entity with the specified position. + * + * @param position The position. + */ + public Entity(Position position) { + this.position = position; + } + + /** + * Gets the value of the attribute with the specified name. + * + * @param name The name of the attribute. + * @return The value of the attribute. + */ + public final Object getAttribute(String name) { + return attributes.get(name); + } + + /** + * Gets all of the attributes of this entity, as a {@link Set} of {@link Entry} objects. + * + * @return The set of attributes. + */ + public final Set> getAttributes() { + return attributes.entrySet(); + } + + /** + * Gets the {@link EntityType} of this entity. + * + * @return The entity type. + */ + public abstract EntityType getEntityType(); + + /** + * Gets the {@link Position} of this entity. + * + * @return The position. + */ + public Position getPosition() { + return position; + } + + /** + * Sets the value of the attribute with the specified name. + * + * @param name The name of the attribute. + * @param value The value of the attribute. + */ + public final void setAttribute(String name, Object value) { + attributes.put(name, value); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/EquipmentConstants.java b/src/org/apollo/game/model/entity/EquipmentConstants.java index 13945d07..efb6d495 100644 --- a/src/org/apollo/game/model/entity/EquipmentConstants.java +++ b/src/org/apollo/game/model/entity/EquipmentConstants.java @@ -7,66 +7,66 @@ package org.apollo.game.model.entity; */ public final class EquipmentConstants { - /** - * The hat slot. - */ - public static final int HAT = 0; + /** + * The hat slot. + */ + public static final int HAT = 0; - /** - * The cape slot. - */ - public static final int CAPE = 1; + /** + * The cape slot. + */ + public static final int CAPE = 1; - /** - * The amulet slot. - */ - public static final int AMULET = 2; + /** + * The amulet slot. + */ + public static final int AMULET = 2; - /** - * The weapon slot. - */ - public static final int WEAPON = 3; + /** + * The weapon slot. + */ + public static final int WEAPON = 3; - /** - * The chest slot. - */ - public static final int CHEST = 4; + /** + * The chest slot. + */ + public static final int CHEST = 4; - /** - * The shield slot. - */ - public static final int SHIELD = 5; + /** + * The shield slot. + */ + public static final int SHIELD = 5; - /** - * The legs slot. - */ - public static final int LEGS = 7; + /** + * The legs slot. + */ + public static final int LEGS = 7; - /** - * The hands slot. - */ - public static final int HANDS = 9; + /** + * The hands slot. + */ + public static final int HANDS = 9; - /** - * The feet slot. - */ - public static final int FEET = 10; + /** + * The feet slot. + */ + public static final int FEET = 10; - /** - * The ring slot. - */ - public static final int RING = 12; + /** + * The ring slot. + */ + public static final int RING = 12; - /** - * The arrows slot. - */ - public static final int ARROWS = 13; + /** + * The arrows slot. + */ + public static final int ARROWS = 13; - /** - * Default private constructor to prevent instantiation; - */ - private EquipmentConstants() { + /** + * Default private constructor to prevent instantiation; + */ + private EquipmentConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/Mob.java b/src/org/apollo/game/model/entity/Mob.java index 2e32eddd..7b907c8c 100644 --- a/src/org/apollo/game/model/entity/Mob.java +++ b/src/org/apollo/game/model/entity/Mob.java @@ -24,425 +24,425 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public abstract class Mob extends Entity { - /** - * This mob's current action. - */ - private transient Action action; + /** + * This mob's current action. + */ + private transient Action action; - /** - * This mob's set of synchronization blocks. - */ - protected transient SynchronizationBlockSet blockSet = new SynchronizationBlockSet(); + /** + * This mob's set of synchronization blocks. + */ + protected transient SynchronizationBlockSet blockSet = new SynchronizationBlockSet(); - /** - * This mob's npc definition. A player only uses this if they are appearing as an npc. - */ - protected NpcDefinition definition; + /** + * This mob's npc definition. A player only uses this if they are appearing as an npc. + */ + protected NpcDefinition definition; - /** - * This mob's equipment. - */ - protected final Inventory equipment = new Inventory(InventoryConstants.EQUIPMENT_CAPACITY, StackMode.STACK_ALWAYS); + /** + * This mob's equipment. + */ + protected final Inventory equipment = new Inventory(InventoryConstants.EQUIPMENT_CAPACITY, StackMode.STACK_ALWAYS); - /** - * The position this mob is facing towards. - */ - private transient Position facingPosition = position; + /** + * The position this mob is facing towards. + */ + private transient Position facingPosition = position; - /** - * This mob's first movement direction. - */ - private transient Direction firstDirection = Direction.NONE; + /** + * This mob's first movement direction. + */ + private transient Direction firstDirection = Direction.NONE; - /** - * The index of this mob. - */ - protected int index = -1; + /** + * The index of this mob. + */ + protected int index = -1; - /** - * The mob this mob is interacting with. - */ - protected Mob interactingMob; + /** + * The mob this mob is interacting with. + */ + protected Mob interactingMob; - /** - * This mob's inventory. - */ - protected final Inventory inventory = new Inventory(InventoryConstants.INVENTORY_CAPACITY); + /** + * This mob's inventory. + */ + protected final Inventory inventory = new Inventory(InventoryConstants.INVENTORY_CAPACITY); - /** - * This mob's list of local npcs. - */ - private final transient List localNpcs = new ArrayList<>(); + /** + * This mob's list of local npcs. + */ + private final transient List localNpcs = new ArrayList<>(); - /** - * This mob's list of local players. - */ - private final transient List localPlayers = new ArrayList<>(); + /** + * This mob's list of local players. + */ + private final transient List localPlayers = new ArrayList<>(); - /** - * This mob's second movement direction. - */ - private transient Direction secondDirection = Direction.NONE; + /** + * This mob's second movement direction. + */ + private transient Direction secondDirection = Direction.NONE; - /** - * This mob's skill set. - */ - protected final SkillSet skillSet = new SkillSet(); + /** + * This mob's skill set. + */ + protected final SkillSet skillSet = new SkillSet(); - /** - * Indicates whether this mob is currently teleporting or not. - */ - private transient boolean teleporting = false; + /** + * Indicates whether this mob is currently teleporting or not. + */ + private transient boolean teleporting = false; - /** - * This mob's walking queue. - */ - protected final transient WalkingQueue walkingQueue = new WalkingQueue(this); + /** + * This mob's walking queue. + */ + protected final transient WalkingQueue walkingQueue = new WalkingQueue(this); - /** - * Creates a new mob with the specified initial {@link Position}. - * - * @param position The initial position. - */ - public Mob(Position position) { - super(position); - init(); + /** + * Creates a new mob with the specified initial {@link Position}. + * + * @param position The initial position. + */ + public Mob(Position position) { + super(position); + init(); + } + + /** + * Deals damage to this mob. + * + * @param damage The damage dealt. + * @param type The type of damage. + * @param secondary If the damage should be dealt as a secondary hit. + */ + public final void damage(int damage, int type, boolean secondary) { + Skill hitpoints = skillSet.getSkill(Skill.HITPOINTS); + int current = Math.max(hitpoints.getCurrentLevel() - damage, 0), maximum = hitpoints.getMaximumLevel(); + + blockSet.add(SynchronizationBlock.createHitUpdateBlock(damage, type, current, maximum, secondary)); + skillSet.setSkill(Skill.HITPOINTS, new Skill(hitpoints.getExperience(), current, maximum)); + } + + /** + * Gets this mob's {@link SynchronizationBlockSet}. + * + * @return The block set. + */ + public final SynchronizationBlockSet getBlockSet() { + return blockSet; + } + + /** + * Gets this mob's movement {@link Direction}s, as an array. + * + * @return A zero, one or two element array containing the directions (in order). + */ + public final Direction[] getDirections() { + if (firstDirection != Direction.NONE) { + return secondDirection == Direction.NONE ? new Direction[] { firstDirection } : new Direction[] { + firstDirection, secondDirection }; } + return Direction.EMPTY_DIRECTION_ARRAY; + } - /** - * Deals damage to this mob. - * - * @param damage The damage dealt. - * @param type The type of damage. - * @param secondary If the damage should be dealt as a secondary hit. - */ - public final void damage(int damage, int type, boolean secondary) { - Skill hitpoints = skillSet.getSkill(Skill.HITPOINTS); - int current = Math.max(hitpoints.getCurrentLevel() - damage, 0), maximum = hitpoints.getMaximumLevel(); + /** + * Gets this mob's equipment. + * + * @return The mob's equipment. + */ + public final Inventory getEquipment() { + return equipment; + } - blockSet.add(SynchronizationBlock.createHitUpdateBlock(damage, type, current, maximum, secondary)); - skillSet.setSkill(Skill.HITPOINTS, new Skill(hitpoints.getExperience(), current, maximum)); + /** + * Gets the {@link Position} this mob is facing towards. + * + * @return The position. + */ + public final Position getFacingPosition() { + return facingPosition; + } + + /** + * Gets the first {@link Direction}. + * + * @return The direction. + */ + public final Direction getFirstDirection() { + return firstDirection; + } + + /** + * Gets the index of this mob. + * + * @return The index. + */ + public final int getIndex() { + synchronized (this) { + return index; } + } - /** - * Gets this mob's {@link SynchronizationBlockSet}. - * - * @return The block set. - */ - public final SynchronizationBlockSet getBlockSet() { - return blockSet; - } + /** + * Gets the mob this mob is interacting with. + * + * @return The mob. + */ + public final Mob getInteractingMob() { + return interactingMob; + } - /** - * Gets this mob's movement {@link Direction}s, as an array. - * - * @return A zero, one or two element array containing the directions (in order). - */ - public final Direction[] getDirections() { - if (firstDirection != Direction.NONE) { - return secondDirection == Direction.NONE ? new Direction[] { firstDirection } : new Direction[] { - firstDirection, secondDirection }; - } - return Direction.EMPTY_DIRECTION_ARRAY; - } + /** + * Gets this mob's inventory. + * + * @return The inventory. + */ + public final Inventory getInventory() { + return inventory; + } - /** - * Gets this mob's equipment. - * - * @return The mob's equipment. - */ - public final Inventory getEquipment() { - return equipment; - } + /** + * Gets this mob's local npc {@link List}. + * + * @return The list. + */ + public final List getLocalNpcList() { + return localNpcs; + } - /** - * Gets the {@link Position} this mob is facing towards. - * - * @return The position. - */ - public final Position getFacingPosition() { - return facingPosition; - } + /** + * Gets this mob' local player {@link List}. + * + * @return The list. + */ + public final List getLocalPlayerList() { + return localPlayers; + } - /** - * Gets the first {@link Direction}. - * - * @return The direction. - */ - public final Direction getFirstDirection() { - return firstDirection; - } + /** + * Gets this mob's {@link NpcDefinition}. + * + * @param definition The definition. + */ + public final NpcDefinition getDefinition() { + return definition; + } - /** - * Gets the index of this mob. - * - * @return The index. - */ - public final int getIndex() { - synchronized (this) { - return index; - } - } + /** + * Gets this mob's second movement {@link Direction}. + * + * @return The direction. + */ + public final Direction getSecondDirection() { + return secondDirection; + } - /** - * Gets the mob this mob is interacting with. - * - * @return The mob. - */ - public final Mob getInteractingMob() { - return interactingMob; - } + /** + * Gets this mob's {@link SkillSet}. + * + * @return The skill set. + */ + public final SkillSet getSkillSet() { + return skillSet; + } - /** - * Gets this mob's inventory. - * - * @return The inventory. - */ - public final Inventory getInventory() { - return inventory; - } + /** + * Gets this mob's {@link WalkingQueue}. + * + * @return The walking queue. + */ + public final WalkingQueue getWalkingQueue() { + return walkingQueue; + } - /** - * Gets this mob's local npc {@link List}. - * - * @return The list. - */ - public final List getLocalNpcList() { - return localNpcs; - } + /** + * Initialises this mob. + */ + private void init() { + World.getWorld().schedule(new SkillNormalizationTask(this)); + } - /** - * Gets this mob' local player {@link List}. - * - * @return The list. - */ - public final List getLocalPlayerList() { - return localPlayers; - } + /** + * Checks if this mob is active. + * + * @return {@code true} if the mob is active, {@code false} if not. + */ + public final boolean isActive() { + return index != -1; + } - /** - * Gets this mob's {@link NpcDefinition}. - * - * @param definition The definition. - */ - public final NpcDefinition getDefinition() { - return definition; - } + /** + * Checks if this mob is currently teleporting. + * + * @return {@code true} if so, {@code false} if not. + */ + public final boolean isTeleporting() { + return teleporting; + } - /** - * Gets this mob's second movement {@link Direction}. - * - * @return The direction. - */ - public final Direction getSecondDirection() { - return secondDirection; - } + /** + * Makes this mob perform the specified {@link Animation}. + * + * @param animation The animation. + */ + public final void playAnimation(Animation animation) { + blockSet.add(SynchronizationBlock.createAnimationBlock(animation)); + } - /** - * Gets this mob's {@link SkillSet}. - * - * @return The skill set. - */ - public final SkillSet getSkillSet() { - return skillSet; - } + /** + * Makes this mob perform the specified {@link Graphic}. + * + * @param graphic The graphic. + */ + public final void playGraphic(Graphic graphic) { + blockSet.add(SynchronizationBlock.createGraphicBlock(graphic)); + } - /** - * Gets this mob's {@link WalkingQueue}. - * - * @return The walking queue. - */ - public final WalkingQueue getWalkingQueue() { - return walkingQueue; - } + /** + * Resets this mob's block set. + */ + public final void resetBlockSet() { + blockSet = new SynchronizationBlockSet(); + } - /** - * Initialises this mob. - */ - private void init() { - World.getWorld().schedule(new SkillNormalizationTask(this)); - } + /** + * Resets the mob this mob is interacting with. + */ + public final void resetInteractingMob() { + interactingMob = null; + blockSet.add(SynchronizationBlock.createInteractingMobBlock(65535)); + } - /** - * Checks if this mob is active. - * - * @return {@code true} if the mob is active, {@code false} if not. - */ - public final boolean isActive() { - return index != -1; - } + /** + * Sets this mob's {@link NpcDefinition}. + * + * @param definition The definition. + */ + public final void setDefinition(NpcDefinition definition) { + this.definition = definition; + } - /** - * Checks if this mob is currently teleporting. - * - * @return {@code true} if so, {@code false} if not. - */ - public final boolean isTeleporting() { - return teleporting; - } + /** + * Sets the next movement {@link Direction}s for this mob. + * + * @param first The first direction. + * @param second The second direction. + */ + public final void setDirections(Direction first, Direction second) { + firstDirection = first; + secondDirection = second; + } - /** - * Makes this mob perform the specified {@link Animation}. - * - * @param animation The animation. - */ - public final void playAnimation(Animation animation) { - blockSet.add(SynchronizationBlock.createAnimationBlock(animation)); + /** + * Sets the index of this mob. + * + * @param index The index. + */ + public final void setIndex(int index) { + synchronized (this) { + this.index = index; } + } - /** - * Makes this mob perform the specified {@link Graphic}. - * - * @param graphic The graphic. - */ - public final void playGraphic(Graphic graphic) { - blockSet.add(SynchronizationBlock.createGraphicBlock(graphic)); - } + /** + * Updates this mob's interacting mob. + * + * @param mob The mob. + */ + public final void setInteractingMob(Mob mob) { + interactingMob = mob; + blockSet.add(SynchronizationBlock.createInteractingMobBlock(mob.index)); + } - /** - * Resets this mob's block set. - */ - public final void resetBlockSet() { - blockSet = new SynchronizationBlockSet(); - } + /** + * Sets the{@link Position} of this mob. + * + * @param position The position. + */ + public final void setPosition(Position position) { + this.position = position; + } - /** - * Resets the mob this mob is interacting with. - */ - public final void resetInteractingMob() { - interactingMob = null; - blockSet.add(SynchronizationBlock.createInteractingMobBlock(65535)); - } + /** + * Sets whether this mob is teleporting or not. + * + * @param teleporting {@code true} if the mob is teleporting, {@code false} if not. + */ + public final void setTeleporting(boolean teleporting) { + this.teleporting = teleporting; + } - /** - * Sets this mob's {@link NpcDefinition}. - * - * @param definition The definition. - */ - public final void setDefinition(NpcDefinition definition) { - this.definition = definition; - } + /** + * Forces this mob to shout a message. Only messages said by a player can be shown in the chat box. + * + * @param message The message. + * @param chatOnly If the message should only be shown in the player's chat box, or above their head too. + */ + public void shout(String message, boolean chatOnly) { + blockSet.add(SynchronizationBlock.createForceChatBlock(message)); + } - /** - * Sets the next movement {@link Direction}s for this mob. - * - * @param first The first direction. - * @param second The second direction. - */ - public final void setDirections(Direction first, Direction second) { - firstDirection = first; - secondDirection = second; + /** + * Starts a new action, stopping the current one if it exists. + * + * @param action The new action. + * @return A flag indicating if the action was started. + */ + public final boolean startAction(Action action) { + if (this.action != null) { + if (this.action.equals(action)) { + return false; + } + stopAction(); } + return World.getWorld().schedule(this.action = action); + } - /** - * Sets the index of this mob. - * - * @param index The index. - */ - public final void setIndex(int index) { - synchronized (this) { - this.index = index; - } + /** + * Stops this mob's current action. + */ + public final void stopAction() { + if (action != null) { + action.stop(); + action = null; } + } - /** - * Updates this mob's interacting mob. - * - * @param mob The mob. - */ - public final void setInteractingMob(Mob mob) { - interactingMob = mob; - blockSet.add(SynchronizationBlock.createInteractingMobBlock(mob.index)); - } + /** + * Stops this mob's current {@link Animation}. + */ + public final void stopAnimation() { + playAnimation(Animation.STOP_ANIMATION); + } - /** - * Sets the{@link Position} of this mob. - * - * @param position The position. - */ - public final void setPosition(Position position) { - this.position = position; - } + /** + * Stops this mob's current {@link Graphic}. + */ + public final void stopGraphic() { + playGraphic(Graphic.STOP_GRAPHIC); + } - /** - * Sets whether this mob is teleporting or not. - * - * @param teleporting {@code true} if the mob is teleporting, {@code false} if not. - */ - public final void setTeleporting(boolean teleporting) { - this.teleporting = teleporting; - } + /** + * Teleports this mob to the specified {@link Position}, setting the appropriate flags and clearing the walking + * queue. + * + * @param position The position. + */ + public void teleport(Position position) { + this.position = position; + teleporting = true; + walkingQueue.clear(); + stopAction(); + } - /** - * Forces this mob to shout a message. Only messages said by a player can be shown in the chat box. - * - * @param message The message. - * @param chatOnly If the message should only be shown in the player's chat box, or above their head too. - */ - public void shout(String message, boolean chatOnly) { - blockSet.add(SynchronizationBlock.createForceChatBlock(message)); - } - - /** - * Starts a new action, stopping the current one if it exists. - * - * @param action The new action. - * @return A flag indicating if the action was started. - */ - public final boolean startAction(Action action) { - if (this.action != null) { - if (this.action.equals(action)) { - return false; - } - stopAction(); - } - return World.getWorld().schedule(this.action = action); - } - - /** - * Stops this mob's current action. - */ - public final void stopAction() { - if (action != null) { - action.stop(); - action = null; - } - } - - /** - * Stops this mob's current {@link Animation}. - */ - public final void stopAnimation() { - playAnimation(Animation.STOP_ANIMATION); - } - - /** - * Stops this mob's current {@link Graphic}. - */ - public final void stopGraphic() { - playGraphic(Graphic.STOP_GRAPHIC); - } - - /** - * Teleports this mob to the specified {@link Position}, setting the appropriate flags and clearing the walking - * queue. - * - * @param position The position. - */ - public void teleport(Position position) { - this.position = position; - teleporting = true; - walkingQueue.clear(); - stopAction(); - } - - /** - * Turns this mob to face the specified {@link Position}. - * - * @param position The position to face. - */ - public final void turnTo(Position position) { - blockSet.add(SynchronizationBlock.createTurnToPositionBlock(this.facingPosition = position)); - } + /** + * Turns this mob to face the specified {@link Position}. + * + * @param position The position to face. + */ + public final void turnTo(Position position) { + blockSet.add(SynchronizationBlock.createTurnToPositionBlock(this.facingPosition = position)); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/Npc.java b/src/org/apollo/game/model/entity/Npc.java index 2fc521e4..ec321e25 100644 --- a/src/org/apollo/game/model/entity/Npc.java +++ b/src/org/apollo/game/model/entity/Npc.java @@ -11,98 +11,98 @@ import org.apollo.game.sync.block.SynchronizationBlock; */ public final class Npc extends Mob { - /** - * This npc's id. - */ - private int id; + /** + * This npc's id. + */ + private int id; - /** - * The positions representing the bounds (i.e. walking limits) of this npc. - */ - private Position[] boundary; + /** + * The positions representing the bounds (i.e. walking limits) of this npc. + */ + private Position[] boundary; - /** - * Creates a new npc with the specified id and {@link Position}. - * - * @param id The id. - * @param position The position. - */ - public Npc(int id, Position position) { - this(NpcDefinition.lookup(id), position); + /** + * Creates a new npc with the specified id and {@link Position}. + * + * @param id The id. + * @param position The position. + */ + public Npc(int id, Position position) { + this(NpcDefinition.lookup(id), position); + } + + /** + * Creates a new npc with the specified {@link NpcDefinition} and {@link Position}. + * + * @param definition The definition. + * @param position The position. + */ + public Npc(NpcDefinition definition, Position position) { + super(position); + this.definition = definition; + this.id = definition.getId(); + } + + /** + * Gets the boundary of this npc. + * + * @return The boundary. + */ + public Position[] getBoundary() { + return boundary; + } + + @Override + public EntityType getEntityType() { + return EntityType.NPC; + } + + /** + * Gets the id of this npc. + * + * @return The id. + */ + public int getId() { + return id; + } + + /** + * Indicates whether or not this npc is bound to a specific set of coordinates. + * + * @return {@code true} if the npc is bound, otherwise {@code false}. + */ + public boolean isBound() { + return boundary == null; + } + + /** + * Sets the boundary of this npc. + * + * @param boundary The boundary. + */ + public void setBoundary(Position[] boundary) { + if (boundary.length != 4) { + throw new IllegalArgumentException("Boundary count must be 4."); } + this.boundary = boundary; + } - /** - * Creates a new npc with the specified {@link NpcDefinition} and {@link Position}. - * - * @param definition The definition. - * @param position The position. - */ - public Npc(NpcDefinition definition, Position position) { - super(position); - this.definition = definition; - this.id = definition.getId(); - } + @Override + public String toString() { + return "[" + Npc.class.getName() + ": id=" + definition.getId() + ", name=" + definition.getName() + "]"; + } - /** - * Gets the boundary of this npc. - * - * @return The boundary. - */ - public Position[] getBoundary() { - return boundary; - } - - @Override - public EntityType getEntityType() { - return EntityType.NPC; - } - - /** - * Gets the id of this npc. - * - * @return The id. - */ - public int getId() { - return id; - } - - /** - * Indicates whether or not this npc is bound to a specific set of coordinates. - * - * @return {@code true} if the npc is bound, otherwise {@code false}. - */ - public boolean isBound() { - return boundary == null; - } - - /** - * Sets the boundary of this npc. - * - * @param boundary The boundary. - */ - public void setBoundary(Position[] boundary) { - if (boundary.length != 4) { - throw new IllegalArgumentException("Boundary count must be 4."); - } - this.boundary = boundary; - } - - @Override - public String toString() { - return "[" + Npc.class.getName() + ": id=" + definition.getId() + ", name=" + definition.getName() + "]"; - } - - /** - * Transforms this npc into the npc with the specified id. - * - * @param id The id. - */ - public void transform(int id) { - if (id < 0 || id >= NpcDefinition.count()) { - throw new IllegalArgumentException("Id to transform to is out of bounds."); - } - definition = NpcDefinition.lookup(this.id = id); - blockSet.add(SynchronizationBlock.createTransformBlock(id)); + /** + * Transforms this npc into the npc with the specified id. + * + * @param id The id. + */ + public void transform(int id) { + if (id < 0 || id >= NpcDefinition.count()) { + throw new IllegalArgumentException("Id to transform to is out of bounds."); } + definition = NpcDefinition.lookup(this.id = id); + blockSet.add(SynchronizationBlock.createTransformBlock(id)); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/Player.java b/src/org/apollo/game/model/entity/Player.java index 51ef17bb..a491a648 100644 --- a/src/org/apollo/game/model/entity/Player.java +++ b/src/org/apollo/game/model/entity/Player.java @@ -47,928 +47,928 @@ import org.apollo.util.Point; */ public final class Player extends Mob { - /** - * The player's appearance. - */ - private Appearance appearance = Appearance.DEFAULT_APPEARANCE; + /** + * The player's appearance. + */ + private Appearance appearance = Appearance.DEFAULT_APPEARANCE; - /** - * This player's bank. - */ - private final Inventory bank = new Inventory(InventoryConstants.BANK_CAPACITY, StackMode.STACK_ALWAYS); + /** + * This player's bank. + */ + private final Inventory bank = new Inventory(InventoryConstants.BANK_CAPACITY, StackMode.STACK_ALWAYS); - /** - * The privacy state of this player's public chat. - */ - private PrivacyState chatPrivacy = PrivacyState.ON; + /** + * The privacy state of this player's public chat. + */ + private PrivacyState chatPrivacy = PrivacyState.ON; - /** - * A deque of this player's mouse clicks. - */ - private transient Deque clicks = new ArrayDeque<>(); + /** + * A deque of this player's mouse clicks. + */ + private transient Deque clicks = new ArrayDeque<>(); - /** - * The version of the client this player is using. This is not the same as the release number, instead denoting the - * custom version. - */ - private transient int clientVersion; + /** + * The version of the client this player is using. This is not the same as the release number, instead denoting the + * custom version. + */ + private transient int clientVersion; - /** - * This player's credentials. - */ - private PlayerCredentials credentials; + /** + * This player's credentials. + */ + private PlayerCredentials credentials; - /** - * A flag which indicates there are npcs that couldn't be added. - */ - private transient boolean excessiveNpcs = false; + /** + * A flag which indicates there are npcs that couldn't be added. + */ + private transient boolean excessiveNpcs = false; - /** - * A flag which indicates there are players that couldn't be added. - */ - private transient boolean excessivePlayers = false; + /** + * A flag which indicates there are players that couldn't be added. + */ + private transient boolean excessivePlayers = false; - /** - * Indicates whether this player has the message filter enabled. - */ - private boolean filteringMessages = false; + /** + * Indicates whether this player has the message filter enabled. + */ + private boolean filteringMessages = false; - /** - * The privacy state of this player's private chat. - */ - private PrivacyState friendPrivacy = PrivacyState.ON; + /** + * The privacy state of this player's private chat. + */ + private PrivacyState friendPrivacy = PrivacyState.ON; - /** - * The list of usernames of players this player has befriended. - */ - private List friends = new ArrayList<>(); + /** + * The list of usernames of players this player has befriended. + */ + private List friends = new ArrayList<>(); - /** - * Whether or not the player is skulled. - */ - private boolean isSkulled = false; + /** + * Whether or not the player is skulled. + */ + private boolean isSkulled = false; - /** - * The list of usernames of players this player has ignored. - */ - private List ignores = new ArrayList<>(); + /** + * The list of usernames of players this player has ignored. + */ + private List ignores = new ArrayList<>(); - /** - * This player's interface set. - */ - private final transient InterfaceSet interfaceSet = new InterfaceSet(this); + /** + * This player's interface set. + */ + private final transient InterfaceSet interfaceSet = new InterfaceSet(this); - /** - * The centre of the last region the client has loaded. - */ - private transient Position lastKnownRegion; + /** + * The centre of the last region the client has loaded. + */ + private transient Position lastKnownRegion; - /** - * The membership flag. - */ - private transient boolean members = false; + /** + * The membership flag. + */ + private transient boolean members = false; - /** - * A flag indicating if the player is new. - */ - private boolean newPlayer = false; + /** + * A flag indicating if the player is new. + */ + private boolean newPlayer = false; - /** - * This player's prayer icon. - */ - private int prayerIcon = -1; + /** + * This player's prayer icon. + */ + private int prayerIcon = -1; - /** - * The privilege level. - */ - private PrivilegeLevel privilegeLevel = PrivilegeLevel.STANDARD; + /** + * The privilege level. + */ + private PrivilegeLevel privilegeLevel = PrivilegeLevel.STANDARD; - /** - * A temporary queue of events sent during the login process. - */ - private final transient Deque queuedEvents = new ArrayDeque<>(); + /** + * A temporary queue of events sent during the login process. + */ + private final transient Deque queuedEvents = new ArrayDeque<>(); - /** - * A flag indicating if the region changed in the last cycle. - */ - private transient boolean regionChanged = false; + /** + * A flag indicating if the region changed in the last cycle. + */ + private transient boolean regionChanged = false; - /** - * The player's run energy. - */ - private int runEnergy = 100; + /** + * The player's run energy. + */ + private int runEnergy = 100; - /** - * A flag indicating if this player is running. - */ - private boolean running = false; + /** + * A flag indicating if this player is running. + */ + private boolean running = false; - /** - * The brightness of this player's screen. - */ - private ScreenBrightness screenBrightness = ScreenBrightness.NORMAL; + /** + * The brightness of this player's screen. + */ + private ScreenBrightness screenBrightness = ScreenBrightness.NORMAL; - /** - * The {@link GameSession} currently attached to this {@link Player}. - */ - private transient GameSession session; + /** + * The {@link GameSession} currently attached to this {@link Player}. + */ + private transient GameSession session; - /** - * The privacy state of this player's trade chat. - */ - private PrivacyState tradePrivacy = PrivacyState.ON; + /** + * The privacy state of this player's trade chat. + */ + private PrivacyState tradePrivacy = PrivacyState.ON; - /** - * The current maximum viewing distance of this player. - */ - private int viewingDistance = 1; + /** + * The current maximum viewing distance of this player. + */ + private int viewingDistance = 1; - /** - * A flag indicating if the player is withdrawing items as notes. - */ - private boolean withdrawingNotes = false; + /** + * A flag indicating if the player is withdrawing items as notes. + */ + private boolean withdrawingNotes = false; - /** - * The id of the world this player is in. - */ - private transient int worldId = 1; + /** + * The id of the world this player is in. + */ + private transient int worldId = 1; - /** - * Creates the {@link Player}. - * - * @param credentials The player's credentials. - * @param position The initial position. - */ - public Player(PlayerCredentials credentials, Position position) { - super(position); - this.credentials = credentials; - init(); + /** + * Creates the {@link Player}. + * + * @param credentials The player's credentials. + * @param position The initial position. + */ + public Player(PlayerCredentials credentials, Position position) { + super(position); + this.credentials = credentials; + init(); + } + + /** + * Adds a click, represented by a {@link Point}, to the {@link List} of clicks. + * + * @param point The point. + * @return {@code true} if the point was added successfully. + */ + public boolean addClick(Point point) { + return clicks.add(point); + } + + /** + * Adds the specified username to this player's friend list. + * + * @param username The username. + */ + public boolean addFriend(String username) { + return friends.add(username.toLowerCase()); + } + + /** + * Adds the specified username to this player's ignore list. + * + * @param username The username. + */ + public boolean addIgnore(String username) { + return ignores.add(username.toLowerCase()); + } + + /** + * Decrements this player's viewing distance if it is greater than 1. + */ + public void decrementViewingDistance() { + if (viewingDistance > 1) { + viewingDistance--; } + } - /** - * Adds a click, represented by a {@link Point}, to the {@link List} of clicks. - * - * @param point The point. - * @return {@code true} if the point was added successfully. - */ - public boolean addClick(Point point) { - return clicks.add(point); + /** + * Sets the excessive npcs flag. + */ + public void flagExcessiveNpcs() { + excessiveNpcs = true; + } + + /** + * Sets the excessive players flag. + */ + public void flagExcessivePlayers() { + excessivePlayers = true; + } + + /** + * Indicates whether this player is friends with the player with the specified username or not. + * + * @param username The username of the other player. + * @return {@code true} if the specified username is on this player's friend list, otherwise {@code false}. + */ + public boolean friendsWith(String username) { + return friends.contains(username.toLowerCase()); + } + + /** + * Gets the player's appearance. + * + * @return The appearance. + */ + public Appearance getAppearance() { + return appearance; + } + + /** + * Gets the mob's bank. + * + * @return The bank. + */ + public Inventory getBank() { + return bank; + } + + /** + * Gets this player's public chat privacy state. + * + * @return The privacy state. + */ + public PrivacyState getChatPrivacy() { + return chatPrivacy; + } + + /** + * Gets the {@link Deque} of clicks. + * + * @return The deque. + */ + public Deque getClicks() { + return clicks; + } + + /** + * Gets the value denoting the clients modified version (0 if it is an unmodified jagex client). + * + * @return The version. + */ + public int getClientVersion() { + return clientVersion; + } + + /** + * Gets the player's credentials. + * + * @return The player's credentials. + */ + public PlayerCredentials getCredentials() { + return credentials; + } + + /** + * Gets the player's name, encoded as a long. + * + * @return The encoded player name. + */ + public long getEncodedName() { + return credentials.getEncodedUsername(); + } + + @Override + public EntityType getEntityType() { + return EntityType.PLAYER; + } + + /** + * Gets this player's friend chat {@link PrivacyState}. + * + * @return The privacy state. + */ + public PrivacyState getFriendPrivacy() { + return friendPrivacy; + } + + /** + * Gets the {@link List} of this player's friends. + * + * @return The list. + */ + public List getFriendUsernames() { + return friends; + } + + /** + * Indicates whether or not the player is skulled + * + * @return {@code true} if the player is skulled, otherwise {@code false}. + */ + public boolean isSkulled() { + return isSkulled; + } + + /** + * Gets the {@link List} of usernames of ignored players. + * + * @return The list. + */ + public List getIgnoredUsernames() { + return ignores; + } + + /** + * Gets this player's interface set. + * + * @return The interface set for this player. + */ + public InterfaceSet getInterfaceSet() { + return interfaceSet; + } + + /** + * Gets this player's last click, represented by a {@link Point}. + * + * @return The click. + */ + public Point getLastClick() { + return clicks.pollLast(); + } + + /** + * Gets the last known region. + * + * @return The last known region, or {@code null} if the player has never known a region. + */ + public Position getLastKnownRegion() { + return lastKnownRegion; + } + + /** + * Gets the player's prayer icon. + * + * @return The prayer icon. + */ + public int getPrayerIcon() { + return prayerIcon; + } + + /** + * Gets the privilege level. + * + * @return The privilege level. + */ + public PrivilegeLevel getPrivilegeLevel() { + return privilegeLevel; + } + + /** + * Gets the player's run energy. + * + * @return The run energy. + */ + public int getRunEnergy() { + return runEnergy; + } + + /** + * Gets this player's {@link ScreenBrightness}. + * + * @return The screen brightness. + */ + public ScreenBrightness getScreenBrightness() { + return screenBrightness; + } + + /** + * Gets the game session. + * + * @return The game session. + */ + public GameSession getSession() { + return session; + } + + /** + * Gets this player's trade {@link PrivacyState}. + * + * @return The privacy state. + */ + public PrivacyState getTradePrivacy() { + return tradePrivacy; + } + + /** + * Gets the player's name. + * + * @return The player's name. + */ + public String getUsername() { + return credentials.getUsername(); + } + + /** + * Gets this player's viewing distance. + * + * @return The viewing distance. + */ + public int getViewingDistance() { + return viewingDistance; + } + + /** + * Gets the id of the world this player is in. + * + * @return The id. + */ + public int getWorldId() { + return worldId; + } + + /** + * Indicates whether or not the player with the specified username is on this player's ignore list. + * + * @param username The username of the player. + * @return {@code true} if the player is ignored, {@code false} if not. + */ + public boolean hasIgnored(String username) { + return ignores.contains(username.toLowerCase()); + } + + /** + * Checks if this player has ever known a region. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasLastKnownRegion() { + return lastKnownRegion != null; + } + + /** + * Checks if the region has changed. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasRegionChanged() { + return regionChanged; + } + + /** + * Increments this player's viewing distance if it is less than the maximum viewing distance. + */ + public void incrementViewingDistance() { + if (viewingDistance < Position.MAX_DISTANCE) { + viewingDistance++; } + } - /** - * Adds the specified username to this player's friend list. - * - * @param username The username. - */ - public boolean addFriend(String username) { - return friends.add(username.toLowerCase()); - } + /** + * Initialises this player. + */ + private void init() { + initInventories(); + initSkills(); + } - /** - * Adds the specified username to this player's ignore list. - * - * @param username The username. - */ - public boolean addIgnore(String username) { - return ignores.add(username.toLowerCase()); - } + /** + * Initialises the player's inventories. + */ + private void initInventories() { + InventoryListener fullInventoryListener = new FullInventoryListener(this, + FullInventoryListener.FULL_INVENTORY_MESSAGE); + InventoryListener fullBankListener = new FullInventoryListener(this, FullInventoryListener.FULL_BANK_MESSAGE); + InventoryListener appearanceListener = new AppearanceInventoryListener(this); - /** - * Decrements this player's viewing distance if it is greater than 1. - */ - public void decrementViewingDistance() { - if (viewingDistance > 1) { - viewingDistance--; + InventoryListener syncInventoryListener = new SynchronizationInventoryListener(this, + SynchronizationInventoryListener.INVENTORY_ID); + InventoryListener syncBankListener = new SynchronizationInventoryListener(this, BankConstants.BANK_INVENTORY_ID); + InventoryListener syncEquipmentListener = new SynchronizationInventoryListener(this, + SynchronizationInventoryListener.EQUIPMENT_ID); + + inventory.addListener(syncInventoryListener); + inventory.addListener(fullInventoryListener); + bank.addListener(syncBankListener); + bank.addListener(fullBankListener); + equipment.addListener(syncEquipmentListener); + equipment.addListener(appearanceListener); + } + + /** + * Initialises the player's skills. + */ + private void initSkills() { + skillSet.addListener(new SynchronizationSkillListener(this)); + skillSet.addListener(new LevelUpSkillListener(this)); + } + + /** + * Checks if there are excessive npcs. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isExcessiveNpcsSet() { + return excessiveNpcs; + } + + /** + * Checks if there are excessive players. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isExcessivePlayersSet() { + return excessivePlayers; + } + + /** + * Checks if this player account has membership. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isMembers() { + return members; + } + + /** + * Checks if this player has logged in before. + * + * @return A flag indicating if the player is new. + */ + public boolean isNew() { + return newPlayer; + } + + /** + * Gets whether the player is running or not. + * + * @return {@code true} if the player is running, otherwise {@code false}. + */ + public boolean isRunning() { + return running; + } + + /** + * Gets the withdrawing notes flag. + * + * @return The flag. + */ + public boolean isWithdrawingNotes() { + return withdrawingNotes; + } + + /** + * Logs the player out, if possible. + */ + public void logout() { + send(new LogoutEvent()); + } + + /** + * Indicates whether the message filter is enabled. + * + * @return {@code true} if the filter is enabled, otherwise {@code false}. + */ + public boolean messageFilterEnabled() { + return filteringMessages; + } + + /** + * Opens this player's bank. + */ + public void openBank() { + InventoryListener invListener = new SynchronizationInventoryListener(this, BankConstants.SIDEBAR_INVENTORY_ID); + InventoryListener bankListener = new SynchronizationInventoryListener(this, BankConstants.BANK_INVENTORY_ID); + + inventory.addListener(invListener); + bank.addListener(bankListener); + inventory.forceRefresh(); + bank.forceRefresh(); + + InterfaceListener interListener = new BankInterfaceListener(this, invListener, bankListener); + interfaceSet.openWindowWithSidebar(interListener, BankConstants.BANK_WINDOW_ID, BankConstants.SIDEBAR_ID); + } + + /** + * Removes the specified username from this player's friend list. + * + * @param username The username. + */ + public boolean removeFriend(String username) { + return friends.remove(username.toLowerCase()); + } + + /** + * Removes the specified username from this player's ignore list. + * + * @param username The username. + */ + public boolean removeIgnore(String username) { + return ignores.remove(username.toLowerCase()); + } + + /** + * Resets the excessive players flag. + */ + public void resetExcessivePlayers() { + excessivePlayers = false; + } + + /** + * Resets this player's viewing distance. + */ + public void resetViewingDistance() { + viewingDistance = 1; + } + + /** + * Sends an {@link Event} to this player. + * + * @param event The event. + */ + public void send(Event event) { + if (isActive()) { + if (!queuedEvents.isEmpty()) { + for (Event queuedEvent : queuedEvents) { + session.dispatchEvent(queuedEvent); } - } - - /** - * Sets the excessive npcs flag. - */ - public void flagExcessiveNpcs() { - excessiveNpcs = true; - } - - /** - * Sets the excessive players flag. - */ - public void flagExcessivePlayers() { - excessivePlayers = true; - } - - /** - * Indicates whether this player is friends with the player with the specified username or not. - * - * @param username The username of the other player. - * @return {@code true} if the specified username is on this player's friend list, otherwise {@code false}. - */ - public boolean friendsWith(String username) { - return friends.contains(username.toLowerCase()); - } - - /** - * Gets the player's appearance. - * - * @return The appearance. - */ - public Appearance getAppearance() { - return appearance; - } - - /** - * Gets the mob's bank. - * - * @return The bank. - */ - public Inventory getBank() { - return bank; - } - - /** - * Gets this player's public chat privacy state. - * - * @return The privacy state. - */ - public PrivacyState getChatPrivacy() { - return chatPrivacy; - } - - /** - * Gets the {@link Deque} of clicks. - * - * @return The deque. - */ - public Deque getClicks() { - return clicks; - } - - /** - * Gets the value denoting the clients modified version (0 if it is an unmodified jagex client). - * - * @return The version. - */ - public int getClientVersion() { - return clientVersion; - } - - /** - * Gets the player's credentials. - * - * @return The player's credentials. - */ - public PlayerCredentials getCredentials() { - return credentials; - } - - /** - * Gets the player's name, encoded as a long. - * - * @return The encoded player name. - */ - public long getEncodedName() { - return credentials.getEncodedUsername(); - } - - @Override - public EntityType getEntityType() { - return EntityType.PLAYER; - } - - /** - * Gets this player's friend chat {@link PrivacyState}. - * - * @return The privacy state. - */ - public PrivacyState getFriendPrivacy() { - return friendPrivacy; - } - - /** - * Gets the {@link List} of this player's friends. - * - * @return The list. - */ - public List getFriendUsernames() { - return friends; - } - - /** - * Indicates whether or not the player is skulled - * - * @return {@code true} if the player is skulled, otherwise {@code false}. - */ - public boolean isSkulled() { - return isSkulled; - } - - /** - * Gets the {@link List} of usernames of ignored players. - * - * @return The list. - */ - public List getIgnoredUsernames() { - return ignores; - } - - /** - * Gets this player's interface set. - * - * @return The interface set for this player. - */ - public InterfaceSet getInterfaceSet() { - return interfaceSet; - } - - /** - * Gets this player's last click, represented by a {@link Point}. - * - * @return The click. - */ - public Point getLastClick() { - return clicks.pollLast(); - } - - /** - * Gets the last known region. - * - * @return The last known region, or {@code null} if the player has never known a region. - */ - public Position getLastKnownRegion() { - return lastKnownRegion; - } - - /** - * Gets the player's prayer icon. - * - * @return The prayer icon. - */ - public int getPrayerIcon() { - return prayerIcon; - } - - /** - * Gets the privilege level. - * - * @return The privilege level. - */ - public PrivilegeLevel getPrivilegeLevel() { - return privilegeLevel; - } - - /** - * Gets the player's run energy. - * - * @return The run energy. - */ - public int getRunEnergy() { - return runEnergy; - } - - /** - * Gets this player's {@link ScreenBrightness}. - * - * @return The screen brightness. - */ - public ScreenBrightness getScreenBrightness() { - return screenBrightness; - } - - /** - * Gets the game session. - * - * @return The game session. - */ - public GameSession getSession() { - return session; - } - - /** - * Gets this player's trade {@link PrivacyState}. - * - * @return The privacy state. - */ - public PrivacyState getTradePrivacy() { - return tradePrivacy; - } - - /** - * Gets the player's name. - * - * @return The player's name. - */ - public String getUsername() { - return credentials.getUsername(); - } - - /** - * Gets this player's viewing distance. - * - * @return The viewing distance. - */ - public int getViewingDistance() { - return viewingDistance; - } - - /** - * Gets the id of the world this player is in. - * - * @return The id. - */ - public int getWorldId() { - return worldId; - } - - /** - * Indicates whether or not the player with the specified username is on this player's ignore list. - * - * @param username The username of the player. - * @return {@code true} if the player is ignored, {@code false} if not. - */ - public boolean hasIgnored(String username) { - return ignores.contains(username.toLowerCase()); - } - - /** - * Checks if this player has ever known a region. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasLastKnownRegion() { - return lastKnownRegion != null; - } - - /** - * Checks if the region has changed. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasRegionChanged() { - return regionChanged; - } - - /** - * Increments this player's viewing distance if it is less than the maximum viewing distance. - */ - public void incrementViewingDistance() { - if (viewingDistance < Position.MAX_DISTANCE) { - viewingDistance++; - } - } - - /** - * Initialises this player. - */ - private void init() { - initInventories(); - initSkills(); - } - - /** - * Initialises the player's inventories. - */ - private void initInventories() { - InventoryListener fullInventoryListener = new FullInventoryListener(this, - FullInventoryListener.FULL_INVENTORY_MESSAGE); - InventoryListener fullBankListener = new FullInventoryListener(this, FullInventoryListener.FULL_BANK_MESSAGE); - InventoryListener appearanceListener = new AppearanceInventoryListener(this); - - InventoryListener syncInventoryListener = new SynchronizationInventoryListener(this, - SynchronizationInventoryListener.INVENTORY_ID); - InventoryListener syncBankListener = new SynchronizationInventoryListener(this, BankConstants.BANK_INVENTORY_ID); - InventoryListener syncEquipmentListener = new SynchronizationInventoryListener(this, - SynchronizationInventoryListener.EQUIPMENT_ID); - - inventory.addListener(syncInventoryListener); - inventory.addListener(fullInventoryListener); - bank.addListener(syncBankListener); - bank.addListener(fullBankListener); - equipment.addListener(syncEquipmentListener); - equipment.addListener(appearanceListener); - } - - /** - * Initialises the player's skills. - */ - private void initSkills() { - skillSet.addListener(new SynchronizationSkillListener(this)); - skillSet.addListener(new LevelUpSkillListener(this)); - } - - /** - * Checks if there are excessive npcs. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isExcessiveNpcsSet() { - return excessiveNpcs; - } - - /** - * Checks if there are excessive players. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isExcessivePlayersSet() { - return excessivePlayers; - } - - /** - * Checks if this player account has membership. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isMembers() { - return members; - } - - /** - * Checks if this player has logged in before. - * - * @return A flag indicating if the player is new. - */ - public boolean isNew() { - return newPlayer; - } - - /** - * Gets whether the player is running or not. - * - * @return {@code true} if the player is running, otherwise {@code false}. - */ - public boolean isRunning() { - return running; - } - - /** - * Gets the withdrawing notes flag. - * - * @return The flag. - */ - public boolean isWithdrawingNotes() { - return withdrawingNotes; - } - - /** - * Logs the player out, if possible. - */ - public void logout() { - send(new LogoutEvent()); - } - - /** - * Indicates whether the message filter is enabled. - * - * @return {@code true} if the filter is enabled, otherwise {@code false}. - */ - public boolean messageFilterEnabled() { - return filteringMessages; - } - - /** - * Opens this player's bank. - */ - public void openBank() { - InventoryListener invListener = new SynchronizationInventoryListener(this, BankConstants.SIDEBAR_INVENTORY_ID); - InventoryListener bankListener = new SynchronizationInventoryListener(this, BankConstants.BANK_INVENTORY_ID); - - inventory.addListener(invListener); - bank.addListener(bankListener); - inventory.forceRefresh(); - bank.forceRefresh(); - - InterfaceListener interListener = new BankInterfaceListener(this, invListener, bankListener); - interfaceSet.openWindowWithSidebar(interListener, BankConstants.BANK_WINDOW_ID, BankConstants.SIDEBAR_ID); - } - - /** - * Removes the specified username from this player's friend list. - * - * @param username The username. - */ - public boolean removeFriend(String username) { - return friends.remove(username.toLowerCase()); - } - - /** - * Removes the specified username from this player's ignore list. - * - * @param username The username. - */ - public boolean removeIgnore(String username) { - return ignores.remove(username.toLowerCase()); - } - - /** - * Resets the excessive players flag. - */ - public void resetExcessivePlayers() { - excessivePlayers = false; - } - - /** - * Resets this player's viewing distance. - */ - public void resetViewingDistance() { - viewingDistance = 1; - } - - /** - * Sends an {@link Event} to this player. - * - * @param event The event. - */ - public void send(Event event) { - if (isActive()) { - if (!queuedEvents.isEmpty()) { - for (Event queuedEvent : queuedEvents) { - session.dispatchEvent(queuedEvent); - } - queuedEvents.clear(); - } - session.dispatchEvent(event); - } else { - queuedEvents.add(event); - } - } - - /** - * Sends the initial events. - */ - private void sendInitialEvents() { - send(new IdAssignmentEvent(index, members)); // TODO should this be sent when we reconnect? - sendMessage("Welcome to RuneScape."); - if (!newPlayer) { - interfaceSet.openWindow(InterfaceConstants.AVATAR_DESIGN); - } - - int[] tabs = InterfaceConstants.DEFAULT_INVENTORY_TABS; - for (int tab = 0; tab < tabs.length; tab++) { - send(new SwitchTabInterfaceEvent(tab, tabs[tab])); - } - - inventory.forceRefresh(); - equipment.forceRefresh(); - bank.forceRefresh(); - skillSet.forceRefresh(); - - World.getWorld().getLoginDispatcher().dispatch(this); - } - - /** - * Sends a message to the player. - * - * @param message The message. - */ - public void sendMessage(String message) { - sendMessage(message, false); - } - - /** - * Sends a message to the player. - * - * @param message The message. - */ - public void sendMessage(String message, boolean filterable) { - if (clientVersion > 0) { - send(new ServerMessageEvent(message, filterable)); - } else if (!filterable || !filteringMessages) { - send(new ServerMessageEvent(message)); - } - } - - /** - * Sends the quest interface - * - * @param text The text to display on the interface. - */ - public void sendQuestInterface(List text) { - int size = text.size(), lines = InterfaceConstants.QUEST_TEXT.length; - if (size > lines) { - throw new IllegalArgumentException("List contains too much text to display on this interface."); - } - - for (int pos = 0; pos < lines; pos++) { - send(new SetWidgetTextEvent(InterfaceConstants.QUEST_TEXT[pos], pos < size ? text.get(pos) : "")); - } - interfaceSet.openWindow(InterfaceConstants.QUEST_INTERFACE); - } - - /** - * Sends the friend and ignore user lists. - */ - public void sendUserLists() { - if (ignores.size() > 0) { - send(new IgnoreListEvent(ignores)); - } - - World world = World.getWorld(); - for (String username : friends) { - int worldId = world.isPlayerOnline(username) ? world.getPlayer(username).worldId : 0; - send(new SendFriendEvent(username, worldId)); - } - } - - /** - * Sets the player's appearance. - * - * @param appearance The new appearance. - */ - public void setAppearance(Appearance appearance) { - this.appearance = appearance; - blockSet.add(SynchronizationBlock.createAppearanceBlock(this)); - } - - /** - * Sets the chat {@link PrivacyState}. - * - * @param chatPrivacy The privacy state. - */ - public void setChatPrivacy(PrivacyState chatPrivacy) { - this.chatPrivacy = chatPrivacy; - } - - /** - * Sets the value denoting the client's modified version. - * - * @param clientVersion The client version. - */ - public void setClientVersion(int clientVersion) { - this.clientVersion = clientVersion; - } - - /** - * Sets the friend {@link PrivacyState}. - * - * @param friendPrivacy The privacy state. - */ - public void setFriendPrivacy(PrivacyState friendPrivacy) { - this.friendPrivacy = friendPrivacy; - } - - /** - * Sets the {@link List} of this player's friends. - * - * @param friends The friends. - */ - public void setFriendUsernames(List friends) { - this.friends = friends; - } - - /** - * Sets whether or not the player is skulled. - * - * @param isSkulled Whether or not the player is skulled. - */ - public void setSkulled(boolean isSkulled) { - this.isSkulled = isSkulled; - } - - /** - * Sets the {@link List} of this player's ignored players. - * - * @param ignores The ignored player list. - */ - public void setIgnoredUsernames(List ignores) { - this.ignores = ignores; - } - - /** - * Sets the last known region. - * - * @param lastKnownRegion The last known region. - */ - public void setLastKnownRegion(Position lastKnownRegion) { - this.lastKnownRegion = lastKnownRegion; - } - - /** - * Changes the membership status of this player. - * - * @param members The new membership flag. - */ - public void setMembers(boolean members) { - this.members = members; - } - - /** - * Sets the new player flag. - * - * @param newPlayer A flag indicating if the player has played before. - */ - public void setNew(boolean newPlayer) { - this.newPlayer = newPlayer; - } - - /** - * Sets the player's prayer icon. - * - * @param prayerIcon The prayer icon. - */ - public void setPrayerIcon(int prayerIcon) { - this.prayerIcon = prayerIcon; - } - - /** - * Sets the privilege level. - * - * @param privilegeLevel The privilege level. - */ - public void setPrivilegeLevel(PrivilegeLevel privilegeLevel) { - this.privilegeLevel = privilegeLevel; - } - - /** - * Sets the region changed flag. - * - * @param regionChanged A flag indicating if the region has changed. - */ - public void setRegionChanged(boolean regionChanged) { - this.regionChanged = regionChanged; - } - - /** - * Sets the player's run energy. - * - * @param runEnergy The energy. - */ - public void setRunEnergy(int runEnergy) { - send(new UpdateRunEnergyEvent(this.runEnergy = runEnergy)); - } - - /** - * Sets the {@link ScreenBrightness} of this player. - * - * @param brightness The screen brightness. - */ - public void setScreenBrightness(ScreenBrightness brightness) { - this.screenBrightness = brightness; - } - - /** - * Sets the player's {@link GameSession}. - * - * @param session The player's {@link GameSession}. - * @param reconnecting The reconnecting flag. - */ - public void setSession(GameSession session, boolean reconnecting) { - this.session = session; - if (!reconnecting) { - sendInitialEvents(); - } - blockSet.add(SynchronizationBlock.createAppearanceBlock(this)); - } - - /** - * Sets the trade {@link PrivacyState}. - * - * @param tradePrivacy The privacy state. - */ - public void setTradePrivacy(PrivacyState tradePrivacy) { - this.tradePrivacy = tradePrivacy; - } - - /** - * Sets whether the player is withdrawing notes from the bank. - * - * @param withdrawingNotes Whether the player is withdrawing noted items or not. - */ - public void setWithdrawingNotes(boolean withdrawingNotes) { - this.withdrawingNotes = withdrawingNotes; - } - - @Override - public void shout(String message, boolean chatOnly) { - blockSet.add(SynchronizationBlock.createForceChatBlock(chatOnly ? message : '~' + message)); - } - - @Override - public void teleport(Position position) { - super.teleport(position); - if (interfaceSet.size() > 0) { - interfaceSet.close(); - } - } - - /** - * Toggles the message filter. - * - * @return The new value of the filter. - */ - public boolean toggleMessageFilter() { - return filteringMessages = !filteringMessages; - } - - /** - * Toggles whether the player is running or not. - */ - public void toggleRunning() { - walkingQueue.setRunningQueue(running = !running); - send(new ConfigEvent(173, running ? 1 : 0)); - } - - @Override - public String toString() { - return Player.class.getName() + " [username=" + getUsername() + ", privilege=" + privilegeLevel + "]"; - } + queuedEvents.clear(); + } + session.dispatchEvent(event); + } else { + queuedEvents.add(event); + } + } + + /** + * Sends the initial events. + */ + private void sendInitialEvents() { + send(new IdAssignmentEvent(index, members)); // TODO should this be sent when we reconnect? + sendMessage("Welcome to RuneScape."); + if (!newPlayer) { + interfaceSet.openWindow(InterfaceConstants.AVATAR_DESIGN); + } + + int[] tabs = InterfaceConstants.DEFAULT_INVENTORY_TABS; + for (int tab = 0; tab < tabs.length; tab++) { + send(new SwitchTabInterfaceEvent(tab, tabs[tab])); + } + + inventory.forceRefresh(); + equipment.forceRefresh(); + bank.forceRefresh(); + skillSet.forceRefresh(); + + World.getWorld().getLoginDispatcher().dispatch(this); + } + + /** + * Sends a message to the player. + * + * @param message The message. + */ + public void sendMessage(String message) { + sendMessage(message, false); + } + + /** + * Sends a message to the player. + * + * @param message The message. + */ + public void sendMessage(String message, boolean filterable) { + if (clientVersion > 0) { + send(new ServerMessageEvent(message, filterable)); + } else if (!filterable || !filteringMessages) { + send(new ServerMessageEvent(message)); + } + } + + /** + * Sends the quest interface + * + * @param text The text to display on the interface. + */ + public void sendQuestInterface(List text) { + int size = text.size(), lines = InterfaceConstants.QUEST_TEXT.length; + if (size > lines) { + throw new IllegalArgumentException("List contains too much text to display on this interface."); + } + + for (int pos = 0; pos < lines; pos++) { + send(new SetWidgetTextEvent(InterfaceConstants.QUEST_TEXT[pos], pos < size ? text.get(pos) : "")); + } + interfaceSet.openWindow(InterfaceConstants.QUEST_INTERFACE); + } + + /** + * Sends the friend and ignore user lists. + */ + public void sendUserLists() { + if (ignores.size() > 0) { + send(new IgnoreListEvent(ignores)); + } + + World world = World.getWorld(); + for (String username : friends) { + int worldId = world.isPlayerOnline(username) ? world.getPlayer(username).worldId : 0; + send(new SendFriendEvent(username, worldId)); + } + } + + /** + * Sets the player's appearance. + * + * @param appearance The new appearance. + */ + public void setAppearance(Appearance appearance) { + this.appearance = appearance; + blockSet.add(SynchronizationBlock.createAppearanceBlock(this)); + } + + /** + * Sets the chat {@link PrivacyState}. + * + * @param chatPrivacy The privacy state. + */ + public void setChatPrivacy(PrivacyState chatPrivacy) { + this.chatPrivacy = chatPrivacy; + } + + /** + * Sets the value denoting the client's modified version. + * + * @param clientVersion The client version. + */ + public void setClientVersion(int clientVersion) { + this.clientVersion = clientVersion; + } + + /** + * Sets the friend {@link PrivacyState}. + * + * @param friendPrivacy The privacy state. + */ + public void setFriendPrivacy(PrivacyState friendPrivacy) { + this.friendPrivacy = friendPrivacy; + } + + /** + * Sets the {@link List} of this player's friends. + * + * @param friends The friends. + */ + public void setFriendUsernames(List friends) { + this.friends = friends; + } + + /** + * Sets whether or not the player is skulled. + * + * @param isSkulled Whether or not the player is skulled. + */ + public void setSkulled(boolean isSkulled) { + this.isSkulled = isSkulled; + } + + /** + * Sets the {@link List} of this player's ignored players. + * + * @param ignores The ignored player list. + */ + public void setIgnoredUsernames(List ignores) { + this.ignores = ignores; + } + + /** + * Sets the last known region. + * + * @param lastKnownRegion The last known region. + */ + public void setLastKnownRegion(Position lastKnownRegion) { + this.lastKnownRegion = lastKnownRegion; + } + + /** + * Changes the membership status of this player. + * + * @param members The new membership flag. + */ + public void setMembers(boolean members) { + this.members = members; + } + + /** + * Sets the new player flag. + * + * @param newPlayer A flag indicating if the player has played before. + */ + public void setNew(boolean newPlayer) { + this.newPlayer = newPlayer; + } + + /** + * Sets the player's prayer icon. + * + * @param prayerIcon The prayer icon. + */ + public void setPrayerIcon(int prayerIcon) { + this.prayerIcon = prayerIcon; + } + + /** + * Sets the privilege level. + * + * @param privilegeLevel The privilege level. + */ + public void setPrivilegeLevel(PrivilegeLevel privilegeLevel) { + this.privilegeLevel = privilegeLevel; + } + + /** + * Sets the region changed flag. + * + * @param regionChanged A flag indicating if the region has changed. + */ + public void setRegionChanged(boolean regionChanged) { + this.regionChanged = regionChanged; + } + + /** + * Sets the player's run energy. + * + * @param runEnergy The energy. + */ + public void setRunEnergy(int runEnergy) { + send(new UpdateRunEnergyEvent(this.runEnergy = runEnergy)); + } + + /** + * Sets the {@link ScreenBrightness} of this player. + * + * @param brightness The screen brightness. + */ + public void setScreenBrightness(ScreenBrightness brightness) { + this.screenBrightness = brightness; + } + + /** + * Sets the player's {@link GameSession}. + * + * @param session The player's {@link GameSession}. + * @param reconnecting The reconnecting flag. + */ + public void setSession(GameSession session, boolean reconnecting) { + this.session = session; + if (!reconnecting) { + sendInitialEvents(); + } + blockSet.add(SynchronizationBlock.createAppearanceBlock(this)); + } + + /** + * Sets the trade {@link PrivacyState}. + * + * @param tradePrivacy The privacy state. + */ + public void setTradePrivacy(PrivacyState tradePrivacy) { + this.tradePrivacy = tradePrivacy; + } + + /** + * Sets whether the player is withdrawing notes from the bank. + * + * @param withdrawingNotes Whether the player is withdrawing noted items or not. + */ + public void setWithdrawingNotes(boolean withdrawingNotes) { + this.withdrawingNotes = withdrawingNotes; + } + + @Override + public void shout(String message, boolean chatOnly) { + blockSet.add(SynchronizationBlock.createForceChatBlock(chatOnly ? message : '~' + message)); + } + + @Override + public void teleport(Position position) { + super.teleport(position); + if (interfaceSet.size() > 0) { + interfaceSet.close(); + } + } + + /** + * Toggles the message filter. + * + * @return The new value of the filter. + */ + public boolean toggleMessageFilter() { + return filteringMessages = !filteringMessages; + } + + /** + * Toggles whether the player is running or not. + */ + public void toggleRunning() { + walkingQueue.setRunningQueue(running = !running); + send(new ConfigEvent(173, running ? 1 : 0)); + } + + @Override + public String toString() { + return Player.class.getName() + " [username=" + getUsername() + ", privilege=" + privilegeLevel + "]"; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/Skill.java b/src/org/apollo/game/model/entity/Skill.java index f0ccdf95..4470ce29 100644 --- a/src/org/apollo/game/model/entity/Skill.java +++ b/src/org/apollo/game/model/entity/Skill.java @@ -7,191 +7,191 @@ package org.apollo.game.model.entity; */ public final class Skill { - /** - * The agility id. - */ - public static final int AGILITY = 16; + /** + * The agility id. + */ + public static final int AGILITY = 16; - /** - * The attack id. - */ - public static final int ATTACK = 0; + /** + * The attack id. + */ + public static final int ATTACK = 0; - /** - * The cooking id. - */ - public static final int COOKING = 7; + /** + * The cooking id. + */ + public static final int COOKING = 7; - /** - * The crafting id. - */ - public static final int CRAFTING = 12; + /** + * The crafting id. + */ + public static final int CRAFTING = 12; - /** - * The defence id. - */ - public static final int DEFENCE = 1; + /** + * The defence id. + */ + public static final int DEFENCE = 1; - /** - * The farming id. - */ - public static final int FARMING = 19; + /** + * The farming id. + */ + public static final int FARMING = 19; - /** - * The firemaking id. - */ - public static final int FIREMAKING = 11; + /** + * The firemaking id. + */ + public static final int FIREMAKING = 11; - /** - * The fishing id. - */ - public static final int FISHING = 10; + /** + * The fishing id. + */ + public static final int FISHING = 10; - /** - * The fletching id. - */ - public static final int FLETCHING = 9; + /** + * The fletching id. + */ + public static final int FLETCHING = 9; - /** - * The herblore id. - */ - public static final int HERBLORE = 15; + /** + * The herblore id. + */ + public static final int HERBLORE = 15; - /** - * The hitpoints id. - */ - public static final int HITPOINTS = 3; + /** + * The hitpoints id. + */ + public static final int HITPOINTS = 3; - /** - * The magic id. - */ - public static final int MAGIC = 6; + /** + * The magic id. + */ + public static final int MAGIC = 6; - /** - * The mining id.rivate - */ - public static final int MINING = 14; + /** + * The mining id.rivate + */ + public static final int MINING = 14; - /** - * The prayer id. - */ - public static final int PRAYER = 5; + /** + * The prayer id. + */ + public static final int PRAYER = 5; - /** - * The ranged id. - */ - public static final int RANGED = 4; + /** + * The ranged id. + */ + public static final int RANGED = 4; - /** - * The runecraft id. - */ - public static final int RUNECRAFT = 20; + /** + * The runecraft id. + */ + public static final int RUNECRAFT = 20; - /** - * The skill names. - */ - private static final String SKILL_NAMES[] = { "Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", - "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", - "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecraft" }; + /** + * The skill names. + */ + private static final String SKILL_NAMES[] = { "Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", + "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", + "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecraft" }; - /** - * The slayer id. - */ - public static final int SLAYER = 18; + /** + * The slayer id. + */ + public static final int SLAYER = 18; - /** - * The smithing id. - */ - public static final int SMITHING = 13; + /** + * The smithing id. + */ + public static final int SMITHING = 13; - /** - * The strength id. - */ - public static final int STRENGTH = 2; + /** + * The strength id. + */ + public static final int STRENGTH = 2; - /** - * The thieving id. - */ - public static final int THIEVING = 17; + /** + * The thieving id. + */ + public static final int THIEVING = 17; - /** - * The woodcutting id. - */ - public static final int WOODCUTTING = 8; + /** + * The woodcutting id. + */ + public static final int WOODCUTTING = 8; - /** - * Gets the name of a skill. - * - * @param id The skill's id. - * @return The skill's name. - */ - public static String getName(int id) { - return SKILL_NAMES[id]; - } + /** + * Gets the name of a skill. + * + * @param id The skill's id. + * @return The skill's name. + */ + public static String getName(int id) { + return SKILL_NAMES[id]; + } - /** - * Whether the skill affects the combat level or not. - * - * @param skill The id of the skill. - * @return {@code true} if the skill is a combat skill, otherwise {@code false}. - */ - public static boolean isCombatSkill(int skill) { - return skill >= ATTACK && skill <= MAGIC; - } + /** + * Whether the skill affects the combat level or not. + * + * @param skill The id of the skill. + * @return {@code true} if the skill is a combat skill, otherwise {@code false}. + */ + public static boolean isCombatSkill(int skill) { + return skill >= ATTACK && skill <= MAGIC; + } - /** - * The current level. - */ - private final int currentLevel; + /** + * The current level. + */ + private final int currentLevel; - /** - * The experience. - */ - private final double experience; + /** + * The experience. + */ + private final double experience; - /** - * The maximum level. - */ - private final int maximumLevel; + /** + * The maximum level. + */ + private final int maximumLevel; - /** - * Creates a skill. - * - * @param experience The experience. - * @param currentLevel The current level. - * @param maximumLevel The maximum level. - */ - public Skill(double experience, int currentLevel, int maximumLevel) { - this.experience = experience; - this.currentLevel = currentLevel; - this.maximumLevel = maximumLevel; - } + /** + * Creates a skill. + * + * @param experience The experience. + * @param currentLevel The current level. + * @param maximumLevel The maximum level. + */ + public Skill(double experience, int currentLevel, int maximumLevel) { + this.experience = experience; + this.currentLevel = currentLevel; + this.maximumLevel = maximumLevel; + } - /** - * Gets the current level. - * - * @return The current level. - */ - public int getCurrentLevel() { - return currentLevel; - } + /** + * Gets the current level. + * + * @return The current level. + */ + public int getCurrentLevel() { + return currentLevel; + } - /** - * Gets the experience. - * - * @return The experience. - */ - public double getExperience() { - return experience; - } + /** + * Gets the experience. + * + * @return The experience. + */ + public double getExperience() { + return experience; + } - /** - * Gets the maximum level. - * - * @return The maximum level. - */ - public int getMaximumLevel() { - return maximumLevel; - } + /** + * Gets the maximum level. + * + * @return The maximum level. + */ + public int getMaximumLevel() { + return maximumLevel; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/SkillSet.java b/src/org/apollo/game/model/entity/SkillSet.java index 308def15..f6862f2d 100644 --- a/src/org/apollo/game/model/entity/SkillSet.java +++ b/src/org/apollo/game/model/entity/SkillSet.java @@ -12,310 +12,310 @@ import org.apollo.game.model.skill.SkillListener; */ public final class SkillSet { - /** - * The minimum amounts of experience required for the levels. - */ - private static final int[] EXPERIENCE_FOR_LEVEL = new int[100]; + /** + * The minimum amounts of experience required for the levels. + */ + private static final int[] EXPERIENCE_FOR_LEVEL = new int[100]; - /** - * The maximum allowed experience. - */ - public static final double MAXIMUM_EXP = 200_000_000; + /** + * The maximum allowed experience. + */ + public static final double MAXIMUM_EXP = 200_000_000; - /** - * The number of skills. - */ - private static final int SKILL_COUNT = 21; + /** + * The number of skills. + */ + private static final int SKILL_COUNT = 21; - static { - int points = 0, output = 0; - for (int lvl = 1; lvl <= 99; lvl++) { - EXPERIENCE_FOR_LEVEL[lvl] = output; - points += Math.floor(lvl + 300.0 * Math.pow(2.0, lvl / 7.0)); - output = (int) Math.floor(points / 4); - } + static { + int points = 0, output = 0; + for (int lvl = 1; lvl <= 99; lvl++) { + EXPERIENCE_FOR_LEVEL[lvl] = output; + points += Math.floor(lvl + 300.0 * Math.pow(2.0, lvl / 7.0)); + output = (int) Math.floor(points / 4); } + } - /** - * Gets the minimum experience required for the specified level. - * - * @param level The level. - * @return The minimum experience. - */ - public static int getExperienceForLevel(int level) { - if (level < 1 || level > 99) { - throw new IllegalArgumentException("Level must be between 1 and 99, inclusive."); - } - return EXPERIENCE_FOR_LEVEL[level]; + /** + * Gets the minimum experience required for the specified level. + * + * @param level The level. + * @return The minimum experience. + */ + public static int getExperienceForLevel(int level) { + if (level < 1 || level > 99) { + throw new IllegalArgumentException("Level must be between 1 and 99, inclusive."); } + return EXPERIENCE_FOR_LEVEL[level]; + } - /** - * Gets the minimum level to get the specified experience. - * - * @param experience The experience. - * @return The minimum level. - */ - public static int getLevelForExperience(double experience) { - if (experience < 0 || experience > MAXIMUM_EXP) { - throw new IllegalArgumentException("Experience must be between 0 and 200,000,000, inclusive."); - } - for (int level = 1; level <= 98; level++) { - if (experience < EXPERIENCE_FOR_LEVEL[level + 1]) { - return level; - } - } - return 99; + /** + * Gets the minimum level to get the specified experience. + * + * @param experience The experience. + * @return The minimum level. + */ + public static int getLevelForExperience(double experience) { + if (experience < 0 || experience > MAXIMUM_EXP) { + throw new IllegalArgumentException("Experience must be between 0 and 200,000,000, inclusive."); } - - /** - * The combat level for this skill set. - */ - private int combatLevel = 3; - - /** - * A flag indicating if events are being fired. - */ - private boolean firingEvents = true; - - /** - * A list of skill listeners. - */ - private final List listeners = new ArrayList<>(); - - /** - * The skills. - */ - private final Skill[] skills = new Skill[SKILL_COUNT]; - - /** - * Creates the skill set. - */ - public SkillSet() { - init(); + for (int level = 1; level <= 98; level++) { + if (experience < EXPERIENCE_FOR_LEVEL[level + 1]) { + return level; + } } + return 99; + } - /** - * Adds experience to the specified skill. - * - * @param id The skill id. - * @param experience The amount of experience. - */ - public void addExperience(int id, double experience) { - checkBounds(id); - Skill old = skills[id]; + /** + * The combat level for this skill set. + */ + private int combatLevel = 3; - double newExperience = old.getExperience() + experience; - newExperience = newExperience > MAXIMUM_EXP ? MAXIMUM_EXP : newExperience; + /** + * A flag indicating if events are being fired. + */ + private boolean firingEvents = true; - int newCurrentLevel = old.getCurrentLevel(); - int newMaximumLevel = getLevelForExperience(newExperience); + /** + * A list of skill listeners. + */ + private final List listeners = new ArrayList<>(); - int delta = newMaximumLevel - old.getMaximumLevel(); - newCurrentLevel += delta > 0 ? delta : 0; + /** + * The skills. + */ + private final Skill[] skills = new Skill[SKILL_COUNT]; - setSkill(id, new Skill(newExperience, newCurrentLevel, newMaximumLevel)); + /** + * Creates the skill set. + */ + public SkillSet() { + init(); + } - if (delta > 0) { - notifyLevelledUp(id); // here so it notifies using the updated skill - } + /** + * Adds experience to the specified skill. + * + * @param id The skill id. + * @param experience The amount of experience. + */ + public void addExperience(int id, double experience) { + checkBounds(id); + Skill old = skills[id]; + + double newExperience = old.getExperience() + experience; + newExperience = newExperience > MAXIMUM_EXP ? MAXIMUM_EXP : newExperience; + + int newCurrentLevel = old.getCurrentLevel(); + int newMaximumLevel = getLevelForExperience(newExperience); + + int delta = newMaximumLevel - old.getMaximumLevel(); + newCurrentLevel += delta > 0 ? delta : 0; + + setSkill(id, new Skill(newExperience, newCurrentLevel, newMaximumLevel)); + + if (delta > 0) { + notifyLevelledUp(id); // here so it notifies using the updated skill } + } - /** - * Adds a {@link SkillListener} to this set. - * - * @param listener The listener. - */ - public boolean addListener(SkillListener listener) { - return listeners.add(listener); + /** + * Adds a {@link SkillListener} to this set. + * + * @param listener The listener. + */ + public boolean addListener(SkillListener listener) { + return listeners.add(listener); + } + + /** + * Calculates the combat level for this skill set. + * + * @return The combat level. + */ + public void calculateCombatLevel() { + int attack = skills[Skill.ATTACK].getMaximumLevel(); + int defence = skills[Skill.DEFENCE].getMaximumLevel(); + int strength = skills[Skill.STRENGTH].getMaximumLevel(); + int hitpoints = skills[Skill.HITPOINTS].getMaximumLevel(); + int prayer = skills[Skill.PRAYER].getMaximumLevel(); + int ranged = skills[Skill.RANGED].getMaximumLevel(); + int magic = skills[Skill.MAGIC].getMaximumLevel(); + + double base = (defence + hitpoints + Math.floor(prayer / 2)) * 0.25; + double melee = (attack + strength) * 0.325; + double range = ranged * 0.4875; + double mage = magic * 0.4875; + + this.combatLevel = (int) (base + Math.max(melee, Math.max(range, mage))); + } + + /** + * Checks the bounds of the id. + * + * @param id The id. + * @throws IndexOutOfBoundsException If the id is out of bounds. + */ + private void checkBounds(int id) { + if (id < 0 || id >= skills.length) { + throw new IndexOutOfBoundsException("Skill id is out of bounds."); } + } - /** - * Calculates the combat level for this skill set. - * - * @return The combat level. - */ - public void calculateCombatLevel() { - int attack = skills[Skill.ATTACK].getMaximumLevel(); - int defence = skills[Skill.DEFENCE].getMaximumLevel(); - int strength = skills[Skill.STRENGTH].getMaximumLevel(); - int hitpoints = skills[Skill.HITPOINTS].getMaximumLevel(); - int prayer = skills[Skill.PRAYER].getMaximumLevel(); - int ranged = skills[Skill.RANGED].getMaximumLevel(); - int magic = skills[Skill.MAGIC].getMaximumLevel(); + /** + * Forces this skill set to refresh. + */ + public void forceRefresh() { + notifySkillsUpdated(); + } - double base = (defence + hitpoints + Math.floor(prayer / 2)) * 0.25; - double melee = (attack + strength) * 0.325; - double range = ranged * 0.4875; - double mage = magic * 0.4875; + /** + * Gets the combat level of this skill set. + * + * @return The combat level. + */ + public int getCombatLevel() { + return combatLevel; + } - this.combatLevel = (int) (base + Math.max(melee, Math.max(range, mage))); + /** + * Gets a skill by its id. + * + * @param id The id. + * @return The skill. + */ + public Skill getSkill(int id) { + checkBounds(id); + return skills[id]; + } + + /** + * Gets the total level for this skill set. + * + * @return The total level. + */ + public int getTotalLevel() { + int total = 0; + for (Skill skill : skills) { + total += skill.getMaximumLevel(); } + return total; + } - /** - * Checks the bounds of the id. - * - * @param id The id. - * @throws IndexOutOfBoundsException If the id is out of bounds. - */ - private void checkBounds(int id) { - if (id < 0 || id >= skills.length) { - throw new IndexOutOfBoundsException("Skill id is out of bounds."); - } + /** + * Initialises the skill set. + */ + private void init() { + for (int id = 0; id < skills.length; id++) { + skills[id] = (id == Skill.HITPOINTS ? new Skill(1154, 10, 10) : new Skill(0, 1, 1)); } + } - /** - * Forces this skill set to refresh. - */ - public void forceRefresh() { - notifySkillsUpdated(); + /** + * Normalizes the skills in this set. + */ + public void normalize() { + for (int id = 0; id < skills.length; id++) { + int current = skills[id].getCurrentLevel(), max = skills[id].getMaximumLevel(); + + if (current == max) { + continue; + } + + current += current < max ? 1 : -1; + setSkill(id, new Skill(skills[id].getExperience(), current, max)); } + } - /** - * Gets the combat level of this skill set. - * - * @return The combat level. - */ - public int getCombatLevel() { - return combatLevel; + /** + * Notifies listeners that a skill has been levelled up. + * + * @param id The skill's id. + */ + private void notifyLevelledUp(int id) { + checkBounds(id); + if (firingEvents) { + for (SkillListener listener : listeners) { + listener.levelledUp(this, id, skills[id]); + } } + } - /** - * Gets a skill by its id. - * - * @param id The id. - * @return The skill. - */ - public Skill getSkill(int id) { - checkBounds(id); - return skills[id]; + /** + * Notifies listeners that the skills in this listener have been updated. + */ + private void notifySkillsUpdated() { + if (firingEvents) { + for (SkillListener listener : listeners) { + listener.skillsUpdated(this); + } } + } - /** - * Gets the total level for this skill set. - * - * @return The total level. - */ - public int getTotalLevel() { - int total = 0; - for (Skill skill : skills) { - total += skill.getMaximumLevel(); - } - return total; + /** + * Notifies listeners that a skill has been updated. + * + * @param id The skill's id. + */ + private void notifySkillUpdated(int id) { + checkBounds(id); + if (firingEvents) { + for (SkillListener listener : listeners) { + listener.skillUpdated(this, id, skills[id]); + } } + } - /** - * Initialises the skill set. - */ - private void init() { - for (int id = 0; id < skills.length; id++) { - skills[id] = (id == Skill.HITPOINTS ? new Skill(1154, 10, 10) : new Skill(0, 1, 1)); - } - } + /** + * Removes all the {@link SkillListener}s. + */ + public void removeAllListeners() { + listeners.clear(); + } - /** - * Normalizes the skills in this set. - */ - public void normalize() { - for (int id = 0; id < skills.length; id++) { - int current = skills[id].getCurrentLevel(), max = skills[id].getMaximumLevel(); + /** + * Removes a {@link SkillListener}. + * + * @param listener The listener to remove. + */ + public boolean removeListener(SkillListener listener) { + return listeners.remove(listener); + } - if (current == max) { - continue; - } + /** + * Sets a {@link Skill}. + * + * @param id The id. + * @param skill The skill. + */ + public void setSkill(int id, Skill skill) { + checkBounds(id); + skills[id] = skill; + notifySkillUpdated(id); + } - current += current < max ? 1 : -1; - setSkill(id, new Skill(skills[id].getExperience(), current, max)); - } - } + /** + * Gets the number of {@link Skill}s in this set. + * + * @return The number of skills. + */ + public int size() { + return skills.length; + } - /** - * Notifies listeners that a skill has been levelled up. - * - * @param id The skill's id. - */ - private void notifyLevelledUp(int id) { - checkBounds(id); - if (firingEvents) { - for (SkillListener listener : listeners) { - listener.levelledUp(this, id, skills[id]); - } - } - } + /** + * Starts the firing of events. + */ + public void startFiringEvents() { + firingEvents = true; + } - /** - * Notifies listeners that the skills in this listener have been updated. - */ - private void notifySkillsUpdated() { - if (firingEvents) { - for (SkillListener listener : listeners) { - listener.skillsUpdated(this); - } - } - } - - /** - * Notifies listeners that a skill has been updated. - * - * @param id The skill's id. - */ - private void notifySkillUpdated(int id) { - checkBounds(id); - if (firingEvents) { - for (SkillListener listener : listeners) { - listener.skillUpdated(this, id, skills[id]); - } - } - } - - /** - * Removes all the {@link SkillListener}s. - */ - public void removeAllListeners() { - listeners.clear(); - } - - /** - * Removes a {@link SkillListener}. - * - * @param listener The listener to remove. - */ - public boolean removeListener(SkillListener listener) { - return listeners.remove(listener); - } - - /** - * Sets a {@link Skill}. - * - * @param id The id. - * @param skill The skill. - */ - public void setSkill(int id, Skill skill) { - checkBounds(id); - skills[id] = skill; - notifySkillUpdated(id); - } - - /** - * Gets the number of {@link Skill}s in this set. - * - * @return The number of skills. - */ - public int size() { - return skills.length; - } - - /** - * Starts the firing of events. - */ - public void startFiringEvents() { - firingEvents = true; - } - - /** - * Stops events from being fired. - */ - public void stopFiringEvents() { - firingEvents = false; - } + /** + * Stops events from being fired. + */ + public void stopFiringEvents() { + firingEvents = false; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/entity/WalkingQueue.java b/src/org/apollo/game/model/entity/WalkingQueue.java index 7f7d283f..59849ace 100644 --- a/src/org/apollo/game/model/entity/WalkingQueue.java +++ b/src/org/apollo/game/model/entity/WalkingQueue.java @@ -14,242 +14,242 @@ import org.apollo.game.model.Position; */ public final class WalkingQueue { + /** + * Represents a single point in the queue. + * + * @author Graham + */ + private static final class Point { + /** - * Represents a single point in the queue. - * - * @author Graham + * The direction to walk to this point. */ - private static final class Point { + private final Direction direction; - /** - * The direction to walk to this point. - */ - private final Direction direction; - - /** - * The point's position. - */ - private final Position position; - - /** - * Creates a point. - * - * @param position The position. - * @param direction The direction. - */ - public Point(Position position, Direction direction) { - this.position = position; - this.direction = direction; - } - - @Override - public String toString() { - return Point.class.getName() + " [direction=" + direction + ", position=" + position + "]"; - } + /** + * The point's position. + */ + private final Position position; + /** + * Creates a point. + * + * @param position The position. + * @param direction The direction. + */ + public Point(Position position, Direction direction) { + this.position = position; + this.direction = direction; } - /** - * The maximum size of the queue. If any additional steps are added, they are discarded. - */ - private static final int MAXIMUM_SIZE = 128; - - /** - * The mob whose walking queue this is. - */ - private final Mob mob; - - /** - * The old queue of directions. - */ - private final Deque oldPoints = new ArrayDeque<>(); - - /** - * The queue of directions. - */ - private final Deque points = new ArrayDeque<>(); - - /** - * Flag indicating if this queue (only) should be ran. - */ - private boolean runningQueue; - - /** - * Creates a walking queue for the specified mob. - * - * @param mob The mob. - */ - public WalkingQueue(Mob mob) { - this.mob = mob; + @Override + public String toString() { + return Point.class.getName() + " [direction=" + direction + ", position=" + position + "]"; } - /** - * Adds the first step to the queue, attempting to connect the server and client position by looking at the previous - * queue. - * - * @param clientPosition The first step. - * @return {@code true} if the queues could be connected correctly, {@code false} if not. - */ - public boolean addFirstStep(Position clientPosition) { - Position serverPosition = mob.getPosition(); + } - int deltaX = clientPosition.getX() - serverPosition.getX(); - int deltaY = clientPosition.getY() - serverPosition.getY(); + /** + * The maximum size of the queue. If any additional steps are added, they are discarded. + */ + private static final int MAXIMUM_SIZE = 128; - if (Direction.isConnectable(deltaX, deltaY)) { - points.clear(); - oldPoints.clear(); + /** + * The mob whose walking queue this is. + */ + private final Mob mob; - addStep(clientPosition); - return true; - } + /** + * The old queue of directions. + */ + private final Deque oldPoints = new ArrayDeque<>(); - Queue travelBackQueue = new ArrayDeque<>(); + /** + * The queue of directions. + */ + private final Deque points = new ArrayDeque<>(); - Point oldPoint; - while ((oldPoint = oldPoints.pollLast()) != null) { - Position oldPosition = oldPoint.position; + /** + * Flag indicating if this queue (only) should be ran. + */ + private boolean runningQueue; - deltaX = oldPosition.getX() - serverPosition.getX(); - deltaY = oldPosition.getX() - serverPosition.getY(); + /** + * Creates a walking queue for the specified mob. + * + * @param mob The mob. + */ + public WalkingQueue(Mob mob) { + this.mob = mob; + } - travelBackQueue.add(oldPosition); + /** + * Adds the first step to the queue, attempting to connect the server and client position by looking at the previous + * queue. + * + * @param clientPosition The first step. + * @return {@code true} if the queues could be connected correctly, {@code false} if not. + */ + public boolean addFirstStep(Position clientPosition) { + Position serverPosition = mob.getPosition(); - if (Direction.isConnectable(deltaX, deltaY)) { - points.clear(); - oldPoints.clear(); + int deltaX = clientPosition.getX() - serverPosition.getX(); + int deltaY = clientPosition.getY() - serverPosition.getY(); - for (Position travelBackPosition : travelBackQueue) { - addStep(travelBackPosition); - } + if (Direction.isConnectable(deltaX, deltaY)) { + points.clear(); + oldPoints.clear(); - addStep(clientPosition); - return true; - } - } - - oldPoints.clear(); - return false; + addStep(clientPosition); + return true; } - /** - * Adds a step. - * - * @param x The x coordinate of this step. - * @param y The y coordinate of this step. - */ - private void addStep(int x, int y) { - if (points.size() >= MAXIMUM_SIZE) { - return; - } + Queue travelBackQueue = new ArrayDeque<>(); - Point last = getLast(); + Point oldPoint; + while ((oldPoint = oldPoints.pollLast()) != null) { + Position oldPosition = oldPoint.position; - int deltaX = x - last.position.getX(); - int deltaY = y - last.position.getY(); + deltaX = oldPosition.getX() - serverPosition.getX(); + deltaY = oldPosition.getX() - serverPosition.getY(); - Direction direction = Direction.fromDeltas(deltaX, deltaY); + travelBackQueue.add(oldPosition); - if (direction != Direction.NONE) { - Point point = new Point(new Position(x, y, mob.getPosition().getHeight()), direction); - points.add(point); - oldPoints.add(point); - } - } - - /** - * Adds a step to the queue. - * - * @param step The step to add. - */ - public void addStep(Position step) { - int x = step.getX(), y = step.getY(); - Point last = getLast(); - - int deltaX = x - last.position.getX(); - int deltaY = y - last.position.getY(); - - int max = Math.max(Math.abs(deltaX), Math.abs(deltaY)); - - for (int i = 0; i < max; i++) { - if (deltaX < 0) { - deltaX++; - } else if (deltaX > 0) { - deltaX--; - } - - if (deltaY < 0) { - deltaY++; - } else if (deltaY > 0) { - deltaY--; - } - - addStep(x - deltaX, y - deltaY); - } - } - - /** - * Clears the walking queue. - */ - public void clear() { + if (Direction.isConnectable(deltaX, deltaY)) { points.clear(); oldPoints.clear(); - } - /** - * Gets the last point. - * - * @return The last point. - */ - private Point getLast() { - Point last = points.peekLast(); - if (last == null) { - return new Point(mob.getPosition(), Direction.NONE); + for (Position travelBackPosition : travelBackQueue) { + addStep(travelBackPosition); } - return last; + + addStep(clientPosition); + return true; + } } - /** - * Called every pulse, updates the queue. - */ - public void pulse() { - Position position = mob.getPosition(); - Direction first = Direction.NONE, second = Direction.NONE; + oldPoints.clear(); + return false; + } - Point next = points.poll(); + /** + * Adds a step. + * + * @param x The x coordinate of this step. + * @param y The y coordinate of this step. + */ + private void addStep(int x, int y) { + if (points.size() >= MAXIMUM_SIZE) { + return; + } + + Point last = getLast(); + + int deltaX = x - last.position.getX(); + int deltaY = y - last.position.getY(); + + Direction direction = Direction.fromDeltas(deltaX, deltaY); + + if (direction != Direction.NONE) { + Point point = new Point(new Position(x, y, mob.getPosition().getHeight()), direction); + points.add(point); + oldPoints.add(point); + } + } + + /** + * Adds a step to the queue. + * + * @param step The step to add. + */ + public void addStep(Position step) { + int x = step.getX(), y = step.getY(); + Point last = getLast(); + + int deltaX = x - last.position.getX(); + int deltaY = y - last.position.getY(); + + int max = Math.max(Math.abs(deltaX), Math.abs(deltaY)); + + for (int i = 0; i < max; i++) { + if (deltaX < 0) { + deltaX++; + } else if (deltaX > 0) { + deltaX--; + } + + if (deltaY < 0) { + deltaY++; + } else if (deltaY > 0) { + deltaY--; + } + + addStep(x - deltaX, y - deltaY); + } + } + + /** + * Clears the walking queue. + */ + public void clear() { + points.clear(); + oldPoints.clear(); + } + + /** + * Gets the last point. + * + * @return The last point. + */ + private Point getLast() { + Point last = points.peekLast(); + if (last == null) { + return new Point(mob.getPosition(), Direction.NONE); + } + return last; + } + + /** + * Called every pulse, updates the queue. + */ + public void pulse() { + Position position = mob.getPosition(); + Direction first = Direction.NONE, second = Direction.NONE; + + Point next = points.poll(); + if (next != null) { + first = next.direction; + position = next.position; + + if (runningQueue /* and enough energy */) { + next = points.poll(); if (next != null) { - first = next.direction; - position = next.position; - - if (runningQueue /* and enough energy */) { - next = points.poll(); - if (next != null) { - second = next.direction; - position = next.position; - } - } + second = next.direction; + position = next.position; } - - mob.setDirections(first, second); - mob.setPosition(position); + } } - /** - * Sets the running queue flag. - * - * @param running The running queue flag. - */ - public void setRunningQueue(boolean running) { - runningQueue = running; - } + mob.setDirections(first, second); + mob.setPosition(position); + } - /** - * Gets the size of the queue. - * - * @return The size of the queue. - */ - public int size() { - return points.size(); - } + /** + * Sets the running queue flag. + * + * @param running The running queue flag. + */ + public void setRunningQueue(boolean running) { + runningQueue = running; + } + + /** + * Gets the size of the queue. + * + * @return The size of the queue. + */ + public int size() { + return points.size(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/EnterAmountListener.java b/src/org/apollo/game/model/inter/EnterAmountListener.java index 01e4b92d..bdf46ff5 100644 --- a/src/org/apollo/game/model/inter/EnterAmountListener.java +++ b/src/org/apollo/game/model/inter/EnterAmountListener.java @@ -8,11 +8,11 @@ package org.apollo.game.model.inter; @FunctionalInterface public interface EnterAmountListener { - /** - * Called when the player enters the specified amount. - * - * @param amount The amount. - */ - public void amountEntered(int amount); + /** + * Called when the player enters the specified amount. + * + * @param amount The amount. + */ + public void amountEntered(int amount); } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/InterfaceConstants.java b/src/org/apollo/game/model/inter/InterfaceConstants.java index 41758107..cbf8fb10 100644 --- a/src/org/apollo/game/model/inter/InterfaceConstants.java +++ b/src/org/apollo/game/model/inter/InterfaceConstants.java @@ -7,57 +7,57 @@ package org.apollo.game.model.inter; */ public class InterfaceConstants { - /** - * The avatar design interface id. - */ - public static final int AVATAR_DESIGN = 3559; + /** + * The avatar design interface id. + */ + public static final int AVATAR_DESIGN = 3559; - /** - * The default inventory tab ids. - */ - public static final int[] DEFAULT_INVENTORY_TABS = { 2423, 3917, 638, 3213, 1644, 5608, 1151, -1, 5065, 5715, 2449, - 904, 147, 962, }; - // 6299 = music tab, music disabled - // 4445 = settings tab, music disabled - // 12855 = ancients magic + /** + * The default inventory tab ids. + */ + public static final int[] DEFAULT_INVENTORY_TABS = { 2423, 3917, 638, 3213, 1644, 5608, 1151, -1, 5065, 5715, 2449, + 904, 147, 962, }; + // 6299 = music tab, music disabled + // 4445 = settings tab, music disabled + // 12855 = ancients magic - /** - * The level-up dialogue interface ids. - */ - public static final int[] LEVEL_UP_INTERFACES = { 6247, 6253, 6206, 6216, 4443, 6242, 6211, 6226, 4272, 6231, 6258, - 4282, 6263, 6221, 4416, 6237, 4277, 4261, 12122, 4887, 4267 }; + /** + * The level-up dialogue interface ids. + */ + public static final int[] LEVEL_UP_INTERFACES = { 6247, 6253, 6206, 6216, 4443, 6242, 6211, 6226, 4272, 6231, 6258, + 4282, 6263, 6221, 4416, 6237, 4277, 4261, 12122, 4887, 4267 }; - /** - * The quest interface id. - */ - public static final int QUEST_INTERFACE = 8134; + /** + * The quest interface id. + */ + public static final int QUEST_INTERFACE = 8134; - /** - * The scroll bar widget. - */ - public static final int QUEST_SCROLL_PANE = 8143; + /** + * The scroll bar widget. + */ + public static final int QUEST_SCROLL_PANE = 8143; - /** - * The array of widgets that display the text. - */ - public static final int[] QUEST_TEXT = { 8144, 8145, 8147, 8148, 8149, 8150, 8151, 8152, 8153, 8154, 8155, 8156, - 8157, 8158, 8159, 8160, 8161, 8162, 8163, 8164, 8165, 8166, 8167, 8168, 8169, 8170, 8171, 8172, 8173, 8174, - 8175, 8176, 8177, 8178, 8179, 8180, 8181, 8182, 8183, 8184, 8185, 8186, 8187, 8188, 8189, 8190, 8191, 8192, - 8193, 8194, 8195, 12174, 12175, 12176, 12177, 12178, 12179, 12180, 12181, 12182, 12183, 12184, 12185, - 12186, 12187, 12188, 12189, 12190, 12191, 12192, 12193, 12194, 12195, 12196, 12197, 12198, 12199, 12200, - 12201, 12202, 12203, 12204, 12205, 12206, 12207, 12208, 12209, 12210, 12211, 12212, 12213, 12214, 12215, - 12216, 12217, 12218, 12219, 12220, 12221, 12222, 12223 }; + /** + * The array of widgets that display the text. + */ + public static final int[] QUEST_TEXT = { 8144, 8145, 8147, 8148, 8149, 8150, 8151, 8152, 8153, 8154, 8155, 8156, + 8157, 8158, 8159, 8160, 8161, 8162, 8163, 8164, 8165, 8166, 8167, 8168, 8169, 8170, 8171, 8172, 8173, 8174, + 8175, 8176, 8177, 8178, 8179, 8180, 8181, 8182, 8183, 8184, 8185, 8186, 8187, 8188, 8189, 8190, 8191, 8192, + 8193, 8194, 8195, 12174, 12175, 12176, 12177, 12178, 12179, 12180, 12181, 12182, 12183, 12184, 12185, + 12186, 12187, 12188, 12189, 12190, 12191, 12192, 12193, 12194, 12195, 12196, 12197, 12198, 12199, 12200, + 12201, 12202, 12203, 12204, 12205, 12206, 12207, 12208, 12209, 12210, 12211, 12212, 12213, 12214, 12215, + 12216, 12217, 12218, 12219, 12220, 12221, 12222, 12223 }; - /** - * The quest title widget id. - */ - public static final int QUEST_TITLE = 8144; + /** + * The quest title widget id. + */ + public static final int QUEST_TITLE = 8144; - /** - * Prevent instantiation. - */ - private InterfaceConstants() { + /** + * Prevent instantiation. + */ + private InterfaceConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/InterfaceListener.java b/src/org/apollo/game/model/inter/InterfaceListener.java index 7e4f21cf..57d2a504 100644 --- a/src/org/apollo/game/model/inter/InterfaceListener.java +++ b/src/org/apollo/game/model/inter/InterfaceListener.java @@ -8,9 +8,9 @@ package org.apollo.game.model.inter; @FunctionalInterface public interface InterfaceListener { - /** - * Called when the interface has been closed. - */ - public void interfaceClosed(); + /** + * Called when the interface has been closed. + */ + public void interfaceClosed(); } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/InterfaceSet.java b/src/org/apollo/game/model/inter/InterfaceSet.java index 1763fe32..75613a20 100644 --- a/src/org/apollo/game/model/inter/InterfaceSet.java +++ b/src/org/apollo/game/model/inter/InterfaceSet.java @@ -31,215 +31,215 @@ import org.apollo.game.model.inter.dialogue.DialogueListener; */ public final class InterfaceSet { - /** - * The current enter amount listener. - */ - private EnterAmountListener amountListener; + /** + * The current enter amount listener. + */ + private EnterAmountListener amountListener; - /** - * The current chat box dialogue listener. - */ - private DialogueListener dialogueListener; + /** + * The current chat box dialogue listener. + */ + private DialogueListener dialogueListener; - /** - * A map of open interfaces. - */ - private Map interfaces = new HashMap<>(); + /** + * A map of open interfaces. + */ + private Map interfaces = new HashMap<>(); - /** - * The current listener. - */ - private InterfaceListener listener; + /** + * The current listener. + */ + private InterfaceListener listener; - /** - * The player whose interfaces are being managed. - */ - private final Player player; // TODO: maybe switch to a listener system like the inventory? + /** + * The player whose interfaces are being managed. + */ + private final Player player; // TODO: maybe switch to a listener system like the inventory? - /** - * Creates an interface set. - * - * @param player The player. - */ - public InterfaceSet(Player player) { - this.player = player; + /** + * Creates an interface set. + * + * @param player The player. + */ + public InterfaceSet(Player player) { + this.player = player; + } + + /** + * Called when the player has clicked the specified button. Notifies the current dialogue listener. + * + * @param button The button. + * @return {@code true} if the event handler chain should be broken. + */ + public boolean buttonClicked(int button) { + if (dialogueListener != null) { + return dialogueListener.buttonClicked(button); } + return false; + } - /** - * Called when the player has clicked the specified button. Notifies the current dialogue listener. - * - * @param button The button. - * @return {@code true} if the event handler chain should be broken. - */ - public boolean buttonClicked(int button) { - if (dialogueListener != null) { - return dialogueListener.buttonClicked(button); - } - return false; + /** + * Closes the current open interface(s). + */ + public void close() { + closeAndNotify(); + player.send(new CloseInterfaceEvent()); + } + + /** + * An internal method for closing the interface, notifying the listener if appropriate, but not sending any events. + */ + private void closeAndNotify() { + amountListener = null; + dialogueListener = null; + + interfaces.clear(); + if (listener != null) { + listener.interfaceClosed(); + listener = null; } + } - /** - * Closes the current open interface(s). - */ - public void close() { - closeAndNotify(); - player.send(new CloseInterfaceEvent()); + /** + * Checks if this interface sets contains the specified interface. + * + * @param id The interface's id. + * @return {@code true} if so, {@code false} if not. + */ + public boolean contains(int id) { + return interfaces.containsValue(id); + } + + /** + * Checks if this interface set contains the specified interface type. + * + * @param type The interface's type. + * @return {@code true} if so, {@code false} if not. + */ + public boolean contains(InterfaceType type) { + return interfaces.containsKey(type); + } + + /** + * Called when the player has clicked the "Click here to continue" button on a dialogue. + */ + public void continueRequested() { + if (dialogueListener != null) { + dialogueListener.continued(); } + } - /** - * An internal method for closing the interface, notifying the listener if appropriate, but not sending any events. - */ - private void closeAndNotify() { - amountListener = null; - dialogueListener = null; - - interfaces.clear(); - if (listener != null) { - listener.interfaceClosed(); - listener = null; - } + /** + * Called when the client has entered the specified amount. Notifies the current listener. + * + * @param amount The amount. + */ + public void enteredAmount(int amount) { + if (amountListener != null) { + amountListener.amountEntered(amount); + amountListener = null; } + } - /** - * Checks if this interface sets contains the specified interface. - * - * @param id The interface's id. - * @return {@code true} if so, {@code false} if not. - */ - public boolean contains(int id) { - return interfaces.containsValue(id); - } + /** + * Sent by the client when it has closed an interface. + */ + public void interfaceClosed() { + closeAndNotify(); + } - /** - * Checks if this interface set contains the specified interface type. - * - * @param type The interface's type. - * @return {@code true} if so, {@code false} if not. - */ - public boolean contains(InterfaceType type) { - return interfaces.containsKey(type); - } + /** + * Opens a chat box dialogue. + * + * @param listener The listener for the dialogue. + * @param dialogueId The dialogue's id. + */ + public void openDialogue(DialogueListener listener, int dialogueId) { + closeAndNotify(); - /** - * Called when the player has clicked the "Click here to continue" button on a dialogue. - */ - public void continueRequested() { - if (dialogueListener != null) { - dialogueListener.continued(); - } - } + this.dialogueListener = listener; + this.listener = listener; - /** - * Called when the client has entered the specified amount. Notifies the current listener. - * - * @param amount The amount. - */ - public void enteredAmount(int amount) { - if (amountListener != null) { - amountListener.amountEntered(amount); - amountListener = null; - } - } + interfaces.put(InterfaceType.DIALOGUE, dialogueId); + player.send(new OpenDialogueInterfaceEvent(dialogueId)); + } - /** - * Sent by the client when it has closed an interface. - */ - public void interfaceClosed() { - closeAndNotify(); - } + /** + * Opens a chat box dialogue. + * + * @param dialogueId The dialogue's id. + */ + public void openDialogue(int dialogueId) { + openDialogue(null, dialogueId); + } - /** - * Opens a chat box dialogue. - * - * @param listener The listener for the dialogue. - * @param dialogueId The dialogue's id. - */ - public void openDialogue(DialogueListener listener, int dialogueId) { - closeAndNotify(); + /** + * Opens the enter amount dialogue. + * + * @param listener The enter amount listener. + */ + public void openEnterAmountDialogue(EnterAmountListener listener) { + amountListener = listener; + player.send(new EnterAmountEvent()); + } - this.dialogueListener = listener; - this.listener = listener; + /** + * Opens a window. + * + * @param windowId The window's id. + */ + public void openWindow(int windowId) { + openWindow(null, windowId); + } - interfaces.put(InterfaceType.DIALOGUE, dialogueId); - player.send(new OpenDialogueInterfaceEvent(dialogueId)); - } + /** + * Opens a window with the specified listener. + * + * @param listener The listener for this interface. + * @param windowId The window's id. + */ + public void openWindow(InterfaceListener listener, int windowId) { + closeAndNotify(); + this.listener = listener; - /** - * Opens a chat box dialogue. - * - * @param dialogueId The dialogue's id. - */ - public void openDialogue(int dialogueId) { - openDialogue(null, dialogueId); - } + interfaces.put(InterfaceType.WINDOW, windowId); + player.send(new OpenInterfaceEvent(windowId)); + } - /** - * Opens the enter amount dialogue. - * - * @param listener The enter amount listener. - */ - public void openEnterAmountDialogue(EnterAmountListener listener) { - amountListener = listener; - player.send(new EnterAmountEvent()); - } + /** + * Opens a window and inventory sidebar. + * + * @param windowId The window's id. + * @param sidebarId The sidebar's id. + */ + public void openWindowWithSidebar(int windowId, int sidebarId) { + openWindowWithSidebar(null, windowId, sidebarId); + } - /** - * Opens a window. - * - * @param windowId The window's id. - */ - public void openWindow(int windowId) { - openWindow(null, windowId); - } + /** + * Opens a window and inventory sidebar with the specified listener. + * + * @param listener The listener for this interface. + * @param windowId The window's id. + * @param sidebarId The sidebar's id. + */ + public void openWindowWithSidebar(InterfaceListener listener, int windowId, int sidebarId) { + closeAndNotify(); + this.listener = listener; - /** - * Opens a window with the specified listener. - * - * @param listener The listener for this interface. - * @param windowId The window's id. - */ - public void openWindow(InterfaceListener listener, int windowId) { - closeAndNotify(); - this.listener = listener; + interfaces.put(InterfaceType.WINDOW, windowId); + interfaces.put(InterfaceType.SIDEBAR, sidebarId); - interfaces.put(InterfaceType.WINDOW, windowId); - player.send(new OpenInterfaceEvent(windowId)); - } + player.send(new OpenInterfaceSidebarEvent(windowId, sidebarId)); + } - /** - * Opens a window and inventory sidebar. - * - * @param windowId The window's id. - * @param sidebarId The sidebar's id. - */ - public void openWindowWithSidebar(int windowId, int sidebarId) { - openWindowWithSidebar(null, windowId, sidebarId); - } - - /** - * Opens a window and inventory sidebar with the specified listener. - * - * @param listener The listener for this interface. - * @param windowId The window's id. - * @param sidebarId The sidebar's id. - */ - public void openWindowWithSidebar(InterfaceListener listener, int windowId, int sidebarId) { - closeAndNotify(); - this.listener = listener; - - interfaces.put(InterfaceType.WINDOW, windowId); - interfaces.put(InterfaceType.SIDEBAR, sidebarId); - - player.send(new OpenInterfaceSidebarEvent(windowId, sidebarId)); - } - - /** - * Gets the size of the interface set. - * - * @return The size. - */ - public int size() { - return interfaces.size(); - } + /** + * Gets the size of the interface set. + * + * @return The size. + */ + public int size() { + return interfaces.size(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/InterfaceType.java b/src/org/apollo/game/model/inter/InterfaceType.java index 882b33c9..75954da6 100644 --- a/src/org/apollo/game/model/inter/InterfaceType.java +++ b/src/org/apollo/game/model/inter/InterfaceType.java @@ -7,35 +7,35 @@ package org.apollo.game.model.inter; */ public enum InterfaceType { - /** - * An interface that appears in the chat box. - */ - DIALOGUE, + /** + * An interface that appears in the chat box. + */ + DIALOGUE, - /** - * An interface shown behind a fullscreen window. - */ - FULLSCREEN_BACKGROUND, + /** + * An interface shown behind a fullscreen window. + */ + FULLSCREEN_BACKGROUND, - /** - * An interface shown in full screen mode. - */ - FULLSCREEN_WINDOW, + /** + * An interface shown in full screen mode. + */ + FULLSCREEN_WINDOW, - /** - * An interface that occupies the game screen like a window, but the player can still perform actions without the - * interface closing. - */ - OVERLAY, + /** + * An interface that occupies the game screen like a window, but the player can still perform actions without the + * interface closing. + */ + OVERLAY, - /** - * An interface displayed over the inventory area. - */ - SIDEBAR, + /** + * An interface displayed over the inventory area. + */ + SIDEBAR, - /** - * An interface that occupies the game screen. - */ - WINDOW; + /** + * An interface that occupies the game screen. + */ + WINDOW; } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/bank/BankConstants.java b/src/org/apollo/game/model/inter/bank/BankConstants.java index f5715911..51cdd8c5 100644 --- a/src/org/apollo/game/model/inter/bank/BankConstants.java +++ b/src/org/apollo/game/model/inter/bank/BankConstants.java @@ -7,31 +7,31 @@ package org.apollo.game.model.inter.bank; */ public final class BankConstants { - /** - * The bank inventory id. - */ - public static final int BANK_INVENTORY_ID = 5382; + /** + * The bank inventory id. + */ + public static final int BANK_INVENTORY_ID = 5382; - /** - * The bank window id. - */ - public static final int BANK_WINDOW_ID = 5292; + /** + * The bank window id. + */ + public static final int BANK_WINDOW_ID = 5292; - /** - * The sidebar id. - */ - public static final int SIDEBAR_ID = 2005; + /** + * The sidebar id. + */ + public static final int SIDEBAR_ID = 2005; - /** - * The sidebar inventory id. - */ - public static final int SIDEBAR_INVENTORY_ID = 2006; + /** + * The sidebar inventory id. + */ + public static final int SIDEBAR_INVENTORY_ID = 2006; - /** - * Default private constructor to prevent instantiation. - */ - private BankConstants() { + /** + * Default private constructor to prevent instantiation. + */ + private BankConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/bank/BankDepositEnterAmountListener.java b/src/org/apollo/game/model/inter/bank/BankDepositEnterAmountListener.java index 866edfe0..1e6ac257 100644 --- a/src/org/apollo/game/model/inter/bank/BankDepositEnterAmountListener.java +++ b/src/org/apollo/game/model/inter/bank/BankDepositEnterAmountListener.java @@ -10,39 +10,39 @@ import org.apollo.game.model.inter.EnterAmountListener; */ public final class BankDepositEnterAmountListener implements EnterAmountListener { - /** - * The item id. - */ - private final int id; + /** + * The item id. + */ + private final int id; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * The item slot. - */ - private final int slot; + /** + * The item slot. + */ + private final int slot; - /** - * Creates the bank deposit amount listener. - * - * @param player The player. - * @param slot The slot. - * @param id The id. - */ - public BankDepositEnterAmountListener(Player player, int slot, int id) { - this.player = player; - this.slot = slot; - this.id = id; - } - - @Override - public void amountEntered(int amount) { - if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { - BankUtils.deposit(player, slot, id, amount); - } + /** + * Creates the bank deposit amount listener. + * + * @param player The player. + * @param slot The slot. + * @param id The id. + */ + public BankDepositEnterAmountListener(Player player, int slot, int id) { + this.player = player; + this.slot = slot; + this.id = id; + } + + @Override + public void amountEntered(int amount) { + if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { + BankUtils.deposit(player, slot, id, amount); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/bank/BankInterfaceListener.java b/src/org/apollo/game/model/inter/bank/BankInterfaceListener.java index a4130a32..23a4aff0 100644 --- a/src/org/apollo/game/model/inter/bank/BankInterfaceListener.java +++ b/src/org/apollo/game/model/inter/bank/BankInterfaceListener.java @@ -11,38 +11,38 @@ import org.apollo.game.model.inv.InventoryListener; */ public final class BankInterfaceListener implements InterfaceListener { - /** - * The bank listener. - */ - private final InventoryListener bankListener; + /** + * The bank listener. + */ + private final InventoryListener bankListener; - /** - * The inventory listener. - */ - private final InventoryListener invListener; + /** + * The inventory listener. + */ + private final InventoryListener invListener; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the bank interface listener. - * - * @param player The player. - * @param invListener The inventory listener. - * @param bankListener The bank listener. - */ - public BankInterfaceListener(Player player, InventoryListener invListener, InventoryListener bankListener) { - this.player = player; - this.invListener = invListener; - this.bankListener = bankListener; - } + /** + * Creates the bank interface listener. + * + * @param player The player. + * @param invListener The inventory listener. + * @param bankListener The bank listener. + */ + public BankInterfaceListener(Player player, InventoryListener invListener, InventoryListener bankListener) { + this.player = player; + this.invListener = invListener; + this.bankListener = bankListener; + } - @Override - public void interfaceClosed() { - player.getInventory().removeListener(invListener); - player.getBank().removeListener(bankListener); - } + @Override + public void interfaceClosed() { + player.getInventory().removeListener(invListener); + player.getBank().removeListener(bankListener); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/bank/BankUtils.java b/src/org/apollo/game/model/inter/bank/BankUtils.java index 01702ba9..fd7ee159 100644 --- a/src/org/apollo/game/model/inter/bank/BankUtils.java +++ b/src/org/apollo/game/model/inter/bank/BankUtils.java @@ -15,120 +15,120 @@ import org.apollo.game.model.inv.SynchronizationInventoryListener; */ public final class BankUtils { - /** - * Deposits an item into the player's bank. - * - * @param player The player. - * @param slot The slot. - * @param id The id. - * @param amount The amount. - * @return {@code false} if the chain should be broken. - */ - public static boolean deposit(Player player, int slot, int id, int amount) { - if (amount == 0) { - return true; - } - - Inventory inventory = player.getInventory(); - Inventory bank = player.getBank(); - - Item item = inventory.get(slot); - int newId = ItemDefinition.noteToItem(item.getId()); - - if (bank.freeSlots() == 0 && !bank.contains(item.getId())) { - bank.forceCapacityExceeded(); - return true; - } - - int removed; - if (amount > 1) { - inventory.stopFiringEvents(); - } - try { - removed = inventory.remove(item.getId(), amount); - } finally { - if (amount > 1) { - inventory.startFiringEvents(); - } - } - if (amount > 1) { - inventory.forceRefresh(); - } - bank.add(newId, removed); - - return true; + /** + * Deposits an item into the player's bank. + * + * @param player The player. + * @param slot The slot. + * @param id The id. + * @param amount The amount. + * @return {@code false} if the chain should be broken. + */ + public static boolean deposit(Player player, int slot, int id, int amount) { + if (amount == 0) { + return true; } - /** - * Opens a player's bank. - * - * @param player The player. - */ - public static void openBank(Player player) { - InventoryListener invListener = new SynchronizationInventoryListener(player, BankConstants.SIDEBAR_INVENTORY_ID); - InventoryListener bankListener = new SynchronizationInventoryListener(player, BankConstants.BANK_INVENTORY_ID); + Inventory inventory = player.getInventory(); + Inventory bank = player.getBank(); - player.getInventory().addListener(invListener); - player.getBank().addListener(bankListener); + Item item = inventory.get(slot); + int newId = ItemDefinition.noteToItem(item.getId()); - player.getInventory().forceRefresh(); - player.getBank().forceRefresh(); - - InterfaceListener interListener = new BankInterfaceListener(player, invListener, bankListener); - - player.getInterfaceSet().openWindowWithSidebar(interListener, BankConstants.BANK_WINDOW_ID, - BankConstants.SIDEBAR_ID); + if (bank.freeSlots() == 0 && !bank.contains(item.getId())) { + bank.forceCapacityExceeded(); + return true; } - /** - * Withdraws an item from a player's bank. - * - * @param player The player. - * @param slot The slot. - * @param id The id. - * @param amount The amount. - * @return {@code false} if the chain should be broken. - */ - public static boolean withdraw(Player player, int slot, int id, int amount) { - if (amount == 0) { - return true; - } + int removed; + if (amount > 1) { + inventory.stopFiringEvents(); + } + try { + removed = inventory.remove(item.getId(), amount); + } finally { + if (amount > 1) { + inventory.startFiringEvents(); + } + } + if (amount > 1) { + inventory.forceRefresh(); + } + bank.add(newId, removed); - Inventory inventory = player.getInventory(); - Inventory bank = player.getBank(); + return true; + } - Item item = bank.get(slot); + /** + * Opens a player's bank. + * + * @param player The player. + */ + public static void openBank(Player player) { + InventoryListener invListener = new SynchronizationInventoryListener(player, BankConstants.SIDEBAR_INVENTORY_ID); + InventoryListener bankListener = new SynchronizationInventoryListener(player, BankConstants.BANK_INVENTORY_ID); - if (amount >= item.getAmount()) { - amount = item.getAmount(); - } + player.getInventory().addListener(invListener); + player.getBank().addListener(bankListener); - int newId = player.isWithdrawingNotes() ? ItemDefinition.itemToNote(item.getId()) : item.getId(); + player.getInventory().forceRefresh(); + player.getBank().forceRefresh(); - if (inventory.freeSlots() == 0 && !(inventory.contains(newId) && ItemDefinition.lookup(newId).isStackable())) { - inventory.forceCapacityExceeded(); - return true; - } + InterfaceListener interListener = new BankInterfaceListener(player, invListener, bankListener); - int remaining = inventory.add(newId, amount); + player.getInterfaceSet().openWindowWithSidebar(interListener, BankConstants.BANK_WINDOW_ID, + BankConstants.SIDEBAR_ID); + } - bank.stopFiringEvents(); - try { - bank.remove(item.getId(), amount - remaining); - bank.shift(); - } finally { - bank.startFiringEvents(); - } - - bank.forceRefresh(); - return true; + /** + * Withdraws an item from a player's bank. + * + * @param player The player. + * @param slot The slot. + * @param id The id. + * @param amount The amount. + * @return {@code false} if the chain should be broken. + */ + public static boolean withdraw(Player player, int slot, int id, int amount) { + if (amount == 0) { + return true; } - /** - * Default private constructor to prevent instantiation. - */ - private BankUtils() { + Inventory inventory = player.getInventory(); + Inventory bank = player.getBank(); + Item item = bank.get(slot); + + if (amount >= item.getAmount()) { + amount = item.getAmount(); } + int newId = player.isWithdrawingNotes() ? ItemDefinition.itemToNote(item.getId()) : item.getId(); + + if (inventory.freeSlots() == 0 && !(inventory.contains(newId) && ItemDefinition.lookup(newId).isStackable())) { + inventory.forceCapacityExceeded(); + return true; + } + + int remaining = inventory.add(newId, amount); + + bank.stopFiringEvents(); + try { + bank.remove(item.getId(), amount - remaining); + bank.shift(); + } finally { + bank.startFiringEvents(); + } + + bank.forceRefresh(); + return true; + } + + /** + * Default private constructor to prevent instantiation. + */ + private BankUtils() { + + } + } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/bank/BankWithdrawEnterAmountListener.java b/src/org/apollo/game/model/inter/bank/BankWithdrawEnterAmountListener.java index f51811cc..8940b09f 100644 --- a/src/org/apollo/game/model/inter/bank/BankWithdrawEnterAmountListener.java +++ b/src/org/apollo/game/model/inter/bank/BankWithdrawEnterAmountListener.java @@ -10,39 +10,39 @@ import org.apollo.game.model.inter.EnterAmountListener; */ public final class BankWithdrawEnterAmountListener implements EnterAmountListener { - /** - * The item id. - */ - private final int id; + /** + * The item id. + */ + private final int id; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * The item slot. - */ - private final int slot; + /** + * The item slot. + */ + private final int slot; - /** - * Creates the bank withdraw amount listener. - * - * @param player The player. - * @param slot The slot. - * @param id The id. - */ - public BankWithdrawEnterAmountListener(Player player, int slot, int id) { - this.player = player; - this.slot = slot; - this.id = id; - } - - @Override - public void amountEntered(int amount) { - if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { - BankUtils.withdraw(player, slot, id, amount); - } + /** + * Creates the bank withdraw amount listener. + * + * @param player The player. + * @param slot The slot. + * @param id The id. + */ + public BankWithdrawEnterAmountListener(Player player, int slot, int id) { + this.player = player; + this.slot = slot; + this.id = id; + } + + @Override + public void amountEntered(int amount) { + if (player.getInterfaceSet().contains(BankConstants.BANK_WINDOW_ID)) { + BankUtils.withdraw(player, slot, id, amount); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/dialogue/DialogueAdapter.java b/src/org/apollo/game/model/inter/dialogue/DialogueAdapter.java index 6c3f0e6e..52c78788 100644 --- a/src/org/apollo/game/model/inter/dialogue/DialogueAdapter.java +++ b/src/org/apollo/game/model/inter/dialogue/DialogueAdapter.java @@ -7,19 +7,19 @@ package org.apollo.game.model.inter.dialogue; */ public abstract class DialogueAdapter implements DialogueListener { - @Override - public boolean buttonClicked(int button) { - return false; - } + @Override + public boolean buttonClicked(int button) { + return false; + } - @Override - public void continued() { + @Override + public void continued() { - } + } - @Override - public void interfaceClosed() { + @Override + public void interfaceClosed() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inter/dialogue/DialogueListener.java b/src/org/apollo/game/model/inter/dialogue/DialogueListener.java index 43e335fb..13ac274e 100644 --- a/src/org/apollo/game/model/inter/dialogue/DialogueListener.java +++ b/src/org/apollo/game/model/inter/dialogue/DialogueListener.java @@ -9,21 +9,21 @@ import org.apollo.game.model.inter.InterfaceListener; */ public interface DialogueListener extends InterfaceListener { - /** - * Called when the player has clicked the specified button. - *

- * Note that this method is invoked when any button is clicked whilst the dialogue is opened. In case the button is - * not being handled by this listener, simply return {@code false} to allow further processing of the event. - *

- * - * @param button The button interface id. - * @return {@code true} if the event handler chain should be broken, {@code false} if it should be continued. - */ - public boolean buttonClicked(int button); + /** + * Called when the player has clicked the specified button. + *

+ * Note that this method is invoked when any button is clicked whilst the dialogue is opened. In case the button is + * not being handled by this listener, simply return {@code false} to allow further processing of the event. + *

+ * + * @param button The button interface id. + * @return {@code true} if the event handler chain should be broken, {@code false} if it should be continued. + */ + public boolean buttonClicked(int button); - /** - * Called when the player has clicked the "Click here to continue" button on a chatting dialogue. - */ - public void continued(); + /** + * Called when the player has clicked the "Click here to continue" button on a chatting dialogue. + */ + public void continued(); } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/AppearanceInventoryListener.java b/src/org/apollo/game/model/inv/AppearanceInventoryListener.java index 54f592b3..3db66776 100644 --- a/src/org/apollo/game/model/inv/AppearanceInventoryListener.java +++ b/src/org/apollo/game/model/inv/AppearanceInventoryListener.java @@ -11,35 +11,35 @@ import org.apollo.game.sync.block.SynchronizationBlock; */ public final class AppearanceInventoryListener extends InventoryAdapter { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the appearance inventory listener. - * - * @param player The player. - */ - public AppearanceInventoryListener(Player player) { - this.player = player; - } + /** + * Creates the appearance inventory listener. + * + * @param player The player. + */ + public AppearanceInventoryListener(Player player) { + this.player = player; + } - @Override - public void itemsUpdated(Inventory inventory) { - update(); - } + @Override + public void itemsUpdated(Inventory inventory) { + update(); + } - @Override - public void itemUpdated(Inventory inventory, int slot, Item item) { - update(); - } + @Override + public void itemUpdated(Inventory inventory, int slot, Item item) { + update(); + } - /** - * Updates the player's appearance. - */ - private void update() { - player.getBlockSet().add(SynchronizationBlock.createAppearanceBlock(player)); - } + /** + * Updates the player's appearance. + */ + private void update() { + player.getBlockSet().add(SynchronizationBlock.createAppearanceBlock(player)); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/FullInventoryListener.java b/src/org/apollo/game/model/inv/FullInventoryListener.java index 0254b964..8ea3f012 100644 --- a/src/org/apollo/game/model/inv/FullInventoryListener.java +++ b/src/org/apollo/game/model/inv/FullInventoryListener.java @@ -11,40 +11,40 @@ import org.apollo.game.model.entity.Player; */ public final class FullInventoryListener extends InventoryAdapter { - /** - * The bank full message. - */ - public static final String FULL_BANK_MESSAGE = "Not enough bank space."; + /** + * The bank full message. + */ + public static final String FULL_BANK_MESSAGE = "Not enough bank space."; - /** - * The inventory full message. - */ - public static final String FULL_INVENTORY_MESSAGE = "Not enough inventory space."; + /** + * The inventory full message. + */ + public static final String FULL_INVENTORY_MESSAGE = "Not enough inventory space."; - /** - * The event to send when the capacity has been exceeded. - */ - private final Event event; + /** + * The event to send when the capacity has been exceeded. + */ + private final Event event; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the empty inventory listener. - * - * @param player The player. - * @param message The message to send when the inventory is empty. - */ - public FullInventoryListener(Player player, String message) { - this.player = player; - event = new ServerMessageEvent(message); - } + /** + * Creates the empty inventory listener. + * + * @param player The player. + * @param message The message to send when the inventory is empty. + */ + public FullInventoryListener(Player player, String message) { + this.player = player; + event = new ServerMessageEvent(message); + } - @Override - public void capacityExceeded(Inventory inventory) { - player.send(event); - } + @Override + public void capacityExceeded(Inventory inventory) { + player.send(event); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/Inventory.java b/src/org/apollo/game/model/inv/Inventory.java index 0805c7b0..183d3f1f 100644 --- a/src/org/apollo/game/model/inv/Inventory.java +++ b/src/org/apollo/game/model/inv/Inventory.java @@ -13,618 +13,618 @@ import org.apollo.game.model.def.ItemDefinition; */ public final class Inventory implements Cloneable { + /** + * An enumeration containing the different 'stacking modes' of an {@link Inventory}. + * + * @author Graham + */ + public enum StackMode { + /** - * An enumeration containing the different 'stacking modes' of an {@link Inventory}. - * - * @author Graham + * When in {@link #STACK_ALWAYS} mode, an {@link Inventory} will stack every single item, regardless of the + * settings of individual items. */ - public enum StackMode { + STACK_ALWAYS, - /** - * When in {@link #STACK_ALWAYS} mode, an {@link Inventory} will stack every single item, regardless of the - * settings of individual items. - */ - STACK_ALWAYS, + /** + * When in {@link #STACK_NEVER} mode, an {@link Inventory} will never stack items. + */ + STACK_NEVER, - /** - * When in {@link #STACK_NEVER} mode, an {@link Inventory} will never stack items. - */ - STACK_NEVER, + /** + * When in {@link #STACK_STACKABLE_ITEMS} mode, an {@link Inventory} will stack items depending on their + * settings. + */ + STACK_STACKABLE_ITEMS; - /** - * When in {@link #STACK_STACKABLE_ITEMS} mode, an {@link Inventory} will stack items depending on their - * settings. - */ - STACK_STACKABLE_ITEMS; + } + /** + * The capacity of this inventory. + */ + private final int capacity; + + /** + * A flag indicating if events are being fired. + */ + private boolean firingEvents = true; // TODO: make this reentrant + + /** + * The items in this inventory. + */ + private Item[] items; + + /** + * A list of inventory listeners. + */ + private final List listeners = new ArrayList<>(); + + /** + * The stacking mode. + */ + private final StackMode mode; + + /** + * The size of this inventory - the number of 'used slots'. + */ + private int size = 0; + + /** + * Creates an inventory. + * + * @param capacity The capacity. + */ + public Inventory(int capacity) { + this(capacity, StackMode.STACK_STACKABLE_ITEMS); + } + + /** + * Creates an inventory. + * + * @param capacity The capacity. + * @param mode The {@link StackMode}. + * @throws IllegalArgumentException If the capacity is negative. + * @throws NullPointerException If the mode is {@code null}. + */ + public Inventory(int capacity, StackMode mode) { + if (capacity < 0) { + throw new IllegalArgumentException("Capacity cannot be negative."); + } else if (mode == null) { + throw new NullPointerException("Stacking mode cannot be null."); } + items = new Item[this.capacity = capacity]; + this.mode = mode; + } - /** - * The capacity of this inventory. - */ - private final int capacity; + /** + * An alias for {@code add(id, 1)}. + * + * @param id The id. + * @return {@code true} if the item was added, {@code false} if there was not enough room. + */ + public boolean add(int id) { + return add(id, 1) == 0; + } - /** - * A flag indicating if events are being fired. - */ - private boolean firingEvents = true; // TODO: make this reentrant + /** + * An alias for {@code add(new Item(id, amount)}. + * + * @param id The id. + * @param amount The amount. + * @return The amount that remains. + */ + public int add(int id, int amount) { + Item item = add(new Item(id, amount)); + return item != null ? item.getAmount() : 0; + } - /** - * The items in this inventory. - */ - private Item[] items; - - /** - * A list of inventory listeners. - */ - private final List listeners = new ArrayList(); - - /** - * The stacking mode. - */ - private final StackMode mode; - - /** - * The size of this inventory - the number of 'used slots'. - */ - private int size = 0; - - /** - * Creates an inventory. - * - * @param capacity The capacity. - */ - public Inventory(int capacity) { - this(capacity, StackMode.STACK_STACKABLE_ITEMS); - } - - /** - * Creates an inventory. - * - * @param capacity The capacity. - * @param mode The {@link StackMode}. - * @throws IllegalArgumentException If the capacity is negative. - * @throws NullPointerException If the mode is {@code null}. - */ - public Inventory(int capacity, StackMode mode) { - if (capacity < 0) { - throw new IllegalArgumentException("Capacity cannot be negative."); - } else if (mode == null) { - throw new NullPointerException("Stacking mode cannot be null."); - } - items = new Item[this.capacity = capacity]; - this.mode = mode; - } - - /** - * An alias for {@code add(id, 1)}. - * - * @param id The id. - * @return {@code true} if the item was added, {@code false} if there was not enough room. - */ - public boolean add(int id) { - return add(id, 1) == 0; - } - - /** - * An alias for {@code add(new Item(id, amount)}. - * - * @param id The id. - * @param amount The amount. - * @return The amount that remains. - */ - public int add(int id, int amount) { - Item item = add(new Item(id, amount)); - return item != null ? item.getAmount() : 0; - } - - /** - * Adds an item to this inventory. This will attempt to add as much of the item that is possible. If the item - * remains, it will be returned (in the case of stackable items, any quantity that remains in the stack is - * returned). If nothing remains, the method will return {@code null}. If something remains, the listener will also - * be notified which could be used, for example, to send a message to the player. - * - * @param item The item to add to this inventory. - * @return The item that remains if there is not enough room in the inventory. If nothing remains, {@code null}. - */ - public Item add(Item item) { - int id = item.getId(); - boolean stackable = isStackable(item.getDefinition()); - if (stackable) { - for (int slot = 0; slot < capacity; slot++) { - Item other = items[slot]; - if (other != null && other.getId() == id) { - long total = item.getAmount() + other.getAmount(); - int amount, remaining; - if (total > Integer.MAX_VALUE) { - amount = (int) (total - Integer.MAX_VALUE); - remaining = (int) (total - amount); - notifyCapacityExceeded(); - } else { - amount = (int) total; - remaining = 0; - } - set(slot, new Item(id, amount)); - return remaining > 0 ? new Item(id, remaining) : null; - } - } - for (int slot = 0; slot < capacity; slot++) { - Item other = items[slot]; - if (other == null) { - set(slot, item); - return null; - } - } + /** + * Adds an item to this inventory. This will attempt to add as much of the item that is possible. If the item + * remains, it will be returned (in the case of stackable items, any quantity that remains in the stack is + * returned). If nothing remains, the method will return {@code null}. If something remains, the listener will also + * be notified which could be used, for example, to send a message to the player. + * + * @param item The item to add to this inventory. + * @return The item that remains if there is not enough room in the inventory. If nothing remains, {@code null}. + */ + public Item add(Item item) { + int id = item.getId(); + boolean stackable = isStackable(item.getDefinition()); + if (stackable) { + for (int slot = 0; slot < capacity; slot++) { + Item other = items[slot]; + if (other != null && other.getId() == id) { + long total = item.getAmount() + other.getAmount(); + int amount, remaining; + if (total > Integer.MAX_VALUE) { + amount = (int) (total - Integer.MAX_VALUE); + remaining = (int) (total - amount); notifyCapacityExceeded(); - return item; + } else { + amount = (int) total; + remaining = 0; + } + set(slot, new Item(id, amount)); + return remaining > 0 ? new Item(id, remaining) : null; } - - int remaining = item.getAmount(); - - stopFiringEvents(); - try { - Item single = new Item(item.getId(), 1); - for (int slot = 0; slot < capacity; slot++) { - if (items[slot] == null) { - remaining--; - set(slot, single); // share the instances - if (remaining <= 0) { - break; - } - } - } - } finally { - startFiringEvents(); + } + for (int slot = 0; slot < capacity; slot++) { + Item other = items[slot]; + if (other == null) { + set(slot, item); + return null; } + } + notifyCapacityExceeded(); + return item; + } - if (remaining != item.getAmount()) { - notifyItemsUpdated(); + int remaining = item.getAmount(); + + stopFiringEvents(); + try { + Item single = new Item(item.getId(), 1); + for (int slot = 0; slot < capacity; slot++) { + if (items[slot] == null) { + remaining--; + set(slot, single); // share the instances + if (remaining <= 0) { + break; + } } - if (remaining > 0) { - notifyCapacityExceeded(); + } + } finally { + startFiringEvents(); + } + + if (remaining != item.getAmount()) { + notifyItemsUpdated(); + } + if (remaining > 0) { + notifyCapacityExceeded(); + } + + return new Item(item.getId(), remaining); + } + + /** + * Adds an {@link InventoryListener}. + * + * @param listener The listener. + */ + public void addListener(InventoryListener listener) { + listeners.add(listener); + } + + /** + * Gets the capacity of this inventory. + * + * @return The capacity. + */ + public int capacity() { + return capacity; + } + + /** + * Checks the bounds of the specified slot. + * + * @param slot The slot. + * @throws IndexOutOfBoundsException If the slot is out of bounds. + */ + private void checkBounds(int slot) { + if (slot < 0 || slot >= capacity) { + throw new IndexOutOfBoundsException("Slot out of bounds."); + } + } + + /** + * Clears the inventory. + */ + public void clear() { + items = new Item[capacity]; + size = 0; + notifyItemsUpdated(); + } + + /** + * Creates a copy of this inventory. Listeners are not copied, they must be added again yourself! This is so cloned + * copies don't send updates to their counterparts. + */ + @Override + public Inventory clone() { + Inventory copy = new Inventory(capacity, mode); + System.arraycopy(items, 0, copy.items, 0, capacity); + copy.size = size; + return copy; + } + + /** + * Checks if this inventory contains an item with the specified id. + * + * @param id The item's id. + * @return {@code true} if so, {@code false} if not. + */ + public boolean contains(int id) { + return slotOf(id) != -1; + } + + /** + * Forces the capacity to exceeded event to be fired. + */ + public void forceCapacityExceeded() { + notifyCapacityExceeded(); + } + + /** + * Forces the refresh of this inventory. + */ + public void forceRefresh() { + notifyItemsUpdated(); + } + + /** + * Forces a refresh of a specific slot. + * + * @param slot The slot. + */ + public void forceRefresh(int slot) { + notifyItemUpdated(slot); + } + + /** + * Gets the number of free slots. + * + * @return The number of free slots. + */ + public int freeSlots() { + return capacity - size; + } + + /** + * Gets the item in the specified slot. + * + * @param slot The slot. + * @return The item, or {@code null} if the slot is empty. + */ + public Item get(int slot) { + checkBounds(slot); + return items[slot]; + } + + /** + * Gets the amount of items with the specified id in this inventory. + * + * @param id The id. + * @return The number of matching items, or {@code 0} if none were found. + */ + public int getAmount(int id) { + if (isStackable(ItemDefinition.lookup(id))) { + int slot = slotOf(id); + if (slot != -1) { + return items[slot].getAmount(); + } + return 0; + } + + int amount = 0, usedSlots = 0; + for (int i = 0; i < capacity && usedSlots <= size; i++) { + Item item = items[i]; + if (item != null) { + if (item.getId() == id) { + amount++; } - - return new Item(item.getId(), remaining); + usedSlots++; + } } + return amount; + } - /** - * Adds an {@link InventoryListener}. - * - * @param listener The listener. - */ - public void addListener(InventoryListener listener) { - listeners.add(listener); + /** + * Gets a clone of the items array. + * + * @return A clone of the items array. + */ + public Item[] getItems() { + return items.clone(); + } + + /** + * Checks if the item with the specified {@link ItemDefinition} should be stacked. + * + * @param definition The item definition. + * @return {@code true} if the item should be stacked, {@code false} otherwise. + */ + private boolean isStackable(ItemDefinition definition) { + if (mode == StackMode.STACK_ALWAYS) { + return true; + } else if (mode == StackMode.STACK_STACKABLE_ITEMS) { + return definition.isStackable(); } + return false; + } - /** - * Gets the capacity of this inventory. - * - * @return The capacity. - */ - public int capacity() { - return capacity; + /** + * Notifies listeners that the capacity of this inventory has been exceeded. + */ + private void notifyCapacityExceeded() { + if (firingEvents) { + for (InventoryListener listener : listeners) { + listener.capacityExceeded(this); + } } + } - /** - * Checks the bounds of the specified slot. - * - * @param slot The slot. - * @throws IndexOutOfBoundsException If the slot is out of bounds. - */ - private void checkBounds(int slot) { - if (slot < 0 || slot >= capacity) { - throw new IndexOutOfBoundsException("Slot out of bounds."); - } + /** + * Notifies listeners that all the items have been updated. + */ + private void notifyItemsUpdated() { + if (firingEvents) { + for (InventoryListener listener : listeners) { + listener.itemsUpdated(this); + } } + } - /** - * Clears the inventory. - */ - public void clear() { - items = new Item[capacity]; - size = 0; - notifyItemsUpdated(); + /** + * Notifies listeners that the specified slot has been updated. + * + * @param slot The slot. + */ + private void notifyItemUpdated(int slot) { + if (firingEvents) { + for (InventoryListener listener : listeners) { + listener.itemUpdated(this, slot, items[slot]); + } } + } - /** - * Creates a copy of this inventory. Listeners are not copied, they must be added again yourself! This is so cloned - * copies don't send updates to their counterparts. - */ - @Override - public Inventory clone() { - Inventory copy = new Inventory(capacity, mode); - System.arraycopy(items, 0, copy.items, 0, capacity); - copy.size = size; - return copy; - } - - /** - * Checks if this inventory contains an item with the specified id. - * - * @param id The item's id. - * @return {@code true} if so, {@code false} if not. - */ - public boolean contains(int id) { - return slotOf(id) != -1; - } - - /** - * Forces the capacity to exceeded event to be fired. - */ - public void forceCapacityExceeded() { - notifyCapacityExceeded(); - } - - /** - * Forces the refresh of this inventory. - */ - public void forceRefresh() { - notifyItemsUpdated(); - } - - /** - * Forces a refresh of a specific slot. - * - * @param slot The slot. - */ - public void forceRefresh(int slot) { - notifyItemUpdated(slot); - } - - /** - * Gets the number of free slots. - * - * @return The number of free slots. - */ - public int freeSlots() { - return capacity - size; - } - - /** - * Gets the item in the specified slot. - * - * @param slot The slot. - * @return The item, or {@code null} if the slot is empty. - */ - public Item get(int slot) { - checkBounds(slot); - return items[slot]; - } - - /** - * Gets the amount of items with the specified id in this inventory. - * - * @param id The id. - * @return The number of matching items, or {@code 0} if none were found. - */ - public int getAmount(int id) { - if (isStackable(ItemDefinition.lookup(id))) { - int slot = slotOf(id); - if (slot != -1) { - return items[slot].getAmount(); - } - return 0; - } - - int amount = 0, usedSlots = 0; - for (int i = 0; i < capacity && usedSlots <= size; i++) { - Item item = items[i]; - if (item != null) { - if (item.getId() == id) { - amount++; - } - usedSlots++; - } - } - return amount; - } - - /** - * Gets a clone of the items array. - * - * @return A clone of the items array. - */ - public Item[] getItems() { - return items.clone(); - } - - /** - * Checks if the item with the specified {@link ItemDefinition} should be stacked. - * - * @param definition The item definition. - * @return {@code true} if the item should be stacked, {@code false} otherwise. - */ - private boolean isStackable(ItemDefinition definition) { - if (mode == StackMode.STACK_ALWAYS) { - return true; - } else if (mode == StackMode.STACK_STACKABLE_ITEMS) { - return definition.isStackable(); - } - return false; - } - - /** - * Notifies listeners that the capacity of this inventory has been exceeded. - */ - private void notifyCapacityExceeded() { - if (firingEvents) { - for (InventoryListener listener : listeners) { - listener.capacityExceeded(this); - } - } - } - - /** - * Notifies listeners that all the items have been updated. - */ - private void notifyItemsUpdated() { - if (firingEvents) { - for (InventoryListener listener : listeners) { - listener.itemsUpdated(this); - } - } - } - - /** - * Notifies listeners that the specified slot has been updated. - * - * @param slot The slot. - */ - private void notifyItemUpdated(int slot) { - if (firingEvents) { - for (InventoryListener listener : listeners) { - listener.itemUpdated(this, slot, items[slot]); - } - } - } - - /** - * Removes one item with the specified id. - * - * @param id The id. - * @return {@code true} if the item was removed, {@code false} otherwise. - */ - public boolean remove(int id) { - return remove(id, 1) == 1; - } - - /** - * Removes {@code amount} of the item with the specified {@code id}. If the item is stackable, it will remove it - * from the stack. If not, it'll remove {@code amount} items. - * - * @param id The id. - * @param amount The amount. - * @return The amount that was removed. - */ - public int remove(int id, int amount) { - ItemDefinition definition = ItemDefinition.lookup(id); - boolean stackable = isStackable(definition); - if (stackable) { - for (int slot = 0; slot < capacity; slot++) { - Item item = items[slot]; - if (item != null && item.getId() == id) { - if (amount >= item.getAmount()) { - set(slot, null); - return item.getAmount(); - } else { - int newAmount = item.getAmount() - amount; - set(slot, new Item(item.getId(), newAmount)); - return amount; - } - } - } - return 0; - } - int removed = 0; - for (int slot = 0; slot < capacity; slot++) { - Item item = items[slot]; - if (item != null && item.getId() == id) { - set(slot, null); - removed++; - } - if (removed >= amount) { - break; - } - } - return removed; - } - - /** - * An alias for {@code remove(item.getId(), item.getAmount())}. - * - * @param item The item to remove. - * @return The amount that was removed. - */ - public int remove(Item item) { - return remove(item.getId(), item.getAmount()); - } - - /** - * Removes all the listeners. - */ - public void removeAllListeners() { - listeners.clear(); - } - - /** - * Removes a listener. - * - * @param listener The listener to remove. - */ - public void removeListener(InventoryListener listener) { - listeners.remove(listener); - } - - /** - * Removes {@code amount} of the item at the specified {@code slot}. If the item is not stacked, it will only remove - * the single item at the slot (meaning it will ignore any amount higher than 1). This means that this method will - * under no circumstances make any changes to other slots. - * - * @param slot The slot. - * @param id The item id. - * @param amount The amount to remove. - * @return The amount that was removed (0 if nothing was removed). - */ - public int removeSlot(int slot, int amount) { - if (amount == 0) { - return 0; - } + /** + * Removes one item with the specified id. + * + * @param id The id. + * @return {@code true} if the item was removed, {@code false} otherwise. + */ + public boolean remove(int id) { + return remove(id, 1) == 1; + } + /** + * Removes {@code amount} of the item with the specified {@code id}. If the item is stackable, it will remove it + * from the stack. If not, it'll remove {@code amount} items. + * + * @param id The id. + * @param amount The amount. + * @return The amount that was removed. + */ + public int remove(int id, int amount) { + ItemDefinition definition = ItemDefinition.lookup(id); + boolean stackable = isStackable(definition); + if (stackable) { + for (int slot = 0; slot < capacity; slot++) { Item item = items[slot]; - if (item != null) { - int itemAmount = item.getAmount(); - int removed = itemAmount; - if (removed > amount) { - removed = amount; - } - - int remainder = itemAmount - removed; - set(slot, remainder > 0 ? new Item(item.getId(), remainder) : null); - - return removed; + if (item != null && item.getId() == id) { + if (amount >= item.getAmount()) { + set(slot, null); + return item.getAmount(); + } else { + int newAmount = item.getAmount() - amount; + set(slot, new Item(item.getId(), newAmount)); + return amount; + } } - return 0; + } + return 0; + } + int removed = 0; + for (int slot = 0; slot < capacity; slot++) { + Item item = items[slot]; + if (item != null && item.getId() == id) { + set(slot, null); + removed++; + } + if (removed >= amount) { + break; + } + } + return removed; + } + + /** + * An alias for {@code remove(item.getId(), item.getAmount())}. + * + * @param item The item to remove. + * @return The amount that was removed. + */ + public int remove(Item item) { + return remove(item.getId(), item.getAmount()); + } + + /** + * Removes all the listeners. + */ + public void removeAllListeners() { + listeners.clear(); + } + + /** + * Removes a listener. + * + * @param listener The listener to remove. + */ + public void removeListener(InventoryListener listener) { + listeners.remove(listener); + } + + /** + * Removes {@code amount} of the item at the specified {@code slot}. If the item is not stacked, it will only remove + * the single item at the slot (meaning it will ignore any amount higher than 1). This means that this method will + * under no circumstances make any changes to other slots. + * + * @param slot The slot. + * @param id The item id. + * @param amount The amount to remove. + * @return The amount that was removed (0 if nothing was removed). + */ + public int removeSlot(int slot, int amount) { + if (amount == 0) { + return 0; } - /** - * Removes the item (if any) that is in the specified slot. - * - * @param slot - * @return The item that was in the slot. - */ - public Item reset(int slot) { - checkBounds(slot); + Item item = items[slot]; + if (item != null) { + int itemAmount = item.getAmount(); + int removed = itemAmount; + if (removed > amount) { + removed = amount; + } - Item old = items[slot]; - if (old != null) { - size--; + int remainder = itemAmount - removed; + set(slot, remainder > 0 ? new Item(item.getId(), remainder) : null); + + return removed; + } + return 0; + } + + /** + * Removes the item (if any) that is in the specified slot. + * + * @param slot + * @return The item that was in the slot. + */ + public Item reset(int slot) { + checkBounds(slot); + + Item old = items[slot]; + if (old != null) { + size--; + } + items[slot] = null; + notifyItemUpdated(slot); + return old; + } + + /** + * Sets the item that is in the specified slot. + * + * @param slot The slot. + * @param item The item, or {@code null} to remove the item that is in the slot. + * @return The item that was in the slot. + */ + public Item set(int slot, Item item) { + if (item == null) { + return reset(slot); + } + checkBounds(slot); + + Item old = items[slot]; + if (old == null) { + size++; + } + items[slot] = item; + notifyItemUpdated(slot); + return old; + } + + /** + * Shifts all items to the top left of the container, leaving no gaps. + */ + public void shift() { + Item[] old = items; + items = new Item[capacity]; + for (int slot = 0, pos = 0; slot < items.length; slot++) { + if (old[slot] != null) { + items[pos++] = old[slot]; + } + } + + if (firingEvents) { + notifyItemsUpdated(); + } + } + + /** + * Gets the size of this inventory - the number of used slots. + * + * @return The size. + */ + public int size() { + return size; + } + + /** + * Gets the inventory slot for the specified id. + * + * @param id The id. + * @return The first slot containing the specified item, or {@code -1} if none of the slots matched the conditions. + */ + public int slotOf(int id) { + int usedSlots = 0; + for (int slot = 0; slot < capacity && usedSlots <= size; slot++) { + Item item = items[slot]; + if (item != null) { + if (item.getId() == id) { + return slot; } - items[slot] = null; - notifyItemUpdated(slot); - return old; + usedSlots++; + } } + return -1; + } - /** - * Sets the item that is in the specified slot. - * - * @param slot The slot. - * @param item The item, or {@code null} to remove the item that is in the slot. - * @return The item that was in the slot. - */ - public Item set(int slot, Item item) { - if (item == null) { - return reset(slot); + /** + * Starts the firing of events. + */ + public void startFiringEvents() { + firingEvents = true; + } + + /** + * Stops the firing of events. + */ + public void stopFiringEvents() { + firingEvents = false; + } + + /** + * Swaps the two items at the specified slots. + * + * @param insert If the swap should be done in insertion mode. + * @param oldSlot The old slot. + * @param newSlot The new slot. + */ + public void swap(boolean insert, int oldSlot, int newSlot) { + checkBounds(oldSlot); + checkBounds(newSlot); + + if (insert) { + if (newSlot > oldSlot) { + for (int slot = oldSlot; slot < newSlot; slot++) { + swap(slot, slot + 1); } - checkBounds(slot); - - Item old = items[slot]; - if (old == null) { - size++; + } else if (oldSlot > newSlot) { + for (int slot = oldSlot; slot > newSlot; slot--) { + swap(slot, slot - 1); } - items[slot] = item; - notifyItemUpdated(slot); - return old; + } + forceRefresh(); + } else { + Item item = items[oldSlot]; + items[oldSlot] = items[newSlot]; + items[newSlot] = item; + notifyItemUpdated(oldSlot); + notifyItemUpdated(newSlot); } + } - /** - * Shifts all items to the top left of the container, leaving no gaps. - */ - public void shift() { - Item[] old = items; - items = new Item[capacity]; - for (int slot = 0, pos = 0; slot < items.length; slot++) { - if (old[slot] != null) { - items[pos++] = old[slot]; - } - } - - if (firingEvents) { - notifyItemsUpdated(); - } - } - - /** - * Gets the size of this inventory - the number of used slots. - * - * @return The size. - */ - public int size() { - return size; - } - - /** - * Gets the inventory slot for the specified id. - * - * @param id The id. - * @return The first slot containing the specified item, or {@code -1} if none of the slots matched the conditions. - */ - public int slotOf(int id) { - int usedSlots = 0; - for (int slot = 0; slot < capacity && usedSlots <= size; slot++) { - Item item = items[slot]; - if (item != null) { - if (item.getId() == id) { - return slot; - } - usedSlots++; - } - } - return -1; - } - - /** - * Starts the firing of events. - */ - public void startFiringEvents() { - firingEvents = true; - } - - /** - * Stops the firing of events. - */ - public void stopFiringEvents() { - firingEvents = false; - } - - /** - * Swaps the two items at the specified slots. - * - * @param insert If the swap should be done in insertion mode. - * @param oldSlot The old slot. - * @param newSlot The new slot. - */ - public void swap(boolean insert, int oldSlot, int newSlot) { - checkBounds(oldSlot); - checkBounds(newSlot); - - if (insert) { - if (newSlot > oldSlot) { - for (int slot = oldSlot; slot < newSlot; slot++) { - swap(slot, slot + 1); - } - } else if (oldSlot > newSlot) { - for (int slot = oldSlot; slot > newSlot; slot--) { - swap(slot, slot - 1); - } - } - forceRefresh(); - } else { - Item item = items[oldSlot]; - items[oldSlot] = items[newSlot]; - items[newSlot] = item; - notifyItemUpdated(oldSlot); - notifyItemUpdated(newSlot); - } - } - - /** - * Swaps the two items at the specified slots. - * - * @param oldSlot The old slot. - * @param newSlot The new slot. - */ - public void swap(int oldSlot, int newSlot) { - swap(false, oldSlot, newSlot); - } + /** + * Swaps the two items at the specified slots. + * + * @param oldSlot The old slot. + * @param newSlot The new slot. + */ + public void swap(int oldSlot, int newSlot) { + swap(false, oldSlot, newSlot); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/InventoryAdapter.java b/src/org/apollo/game/model/inv/InventoryAdapter.java index 52cb6260..57a5ca77 100644 --- a/src/org/apollo/game/model/inv/InventoryAdapter.java +++ b/src/org/apollo/game/model/inv/InventoryAdapter.java @@ -9,19 +9,19 @@ import org.apollo.game.model.Item; */ public abstract class InventoryAdapter implements InventoryListener { - @Override - public void capacityExceeded(Inventory inventory) { + @Override + public void capacityExceeded(Inventory inventory) { - } + } - @Override - public void itemsUpdated(Inventory inventory) { + @Override + public void itemsUpdated(Inventory inventory) { - } + } - @Override - public void itemUpdated(Inventory inventory, int slot, Item item) { + @Override + public void itemUpdated(Inventory inventory, int slot, Item item) { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/InventoryConstants.java b/src/org/apollo/game/model/inv/InventoryConstants.java index 82fa704a..c47874fe 100644 --- a/src/org/apollo/game/model/inv/InventoryConstants.java +++ b/src/org/apollo/game/model/inv/InventoryConstants.java @@ -7,26 +7,26 @@ package org.apollo.game.model.inv; */ public final class InventoryConstants { - /** - * The capacity of the bank. - */ - public static final int BANK_CAPACITY = 352; + /** + * The capacity of the bank. + */ + public static final int BANK_CAPACITY = 352; - /** - * The capacity of the equipment inventory. - */ - public static final int EQUIPMENT_CAPACITY = 14; + /** + * The capacity of the equipment inventory. + */ + public static final int EQUIPMENT_CAPACITY = 14; - /** - * The capacity of the inventory. - */ - public static final int INVENTORY_CAPACITY = 28; + /** + * The capacity of the inventory. + */ + public static final int INVENTORY_CAPACITY = 28; - /** - * Default private constructor to prevent instantiation. - */ - private InventoryConstants() { + /** + * Default private constructor to prevent instantiation. + */ + private InventoryConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/InventoryListener.java b/src/org/apollo/game/model/inv/InventoryListener.java index 152fd956..6047ba42 100644 --- a/src/org/apollo/game/model/inv/InventoryListener.java +++ b/src/org/apollo/game/model/inv/InventoryListener.java @@ -9,27 +9,27 @@ import org.apollo.game.model.Item; */ public interface InventoryListener { - /** - * Called when the capacity of an inventory has been exceeded. - * - * @param inventory The inventory. - */ - public void capacityExceeded(Inventory inventory); + /** + * Called when the capacity of an inventory has been exceeded. + * + * @param inventory The inventory. + */ + public void capacityExceeded(Inventory inventory); - /** - * Called when items have been updated in bulk. - * - * @param inventory The inventory. - */ - public void itemsUpdated(Inventory inventory); + /** + * Called when items have been updated in bulk. + * + * @param inventory The inventory. + */ + public void itemsUpdated(Inventory inventory); - /** - * Called when an item has been updated. - * - * @param inventory The inventory. - * @param slot The slot. - * @param item The new item, or {@code null} if there is no new item. - */ - public void itemUpdated(Inventory inventory, int slot, Item item); + /** + * Called when an item has been updated. + * + * @param inventory The inventory. + * @param slot The slot. + * @param item The new item, or {@code null} if there is no new item. + */ + public void itemUpdated(Inventory inventory, int slot, Item item); } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/SlottedItem.java b/src/org/apollo/game/model/inv/SlottedItem.java index 266b2109..a1ec9e8c 100644 --- a/src/org/apollo/game/model/inv/SlottedItem.java +++ b/src/org/apollo/game/model/inv/SlottedItem.java @@ -9,61 +9,61 @@ import org.apollo.game.model.Item; */ public final class SlottedItem { - /** - * The item. - */ - private final Item item; + /** + * The item. + */ + private final Item item; - /** - * The slot. - */ - private final int slot; + /** + * The slot. + */ + private final int slot; - /** - * Creates a new slotted item. - * - * @param slot The slot. - * @param item The item. - */ - public SlottedItem(int slot, Item item) { - this.slot = slot; - this.item = item; - } + /** + * Creates a new slotted item. + * + * @param slot The slot. + * @param item The item. + */ + public SlottedItem(int slot, Item item) { + this.slot = slot; + this.item = item; + } - /** - * Gets the amount of the {@link Item}. - * - * @return The amount. - */ - public int getAmount() { - return item.getAmount(); - } + /** + * Gets the amount of the {@link Item}. + * + * @return The amount. + */ + public int getAmount() { + return item.getAmount(); + } - /** - * Gets the id of the {@link Item}. - * - * @return The id. - */ - public int getId() { - return item.getId(); - } + /** + * Gets the id of the {@link Item}. + * + * @return The id. + */ + public int getId() { + return item.getId(); + } - /** - * Gets the item. - * - * @return The item. - */ - public Item getItem() { - return item; - } + /** + * Gets the item. + * + * @return The item. + */ + public Item getItem() { + return item; + } - /** - * Gets the slot. - * - * @return The slot. - */ - public int getSlot() { - return slot; - } + /** + * Gets the slot. + * + * @return The slot. + */ + public int getSlot() { + return slot; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/inv/SynchronizationInventoryListener.java b/src/org/apollo/game/model/inv/SynchronizationInventoryListener.java index 7569e998..8da9a3d8 100644 --- a/src/org/apollo/game/model/inv/SynchronizationInventoryListener.java +++ b/src/org/apollo/game/model/inv/SynchronizationInventoryListener.java @@ -12,45 +12,45 @@ import org.apollo.game.model.entity.Player; */ public final class SynchronizationInventoryListener extends InventoryAdapter { - /** - * The equipment interface id. - */ - public static final int EQUIPMENT_ID = 1688; + /** + * The equipment interface id. + */ + public static final int EQUIPMENT_ID = 1688; - /** - * The inventory interface id. - */ - public static final int INVENTORY_ID = 3214; + /** + * The inventory interface id. + */ + public static final int INVENTORY_ID = 3214; - /** - * The interface id. - */ - private final int interfaceId; + /** + * The interface id. + */ + private final int interfaceId; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the synchronization inventory listener. - * - * @param player The player. - * @param interfaceId The interface id. - */ - public SynchronizationInventoryListener(Player player, int interfaceId) { - this.player = player; - this.interfaceId = interfaceId; - } + /** + * Creates the synchronization inventory listener. + * + * @param player The player. + * @param interfaceId The interface id. + */ + public SynchronizationInventoryListener(Player player, int interfaceId) { + this.player = player; + this.interfaceId = interfaceId; + } - @Override - public void itemsUpdated(Inventory inventory) { - player.send(new UpdateItemsEvent(interfaceId, inventory.getItems())); - } + @Override + public void itemsUpdated(Inventory inventory) { + player.send(new UpdateItemsEvent(interfaceId, inventory.getItems())); + } - @Override - public void itemUpdated(Inventory inventory, int slot, Item item) { - player.send(new UpdateSlottedItemsEvent(interfaceId, new SlottedItem(slot, item))); - } + @Override + public void itemUpdated(Inventory inventory, int slot, Item item) { + player.send(new UpdateSlottedItemsEvent(interfaceId, new SlottedItem(slot, item))); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/obj/GameObject.java b/src/org/apollo/game/model/obj/GameObject.java index 11f5a19f..6d298feb 100644 --- a/src/org/apollo/game/model/obj/GameObject.java +++ b/src/org/apollo/game/model/obj/GameObject.java @@ -12,72 +12,72 @@ import org.apollo.game.model.entity.Entity; */ public final class GameObject extends Entity { - /** - * The object's definition. - */ - private final ObjectDefinition definition; + /** + * The object's definition. + */ + private final ObjectDefinition definition; - /** - * The object's rotation. - */ - private final int rotation; + /** + * The object's rotation. + */ + private final int rotation; - /** - * The object type. - */ - private final int type; + /** + * The object type. + */ + private final int type; - /** - * Creates a game object. - * - * @param id The object's id. - * @param position The position. - * @param type The type code of the object. - * @param rotation The rotation of the object. - */ - public GameObject(int id, Position position, int type, int rotation) { - super(position); - this.type = type; - this.rotation = rotation; - definition = ObjectDefinition.lookup(id); - } + /** + * Creates a game object. + * + * @param id The object's id. + * @param position The position. + * @param type The type code of the object. + * @param rotation The rotation of the object. + */ + public GameObject(int id, Position position, int type, int rotation) { + super(position); + this.type = type; + this.rotation = rotation; + definition = ObjectDefinition.lookup(id); + } - /** - * Gets the definition of this object. - * - * @return The object's definition. - */ - public ObjectDefinition getDefinition() { - return definition; - } + /** + * Gets the definition of this object. + * + * @return The object's definition. + */ + public ObjectDefinition getDefinition() { + return definition; + } - @Override - public EntityType getEntityType() { - return EntityType.GAME_OBJECT; - } + @Override + public EntityType getEntityType() { + return EntityType.GAME_OBJECT; + } - /** - * Gets the object's rotation. - * - * @return The rotation. - */ - public int getRotation() { - return rotation; - } + /** + * Gets the object's rotation. + * + * @return The rotation. + */ + public int getRotation() { + return rotation; + } - /** - * Gets the type code of the object. - * - * @return The type. - */ - public int getType() { - return type; - } + /** + * Gets the type code of the object. + * + * @return The type. + */ + public int getType() { + return type; + } - @Override - public String toString() { - return GameObject.class.getName() + " [id=" + definition.getId() + ", type=" + type + ", rotation=" + rotation - + "]"; - } + @Override + public String toString() { + return GameObject.class.getName() + " [id=" + definition.getId() + ", type=" + type + ", rotation=" + rotation + + "]"; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/sector/Sector.java b/src/org/apollo/game/model/sector/Sector.java index 30fbd4c1..bb7a6f79 100644 --- a/src/org/apollo/game/model/sector/Sector.java +++ b/src/org/apollo/game/model/sector/Sector.java @@ -16,145 +16,145 @@ import org.apollo.game.model.Position; */ public final class Sector { - /** - * The width and height of a sector, in tiles. - */ - public static final int SECTOR_SIZE = 8; + /** + * The width and height of a sector, in tiles. + */ + public static final int SECTOR_SIZE = 8; - /** - * The sector coordinates of this sector. - */ - private final SectorCoordinates coordinates; + /** + * The sector coordinates of this sector. + */ + private final SectorCoordinates coordinates; - /** - * A map of positions to entities in that position. - */ - private final Map> entities = new HashMap<>(); + /** + * A map of positions to entities in that position. + */ + private final Map> entities = new HashMap<>(); - /** - * A list of listeners registered to this sector. - */ - private final List listeners = new ArrayList<>(); + /** + * A list of listeners registered to this sector. + */ + private final List listeners = new ArrayList<>(); - /** - * Creates a new sector. - * - * @param x The x coordinate of the sector. - * @param y The y coordinate of the sector. - */ - public Sector(int x, int y) { - this(new SectorCoordinates(x, y)); + /** + * Creates a new sector. + * + * @param x The x coordinate of the sector. + * @param y The y coordinate of the sector. + */ + public Sector(int x, int y) { + this(new SectorCoordinates(x, y)); + } + + /** + * Creates a new sector with the specified {@link SectorCoordinates}. + * + * @param coordinates The coordinates. + */ + public Sector(SectorCoordinates coordinates) { + this.coordinates = coordinates; + } + + /** + * Adds a {@link Entity} from to sector. Note that this does not spawn the entity, or do any other action other than + * register it to this sector. + * + * @param entity The entity. + * @return {@code true} if the entity was added successfully, otherwise {@code false}. + */ + public boolean addEntity(Entity entity) { + Position position = entity.getPosition(); + List entities = this.entities.get(position); + if (entities == null) { + entities = new ArrayList<>(); } - /** - * Creates a new sector with the specified {@link SectorCoordinates}. - * - * @param coordinates The coordinates. - */ - public Sector(SectorCoordinates coordinates) { - this.coordinates = coordinates; + if (entities.add(entity)) { + this.entities.put(position, entities); + notifyListeners(entity); + return true; + } + return false; + } + + /** + * Checks if this sector contains the specified entity. + * + * @param entity The entity. + * @return {@code true} if this sector contains the entity, otherwise {@code false}. + */ + public boolean contains(Entity entity) { + List entities = this.entities.get(entity.getPosition()); + return entities.contains(entity); + } + + /** + * Gets this sector's {@link SectorCoordinates}. + * + * @return The sector coordinates. + */ + public SectorCoordinates getCoordinates() { + return coordinates; + } + + /** + * Gets a copy of the {@link List} of {@link Entity}s. + * + * @param position The position containing the entities. + * @return The list. + */ + public List getEntities(Position position) { + return new ArrayList<>(entities.get(position)); + } + + /** + * Gets a copy of the {@link List} of {@link Entity}s with the specified {@link EntityType}. + * + * @param position The {@link Position} containing the entities. + * @param type The {@link EntityType}. + * @return The list of entities. + */ + @SuppressWarnings("unchecked") + public List getEntities(Position position, EntityType type) { + List entities = getEntities(position); + List filtered = new ArrayList<>(); + for (Entity entity : entities) { + if (entity.getEntityType() == type) { + filtered.add((T) entity); + } + } + return filtered; + } + + /** + * Notifies the listeners registered to this sector that an update has occurred. + * + * @param entity The entity that was updated. + */ + public void notifyListeners(Entity entity) { + for (SectorListener listener : listeners) { + listener.execute(this, entity); + } + } + + /** + * Removes a {@link Entity} from this sector. + * + * @param entity The entity. + * @return {@code true} if the entity was removed, otherwise {@code false}. + */ + public boolean removeEntity(Entity entity) { + List entities = this.entities.get(entity.getPosition()); + if (entities == null) { + this.entities.put(entity.getPosition(), new ArrayList<>()); + return false; } - /** - * Adds a {@link Entity} from to sector. Note that this does not spawn the entity, or do any other action other than - * register it to this sector. - * - * @param entity The entity. - * @return {@code true} if the entity was added successfully, otherwise {@code false}. - */ - public boolean addEntity(Entity entity) { - Position position = entity.getPosition(); - List entities = this.entities.get(position); - if (entities == null) { - entities = new ArrayList<>(); - } - - if (entities.add(entity)) { - this.entities.put(position, entities); - notifyListeners(entity); - return true; - } - return false; - } - - /** - * Checks if this sector contains the specified entity. - * - * @param entity The entity. - * @return {@code true} if this sector contains the entity, otherwise {@code false}. - */ - public boolean contains(Entity entity) { - List entities = this.entities.get(entity.getPosition()); - return entities.contains(entity); - } - - /** - * Gets this sector's {@link SectorCoordinates}. - * - * @return The sector coordinates. - */ - public SectorCoordinates getCoordinates() { - return coordinates; - } - - /** - * Gets a copy of the {@link List} of {@link Entity}s. - * - * @param position The position containing the entities. - * @return The list. - */ - public List getEntities(Position position) { - return new ArrayList<>(entities.get(position)); - } - - /** - * Gets a copy of the {@link List} of {@link Entity}s with the specified {@link EntityType}. - * - * @param position The {@link Position} containing the entities. - * @param type The {@link EntityType}. - * @return The list of entities. - */ - @SuppressWarnings("unchecked") - public List getEntities(Position position, EntityType type) { - List entities = getEntities(position); - List filtered = new ArrayList<>(); - for (Entity entity : entities) { - if (entity.getEntityType() == type) { - filtered.add((T) entity); - } - } - return filtered; - } - - /** - * Notifies the listeners registered to this sector that an update has occurred. - * - * @param entity The entity that was updated. - */ - public void notifyListeners(Entity entity) { - for (SectorListener listener : listeners) { - listener.execute(this, entity); - } - } - - /** - * Removes a {@link Entity} from this sector. - * - * @param entity The entity. - * @return {@code true} if the entity was removed, otherwise {@code false}. - */ - public boolean removeEntity(Entity entity) { - List entities = this.entities.get(entity.getPosition()); - if (entities == null) { - this.entities.put(entity.getPosition(), new ArrayList<>()); - return false; - } - - if (entities.remove(entity)) { - notifyListeners(entity); - return true; - } - return false; + if (entities.remove(entity)) { + notifyListeners(entity); + return true; } + return false; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/sector/SectorCoordinates.java b/src/org/apollo/game/model/sector/SectorCoordinates.java index 10c116f2..c26200b9 100644 --- a/src/org/apollo/game/model/sector/SectorCoordinates.java +++ b/src/org/apollo/game/model/sector/SectorCoordinates.java @@ -10,70 +10,70 @@ import org.apollo.game.model.Position; */ public final class SectorCoordinates { - /** - * Gets a pair of sector coordinates from a {@link Position}. - * - * @param position The position. - * @return The sector coordinates. - */ - public static SectorCoordinates fromPosition(Position position) { - return new SectorCoordinates(position.getTopLeftSectorX(), position.getTopLeftSectorY()); + /** + * Gets a pair of sector coordinates from a {@link Position}. + * + * @param position The position. + * @return The sector coordinates. + */ + public static SectorCoordinates fromPosition(Position position) { + return new SectorCoordinates(position.getTopLeftSectorX(), position.getTopLeftSectorY()); + } + + /** + * The x coordinate of this sector. + */ + private final int x; + + /** + * The y coordinate of this sector. + */ + private final int y; + + /** + * Creates the sector coordinates. + * + * @param x The x coordinate. + * @param y The y coordinate. + */ + public SectorCoordinates(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { + return false; } - - /** - * The x coordinate of this sector. - */ - private final int x; - - /** - * The y coordinate of this sector. - */ - private final int y; - - /** - * Creates the sector coordinates. - * - * @param x The x coordinate. - * @param y The y coordinate. - */ - public SectorCoordinates(int x, int y) { - this.x = x; - this.y = y; + final SectorCoordinates other = (SectorCoordinates) obj; + if (x != other.x || y != other.y) { + return false; } + return true; + } - @Override - public boolean equals(Object obj) { - if (obj == null || getClass() != obj.getClass()) { - return false; - } - final SectorCoordinates other = (SectorCoordinates) obj; - if (x != other.x || y != other.y) { - return false; - } - return true; - } + /** + * Gets the x coordinate (equivalent to the {@link Position#getTopLeftSectorX()} of a position within this sector). + * + * @return The x coordinate. + */ + public int getX() { + return x; + } - /** - * Gets the x coordinate (equivalent to the {@link Position#getTopLeftSectorX()} of a position within this sector). - * - * @return The x coordinate. - */ - public int getX() { - return x; - } + /** + * Gets the y coordinate (equivalent to the {@link Position#getTopLeftSectorY()} of a position within this sector). + * + * @return The y coordinate. + */ + public int getY() { + return y; + } - /** - * Gets the y coordinate (equivalent to the {@link Position#getTopLeftSectorY()} of a position within this sector). - * - * @return The y coordinate. - */ - public int getY() { - return y; - } - - @Override - public int hashCode() { - return 61 * (427 + x) + y; - } + @Override + public int hashCode() { + return 61 * (427 + x) + y; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/sector/SectorListener.java b/src/org/apollo/game/model/sector/SectorListener.java index 93d1539a..72761b55 100644 --- a/src/org/apollo/game/model/sector/SectorListener.java +++ b/src/org/apollo/game/model/sector/SectorListener.java @@ -9,12 +9,12 @@ import org.apollo.game.model.entity.Entity; */ public abstract class SectorListener { - /** - * Executes the action for this listener. - * - * @param The sector that was updated. - * @param entity The affected entity. - */ - public abstract void execute(Sector sector, Entity entity); + /** + * Executes the action for this listener. + * + * @param The sector that was updated. + * @param entity The affected entity. + */ + public abstract void execute(Sector sector, Entity entity); } \ No newline at end of file diff --git a/src/org/apollo/game/model/sector/SectorRepository.java b/src/org/apollo/game/model/sector/SectorRepository.java index d068e575..2f1dc2bf 100644 --- a/src/org/apollo/game/model/sector/SectorRepository.java +++ b/src/org/apollo/game/model/sector/SectorRepository.java @@ -13,99 +13,99 @@ import java.util.Map; */ public final class SectorRepository { - /** - * Indicates whether sectors can be removed from this repository. - */ - private final boolean permitRemoval; + /** + * Indicates whether sectors can be removed from this repository. + */ + private final boolean permitRemoval; - /** - * A {@link Map} of {@link SectorCoordinates} that correspond to the appropriate {@link Sector}s.. - */ - private final Map sectors = new HashMap<>(); + /** + * A {@link Map} of {@link SectorCoordinates} that correspond to the appropriate {@link Sector}s.. + */ + private final Map sectors = new HashMap<>(); - /** - * Creates a new sector repository. - * - * @param permitRemoval If removal (of {@link Sector}s) from this repository should be permitted. - */ - public SectorRepository(boolean permitRemoval) { - this.permitRemoval = permitRemoval; - } + /** + * Creates a new sector repository. + * + * @param permitRemoval If removal (of {@link Sector}s) from this repository should be permitted. + */ + public SectorRepository(boolean permitRemoval) { + this.permitRemoval = permitRemoval; + } - /** - * Adds a {@link Sector} to the repository. - * - * @param sector The sector. - * @throws IllegalArgumentException If the provided sector is null. - * @throws UnsupportedOperationException If the coordinates of the provided sector are already mapped (and hence the - * existing sector would be replaced), and removal of sectors is not permitted. - */ - public void add(Sector sector) { - if (sector == null) { - throw new IllegalArgumentException("Sector cannot be null."); - } else if (sectors.containsKey(sector.getCoordinates()) && !permitRemoval) { - throw new UnsupportedOperationException( - "Cannot add a sector with the same coordinates as an existing sector."); - } - sectors.put(sector.getCoordinates(), sector); + /** + * Adds a {@link Sector} to the repository. + * + * @param sector The sector. + * @throws IllegalArgumentException If the provided sector is null. + * @throws UnsupportedOperationException If the coordinates of the provided sector are already mapped (and hence the + * existing sector would be replaced), and removal of sectors is not permitted. + */ + public void add(Sector sector) { + if (sector == null) { + throw new IllegalArgumentException("Sector cannot be null."); + } else if (sectors.containsKey(sector.getCoordinates()) && !permitRemoval) { + throw new UnsupportedOperationException( + "Cannot add a sector with the same coordinates as an existing sector."); } + sectors.put(sector.getCoordinates(), sector); + } - /** - * Indicates whether the supplied value (i.e. the {@link Sector}) has a mapping. - * - * @param sector The sector. - * @return {@code true} if the value is mapped by a key (i.e. {@link SectorCoordinates}), otherwise {@code false}. - */ - public boolean contains(Sector sector) { - return sectors.containsValue(sector); - } + /** + * Indicates whether the supplied value (i.e. the {@link Sector}) has a mapping. + * + * @param sector The sector. + * @return {@code true} if the value is mapped by a key (i.e. {@link SectorCoordinates}), otherwise {@code false}. + */ + public boolean contains(Sector sector) { + return sectors.containsValue(sector); + } - /** - * Indicates whether the supplied key (i.e. the {@link SectorCoordinates}) has a mapping. - * - * @param coordinates The coordinates. - * @return {@code true} if the key is already mapped to a value (i.e. a {@link Sector}), otherwise {@code false}. - */ - public boolean contains(SectorCoordinates coordinates) { - return sectors.containsKey(coordinates); - } - - /** - * Gets a {@link Sector} with the specified {@link SectorCoordinates}. If the sector does not exist (i.e. - * {@link #sectors}{@code .get()} returns {@code null}) then a new sector is created, submitted to the repository, - * and returned. - * - * @param coordinates The coordinates. - * @return The sector. - */ - public Sector get(SectorCoordinates coordinates) { - Sector sector = sectors.get(coordinates); - if (sector == null) { - add(sector = new Sector(coordinates)); - } - return sector; - } + /** + * Indicates whether the supplied key (i.e. the {@link SectorCoordinates}) has a mapping. + * + * @param coordinates The coordinates. + * @return {@code true} if the key is already mapped to a value (i.e. a {@link Sector}), otherwise {@code false}. + */ + public boolean contains(SectorCoordinates coordinates) { + return sectors.containsKey(coordinates); + } - /** - * Gets the {@link List} of {@link Sector}s. - * - * @return The list. - */ - public List getSectors() { - return new ArrayList<>(sectors.values()); + /** + * Gets a {@link Sector} with the specified {@link SectorCoordinates}. If the sector does not exist (i.e. + * {@link #sectors}{@code .get()} returns {@code null}) then a new sector is created, submitted to the repository, + * and returned. + * + * @param coordinates The coordinates. + * @return The sector. + */ + public Sector get(SectorCoordinates coordinates) { + Sector sector = sectors.get(coordinates); + if (sector == null) { + add(sector = new Sector(coordinates)); } + return sector; + } - /** - * Removes a {@link Sector} from the repository, if permitted. - * - * @param sector The sector to remove. - * @throws UnsupportedOperationException If this method is called on a repository that does not permit removal. - */ - public void remove(Sector sector) { - if (!permitRemoval) { - throw new UnsupportedOperationException("Cannot remove sectors from this repository."); - } - sectors.remove(sector.getCoordinates()); + /** + * Gets the {@link List} of {@link Sector}s. + * + * @return The list. + */ + public List getSectors() { + return new ArrayList<>(sectors.values()); + } + + /** + * Removes a {@link Sector} from the repository, if permitted. + * + * @param sector The sector to remove. + * @throws UnsupportedOperationException If this method is called on a repository that does not permit removal. + */ + public void remove(Sector sector) { + if (!permitRemoval) { + throw new UnsupportedOperationException("Cannot remove sectors from this repository."); } + sectors.remove(sector.getCoordinates()); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/settings/Gender.java b/src/org/apollo/game/model/settings/Gender.java index 81a7fac6..c81b28a8 100644 --- a/src/org/apollo/game/model/settings/Gender.java +++ b/src/org/apollo/game/model/settings/Gender.java @@ -8,23 +8,23 @@ package org.apollo.game.model.settings; */ public enum Gender { - /** - * The male gender. - */ - MALE, + /** + * The male gender. + */ + MALE, - /** - * The female gender. - */ - FEMALE; + /** + * The female gender. + */ + FEMALE; - /** - * Converts this gender to an integer. - * - * @return The numerical value used by the client. - */ - public int toInteger() { - return ordinal(); - } + /** + * Converts this gender to an integer. + * + * @return The numerical value used by the client. + */ + public int toInteger() { + return ordinal(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/settings/PrivacyState.java b/src/org/apollo/game/model/settings/PrivacyState.java index 48cfc75e..66384c82 100644 --- a/src/org/apollo/game/model/settings/PrivacyState.java +++ b/src/org/apollo/game/model/settings/PrivacyState.java @@ -9,81 +9,81 @@ package org.apollo.game.model.settings; */ public enum PrivacyState { - /** - * Represents the 'on' state, when all messages are displayed. - */ - ON(0), + /** + * Represents the 'on' state, when all messages are displayed. + */ + ON(0), - /** - * Represents the 'hidden' state, when all public chat text is displayed over the heads of players, but not in the - * chat interface. This state only applies to public chat. - */ - HIDE(1), + /** + * Represents the 'hidden' state, when all public chat text is displayed over the heads of players, but not in the + * chat interface. This state only applies to public chat. + */ + HIDE(1), - /** - * Represents the 'friends' state, when only messages from friends and moderators are displayed. - */ - FRIENDS(2), + /** + * Represents the 'friends' state, when only messages from friends and moderators are displayed. + */ + FRIENDS(2), - /** - * Represents the 'off' state, when only messages from moderators are displayed. - */ - OFF(3), + /** + * Represents the 'off' state, when only messages from moderators are displayed. + */ + OFF(3), - /** - * Represents the 'filterable' state - a custom state that filters 'unnecessary' server messages. This state only - * applies to public chat. - */ - FILTERABLE(4); + /** + * Represents the 'filterable' state - a custom state that filters 'unnecessary' server messages. This state only + * applies to public chat. + */ + FILTERABLE(4); - /** - * Gets the privacy state for the specified numerical value. - * - * @param value The numerical value. - * @return The privacy state. - * @throws IllegalArgumentException If the specified value is out of bounds. - */ - public static PrivacyState valueOf(int value, boolean chat) { - PrivacyState[] values = values(); - if (!chat && value != 0) { - value++; - } - if (value < 0 || value >= values.length) { - throw new IllegalArgumentException("Invalid privacy option integer value specified: " + value + "."); - } - - return values[value]; + /** + * Gets the privacy state for the specified numerical value. + * + * @param value The numerical value. + * @return The privacy state. + * @throws IllegalArgumentException If the specified value is out of bounds. + */ + public static PrivacyState valueOf(int value, boolean chat) { + PrivacyState[] values = values(); + if (!chat && value != 0) { + value++; + } + if (value < 0 || value >= values.length) { + throw new IllegalArgumentException("Invalid privacy option integer value specified: " + value + "."); } - /** - * The numerical value used by the client. - */ - private final int value; + return values[value]; + } - /** - * Creates the privacy state. - * - * @param value The numerical value. - */ - private PrivacyState(int value) { - this.value = value; - } - - /* - * Horrible workarounds are required here because public chat supports ON, HIDE, FRIENDS, and OFF, but trade and - * private only support ON, FRIENDS, and OFF. - */ - - /** - * Converts this privacy state to an integer. - * - * @return The numerical value used by the client. - */ - public int toInteger(boolean chat) { - if (chat) { - return value; - } - return value == 0 ? 0 : value - 1; + /** + * The numerical value used by the client. + */ + private final int value; + + /** + * Creates the privacy state. + * + * @param value The numerical value. + */ + private PrivacyState(int value) { + this.value = value; + } + + /* + * Horrible workarounds are required here because public chat supports ON, HIDE, FRIENDS, and OFF, but trade and + * private only support ON, FRIENDS, and OFF. + */ + + /** + * Converts this privacy state to an integer. + * + * @return The numerical value used by the client. + */ + public int toInteger(boolean chat) { + if (chat) { + return value; } + return value == 0 ? 0 : value - 1; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/settings/PrivilegeLevel.java b/src/org/apollo/game/model/settings/PrivilegeLevel.java index 77a8e45d..cc0c498a 100644 --- a/src/org/apollo/game/model/settings/PrivilegeLevel.java +++ b/src/org/apollo/game/model/settings/PrivilegeLevel.java @@ -8,43 +8,43 @@ package org.apollo.game.model.settings; */ public enum PrivilegeLevel { - /** - * A standard (rights 0) account. - */ - STANDARD, + /** + * A standard (rights 0) account. + */ + STANDARD, - /** - * A player moderator (rights 1) account. - */ - MODERATOR, + /** + * A player moderator (rights 1) account. + */ + MODERATOR, - /** - * An administrator (rights 2) account. - */ - ADMINISTRATOR; + /** + * An administrator (rights 2) account. + */ + ADMINISTRATOR; - /** - * Gets the privilege level for the specified numerical value. - * - * @param value The numerical value. - * @return The privilege level. - * @throws IllegalArgumentException If the specified value is out of bounds. - */ - public static PrivilegeLevel valueOf(int value) { - PrivilegeLevel[] values = values(); - if (value < 0 || value >= values.length) { - throw new IndexOutOfBoundsException("Invalid privilege level integer value supplied " + value + "."); - } - return values[value]; + /** + * Gets the privilege level for the specified numerical value. + * + * @param value The numerical value. + * @return The privilege level. + * @throws IllegalArgumentException If the specified value is out of bounds. + */ + public static PrivilegeLevel valueOf(int value) { + PrivilegeLevel[] values = values(); + if (value < 0 || value >= values.length) { + throw new IndexOutOfBoundsException("Invalid privilege level integer value supplied " + value + "."); } + return values[value]; + } - /** - * Gets the numerical value of this privilege level. - * - * @return The numerical value used in the protocol. - */ - public int toInteger() { - return ordinal(); - } + /** + * Gets the numerical value of this privilege level. + * + * @return The numerical value used in the protocol. + */ + public int toInteger() { + return ordinal(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/settings/ScreenBrightness.java b/src/org/apollo/game/model/settings/ScreenBrightness.java index 10bddb68..7f0c0aa1 100644 --- a/src/org/apollo/game/model/settings/ScreenBrightness.java +++ b/src/org/apollo/game/model/settings/ScreenBrightness.java @@ -8,48 +8,48 @@ package org.apollo.game.model.settings; */ public enum ScreenBrightness { - /** - * Represents the 'dark' screen brightness. - */ - DARK, + /** + * Represents the 'dark' screen brightness. + */ + DARK, - /** - * Represents the 'normal' screen brightness. - */ - NORMAL, + /** + * Represents the 'normal' screen brightness. + */ + NORMAL, - /** - * Represents the 'bright' screen brightness. - */ - BRIGHT, + /** + * Represents the 'bright' screen brightness. + */ + BRIGHT, - /** - * Represents the 'very bright' screen brightness. - */ - VERY_BRIGHT; + /** + * Represents the 'very bright' screen brightness. + */ + VERY_BRIGHT; - /** - * Gets the screen brightness for the specified numerical value. - * - * @param value The numerical value. - * @return The screen brightness. - * @throws IllegalArgumentException If the specified value is out of bounds. - */ - public static ScreenBrightness valueOf(int value) { - ScreenBrightness[] values = values(); - if (value < 0 || value >= values.length) { - throw new IllegalArgumentException("Invalid screen brightness integer value specified " + value + "."); - } - return values[value]; + /** + * Gets the screen brightness for the specified numerical value. + * + * @param value The numerical value. + * @return The screen brightness. + * @throws IllegalArgumentException If the specified value is out of bounds. + */ + public static ScreenBrightness valueOf(int value) { + ScreenBrightness[] values = values(); + if (value < 0 || value >= values.length) { + throw new IllegalArgumentException("Invalid screen brightness integer value specified " + value + "."); } + return values[value]; + } - /** - * Converts this screen brightness to an integer. - * - * @return The numerical value. - */ - public int toInteger() { - return ordinal(); - } + /** + * Converts this screen brightness to an integer. + * + * @return The numerical value. + */ + public int toInteger() { + return ordinal(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/settings/ServerStatus.java b/src/org/apollo/game/model/settings/ServerStatus.java index 55f5fb42..aa705084 100644 --- a/src/org/apollo/game/model/settings/ServerStatus.java +++ b/src/org/apollo/game/model/settings/ServerStatus.java @@ -8,43 +8,43 @@ package org.apollo.game.model.settings; */ public enum ServerStatus { - /** - * Indicates the friend server is offline. - */ - OFFLINE, + /** + * Indicates the friend server is offline. + */ + OFFLINE, - /** - * Indicates the friend server is being connected to. - */ - CONNECTING, + /** + * Indicates the friend server is being connected to. + */ + CONNECTING, - /** - * Indicates the friend server is online and connected. - */ - ONLINE; + /** + * Indicates the friend server is online and connected. + */ + ONLINE; - /** - * Gets the code of this server status. - * - * @return The code. - */ - public int getCode() { - return ordinal(); - } - - /** - * Gets the server status for the specified numerical value. - * - * @param value The value. - * @return The server status. - * @throws IndexOutOfBoundsException If the specified value is out of bounds. - */ - public static ServerStatus valueOf(int value) { - ServerStatus[] values = values(); - if (value < 0 || value >= values.length) { - throw new IndexOutOfBoundsException("Invalid server status integer value supplied " + value + "."); - } - return values[value]; + /** + * Gets the code of this server status. + * + * @return The code. + */ + public int getCode() { + return ordinal(); + } + + /** + * Gets the server status for the specified numerical value. + * + * @param value The value. + * @return The server status. + * @throws IndexOutOfBoundsException If the specified value is out of bounds. + */ + public static ServerStatus valueOf(int value) { + ServerStatus[] values = values(); + if (value < 0 || value >= values.length) { + throw new IndexOutOfBoundsException("Invalid server status integer value supplied " + value + "."); } + return values[value]; + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/skill/LevelUpSkillListener.java b/src/org/apollo/game/model/skill/LevelUpSkillListener.java index 953706f8..9210b979 100644 --- a/src/org/apollo/game/model/skill/LevelUpSkillListener.java +++ b/src/org/apollo/game/model/skill/LevelUpSkillListener.java @@ -12,31 +12,31 @@ import org.apollo.util.LanguageUtil; */ public final class LevelUpSkillListener extends SkillAdapter { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the level up listener for the specified player. - * - * @param player The player. - */ - public LevelUpSkillListener(Player player) { - this.player = player; - } - - @Override - public void levelledUp(SkillSet set, int id, Skill skill) { - // TODO show the interface - String name = Skill.getName(id); - String article = LanguageUtil.getIndefiniteArticle(name); - player.sendMessage("You've just advanced " + article + " " + name + " level! You have reached level " - + skill.getMaximumLevel() + "."); - - if (Skill.isCombatSkill(id)) { - player.getSkillSet().calculateCombatLevel(); - } + /** + * Creates the level up listener for the specified player. + * + * @param player The player. + */ + public LevelUpSkillListener(Player player) { + this.player = player; + } + + @Override + public void levelledUp(SkillSet set, int id, Skill skill) { + // TODO show the interface + String name = Skill.getName(id); + String article = LanguageUtil.getIndefiniteArticle(name); + player.sendMessage("You've just advanced " + article + " " + name + " level! You have reached level " + + skill.getMaximumLevel() + "."); + + if (Skill.isCombatSkill(id)) { + player.getSkillSet().calculateCombatLevel(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/skill/SkillAdapter.java b/src/org/apollo/game/model/skill/SkillAdapter.java index 83c98a34..516cf0a9 100644 --- a/src/org/apollo/game/model/skill/SkillAdapter.java +++ b/src/org/apollo/game/model/skill/SkillAdapter.java @@ -10,19 +10,19 @@ import org.apollo.game.model.entity.SkillSet; */ public abstract class SkillAdapter implements SkillListener { - @Override - public void levelledUp(SkillSet set, int id, Skill skill) { + @Override + public void levelledUp(SkillSet set, int id, Skill skill) { - } + } - @Override - public void skillsUpdated(SkillSet set) { + @Override + public void skillsUpdated(SkillSet set) { - } + } - @Override - public void skillUpdated(SkillSet set, int id, Skill skill) { + @Override + public void skillUpdated(SkillSet set, int id, Skill skill) { - } + } } \ No newline at end of file diff --git a/src/org/apollo/game/model/skill/SkillListener.java b/src/org/apollo/game/model/skill/SkillListener.java index aa6cc33d..9f14fa95 100644 --- a/src/org/apollo/game/model/skill/SkillListener.java +++ b/src/org/apollo/game/model/skill/SkillListener.java @@ -10,29 +10,29 @@ import org.apollo.game.model.entity.SkillSet; */ public interface SkillListener { - /** - * Called when a {@link Skill} is levelled up. - * - * @param set The {@link SkillSet}. - * @param id The skill's id. - * @param skill The skill. - */ - public void levelledUp(SkillSet set, int id, Skill skill); + /** + * Called when a {@link Skill} is levelled up. + * + * @param set The {@link SkillSet}. + * @param id The skill's id. + * @param skill The skill. + */ + public void levelledUp(SkillSet set, int id, Skill skill); - /** - * Called when all {@link Skill}s are updated. - * - * @param set The {@link SkillSet}. - */ - public void skillsUpdated(SkillSet set); + /** + * Called when all {@link Skill}s are updated. + * + * @param set The {@link SkillSet}. + */ + public void skillsUpdated(SkillSet set); - /** - * Called when a single {@link Skill} is updated. - * - * @param set The {@link SkillSet}. - * @param id The skill's id. - * @param skill The skill. - */ - public void skillUpdated(SkillSet set, int id, Skill skill); + /** + * Called when a single {@link Skill} is updated. + * + * @param set The {@link SkillSet}. + * @param id The skill's id. + * @param skill The skill. + */ + public void skillUpdated(SkillSet set, int id, Skill skill); } \ No newline at end of file diff --git a/src/org/apollo/game/model/skill/SynchronizationSkillListener.java b/src/org/apollo/game/model/skill/SynchronizationSkillListener.java index 0313c4c5..f2aa3177 100644 --- a/src/org/apollo/game/model/skill/SynchronizationSkillListener.java +++ b/src/org/apollo/game/model/skill/SynchronizationSkillListener.java @@ -13,35 +13,35 @@ import org.apollo.game.sync.block.SynchronizationBlock; */ public final class SynchronizationSkillListener extends SkillAdapter { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the skill synchronization listener. - * - * @param player The player. - */ - public SynchronizationSkillListener(Player player) { - this.player = player; - } + /** + * Creates the skill synchronization listener. + * + * @param player The player. + */ + public SynchronizationSkillListener(Player player) { + this.player = player; + } - @Override - public void levelledUp(SkillSet set, int id, Skill skill) { - player.getBlockSet().add(SynchronizationBlock.createAppearanceBlock(player)); - } + @Override + public void levelledUp(SkillSet set, int id, Skill skill) { + player.getBlockSet().add(SynchronizationBlock.createAppearanceBlock(player)); + } - @Override - public void skillsUpdated(SkillSet set) { - for (int id = 0; id < set.size(); id++) { - player.send(new UpdateSkillEvent(id, set.getSkill(id))); - } + @Override + public void skillsUpdated(SkillSet set) { + for (int id = 0; id < set.size(); id++) { + player.send(new UpdateSkillEvent(id, set.getSkill(id))); } + } - @Override - public void skillUpdated(SkillSet set, int id, Skill skill) { - player.send(new UpdateSkillEvent(id, skill)); - } + @Override + public void skillUpdated(SkillSet set, int id, Skill skill) { + player.send(new UpdateSkillEvent(id, skill)); + } } \ No newline at end of file diff --git a/src/org/apollo/game/scheduling/ScheduledTask.java b/src/org/apollo/game/scheduling/ScheduledTask.java index d97ac584..64f08a92 100644 --- a/src/org/apollo/game/scheduling/ScheduledTask.java +++ b/src/org/apollo/game/scheduling/ScheduledTask.java @@ -7,76 +7,76 @@ package org.apollo.game.scheduling; */ public abstract class ScheduledTask { - /** - * The delay between executions of the task, in pulses. - */ - private int delay; + /** + * The delay between executions of the task, in pulses. + */ + private int delay; - /** - * The number of pulses remaining until the task is next executed. - */ - private int pulses; + /** + * The number of pulses remaining until the task is next executed. + */ + private int pulses; - /** - * A flag indicating if the task is running. - */ - private boolean running = true; + /** + * A flag indicating if the task is running. + */ + private boolean running = true; - /** - * Creates a new scheduled task. - * - * @param delay The delay between executions of the task, in pulses. - * @param immediate A flag indicating if this task should (for the first execution) be ran immediately, or after the - * {@code delay}. - * @throws IllegalArgumentException If the delay is less than or equal to zero. - */ - public ScheduledTask(int delay, boolean immediate) { - setDelay(delay); - pulses = immediate ? 0 : delay; + /** + * Creates a new scheduled task. + * + * @param delay The delay between executions of the task, in pulses. + * @param immediate A flag indicating if this task should (for the first execution) be ran immediately, or after the + * {@code delay}. + * @throws IllegalArgumentException If the delay is less than or equal to zero. + */ + public ScheduledTask(int delay, boolean immediate) { + setDelay(delay); + pulses = immediate ? 0 : delay; + } + + /** + * Executes this task. + */ + public abstract void execute(); + + /** + * Checks if this task is running. + * + * @return {@code true} if so, {@code false} if not. + */ + public final boolean isRunning() { + return running; + } + + /** + * Pulses this task: updates the delay and calls {@link #execute()} if necessary. + */ + final void pulse() { + if (running && pulses-- == 0) { + execute(); + pulses = delay; } + } - /** - * Executes this task. - */ - public abstract void execute(); - - /** - * Checks if this task is running. - * - * @return {@code true} if so, {@code false} if not. - */ - public final boolean isRunning() { - return running; + /** + * Sets the delay. + * + * @param delay The delay. + * @throws IllegalArgumentException If the delay is less than or equal to zero. + */ + public void setDelay(int delay) { + if (delay < 0) { + throw new IllegalArgumentException("Delay cannot be less than 0."); } + this.delay = delay; + } - /** - * Pulses this task: updates the delay and calls {@link #execute()} if necessary. - */ - final void pulse() { - if (running && pulses-- == 0) { - execute(); - pulses = delay; - } - } - - /** - * Sets the delay. - * - * @param delay The delay. - * @throws IllegalArgumentException If the delay is less than or equal to zero. - */ - public void setDelay(int delay) { - if (delay < 0) { - throw new IllegalArgumentException("Delay cannot be less than 0."); - } - this.delay = delay; - } - - /** - * Stops the task. - */ - public void stop() { - running = false; - } + /** + * Stops the task. + */ + public void stop() { + running = false; + } } \ No newline at end of file diff --git a/src/org/apollo/game/scheduling/Scheduler.java b/src/org/apollo/game/scheduling/Scheduler.java index 1a267ad1..dfca20ed 100644 --- a/src/org/apollo/game/scheduling/Scheduler.java +++ b/src/org/apollo/game/scheduling/Scheduler.java @@ -13,41 +13,41 @@ import java.util.Queue; */ public final class Scheduler { - /** - * A queue of new tasks that should be added. - */ - private Queue newTasks = new ArrayDeque(); + /** + * A queue of new tasks that should be added. + */ + private Queue newTasks = new ArrayDeque<>(); - /** - * A list of currently active tasks. - */ - private List tasks = new ArrayList(); + /** + * A list of currently active tasks. + */ + private List tasks = new ArrayList<>(); - /** - * Called every pulse: executes tasks that are still pending, adds new tasks and stops old tasks. - */ - public void pulse() { - ScheduledTask task; - while ((task = newTasks.poll()) != null) { - tasks.add(task); - } - - for (Iterator it = tasks.iterator(); it.hasNext();) { - task = it.next(); - task.pulse(); - if (!task.isRunning()) { - it.remove(); - } - } + /** + * Called every pulse: executes tasks that are still pending, adds new tasks and stops old tasks. + */ + public void pulse() { + ScheduledTask task; + while ((task = newTasks.poll()) != null) { + tasks.add(task); } - /** - * Schedules a new task. - * - * @param task The task to schedule. - */ - public boolean schedule(ScheduledTask task) { - return newTasks.add(task); + for (Iterator it = tasks.iterator(); it.hasNext();) { + task = it.next(); + task.pulse(); + if (!task.isRunning()) { + it.remove(); + } } + } + + /** + * Schedules a new task. + * + * @param task The task to schedule. + */ + public boolean schedule(ScheduledTask task) { + return newTasks.add(task); + } } \ No newline at end of file diff --git a/src/org/apollo/game/scheduling/impl/SkillNormalizationTask.java b/src/org/apollo/game/scheduling/impl/SkillNormalizationTask.java index 8e88a3fc..df7046dd 100644 --- a/src/org/apollo/game/scheduling/impl/SkillNormalizationTask.java +++ b/src/org/apollo/game/scheduling/impl/SkillNormalizationTask.java @@ -11,28 +11,28 @@ import org.apollo.game.scheduling.ScheduledTask; */ public final class SkillNormalizationTask extends ScheduledTask { - /** - * The mob. - */ - private final Mob mob; + /** + * The mob. + */ + private final Mob mob; - /** - * Creates the skill normalization task. - * - * @param mob The mob. - */ - public SkillNormalizationTask(Mob mob) { - super(100, false); - this.mob = mob; - } + /** + * Creates the skill normalization task. + * + * @param mob The mob. + */ + public SkillNormalizationTask(Mob mob) { + super(100, false); + this.mob = mob; + } - @Override - public void execute() { - if (!mob.isActive()) { - stop(); - } else { - mob.getSkillSet().normalize(); - } + @Override + public void execute() { + if (!mob.isActive()) { + stop(); + } else { + mob.getSkillSet().normalize(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/ClientSynchronizer.java b/src/org/apollo/game/sync/ClientSynchronizer.java index eb96fc98..542441b6 100644 --- a/src/org/apollo/game/sync/ClientSynchronizer.java +++ b/src/org/apollo/game/sync/ClientSynchronizer.java @@ -14,9 +14,9 @@ package org.apollo.game.sync; */ public abstract class ClientSynchronizer { - /** - * Synchronizes the state of the clients with the state of the server. - */ - public abstract void synchronize(); + /** + * Synchronizes the state of the clients with the state of the server. + */ + public abstract void synchronize(); } \ No newline at end of file diff --git a/src/org/apollo/game/sync/ParallelClientSynchronizer.java b/src/org/apollo/game/sync/ParallelClientSynchronizer.java index 8a62ad92..b35e9f1d 100644 --- a/src/org/apollo/game/sync/ParallelClientSynchronizer.java +++ b/src/org/apollo/game/sync/ParallelClientSynchronizer.java @@ -32,74 +32,74 @@ import org.apollo.util.NamedThreadFactory; */ public final class ParallelClientSynchronizer extends ClientSynchronizer { - /** - * The executor service. - */ - private final ExecutorService executor; + /** + * The executor service. + */ + private final ExecutorService executor; - /** - * The phaser. - */ - private final Phaser phaser = new Phaser(1); + /** + * The phaser. + */ + private final Phaser phaser = new Phaser(1); - /** - * Creates the parallel client synchronizer backed by a thread pool with a number of threads equal to the number of - * processing cores available (this is found by the {@link Runtime#availableProcessors()} method. - */ - public ParallelClientSynchronizer() { - int processors = Runtime.getRuntime().availableProcessors(); - ThreadFactory factory = new NamedThreadFactory("ClientSynchronizer"); - executor = Executors.newFixedThreadPool(processors, factory); + /** + * Creates the parallel client synchronizer backed by a thread pool with a number of threads equal to the number of + * processing cores available (this is found by the {@link Runtime#availableProcessors()} method. + */ + public ParallelClientSynchronizer() { + int processors = Runtime.getRuntime().availableProcessors(); + ThreadFactory factory = new NamedThreadFactory("ClientSynchronizer"); + executor = Executors.newFixedThreadPool(processors, factory); + } + + @Override + public void synchronize() { + MobRepository players = World.getWorld().getPlayerRepository(); + MobRepository npcs = World.getWorld().getNpcRepository(); + int playerCount = players.size(); + int npcCount = npcs.size(); + + phaser.bulkRegister(playerCount); + for (Player player : players) { + SynchronizationTask task = new PrePlayerSynchronizationTask(player); + executor.submit(new PhasedSynchronizationTask(phaser, task)); } + phaser.arriveAndAwaitAdvance(); - @Override - public void synchronize() { - MobRepository players = World.getWorld().getPlayerRepository(); - MobRepository npcs = World.getWorld().getNpcRepository(); - int playerCount = players.size(); - int npcCount = npcs.size(); - - phaser.bulkRegister(playerCount); - for (Player player : players) { - SynchronizationTask task = new PrePlayerSynchronizationTask(player); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); - - phaser.bulkRegister(npcCount); - for (Npc npc : npcs) { - SynchronizationTask task = new PreNpcSynchronizationTask(npc); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); - - phaser.bulkRegister(playerCount); - for (Player player : players) { - SynchronizationTask task = new PlayerSynchronizationTask(player); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); - - phaser.bulkRegister(playerCount); - for (Player player : players) { - SynchronizationTask task = new NpcSynchronizationTask(player); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); - - phaser.bulkRegister(playerCount); - for (Player player : players) { - SynchronizationTask task = new PostPlayerSynchronizationTask(player); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); - - phaser.bulkRegister(npcCount); - for (Npc npc : npcs) { - SynchronizationTask task = new PostNpcSynchronizationTask(npc); - executor.submit(new PhasedSynchronizationTask(phaser, task)); - } - phaser.arriveAndAwaitAdvance(); + phaser.bulkRegister(npcCount); + for (Npc npc : npcs) { + SynchronizationTask task = new PreNpcSynchronizationTask(npc); + executor.submit(new PhasedSynchronizationTask(phaser, task)); } + phaser.arriveAndAwaitAdvance(); + + phaser.bulkRegister(playerCount); + for (Player player : players) { + SynchronizationTask task = new PlayerSynchronizationTask(player); + executor.submit(new PhasedSynchronizationTask(phaser, task)); + } + phaser.arriveAndAwaitAdvance(); + + phaser.bulkRegister(playerCount); + for (Player player : players) { + SynchronizationTask task = new NpcSynchronizationTask(player); + executor.submit(new PhasedSynchronizationTask(phaser, task)); + } + phaser.arriveAndAwaitAdvance(); + + phaser.bulkRegister(playerCount); + for (Player player : players) { + SynchronizationTask task = new PostPlayerSynchronizationTask(player); + executor.submit(new PhasedSynchronizationTask(phaser, task)); + } + phaser.arriveAndAwaitAdvance(); + + phaser.bulkRegister(npcCount); + for (Npc npc : npcs) { + SynchronizationTask task = new PostNpcSynchronizationTask(npc); + executor.submit(new PhasedSynchronizationTask(phaser, task)); + } + phaser.arriveAndAwaitAdvance(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/SequentialClientSynchronizer.java b/src/org/apollo/game/sync/SequentialClientSynchronizer.java index 4a5360c9..ffe18392 100644 --- a/src/org/apollo/game/sync/SequentialClientSynchronizer.java +++ b/src/org/apollo/game/sync/SequentialClientSynchronizer.java @@ -24,37 +24,37 @@ import org.apollo.util.MobRepository; */ public final class SequentialClientSynchronizer extends ClientSynchronizer { - @Override - public void synchronize() { - MobRepository players = World.getWorld().getPlayerRepository(); - MobRepository npcs = World.getWorld().getNpcRepository(); + @Override + public void synchronize() { + MobRepository players = World.getWorld().getPlayerRepository(); + MobRepository npcs = World.getWorld().getNpcRepository(); - for (Player player : players) { - SynchronizationTask task = new PrePlayerSynchronizationTask(player); - task.run(); - } - - for (Npc npc : npcs) { - SynchronizationTask task = new PreNpcSynchronizationTask(npc); - task.run(); - } - - for (Player player : players) { - SynchronizationTask task = new PlayerSynchronizationTask(player); - task.run(); - task = new NpcSynchronizationTask(player); - task.run(); - } - - for (Player player : players) { - SynchronizationTask task = new PostPlayerSynchronizationTask(player); - task.run(); - } - - for (Npc npc : npcs) { - SynchronizationTask task = new PostNpcSynchronizationTask(npc); - task.run(); - } + for (Player player : players) { + SynchronizationTask task = new PrePlayerSynchronizationTask(player); + task.run(); } + for (Npc npc : npcs) { + SynchronizationTask task = new PreNpcSynchronizationTask(npc); + task.run(); + } + + for (Player player : players) { + SynchronizationTask task = new PlayerSynchronizationTask(player); + task.run(); + task = new NpcSynchronizationTask(player); + task.run(); + } + + for (Player player : players) { + SynchronizationTask task = new PostPlayerSynchronizationTask(player); + task.run(); + } + + for (Npc npc : npcs) { + SynchronizationTask task = new PostNpcSynchronizationTask(npc); + task.run(); + } + } + } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/AnimationBlock.java b/src/org/apollo/game/sync/block/AnimationBlock.java index bfee77ef..999c3d92 100644 --- a/src/org/apollo/game/sync/block/AnimationBlock.java +++ b/src/org/apollo/game/sync/block/AnimationBlock.java @@ -9,27 +9,27 @@ import org.apollo.game.model.Animation; */ public final class AnimationBlock extends SynchronizationBlock { - /** - * The animation. - */ - private final Animation animation; + /** + * The animation. + */ + private final Animation animation; - /** - * Creates the animation block. - * - * @param animation The animation. - */ - AnimationBlock(Animation animation) { - this.animation = animation; - } + /** + * Creates the animation block. + * + * @param animation The animation. + */ + AnimationBlock(Animation animation) { + this.animation = animation; + } - /** - * Gets the {@link Animation}. - * - * @return The animation. - */ - public Animation getAnimation() { - return animation; - } + /** + * Gets the {@link Animation}. + * + * @return The animation. + */ + public Animation getAnimation() { + return animation; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/AppearanceBlock.java b/src/org/apollo/game/sync/block/AppearanceBlock.java index 5e008191..badf1f75 100644 --- a/src/org/apollo/game/sync/block/AppearanceBlock.java +++ b/src/org/apollo/game/sync/block/AppearanceBlock.java @@ -10,165 +10,165 @@ import org.apollo.game.model.inv.Inventory; */ public final class AppearanceBlock extends SynchronizationBlock { - /** - * The player's appearance. - */ - private final Appearance appearance; + /** + * The player's appearance. + */ + private final Appearance appearance; - /** - * The player's combat level. - */ - private final int combat; + /** + * The player's combat level. + */ + private final int combat; - /** - * The player's equipment. - */ - private final Inventory equipment; + /** + * The player's equipment. + */ + private final Inventory equipment; - /** - * Whether or not the player is skulled. - */ - private final boolean isSkulled; + /** + * Whether or not the player is skulled. + */ + private final boolean isSkulled; - /** - * The player's name. - */ - private final long name; + /** + * The player's name. + */ + private final long name; - /** - * The npc id this player is appearing as, if any. - */ - private final int npcId; + /** + * The npc id this player is appearing as, if any. + */ + private final int npcId; - /** - * The player's prayer icon. - */ - private final int headIcon; + /** + * The player's prayer icon. + */ + private final int headIcon; - /** - * The player's total skill level (or 0). - */ - private final int skill; + /** + * The player's total skill level (or 0). + */ + private final int skill; - /** - * Creates the appearance block. Assumes that the player is not appearing as an npc. - * - * @param name The player's username, encoded to base 37. - * @param appearance The {@link Appearance}. - * @param combat The player's combat. - * @param skill The player's skill, or 0 if showing the combat level. - * @param equipment The player's equipment. - * @param headIcon The head icon id of the player. - * @param isSkulled Whether or not the player is skulled. - */ - AppearanceBlock(long name, Appearance appearance, int combat, int skill, Inventory equipment, int headIcon, - boolean isSkulled) { - this(name, appearance, combat, skill, equipment, headIcon, isSkulled, -1); - } + /** + * Creates the appearance block. Assumes that the player is not appearing as an npc. + * + * @param name The player's username, encoded to base 37. + * @param appearance The {@link Appearance}. + * @param combat The player's combat. + * @param skill The player's skill, or 0 if showing the combat level. + * @param equipment The player's equipment. + * @param headIcon The head icon id of the player. + * @param isSkulled Whether or not the player is skulled. + */ + AppearanceBlock(long name, Appearance appearance, int combat, int skill, Inventory equipment, int headIcon, + boolean isSkulled) { + this(name, appearance, combat, skill, equipment, headIcon, isSkulled, -1); + } - /** - * Creates the appearance block. - * - * @param name The player's username, encoded to base 37. - * @param appearance The {@link Appearance}. - * @param combat The player's combat. - * @param skill The player's skill, or 0 if showing the combat level. - * @param equipment The player's equipment. - * @param headIcon The prayer icon id of this player. - * @param isSkulled Whether or not the player is skulled. - * @param npcId The npc id of the player, if they are appearing as an npc, (otherwise {@code -1}). - */ - AppearanceBlock(long name, Appearance appearance, int combat, int skill, Inventory equipment, int headIcon, - boolean isSkulled, int npcId) { - this.name = name; - this.appearance = appearance; - this.combat = combat; - this.skill = skill; - this.equipment = equipment.clone(); - this.headIcon = headIcon; - this.isSkulled = isSkulled; - this.npcId = npcId; - } + /** + * Creates the appearance block. + * + * @param name The player's username, encoded to base 37. + * @param appearance The {@link Appearance}. + * @param combat The player's combat. + * @param skill The player's skill, or 0 if showing the combat level. + * @param equipment The player's equipment. + * @param headIcon The prayer icon id of this player. + * @param isSkulled Whether or not the player is skulled. + * @param npcId The npc id of the player, if they are appearing as an npc, (otherwise {@code -1}). + */ + AppearanceBlock(long name, Appearance appearance, int combat, int skill, Inventory equipment, int headIcon, + boolean isSkulled, int npcId) { + this.name = name; + this.appearance = appearance; + this.combat = combat; + this.skill = skill; + this.equipment = equipment.clone(); + this.headIcon = headIcon; + this.isSkulled = isSkulled; + this.npcId = npcId; + } - /** - * If the player is appearing as an npc or not. - * - * @return {@code true} if the player is appearing as an npc, otherwise {@code false}. - */ - public boolean appearingAsNpc() { - return npcId != -1; - } + /** + * If the player is appearing as an npc or not. + * + * @return {@code true} if the player is appearing as an npc, otherwise {@code false}. + */ + public boolean appearingAsNpc() { + return npcId != -1; + } - /** - * Gets the player's {@link Appearance}. - * - * @return The player's appearance. - */ - public Appearance getAppearance() { - return appearance; - } + /** + * Gets the player's {@link Appearance}. + * + * @return The player's appearance. + */ + public Appearance getAppearance() { + return appearance; + } - /** - * Gets the player's combat level. - * - * @return The player's combat level. - */ - public int getCombatLevel() { - return combat; - } + /** + * Gets the player's combat level. + * + * @return The player's combat level. + */ + public int getCombatLevel() { + return combat; + } - /** - * Gets the player's equipment. - * - * @return The player's equipment. - */ - public Inventory getEquipment() { - return equipment; - } + /** + * Gets the player's equipment. + * + * @return The player's equipment. + */ + public Inventory getEquipment() { + return equipment; + } - /** - * Whether or not the player is skulled. - * - * @return {@code true} if the player is skulled, otherwise {@code false}. - */ - public boolean isSkulled() { - return isSkulled; - } + /** + * Whether or not the player is skulled. + * + * @return {@code true} if the player is skulled, otherwise {@code false}. + */ + public boolean isSkulled() { + return isSkulled; + } - /** - * Gets the player's name. - * - * @return The player's name. - */ - public long getName() { - return name; - } + /** + * Gets the player's name. + * + * @return The player's name. + */ + public long getName() { + return name; + } - /** - * Gets the npc id the player is appearing as, or {@code -1} if the player is not appearing as one. - * - * @return The npc id. - */ - public int getNpcId() { - return npcId; - } + /** + * Gets the npc id the player is appearing as, or {@code -1} if the player is not appearing as one. + * + * @return The npc id. + */ + public int getNpcId() { + return npcId; + } - /** - * Gets the player's head icon. - * - * @return The head icon. - */ - public int getHeadIcon() { - return headIcon; - } + /** + * Gets the player's head icon. + * + * @return The head icon. + */ + public int getHeadIcon() { + return headIcon; + } - /** - * Gets the player's skill level. - * - * @return The player's skill level. - */ - public int getSkillLevel() { - return skill; - } + /** + * Gets the player's skill level. + * + * @return The player's skill level. + */ + public int getSkillLevel() { + return skill; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/ChatBlock.java b/src/org/apollo/game/sync/block/ChatBlock.java index 1a87476f..68e2edbf 100644 --- a/src/org/apollo/game/sync/block/ChatBlock.java +++ b/src/org/apollo/game/sync/block/ChatBlock.java @@ -10,70 +10,70 @@ import org.apollo.game.model.settings.PrivilegeLevel; */ public final class ChatBlock extends SynchronizationBlock { - /** - * The {@link ChatEvent}. - */ - private final ChatEvent chatEvent; + /** + * The {@link ChatEvent}. + */ + private final ChatEvent chatEvent; - /** - * The {@link PrivilegeLevel}. - */ - private final PrivilegeLevel privilegeLevel; + /** + * The {@link PrivilegeLevel}. + */ + private final PrivilegeLevel privilegeLevel; - /** - * Creates the chat block. - * - * @param privilegeLevel The {@link PrivilegeLevel} of the player who said the message. - * @param chatEvent The {@link ChatEvent}. - */ - ChatBlock(PrivilegeLevel privilegeLevel, ChatEvent chatEvent) { - this.privilegeLevel = privilegeLevel; - this.chatEvent = chatEvent; - } + /** + * Creates the chat block. + * + * @param privilegeLevel The {@link PrivilegeLevel} of the player who said the message. + * @param chatEvent The {@link ChatEvent}. + */ + ChatBlock(PrivilegeLevel privilegeLevel, ChatEvent chatEvent) { + this.privilegeLevel = privilegeLevel; + this.chatEvent = chatEvent; + } - /** - * Gets the compressed message. - * - * @return The compressed message. - */ - public byte[] getCompressedMessage() { - return chatEvent.getCompressedMessage(); - } + /** + * Gets the compressed message. + * + * @return The compressed message. + */ + public byte[] getCompressedMessage() { + return chatEvent.getCompressedMessage(); + } - /** - * Gets the message. - * - * @return The message. - */ - public String getMessage() { - return chatEvent.getMessage(); - } + /** + * Gets the message. + * + * @return The message. + */ + public String getMessage() { + return chatEvent.getMessage(); + } - /** - * Gets the {@link PrivilegeLevel} of the player who said the message. - * - * @return The privilege level. - */ - public PrivilegeLevel getPrivilegeLevel() { - return privilegeLevel; - } + /** + * Gets the {@link PrivilegeLevel} of the player who said the message. + * + * @return The privilege level. + */ + public PrivilegeLevel getPrivilegeLevel() { + return privilegeLevel; + } - /** - * Gets the text color. - * - * @return The text color. - */ - public int getTextColor() { - return chatEvent.getTextColor(); - } + /** + * Gets the text color. + * + * @return The text color. + */ + public int getTextColor() { + return chatEvent.getTextColor(); + } - /** - * Gets the text effects. - * - * @return The text effects. - */ - public int getTextEffects() { - return chatEvent.getTextEffects(); - } + /** + * Gets the text effects. + * + * @return The text effects. + */ + public int getTextEffects() { + return chatEvent.getTextEffects(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/ForceChatBlock.java b/src/org/apollo/game/sync/block/ForceChatBlock.java index 1bd0a580..593695b9 100644 --- a/src/org/apollo/game/sync/block/ForceChatBlock.java +++ b/src/org/apollo/game/sync/block/ForceChatBlock.java @@ -8,27 +8,27 @@ package org.apollo.game.sync.block; */ public final class ForceChatBlock extends SynchronizationBlock { - /** - * The chat text. - */ - private final String message; + /** + * The chat text. + */ + private final String message; - /** - * Creates the force chat block. - * - * @param message The message. - */ - ForceChatBlock(String message) { - this.message = message; - } + /** + * Creates the force chat block. + * + * @param message The message. + */ + ForceChatBlock(String message) { + this.message = message; + } - /** - * Gets the message being sent by this block. - * - * @return The message. - */ - public String getMessage() { - return message; - } + /** + * Gets the message being sent by this block. + * + * @return The message. + */ + public String getMessage() { + return message; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/ForceMovementBlock.java b/src/org/apollo/game/sync/block/ForceMovementBlock.java index b213492a..b6e266e6 100644 --- a/src/org/apollo/game/sync/block/ForceMovementBlock.java +++ b/src/org/apollo/game/sync/block/ForceMovementBlock.java @@ -14,110 +14,110 @@ import org.apollo.game.model.Position; */ public final class ForceMovementBlock extends SynchronizationBlock { - /** - * The direction the player is moving. - */ - private final Direction direction; + /** + * The direction the player is moving. + */ + private final Direction direction; - /** - * The {@link Position} the player is being moved to. - */ - private final Position finalPosition; + /** + * The {@link Position} the player is being moved to. + */ + private final Position finalPosition; - /** - * The initial {@link Position} of the player. - */ - private final Position initialPosition; + /** + * The initial {@link Position} of the player. + */ + private final Position initialPosition; - /** - * The length of time (in game pulses) the player's movement along the X-axis will last. - */ - private final int travelDurationX; + /** + * The length of time (in game pulses) the player's movement along the X-axis will last. + */ + private final int travelDurationX; - /** - * The length of time (in game pulses) the player's movement along the Y-axis will last. - */ - private final int travelDurationY; + /** + * The length of time (in game pulses) the player's movement along the Y-axis will last. + */ + private final int travelDurationY; - /** - * Creates a new force movement block. - * - * @param initialPosition The initial {@link Position} of the player. - * @param finalPosition The final {@link Position} of the player - * @param travelDurationX The length of time (in game pulses) the player's movement along the X-axis will last. - * @param travelDurationY The length of time (in game pulses) the player's movement along the Y-axis will last. - * @param direction The direction the player should move. - */ - ForceMovementBlock(Position initialPosition, Position finalPosition, int travelDurationX, int travelDurationY, - Direction direction) { - this.initialPosition = initialPosition; - this.finalPosition = finalPosition; - this.travelDurationX = travelDurationX; - this.travelDurationY = travelDurationY; - this.direction = direction; - } + /** + * Creates a new force movement block. + * + * @param initialPosition The initial {@link Position} of the player. + * @param finalPosition The final {@link Position} of the player + * @param travelDurationX The length of time (in game pulses) the player's movement along the X-axis will last. + * @param travelDurationY The length of time (in game pulses) the player's movement along the Y-axis will last. + * @param direction The direction the player should move. + */ + ForceMovementBlock(Position initialPosition, Position finalPosition, int travelDurationX, int travelDurationY, + Direction direction) { + this.initialPosition = initialPosition; + this.finalPosition = finalPosition; + this.travelDurationX = travelDurationX; + this.travelDurationY = travelDurationY; + this.direction = direction; + } - /** - * Gets the {@link Direction} the player should move. - * - * @return The direction. - */ - public Direction getDirection() { - return direction; - } + /** + * Gets the {@link Direction} the player should move. + * + * @return The direction. + */ + public Direction getDirection() { + return direction; + } - /** - * Gets the X coordinate of the final {@link Position}. - * - * @return The X coordinate. - */ - public int getFinalX() { - return finalPosition.getX(); - } + /** + * Gets the X coordinate of the final {@link Position}. + * + * @return The X coordinate. + */ + public int getFinalX() { + return finalPosition.getX(); + } - /** - * Gets the Y coordinate of the final {@link Position}. - * - * @return The Y coordinate. - */ - public int getFinalY() { - return finalPosition.getY(); - } + /** + * Gets the Y coordinate of the final {@link Position}. + * + * @return The Y coordinate. + */ + public int getFinalY() { + return finalPosition.getY(); + } - /** - * Gets the X coordinate of the initial {@link Position}. - * - * @return The X coordinate. - */ - public int getInitialX() { - return initialPosition.getX(); - } + /** + * Gets the X coordinate of the initial {@link Position}. + * + * @return The X coordinate. + */ + public int getInitialX() { + return initialPosition.getX(); + } - /** - * Gets the Y coordinate of the initial {@link Position}. - * - * @return The Y coordinate. - */ - public int getInitialY() { - return initialPosition.getY(); - } + /** + * Gets the Y coordinate of the initial {@link Position}. + * + * @return The Y coordinate. + */ + public int getInitialY() { + return initialPosition.getY(); + } - /** - * Gets the length of time (in game pulses) the player's movement along the X-axis will last. - * - * @return The time period. - */ - public int getTravelDurationX() { - return travelDurationX; - } + /** + * Gets the length of time (in game pulses) the player's movement along the X-axis will last. + * + * @return The time period. + */ + public int getTravelDurationX() { + return travelDurationX; + } - /** - * Gets the length of time (in game pulses) the player's movement along the Y-axis will last. - * - * @return The time period. - */ - public int getTravelDurationY() { - return travelDurationY; - } + /** + * Gets the length of time (in game pulses) the player's movement along the Y-axis will last. + * + * @return The time period. + */ + public int getTravelDurationY() { + return travelDurationY; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/GraphicBlock.java b/src/org/apollo/game/sync/block/GraphicBlock.java index 9377efa9..c0b313ab 100644 --- a/src/org/apollo/game/sync/block/GraphicBlock.java +++ b/src/org/apollo/game/sync/block/GraphicBlock.java @@ -9,27 +9,27 @@ import org.apollo.game.model.Graphic; */ public final class GraphicBlock extends SynchronizationBlock { - /** - * The graphic. - */ - private final Graphic graphic; + /** + * The graphic. + */ + private final Graphic graphic; - /** - * Creates the graphic block. - * - * @param graphic The graphic. - */ - GraphicBlock(Graphic graphic) { - this.graphic = graphic; - } + /** + * Creates the graphic block. + * + * @param graphic The graphic. + */ + GraphicBlock(Graphic graphic) { + this.graphic = graphic; + } - /** - * Gets the {@link Graphic}. - * - * @return The graphic. - */ - public Graphic getGraphic() { - return graphic; - } + /** + * Gets the {@link Graphic}. + * + * @return The graphic. + */ + public Graphic getGraphic() { + return graphic; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/HitUpdateBlock.java b/src/org/apollo/game/sync/block/HitUpdateBlock.java index 9fd9f770..4ce68792 100644 --- a/src/org/apollo/game/sync/block/HitUpdateBlock.java +++ b/src/org/apollo/game/sync/block/HitUpdateBlock.java @@ -7,75 +7,75 @@ package org.apollo.game.sync.block; */ public final class HitUpdateBlock extends SynchronizationBlock { - /** - * The mob's current health. - */ - private final int currentHealth; + /** + * The mob's current health. + */ + private final int currentHealth; - /** - * The amount of damage the hit will do. - */ - private final int damage; + /** + * The amount of damage the hit will do. + */ + private final int damage; - /** - * The mob's maximum health. - */ - private final int maximumHealth; + /** + * The mob's maximum health. + */ + private final int maximumHealth; - /** - * The type of hit (e.g. normal, poison). - */ - private final int type; + /** + * The type of hit (e.g. normal, poison). + */ + private final int type; - /** - * Creates the hit update block. - * - * @param damage The damage dealt by the hit. - * @param type The type of hit. - * @param currentHealth The current health of the mob. - * @param maximumHealth The maximum health of the mob. - */ - HitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth) { - this.damage = damage; - this.type = type; - this.currentHealth = currentHealth; - this.maximumHealth = maximumHealth; - } + /** + * Creates the hit update block. + * + * @param damage The damage dealt by the hit. + * @param type The type of hit. + * @param currentHealth The current health of the mob. + * @param maximumHealth The maximum health of the mob. + */ + HitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth) { + this.damage = damage; + this.type = type; + this.currentHealth = currentHealth; + this.maximumHealth = maximumHealth; + } - /** - * Gets the current health of the mob. - * - * @return The current health; - */ - public int getCurrentHealth() { - return currentHealth; - } + /** + * Gets the current health of the mob. + * + * @return The current health; + */ + public int getCurrentHealth() { + return currentHealth; + } - /** - * Gets the damage done by the hit. - * - * @return The damage. - */ - public int getDamage() { - return damage; - } + /** + * Gets the damage done by the hit. + * + * @return The damage. + */ + public int getDamage() { + return damage; + } - /** - * Gets the maximum health of the mob. - * - * @return The maximum health. - */ - public int getMaximumHealth() { - return maximumHealth; - } + /** + * Gets the maximum health of the mob. + * + * @return The maximum health. + */ + public int getMaximumHealth() { + return maximumHealth; + } - /** - * Gets the hit type. - * - * @return The type. - */ - public int getType() { - return type; - } + /** + * Gets the hit type. + * + * @return The type. + */ + public int getType() { + return type; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/InteractingMobBlock.java b/src/org/apollo/game/sync/block/InteractingMobBlock.java index d5f2a7ba..8260307a 100644 --- a/src/org/apollo/game/sync/block/InteractingMobBlock.java +++ b/src/org/apollo/game/sync/block/InteractingMobBlock.java @@ -7,27 +7,27 @@ package org.apollo.game.sync.block; */ public final class InteractingMobBlock extends SynchronizationBlock { - /** - * The index of the mob. - */ - private final int mobIndex; + /** + * The index of the mob. + */ + private final int mobIndex; - /** - * Creates the interacting mob block. - * - * @param mobIndex The index of the current interacting mob. - */ - InteractingMobBlock(int mobIndex) { - this.mobIndex = mobIndex; - } + /** + * Creates the interacting mob block. + * + * @param mobIndex The index of the current interacting mob. + */ + InteractingMobBlock(int mobIndex) { + this.mobIndex = mobIndex; + } - /** - * Gets the interacting mob's index. - * - * @return The index. - */ - public int getInteractingMobIndex() { - return mobIndex; - } + /** + * Gets the interacting mob's index. + * + * @return The index. + */ + public int getInteractingMobIndex() { + return mobIndex; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/SecondaryHitUpdateBlock.java b/src/org/apollo/game/sync/block/SecondaryHitUpdateBlock.java index 21e66686..6d353581 100644 --- a/src/org/apollo/game/sync/block/SecondaryHitUpdateBlock.java +++ b/src/org/apollo/game/sync/block/SecondaryHitUpdateBlock.java @@ -8,75 +8,75 @@ package org.apollo.game.sync.block; */ public final class SecondaryHitUpdateBlock extends SynchronizationBlock { - /** - * The mob's current health. - */ - private final int currentHealth; + /** + * The mob's current health. + */ + private final int currentHealth; - /** - * The amount of damage the hit will do. - */ - private final int damage; + /** + * The amount of damage the hit will do. + */ + private final int damage; - /** - * The mob's maximum health. - */ - private final int maximumHealth; + /** + * The mob's maximum health. + */ + private final int maximumHealth; - /** - * The type of hit (e.g. normal, poison). - */ - private final int type; + /** + * The type of hit (e.g. normal, poison). + */ + private final int type; - /** - * Creates a new secondary hit update block. - * - * @param damage The damage dealt by the hit. - * @param type The type of hit. - * @param currentHealth The current health of the mob. - * @param maximumHealth The maximum health of the mob. - */ - SecondaryHitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth) { - this.damage = damage; - this.type = type; - this.currentHealth = currentHealth; - this.maximumHealth = maximumHealth; - } + /** + * Creates a new secondary hit update block. + * + * @param damage The damage dealt by the hit. + * @param type The type of hit. + * @param currentHealth The current health of the mob. + * @param maximumHealth The maximum health of the mob. + */ + SecondaryHitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth) { + this.damage = damage; + this.type = type; + this.currentHealth = currentHealth; + this.maximumHealth = maximumHealth; + } - /** - * Gets the current health of the mob. - * - * @return The current health; - */ - public int getCurrentHealth() { - return currentHealth; - } + /** + * Gets the current health of the mob. + * + * @return The current health; + */ + public int getCurrentHealth() { + return currentHealth; + } - /** - * Gets the damage done by the hit. - * - * @return The damage. - */ - public int getDamage() { - return damage; - } + /** + * Gets the damage done by the hit. + * + * @return The damage. + */ + public int getDamage() { + return damage; + } - /** - * Gets the maximum health of the mob. - * - * @return The maximum health. - */ - public int getMaximumHealth() { - return maximumHealth; - } + /** + * Gets the maximum health of the mob. + * + * @return The maximum health. + */ + public int getMaximumHealth() { + return maximumHealth; + } - /** - * Gets the hit type. - * - * @return The type. - */ - public int getType() { - return type; - } + /** + * Gets the hit type. + * + * @return The type. + */ + public int getType() { + return type; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/SynchronizationBlock.java b/src/org/apollo/game/sync/block/SynchronizationBlock.java index f4e4ff85..b8ed4998 100644 --- a/src/org/apollo/game/sync/block/SynchronizationBlock.java +++ b/src/org/apollo/game/sync/block/SynchronizationBlock.java @@ -17,119 +17,119 @@ import org.apollo.game.sync.seg.SynchronizationSegment; */ public abstract class SynchronizationBlock { - /** - * Creates an {@link AnimationBlock} with the specified animation. - * - * @param animation The animation. - * @return The animation block. - */ - public static SynchronizationBlock createAnimationBlock(Animation animation) { - return new AnimationBlock(animation); - } + /** + * Creates an {@link AnimationBlock} with the specified animation. + * + * @param animation The animation. + * @return The animation block. + */ + public static SynchronizationBlock createAnimationBlock(Animation animation) { + return new AnimationBlock(animation); + } - /** - * Creates an {@link AppearanceBlock} for the specified player. - * - * @param player The player. - * @return The appearance block. - */ - public static SynchronizationBlock createAppearanceBlock(Player player) { - return new AppearanceBlock(player.getEncodedName(), player.getAppearance(), player.getSkillSet() - .getCombatLevel(), 0, player.getEquipment(), player.getPrayerIcon(), player.isSkulled(), - player.getDefinition() == null ? -1 : player.getDefinition().getId()); - } + /** + * Creates an {@link AppearanceBlock} for the specified player. + * + * @param player The player. + * @return The appearance block. + */ + public static SynchronizationBlock createAppearanceBlock(Player player) { + return new AppearanceBlock(player.getEncodedName(), player.getAppearance(), player.getSkillSet() + .getCombatLevel(), 0, player.getEquipment(), player.getPrayerIcon(), player.isSkulled(), + player.getDefinition() == null ? -1 : player.getDefinition().getId()); + } - /** - * Creates a {@link ChatBlock} for the specified player. - * - * @param player The player. - * @param chatEvent The chat event. - * @return The chat block. - */ - public static SynchronizationBlock createChatBlock(Player player, ChatEvent chatEvent) { - return new ChatBlock(player.getPrivilegeLevel(), chatEvent); - } + /** + * Creates a {@link ChatBlock} for the specified player. + * + * @param player The player. + * @param chatEvent The chat event. + * @return The chat block. + */ + public static SynchronizationBlock createChatBlock(Player player, ChatEvent chatEvent) { + return new ChatBlock(player.getPrivilegeLevel(), chatEvent); + } - /** - * Creates a {@link ForceChatBlock} with the specified message. - * - * @param message The message. - * @return The force chat block. - */ - public static SynchronizationBlock createForceChatBlock(String message) { - return new ForceChatBlock(message); - } + /** + * Creates a {@link ForceChatBlock} with the specified message. + * + * @param message The message. + * @return The force chat block. + */ + public static SynchronizationBlock createForceChatBlock(String message) { + return new ForceChatBlock(message); + } - /** - * Creates a {@link ForceMovement} block with the specified parameters. - * - * @param initialPosition The initial {@link Position} of the player. - * @param finalPosition The final position of the player - * @param travelDurationX The length of time (in game pulses) the player's movement along the X axis will last. - * @param travelDurationY The length of time (in game pulses) the player's movement along the Y axis will last. - * @param direction The {@link Direction} the player should move. - * @return The force movement block. - */ - public static SynchronizationBlock createForceMovementBlock(Position initialPosition, Position finalPosition, - int travelDurationX, int travelDurationY, Direction direction) { - return new ForceMovementBlock(initialPosition, finalPosition, travelDurationX, travelDurationY, direction); - } + /** + * Creates a {@link ForceMovement} block with the specified parameters. + * + * @param initialPosition The initial {@link Position} of the player. + * @param finalPosition The final position of the player + * @param travelDurationX The length of time (in game pulses) the player's movement along the X axis will last. + * @param travelDurationY The length of time (in game pulses) the player's movement along the Y axis will last. + * @param direction The {@link Direction} the player should move. + * @return The force movement block. + */ + public static SynchronizationBlock createForceMovementBlock(Position initialPosition, Position finalPosition, + int travelDurationX, int travelDurationY, Direction direction) { + return new ForceMovementBlock(initialPosition, finalPosition, travelDurationX, travelDurationY, direction); + } - /** - * Creates a {@link GraphicBlock} with the specified graphic. - * - * @param graphic The graphic. - * @return The graphic block. - */ - public static SynchronizationBlock createGraphicBlock(Graphic graphic) { - return new GraphicBlock(graphic); - } + /** + * Creates a {@link GraphicBlock} with the specified graphic. + * + * @param graphic The graphic. + * @return The graphic block. + */ + public static SynchronizationBlock createGraphicBlock(Graphic graphic) { + return new GraphicBlock(graphic); + } - /** - * Creates a {@link HitUpdateBlock} or {@link SecondaryHitUpdateBlock}, depending on the value of the - * {@code secondary} flag. - * - * @param damage The damage dealt by the hit. - * @param type The type of hit. - * @param currentHealth The current health of the mob. - * @param maximumHealth The maximum health of the mob. - * @param secondary If the block is a secondary hit or not. - * @return The hit update block. - */ - public static SynchronizationBlock createHitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth, - boolean secondary) { - return secondary ? new SecondaryHitUpdateBlock(damage, type, currentHealth, maximumHealth) - : new HitUpdateBlock(damage, type, currentHealth, maximumHealth); - } + /** + * Creates a {@link HitUpdateBlock} or {@link SecondaryHitUpdateBlock}, depending on the value of the + * {@code secondary} flag. + * + * @param damage The damage dealt by the hit. + * @param type The type of hit. + * @param currentHealth The current health of the mob. + * @param maximumHealth The maximum health of the mob. + * @param secondary If the block is a secondary hit or not. + * @return The hit update block. + */ + public static SynchronizationBlock createHitUpdateBlock(int damage, int type, int currentHealth, int maximumHealth, + boolean secondary) { + return secondary ? new SecondaryHitUpdateBlock(damage, type, currentHealth, maximumHealth) + : new HitUpdateBlock(damage, type, currentHealth, maximumHealth); + } - /** - * Creates an {@link InteractingMobBlock} with the specified index. - * - * @param index The index of the mob being interacted with. - * @return The interacting mob block. - */ - public static SynchronizationBlock createInteractingMobBlock(int index) { - return new InteractingMobBlock(index); - } + /** + * Creates an {@link InteractingMobBlock} with the specified index. + * + * @param index The index of the mob being interacted with. + * @return The interacting mob block. + */ + public static SynchronizationBlock createInteractingMobBlock(int index) { + return new InteractingMobBlock(index); + } - /** - * Creates a {@link TransformBlock} with the specified id. - * - * @param id The id. - * @return The transform block. - */ - public static SynchronizationBlock createTransformBlock(int id) { - return new TransformBlock(id); - } + /** + * Creates a {@link TransformBlock} with the specified id. + * + * @param id The id. + * @return The transform block. + */ + public static SynchronizationBlock createTransformBlock(int id) { + return new TransformBlock(id); + } - /** - * Creates a {@link TurnToPositionBlock} with the specified {@link Position}. - * - * @param position The position. - * @return The turn to position block. - */ - public static SynchronizationBlock createTurnToPositionBlock(Position position) { - return new TurnToPositionBlock(position); - } + /** + * Creates a {@link TurnToPositionBlock} with the specified {@link Position}. + * + * @param position The position. + * @return The turn to position block. + */ + public static SynchronizationBlock createTurnToPositionBlock(Position position) { + return new TurnToPositionBlock(position); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/SynchronizationBlockSet.java b/src/org/apollo/game/sync/block/SynchronizationBlockSet.java index a5ff0510..3b8e9e2d 100644 --- a/src/org/apollo/game/sync/block/SynchronizationBlockSet.java +++ b/src/org/apollo/game/sync/block/SynchronizationBlockSet.java @@ -10,74 +10,74 @@ import java.util.Map; */ public final class SynchronizationBlockSet implements Cloneable { - /** - * A {@link Map} of {@link SynchronizationBlock}s. - */ - private final Map, SynchronizationBlock> blocks = new HashMap<>(); + /** + * A {@link Map} of {@link SynchronizationBlock}s. + */ + private final Map, SynchronizationBlock> blocks = new HashMap<>(); - /** - * Adds a {@link SynchronizationBlock}. - * - * @param block The block to add. - */ - public void add(SynchronizationBlock block) { - Class clazz = block.getClass(); - blocks.put(clazz, block); - } + /** + * Adds a {@link SynchronizationBlock}. + * + * @param block The block to add. + */ + public void add(SynchronizationBlock block) { + Class clazz = block.getClass(); + blocks.put(clazz, block); + } - /** - * Clears the set. - */ - public void clear() { - blocks.clear(); - } + /** + * Clears the set. + */ + public void clear() { + blocks.clear(); + } - @Override - public SynchronizationBlockSet clone() { - SynchronizationBlockSet copy = new SynchronizationBlockSet(); - copy.blocks.putAll(blocks); - return copy; - } + @Override + public SynchronizationBlockSet clone() { + SynchronizationBlockSet copy = new SynchronizationBlockSet(); + copy.blocks.putAll(blocks); + return copy; + } - /** - * Checks if this set contains the specified {@link SynchronizationBlock}. - * - * @param clazz The block's class. - * @return {@code true} if so, {@code false} if not. - */ - public boolean contains(Class clazz) { - return blocks.containsKey(clazz); - } + /** + * Checks if this set contains the specified {@link SynchronizationBlock}. + * + * @param clazz The block's class. + * @return {@code true} if so, {@code false} if not. + */ + public boolean contains(Class clazz) { + return blocks.containsKey(clazz); + } - /** - * Gets a {@link SynchronizationBlock} from this set. - * - * @param The type of block. - * @param clazz The block's class. - * @return The block. - */ - @SuppressWarnings("unchecked") - public T get(Class clazz) { - return (T) blocks.get(clazz); - } + /** + * Gets a {@link SynchronizationBlock} from this set. + * + * @param The type of block. + * @param clazz The block's class. + * @return The block. + */ + @SuppressWarnings("unchecked") + public T get(Class clazz) { + return (T) blocks.get(clazz); + } - /** - * Removes a {@link SynchronizationBlock} from this set. - * - * @param clazz The block's class. - */ - @SuppressWarnings("unchecked") - public T remove(Class clazz) { - return (T) blocks.remove(clazz); - } + /** + * Removes a {@link SynchronizationBlock} from this set. + * + * @param clazz The block's class. + */ + @SuppressWarnings("unchecked") + public T remove(Class clazz) { + return (T) blocks.remove(clazz); + } - /** - * Gets the size of this set. - * - * @return The size. - */ - public int size() { - return blocks.size(); - } + /** + * Gets the size of this set. + * + * @return The size. + */ + public int size() { + return blocks.size(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/TransformBlock.java b/src/org/apollo/game/sync/block/TransformBlock.java index c0082594..4ed5caad 100644 --- a/src/org/apollo/game/sync/block/TransformBlock.java +++ b/src/org/apollo/game/sync/block/TransformBlock.java @@ -7,27 +7,27 @@ package org.apollo.game.sync.block; */ public final class TransformBlock extends SynchronizationBlock { - /** - * The id to transform to. - */ - private final int id; + /** + * The id to transform to. + */ + private final int id; - /** - * Creates a new transform block. - * - * @param id The id. - */ - TransformBlock(int id) { - this.id = id; - } + /** + * Creates a new transform block. + * + * @param id The id. + */ + TransformBlock(int id) { + this.id = id; + } - /** - * Gets the id of the npc to transform into. - * - * @return The id. - */ - public int getId() { - return id; - } + /** + * Gets the id of the npc to transform into. + * + * @return The id. + */ + public int getId() { + return id; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/block/TurnToPositionBlock.java b/src/org/apollo/game/sync/block/TurnToPositionBlock.java index ad9af989..a02198a9 100644 --- a/src/org/apollo/game/sync/block/TurnToPositionBlock.java +++ b/src/org/apollo/game/sync/block/TurnToPositionBlock.java @@ -9,27 +9,27 @@ import org.apollo.game.model.Position; */ public final class TurnToPositionBlock extends SynchronizationBlock { - /** - * The position to turn to. - */ - private final Position position; + /** + * The position to turn to. + */ + private final Position position; - /** - * Creates the turn to position block. - * - * @param position The position to turn to. - */ - TurnToPositionBlock(Position position) { - this.position = position; - } + /** + * Creates the turn to position block. + * + * @param position The position to turn to. + */ + TurnToPositionBlock(Position position) { + this.position = position; + } - /** - * Gets the {@link Position} to turn to. - * - * @return The position to turn to. - */ - public Position getPosition() { - return position; - } + /** + * Gets the {@link Position} to turn to. + * + * @return The position to turn to. + */ + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/AddNpcSegment.java b/src/org/apollo/game/sync/seg/AddNpcSegment.java index 18527207..3bc21506 100644 --- a/src/org/apollo/game/sync/seg/AddNpcSegment.java +++ b/src/org/apollo/game/sync/seg/AddNpcSegment.java @@ -10,66 +10,66 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public final class AddNpcSegment extends SynchronizationSegment { - /** - * The index. - */ - private final int index; + /** + * The index. + */ + private final int index; - /** - * The id of the npc. - */ - private final int npcId; + /** + * The id of the npc. + */ + private final int npcId; - /** - * The position. - */ - private final Position position; + /** + * The position. + */ + private final Position position; - /** - * Creates the add npc segment. - * - * @param blockSet The block set. - * @param index The npcs's index. - * @param position The position. - * @param npcId The id of the npc. - */ - public AddNpcSegment(SynchronizationBlockSet blockSet, int index, Position position, int npcId) { - super(blockSet); - this.index = index; - this.position = position; - this.npcId = npcId; - } + /** + * Creates the add npc segment. + * + * @param blockSet The block set. + * @param index The npcs's index. + * @param position The position. + * @param npcId The id of the npc. + */ + public AddNpcSegment(SynchronizationBlockSet blockSet, int index, Position position, int npcId) { + super(blockSet); + this.index = index; + this.position = position; + this.npcId = npcId; + } - /** - * Gets the npc's index. - * - * @return The index. - */ - public int getIndex() { - return index; - } + /** + * Gets the npc's index. + * + * @return The index. + */ + public int getIndex() { + return index; + } - /** - * Gets the npc id. - * - * @return The npcId - */ - public int getNpcId() { - return npcId; - } + /** + * Gets the npc id. + * + * @return The npcId + */ + public int getNpcId() { + return npcId; + } - /** - * Gets the position. - * - * @return The position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position. + * + * @return The position. + */ + public Position getPosition() { + return position; + } - @Override - public SegmentType getType() { - return SegmentType.ADD_MOB; - } + @Override + public SegmentType getType() { + return SegmentType.ADD_MOB; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/AddPlayerSegment.java b/src/org/apollo/game/sync/seg/AddPlayerSegment.java index 69f7d4f9..23e944d4 100644 --- a/src/org/apollo/game/sync/seg/AddPlayerSegment.java +++ b/src/org/apollo/game/sync/seg/AddPlayerSegment.java @@ -10,50 +10,50 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public final class AddPlayerSegment extends SynchronizationSegment { - /** - * The index. - */ - private final int index; + /** + * The index. + */ + private final int index; - /** - * The position. - */ - private final Position position; + /** + * The position. + */ + private final Position position; - /** - * Creates the add player segment. - * - * @param blockSet The block set. - * @param index The player's index. - * @param position The position. - */ - public AddPlayerSegment(SynchronizationBlockSet blockSet, int index, Position position) { - super(blockSet); - this.index = index; - this.position = position; - } + /** + * Creates the add player segment. + * + * @param blockSet The block set. + * @param index The player's index. + * @param position The position. + */ + public AddPlayerSegment(SynchronizationBlockSet blockSet, int index, Position position) { + super(blockSet); + this.index = index; + this.position = position; + } - /** - * Gets the player's index. - * - * @return The index. - */ - public int getIndex() { - return index; - } + /** + * Gets the player's index. + * + * @return The index. + */ + public int getIndex() { + return index; + } - /** - * Gets the position. - * - * @return The position. - */ - public Position getPosition() { - return position; - } + /** + * Gets the position. + * + * @return The position. + */ + public Position getPosition() { + return position; + } - @Override - public SegmentType getType() { - return SegmentType.ADD_MOB; - } + @Override + public SegmentType getType() { + return SegmentType.ADD_MOB; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/MovementSegment.java b/src/org/apollo/game/sync/seg/MovementSegment.java index 50e60e7f..537f02b7 100644 --- a/src/org/apollo/game/sync/seg/MovementSegment.java +++ b/src/org/apollo/game/sync/seg/MovementSegment.java @@ -10,47 +10,47 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public final class MovementSegment extends SynchronizationSegment { - /** - * The directions. - */ - private final Direction[] directions; + /** + * The directions. + */ + private final Direction[] directions; - /** - * Creates the movement segment. - * - * @param blockSet The block set. - * @param directions The directions array. - * @throws IllegalArgumentException If there are not 0, 1 or 2 directions. - */ - public MovementSegment(SynchronizationBlockSet blockSet, Direction[] directions) { - super(blockSet); - if (directions.length < 0 || directions.length > 2) { - throw new IllegalArgumentException("Directions length must be between 0 and 2 inclusive."); - } - this.directions = directions; + /** + * Creates the movement segment. + * + * @param blockSet The block set. + * @param directions The directions array. + * @throws IllegalArgumentException If there are not 0, 1 or 2 directions. + */ + public MovementSegment(SynchronizationBlockSet blockSet, Direction[] directions) { + super(blockSet); + if (directions.length < 0 || directions.length > 2) { + throw new IllegalArgumentException("Directions length must be between 0 and 2 inclusive."); } + this.directions = directions; + } - /** - * Gets the directions. - * - * @return The directions. - */ - public Direction[] getDirections() { - return directions; - } + /** + * Gets the directions. + * + * @return The directions. + */ + public Direction[] getDirections() { + return directions; + } - @Override - public SegmentType getType() { - switch (directions.length) { - case 0: - return SegmentType.NO_MOVEMENT; - case 1: - return SegmentType.WALK; - case 2: - return SegmentType.RUN; - default: - throw new IllegalStateException("Direction type unsupported."); - } + @Override + public SegmentType getType() { + switch (directions.length) { + case 0: + return SegmentType.NO_MOVEMENT; + case 1: + return SegmentType.WALK; + case 2: + return SegmentType.RUN; + default: + throw new IllegalStateException("Direction type unsupported."); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/RemoveMobSegment.java b/src/org/apollo/game/sync/seg/RemoveMobSegment.java index 10b6fd08..743a1692 100644 --- a/src/org/apollo/game/sync/seg/RemoveMobSegment.java +++ b/src/org/apollo/game/sync/seg/RemoveMobSegment.java @@ -9,21 +9,21 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public final class RemoveMobSegment extends SynchronizationSegment { - /** - * An empty {@link SynchronizationBlockSet}. - */ - private static final SynchronizationBlockSet EMPTY_BLOCK_SET = new SynchronizationBlockSet(); + /** + * An empty {@link SynchronizationBlockSet}. + */ + private static final SynchronizationBlockSet EMPTY_BLOCK_SET = new SynchronizationBlockSet(); - /** - * Creates the remove mob segment. - */ - public RemoveMobSegment() { - super(EMPTY_BLOCK_SET); - } + /** + * Creates the remove mob segment. + */ + public RemoveMobSegment() { + super(EMPTY_BLOCK_SET); + } - @Override - public SegmentType getType() { - return SegmentType.REMOVE_MOB; - } + @Override + public SegmentType getType() { + return SegmentType.REMOVE_MOB; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/SegmentType.java b/src/org/apollo/game/sync/seg/SegmentType.java index 6e460092..87f3a39d 100644 --- a/src/org/apollo/game/sync/seg/SegmentType.java +++ b/src/org/apollo/game/sync/seg/SegmentType.java @@ -7,34 +7,34 @@ package org.apollo.game.sync.seg; */ public enum SegmentType { - /** - * A segment where the mob is added. - */ - ADD_MOB, + /** + * A segment where the mob is added. + */ + ADD_MOB, - /** - * A segment without any movement. - */ - NO_MOVEMENT, + /** + * A segment without any movement. + */ + NO_MOVEMENT, - /** - * A segment where the mob is removed. - */ - REMOVE_MOB, + /** + * A segment where the mob is removed. + */ + REMOVE_MOB, - /** - * A segment with movement in two directions. - */ - RUN, + /** + * A segment with movement in two directions. + */ + RUN, - /** - * A segment where the mob is teleported. - */ - TELEPORT, + /** + * A segment where the mob is teleported. + */ + TELEPORT, - /** - * A segment with movement in a single direction. - */ - WALK; + /** + * A segment with movement in a single direction. + */ + WALK; } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/SynchronizationSegment.java b/src/org/apollo/game/sync/seg/SynchronizationSegment.java index afc60efd..40825fd8 100644 --- a/src/org/apollo/game/sync/seg/SynchronizationSegment.java +++ b/src/org/apollo/game/sync/seg/SynchronizationSegment.java @@ -13,34 +13,34 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public abstract class SynchronizationSegment { - /** - * The {@link SynchronizationBlockSet}. - */ - private final SynchronizationBlockSet blockSet; + /** + * The {@link SynchronizationBlockSet}. + */ + private final SynchronizationBlockSet blockSet; - /** - * Creates the segment. - * - * @param blockSet The block set. - */ - public SynchronizationSegment(SynchronizationBlockSet blockSet) { - this.blockSet = blockSet; - } + /** + * Creates the segment. + * + * @param blockSet The block set. + */ + public SynchronizationSegment(SynchronizationBlockSet blockSet) { + this.blockSet = blockSet; + } - /** - * Gets the block set. - * - * @return The block set. - */ - public final SynchronizationBlockSet getBlockSet() { - return blockSet; - } + /** + * Gets the block set. + * + * @return The block set. + */ + public final SynchronizationBlockSet getBlockSet() { + return blockSet; + } - /** - * Gets the type of segment. - * - * @return The type of segment. - */ - public abstract SegmentType getType(); + /** + * Gets the type of segment. + * + * @return The type of segment. + */ + public abstract SegmentType getType(); } \ No newline at end of file diff --git a/src/org/apollo/game/sync/seg/TeleportSegment.java b/src/org/apollo/game/sync/seg/TeleportSegment.java index f607d2e6..5956ceba 100644 --- a/src/org/apollo/game/sync/seg/TeleportSegment.java +++ b/src/org/apollo/game/sync/seg/TeleportSegment.java @@ -10,34 +10,34 @@ import org.apollo.game.sync.block.SynchronizationBlockSet; */ public final class TeleportSegment extends SynchronizationSegment { - /** - * The destination. - */ - private final Position destination; + /** + * The destination. + */ + private final Position destination; - /** - * Creates the teleport segment. - * - * @param blockSet The block set. - * @param destination The destination. - */ - public TeleportSegment(SynchronizationBlockSet blockSet, Position destination) { - super(blockSet); - this.destination = destination; - } + /** + * Creates the teleport segment. + * + * @param blockSet The block set. + * @param destination The destination. + */ + public TeleportSegment(SynchronizationBlockSet blockSet, Position destination) { + super(blockSet); + this.destination = destination; + } - /** - * Gets the destination. - * - * @return The destination. - */ - public Position getDestination() { - return destination; - } + /** + * Gets the destination. + * + * @return The destination. + */ + public Position getDestination() { + return destination; + } - @Override - public SegmentType getType() { - return SegmentType.TELEPORT; - } + @Override + public SegmentType getType() { + return SegmentType.TELEPORT; + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/NpcSynchronizationTask.java b/src/org/apollo/game/sync/task/NpcSynchronizationTask.java index c19b8e60..b447e0f1 100644 --- a/src/org/apollo/game/sync/task/NpcSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/NpcSynchronizationTask.java @@ -21,65 +21,65 @@ import org.apollo.game.sync.seg.SynchronizationSegment; */ public final class NpcSynchronizationTask extends SynchronizationTask { - /** - * The maximum number of npcs to load per cycle. This prevents the update packet from becoming too large (the client - * uses a 5000 byte buffer) and also stops old spec PCs from crashing when they login or teleport. - */ - private static final int NEW_NPCS_PER_CYCLE = 20; + /** + * The maximum number of npcs to load per cycle. This prevents the update packet from becoming too large (the client + * uses a 5000 byte buffer) and also stops old spec PCs from crashing when they login or teleport. + */ + private static final int NEW_NPCS_PER_CYCLE = 20; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the {@link NpcSynchronizationTask} for the specified player. - * - * @param player The player. - */ - public NpcSynchronizationTask(Player player) { - this.player = player; + /** + * Creates the {@link NpcSynchronizationTask} for the specified player. + * + * @param player The player. + */ + public NpcSynchronizationTask(Player player) { + this.player = player; + } + + @Override + public void run() { + List localNpcs = player.getLocalNpcList(); + List segments = new ArrayList<>(); + int oldLocalNpcs = localNpcs.size(); + final Position playerPosition = player.getPosition(); + + for (Iterator it = localNpcs.iterator(); it.hasNext();) { + Npc npc = it.next(); + if (!npc.isActive() || npc.isTeleporting() + || npc.getPosition().getLongestDelta(playerPosition) > player.getViewingDistance()) { + it.remove(); + segments.add(new RemoveMobSegment()); + } else { + segments.add(new MovementSegment(npc.getBlockSet(), npc.getDirections())); + } } - @Override - public void run() { - List localNpcs = player.getLocalNpcList(); - List segments = new ArrayList<>(); - int oldLocalNpcs = localNpcs.size(); - final Position playerPosition = player.getPosition(); + int added = 0; - for (Iterator it = localNpcs.iterator(); it.hasNext();) { - Npc npc = it.next(); - if (!npc.isActive() || npc.isTeleporting() - || npc.getPosition().getLongestDelta(playerPosition) > player.getViewingDistance()) { - it.remove(); - segments.add(new RemoveMobSegment()); - } else { - segments.add(new MovementSegment(npc.getBlockSet(), npc.getDirections())); - } - } + for (Npc npc : World.getWorld().getNpcRepository()) { + if (localNpcs.size() >= 255) { + player.flagExcessiveNpcs(); + break; + } else if (added >= NEW_NPCS_PER_CYCLE) { + break; + } - int added = 0; - - for (Npc npc : World.getWorld().getNpcRepository()) { - if (localNpcs.size() >= 255) { - player.flagExcessiveNpcs(); - break; - } else if (added >= NEW_NPCS_PER_CYCLE) { - break; - } - - Position npcPosition = npc.getPosition(); - if (npcPosition.isWithinDistance(playerPosition, player.getViewingDistance()) && !localNpcs.contains(npc) - && npcPosition.getHeight() == playerPosition.getHeight()) { - localNpcs.add(npc); - added++; - npc.turnTo(npc.getFacingPosition()); - segments.add(new AddNpcSegment(npc.getBlockSet(), npc.getIndex(), npcPosition, npc.getId())); - } - } - - player.send(new NpcSynchronizationEvent(playerPosition, segments, oldLocalNpcs)); + Position npcPosition = npc.getPosition(); + if (npcPosition.isWithinDistance(playerPosition, player.getViewingDistance()) && !localNpcs.contains(npc) + && npcPosition.getHeight() == playerPosition.getHeight()) { + localNpcs.add(npc); + added++; + npc.turnTo(npc.getFacingPosition()); + segments.add(new AddNpcSegment(npc.getBlockSet(), npc.getIndex(), npcPosition, npc.getId())); + } } + player.send(new NpcSynchronizationEvent(playerPosition, segments, oldLocalNpcs)); + } + } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PhasedSynchronizationTask.java b/src/org/apollo/game/sync/task/PhasedSynchronizationTask.java index 31ae0c61..1a49bc31 100644 --- a/src/org/apollo/game/sync/task/PhasedSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PhasedSynchronizationTask.java @@ -13,34 +13,34 @@ import java.util.concurrent.Phaser; */ public final class PhasedSynchronizationTask extends SynchronizationTask { - /** - * The phaser. - */ - private final Phaser phaser; + /** + * The phaser. + */ + private final Phaser phaser; - /** - * The task. - */ - private final SynchronizationTask task; + /** + * The task. + */ + private final SynchronizationTask task; - /** - * Creates the phased synchronization task. - * - * @param phaser The phaser. - * @param task The task. - */ - public PhasedSynchronizationTask(Phaser phaser, SynchronizationTask task) { - this.phaser = phaser; - this.task = task; - } - - @Override - public void run() { - try { - task.run(); - } finally { - phaser.arriveAndDeregister(); - } + /** + * Creates the phased synchronization task. + * + * @param phaser The phaser. + * @param task The task. + */ + public PhasedSynchronizationTask(Phaser phaser, SynchronizationTask task) { + this.phaser = phaser; + this.task = task; + } + + @Override + public void run() { + try { + task.run(); + } finally { + phaser.arriveAndDeregister(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PlayerSynchronizationTask.java b/src/org/apollo/game/sync/task/PlayerSynchronizationTask.java index 46d637d0..5d09d0e5 100644 --- a/src/org/apollo/game/sync/task/PlayerSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PlayerSynchronizationTask.java @@ -26,90 +26,90 @@ import org.apollo.util.MobRepository; */ public final class PlayerSynchronizationTask extends SynchronizationTask { - /** - * The maximum number of players to load per cycle. This prevents the update packet from becoming too large (the - * client uses a 5000 byte buffer) and also stops old spec PCs from crashing when they login or teleport. - */ - private static final int NEW_PLAYERS_PER_CYCLE = 20; + /** + * The maximum number of players to load per cycle. This prevents the update packet from becoming too large (the + * client uses a 5000 byte buffer) and also stops old spec PCs from crashing when they login or teleport. + */ + private static final int NEW_PLAYERS_PER_CYCLE = 20; - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the {@link PlayerSynchronizationTask} for the specified player. - * - * @param player The player. - */ - public PlayerSynchronizationTask(Player player) { - this.player = player; + /** + * Creates the {@link PlayerSynchronizationTask} for the specified player. + * + * @param player The player. + */ + public PlayerSynchronizationTask(Player player) { + this.player = player; + } + + @Override + public void run() { + Position lastKnownRegion = player.getLastKnownRegion(); + boolean regionChanged = player.hasRegionChanged(); + + SynchronizationSegment segment; + SynchronizationBlockSet blockSet = player.getBlockSet(); + if (blockSet.contains(ChatBlock.class)) { + blockSet = blockSet.clone(); + blockSet.remove(ChatBlock.class); } - @Override - public void run() { - Position lastKnownRegion = player.getLastKnownRegion(); - boolean regionChanged = player.hasRegionChanged(); - - SynchronizationSegment segment; - SynchronizationBlockSet blockSet = player.getBlockSet(); - if (blockSet.contains(ChatBlock.class)) { - blockSet = blockSet.clone(); - blockSet.remove(ChatBlock.class); - } - - if (player.isTeleporting() || player.hasRegionChanged()) { - segment = new TeleportSegment(blockSet, player.getPosition()); - } else { - segment = new MovementSegment(blockSet, player.getDirections()); - } - - List localPlayers = player.getLocalPlayerList(); - int oldLocalPlayers = localPlayers.size(); - List segments = new ArrayList(); - - for (Iterator it = localPlayers.iterator(); it.hasNext();) { - Player p = it.next(); - if (!p.isActive() || p.isTeleporting() - || p.getPosition().getLongestDelta(player.getPosition()) > player.getViewingDistance()) { - it.remove(); - segments.add(new RemoveMobSegment()); - } else { - segments.add(new MovementSegment(p.getBlockSet(), p.getDirections())); - } - } - - int added = 0; - - MobRepository repository = World.getWorld().getPlayerRepository(); - for (Iterator it = repository.iterator(); it.hasNext();) { - Player p = it.next(); - if (localPlayers.size() >= 255) { - player.flagExcessivePlayers(); - break; - } else if (added >= NEW_PLAYERS_PER_CYCLE) { - break; - } - - if (p != player && p.getPosition().isWithinDistance(player.getPosition(), player.getViewingDistance()) - && !localPlayers.contains(p)) { - localPlayers.add(p); - added++; - - blockSet = p.getBlockSet(); - if (!blockSet.contains(AppearanceBlock.class)) { - // TODO check if client has cached appearance - blockSet = blockSet.clone(); - blockSet.add(SynchronizationBlock.createAppearanceBlock(p)); - } - - segments.add(new AddPlayerSegment(blockSet, p.getIndex(), p.getPosition())); - } - } - - PlayerSynchronizationEvent event = new PlayerSynchronizationEvent(lastKnownRegion, player.getPosition(), - regionChanged, segment, oldLocalPlayers, segments); - player.send(event); + if (player.isTeleporting() || player.hasRegionChanged()) { + segment = new TeleportSegment(blockSet, player.getPosition()); + } else { + segment = new MovementSegment(blockSet, player.getDirections()); } + List localPlayers = player.getLocalPlayerList(); + int oldLocalPlayers = localPlayers.size(); + List segments = new ArrayList<>(); + + for (Iterator it = localPlayers.iterator(); it.hasNext();) { + Player p = it.next(); + if (!p.isActive() || p.isTeleporting() + || p.getPosition().getLongestDelta(player.getPosition()) > player.getViewingDistance()) { + it.remove(); + segments.add(new RemoveMobSegment()); + } else { + segments.add(new MovementSegment(p.getBlockSet(), p.getDirections())); + } + } + + int added = 0; + + MobRepository repository = World.getWorld().getPlayerRepository(); + for (Iterator it = repository.iterator(); it.hasNext();) { + Player p = it.next(); + if (localPlayers.size() >= 255) { + player.flagExcessivePlayers(); + break; + } else if (added >= NEW_PLAYERS_PER_CYCLE) { + break; + } + + if (p != player && p.getPosition().isWithinDistance(player.getPosition(), player.getViewingDistance()) + && !localPlayers.contains(p)) { + localPlayers.add(p); + added++; + + blockSet = p.getBlockSet(); + if (!blockSet.contains(AppearanceBlock.class)) { + // TODO check if client has cached appearance + blockSet = blockSet.clone(); + blockSet.add(SynchronizationBlock.createAppearanceBlock(p)); + } + + segments.add(new AddPlayerSegment(blockSet, p.getIndex(), p.getPosition())); + } + } + + PlayerSynchronizationEvent event = new PlayerSynchronizationEvent(lastKnownRegion, player.getPosition(), + regionChanged, segment, oldLocalPlayers, segments); + player.send(event); + } + } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PostNpcSynchronizationTask.java b/src/org/apollo/game/sync/task/PostNpcSynchronizationTask.java index 172ffba0..9b0b9839 100644 --- a/src/org/apollo/game/sync/task/PostNpcSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PostNpcSynchronizationTask.java @@ -9,24 +9,24 @@ import org.apollo.game.model.entity.Npc; */ public final class PostNpcSynchronizationTask extends SynchronizationTask { - /** - * The npc. - */ - private final Npc npc; + /** + * The npc. + */ + private final Npc npc; - /** - * Creates the {@link PostNpcSynchronizationTask} for the specified player. - * - * @param npc The npc. - */ - public PostNpcSynchronizationTask(Npc npc) { - this.npc = npc; - } + /** + * Creates the {@link PostNpcSynchronizationTask} for the specified player. + * + * @param npc The npc. + */ + public PostNpcSynchronizationTask(Npc npc) { + this.npc = npc; + } - @Override - public void run() { - npc.setTeleporting(false); - npc.resetBlockSet(); - } + @Override + public void run() { + npc.setTeleporting(false); + npc.resetBlockSet(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PostPlayerSynchronizationTask.java b/src/org/apollo/game/sync/task/PostPlayerSynchronizationTask.java index 5864311c..b3b73d1e 100644 --- a/src/org/apollo/game/sync/task/PostPlayerSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PostPlayerSynchronizationTask.java @@ -9,31 +9,31 @@ import org.apollo.game.model.entity.Player; */ public final class PostPlayerSynchronizationTask extends SynchronizationTask { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the {@link PostPlayerSynchronizationTask} for the specified player. - * - * @param player The player. - */ - public PostPlayerSynchronizationTask(Player player) { - this.player = player; - } + /** + * Creates the {@link PostPlayerSynchronizationTask} for the specified player. + * + * @param player The player. + */ + public PostPlayerSynchronizationTask(Player player) { + this.player = player; + } - @Override - public void run() { - player.setTeleporting(false); - player.setRegionChanged(false); - player.resetBlockSet(); - if (!player.isExcessivePlayersSet()) { - player.incrementViewingDistance(); - } else { - player.decrementViewingDistance(); - player.resetExcessivePlayers(); - } + @Override + public void run() { + player.setTeleporting(false); + player.setRegionChanged(false); + player.resetBlockSet(); + if (!player.isExcessivePlayersSet()) { + player.incrementViewingDistance(); + } else { + player.decrementViewingDistance(); + player.resetExcessivePlayers(); } + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PreNpcSynchronizationTask.java b/src/org/apollo/game/sync/task/PreNpcSynchronizationTask.java index 28870d99..8469e9ad 100644 --- a/src/org/apollo/game/sync/task/PreNpcSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PreNpcSynchronizationTask.java @@ -9,23 +9,23 @@ import org.apollo.game.model.entity.Npc; */ public final class PreNpcSynchronizationTask extends SynchronizationTask { - /** - * The npc. - */ - private final Npc npc; + /** + * The npc. + */ + private final Npc npc; - /** - * Creates the {@link PreNpcSynchronizationTask} for the specified npc. - * - * @param npc The npc. - */ - public PreNpcSynchronizationTask(Npc npc) { - this.npc = npc; - } + /** + * Creates the {@link PreNpcSynchronizationTask} for the specified npc. + * + * @param npc The npc. + */ + public PreNpcSynchronizationTask(Npc npc) { + this.npc = npc; + } - @Override - public void run() { - npc.getWalkingQueue().pulse(); - } + @Override + public void run() { + npc.getWalkingQueue().pulse(); + } } \ No newline at end of file diff --git a/src/org/apollo/game/sync/task/PrePlayerSynchronizationTask.java b/src/org/apollo/game/sync/task/PrePlayerSynchronizationTask.java index bbd14280..5ab6bf09 100644 --- a/src/org/apollo/game/sync/task/PrePlayerSynchronizationTask.java +++ b/src/org/apollo/game/sync/task/PrePlayerSynchronizationTask.java @@ -11,51 +11,51 @@ import org.apollo.game.model.entity.Player; */ public final class PrePlayerSynchronizationTask extends SynchronizationTask { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates the {@link PrePlayerSynchronizationTask} for the specified player. - * - * @param player The player. - */ - public PrePlayerSynchronizationTask(Player player) { - this.player = player; + /** + * Creates the {@link PrePlayerSynchronizationTask} for the specified player. + * + * @param player The player. + */ + public PrePlayerSynchronizationTask(Player player) { + this.player = player; + } + + /** + * Checks if a region update is required. + * + * @return {@code true} if so, {@code false} otherwise. + */ + private boolean isRegionUpdateRequired() { + Position current = player.getPosition(); + Position last = player.getLastKnownRegion(); + + int deltaX = current.getLocalX(last); + int deltaY = current.getLocalY(last); + + return deltaX < 16 || deltaX >= 88 || deltaY < 16 || deltaY >= 88; + } + + @Override + public void run() { + player.getWalkingQueue().pulse(); + + if (player.isTeleporting()) { + player.resetViewingDistance(); } - /** - * Checks if a region update is required. - * - * @return {@code true} if so, {@code false} otherwise. - */ - private boolean isRegionUpdateRequired() { - Position current = player.getPosition(); - Position last = player.getLastKnownRegion(); + if (!player.hasLastKnownRegion() || isRegionUpdateRequired()) { + player.setRegionChanged(true); - int deltaX = current.getLocalX(last); - int deltaY = current.getLocalY(last); + Position position = player.getPosition(); + player.setLastKnownRegion(position); - return deltaX < 16 || deltaX >= 88 || deltaY < 16 || deltaY >= 88; - } - - @Override - public void run() { - player.getWalkingQueue().pulse(); - - if (player.isTeleporting()) { - player.resetViewingDistance(); - } - - if (!player.hasLastKnownRegion() || isRegionUpdateRequired()) { - player.setRegionChanged(true); - - Position position = player.getPosition(); - player.setLastKnownRegion(position); - - player.send(new RegionChangeEvent(position)); - } + player.send(new RegionChangeEvent(position)); } + } } \ No newline at end of file diff --git a/src/org/apollo/io/EquipmentDefinitionParser.java b/src/org/apollo/io/EquipmentDefinitionParser.java index e1f9333f..b9cef897 100644 --- a/src/org/apollo/io/EquipmentDefinitionParser.java +++ b/src/org/apollo/io/EquipmentDefinitionParser.java @@ -13,55 +13,55 @@ import org.apollo.game.model.def.EquipmentDefinition; */ public final class EquipmentDefinitionParser { - /** - * The input stream. - */ - private final InputStream is; + /** + * The input stream. + */ + private final InputStream is; - /** - * Creates the equipment definition parser. - * - * @param is The input stream. - */ - public EquipmentDefinitionParser(InputStream is) { - this.is = is; + /** + * Creates the equipment definition parser. + * + * @param is The input stream. + */ + public EquipmentDefinitionParser(InputStream is) { + this.is = is; + } + + /** + * Parses the input stream. + * + * @return The equipment definition array. + * @throws IOException If an I/O error occurs. + */ + public EquipmentDefinition[] parse() throws IOException { + DataInputStream dis = new DataInputStream(is); + + int count = dis.readShort() & 0xFFFF; + EquipmentDefinition[] definitions = new EquipmentDefinition[count]; + + for (int id = 0; id < count; id++) { + int slot = dis.readByte() & 0xFF; + if (slot != 0xFF) { + boolean twoHanded = dis.readBoolean(); + boolean fullBody = dis.readBoolean(); + boolean fullHat = dis.readBoolean(); + boolean fullMask = dis.readBoolean(); + int attack = dis.readByte() & 0xFF; + int strength = dis.readByte() & 0xFF; + int defence = dis.readByte() & 0xFF; + int ranged = dis.readByte() & 0xFF; + int magic = dis.readByte() & 0xFF; + + EquipmentDefinition definition = new EquipmentDefinition(id); + definition.setLevels(attack, strength, defence, ranged, magic); + definition.setSlot(slot); + definition.setFlags(twoHanded, fullBody, fullHat, fullMask); + + definitions[id] = definition; + } } - /** - * Parses the input stream. - * - * @return The equipment definition array. - * @throws IOException If an I/O error occurs. - */ - public EquipmentDefinition[] parse() throws IOException { - DataInputStream dis = new DataInputStream(is); - - int count = dis.readShort() & 0xFFFF; - EquipmentDefinition[] definitions = new EquipmentDefinition[count]; - - for (int id = 0; id < count; id++) { - int slot = dis.readByte() & 0xFF; - if (slot != 0xFF) { - boolean twoHanded = dis.readBoolean(); - boolean fullBody = dis.readBoolean(); - boolean fullHat = dis.readBoolean(); - boolean fullMask = dis.readBoolean(); - int attack = dis.readByte() & 0xFF; - int strength = dis.readByte() & 0xFF; - int defence = dis.readByte() & 0xFF; - int ranged = dis.readByte() & 0xFF; - int magic = dis.readByte() & 0xFF; - - EquipmentDefinition definition = new EquipmentDefinition(id); - definition.setLevels(attack, strength, defence, ranged, magic); - definition.setSlot(slot); - definition.setFlags(twoHanded, fullBody, fullHat, fullMask); - - definitions[id] = definition; - } - } - - return definitions; - } + return definitions; + } } \ No newline at end of file diff --git a/src/org/apollo/io/EventHandlerChainParser.java b/src/org/apollo/io/EventHandlerChainParser.java index 19da3c7a..fa36daf5 100644 --- a/src/org/apollo/io/EventHandlerChainParser.java +++ b/src/org/apollo/io/EventHandlerChainParser.java @@ -22,93 +22,93 @@ import org.xml.sax.SAXException; */ public final class EventHandlerChainParser { - /** - * The source {@link InputStream}. - */ - private final InputStream is; + /** + * The source {@link InputStream}. + */ + private final InputStream is; - /** - * The {@link XmlParser} instance. - */ - private final XmlParser parser; + /** + * The {@link XmlParser} instance. + */ + private final XmlParser parser; - /** - * Creates the event chain parser. - * - * @param is The source {@link InputStream}. - * @throws SAXException If a SAX error occurs. - */ - public EventHandlerChainParser(InputStream is) throws SAXException { - this.is = is; - parser = new XmlParser(); + /** + * Creates the event chain parser. + * + * @param is The source {@link InputStream}. + * @throws SAXException If a SAX error occurs. + */ + public EventHandlerChainParser(InputStream is) throws SAXException { + this.is = is; + parser = new XmlParser(); + } + + /** + * Parses the XML and produces a group of {@link EventHandlerChain}s. + * + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + * @throws ClassNotFoundException If a class was not found. + * @throws IllegalAccessException If a class was accessed illegally. + * @throws InstantiationException If a class could not be instantiated. + * @return An {@link EventHandlerChainGroup}. + */ + @SuppressWarnings("unchecked") + public EventHandlerChainGroup parse() throws IOException, SAXException, ClassNotFoundException, + InstantiationException, IllegalAccessException { + XmlNode rootNode = parser.parse(is); + if (!rootNode.getName().equals("events")) { + throw new IOException("Root node name is not 'events'."); } - /** - * Parses the XML and produces a group of {@link EventHandlerChain}s. - * - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - * @throws ClassNotFoundException If a class was not found. - * @throws IllegalAccessException If a class was accessed illegally. - * @throws InstantiationException If a class could not be instantiated. - * @return An {@link EventHandlerChainGroup}. - */ - @SuppressWarnings("unchecked") - public EventHandlerChainGroup parse() throws IOException, SAXException, ClassNotFoundException, - InstantiationException, IllegalAccessException { - XmlNode rootNode = parser.parse(is); - if (!rootNode.getName().equals("events")) { - throw new IOException("Root node name is not 'events'."); + Map, EventHandlerChain> chains = new HashMap, EventHandlerChain>(); + + for (XmlNode eventNode : rootNode) { + if (!eventNode.getName().equals("event")) { + throw new IOException("Only expected nodes named 'event' beneath the root node."); + } + + XmlNode typeNode = eventNode.getChild("type"); + if (typeNode == null) { + throw new IOException("No node named 'type' beneath current event node."); + } + XmlNode chainNode = eventNode.getChild("chain"); + if (chainNode == null) { + throw new IOException("No node named 'chain' beneath current event node."); + } + + String eventClassName = typeNode.getValue(); + if (eventClassName == null) { + throw new IOException("Type node must have a value."); + } + + Class eventClass = (Class) Class.forName(eventClassName); + List> handlers = new ArrayList>(); + + for (XmlNode handlerNode : chainNode) { + if (!handlerNode.getName().equals("handler")) { + throw new IOException("Only expected nodes named 'handler' beneath the root node."); } - Map, EventHandlerChain> chains = new HashMap, EventHandlerChain>(); - - for (XmlNode eventNode : rootNode) { - if (!eventNode.getName().equals("event")) { - throw new IOException("Only expected nodes named 'event' beneath the root node."); - } - - XmlNode typeNode = eventNode.getChild("type"); - if (typeNode == null) { - throw new IOException("No node named 'type' beneath current event node."); - } - XmlNode chainNode = eventNode.getChild("chain"); - if (chainNode == null) { - throw new IOException("No node named 'chain' beneath current event node."); - } - - String eventClassName = typeNode.getValue(); - if (eventClassName == null) { - throw new IOException("Type node must have a value."); - } - - Class eventClass = (Class) Class.forName(eventClassName); - List> handlers = new ArrayList>(); - - for (XmlNode handlerNode : chainNode) { - if (!handlerNode.getName().equals("handler")) { - throw new IOException("Only expected nodes named 'handler' beneath the root node."); - } - - String handlerClassName = handlerNode.getValue(); - if (handlerClassName == null) { - throw new IOException("Handler node must have a value."); - } - - Class> handlerClass = (Class>) Class - .forName(handlerClassName); - EventHandler handler = handlerClass.newInstance(); - handlers.add(handler); - } - - EventHandler[] handlersArray = handlers.toArray(new EventHandler[handlers.size()]); - @SuppressWarnings("rawtypes") - EventHandlerChain chain = new EventHandlerChain(handlersArray); - - chains.put(eventClass, chain); + String handlerClassName = handlerNode.getValue(); + if (handlerClassName == null) { + throw new IOException("Handler node must have a value."); } - return new EventHandlerChainGroup(chains); + Class> handlerClass = (Class>) Class + .forName(handlerClassName); + EventHandler handler = handlerClass.newInstance(); + handlers.add(handler); + } + + EventHandler[] handlersArray = handlers.toArray(new EventHandler[handlers.size()]); + @SuppressWarnings("rawtypes") + EventHandlerChain chain = new EventHandlerChain(handlersArray); + + chains.put(eventClass, chain); } + return new EventHandlerChainGroup(chains); + } + } \ No newline at end of file diff --git a/src/org/apollo/io/PluginMetaDataParser.java b/src/org/apollo/io/PluginMetaDataParser.java index 56e6c343..74f767be 100644 --- a/src/org/apollo/io/PluginMetaDataParser.java +++ b/src/org/apollo/io/PluginMetaDataParser.java @@ -16,109 +16,109 @@ import org.xml.sax.SAXException; */ public final class PluginMetaDataParser { - /** - * An empty xml node array. - */ - private static final XmlNode[] EMPTY_NODE_ARRAY = new XmlNode[0]; + /** + * An empty xml node array. + */ + private static final XmlNode[] EMPTY_NODE_ARRAY = new XmlNode[0]; - /** - * The input stream. - */ - private final InputStream is; + /** + * The input stream. + */ + private final InputStream is; - /** - * The XML parser. - */ - private final XmlParser parser; + /** + * The XML parser. + */ + private final XmlParser parser; - /** - * Creates the plugin meta data parser. - * - * @param is The input stream. - * @throws SAXException If a SAX error occurs. - */ - public PluginMetaDataParser(InputStream is) throws SAXException { - this.is = is; - parser = new XmlParser(); + /** + * Creates the plugin meta data parser. + * + * @param is The input stream. + * @throws SAXException If a SAX error occurs. + */ + public PluginMetaDataParser(InputStream is) throws SAXException { + this.is = is; + parser = new XmlParser(); + } + + /** + * Gets the specified child element, if it exists. + * + * @param node The root node. + * @param name The element name. + * @return The node object. + * @throws IOException If the element does not exist. + */ + private XmlNode getElement(XmlNode node, String name) throws IOException { + XmlNode child = node.getChild(name); + if (child == null) { + throw new IOException("No " + name + " element found."); + } + return child; + } + + /** + * Parses the XML and creates a meta data object. + * + * @param base The base path for this plugin + * @return The meta data object. + * @throws SAXException If a SAX error occurs. + * @throws IOException If an I/O error occurs. + */ + public PluginMetaData parse(File base) throws IOException, SAXException { + XmlNode rootNode = parser.parse(is); + if (!rootNode.getName().equals("plugin")) { + throw new IOException("Root node must be named plugin."); } - /** - * Gets the specified child element, if it exists. - * - * @param node The root node. - * @param name The element name. - * @return The node object. - * @throws IOException If the element does not exist. - */ - private XmlNode getElement(XmlNode node, String name) throws IOException { - XmlNode child = node.getChild(name); - if (child == null) { - throw new IOException("No " + name + " element found."); - } - return child; + XmlNode idNode = getElement(rootNode, "id"); + XmlNode nameNode = getElement(rootNode, "name"); + XmlNode descriptionNode = getElement(rootNode, "description"); + XmlNode authorsNode = getElement(rootNode, "authors"); + XmlNode scriptsNode = getElement(rootNode, "scripts"); + XmlNode dependenciesNode = getElement(rootNode, "dependencies"); + XmlNode versionNode = getElement(rootNode, "version"); + + String id = idNode.getValue(); + String name = nameNode.getValue(); + String description = descriptionNode.getValue(); + double version = Double.parseDouble(versionNode.getValue()); + + if (id == null || name == null || description == null) { + throw new IOException("Id, name and description must have values."); } - /** - * Parses the XML and creates a meta data object. - * - * @param base The base path for this plugin - * @return The meta data object. - * @throws SAXException If a SAX error occurs. - * @throws IOException If an I/O error occurs. - */ - public PluginMetaData parse(File base) throws IOException, SAXException { - XmlNode rootNode = parser.parse(is); - if (!rootNode.getName().equals("plugin")) { - throw new IOException("Root node must be named plugin."); - } + XmlNode[] authorNodes = authorsNode.getChildren().toArray(EMPTY_NODE_ARRAY); + XmlNode[] scriptNodes = scriptsNode.getChildren().toArray(EMPTY_NODE_ARRAY); + XmlNode[] dependencyNodes = dependenciesNode.getChildren().toArray(EMPTY_NODE_ARRAY); - XmlNode idNode = getElement(rootNode, "id"); - XmlNode nameNode = getElement(rootNode, "name"); - XmlNode descriptionNode = getElement(rootNode, "description"); - XmlNode authorsNode = getElement(rootNode, "authors"); - XmlNode scriptsNode = getElement(rootNode, "scripts"); - XmlNode dependenciesNode = getElement(rootNode, "dependencies"); - XmlNode versionNode = getElement(rootNode, "version"); + String[] authors = new String[authorNodes.length]; + String[] scripts = new String[scriptNodes.length]; + String[] dependencies = new String[dependencyNodes.length]; - String id = idNode.getValue(); - String name = nameNode.getValue(); - String description = descriptionNode.getValue(); - double version = Double.parseDouble(versionNode.getValue()); - - if (id == null || name == null || description == null) { - throw new IOException("Id, name and description must have values."); - } - - XmlNode[] authorNodes = authorsNode.getChildren().toArray(EMPTY_NODE_ARRAY); - XmlNode[] scriptNodes = scriptsNode.getChildren().toArray(EMPTY_NODE_ARRAY); - XmlNode[] dependencyNodes = dependenciesNode.getChildren().toArray(EMPTY_NODE_ARRAY); - - String[] authors = new String[authorNodes.length]; - String[] scripts = new String[scriptNodes.length]; - String[] dependencies = new String[dependencyNodes.length]; - - for (int i = 0; i < authorNodes.length; i++) { - authors[i] = authorNodes[i].getValue(); - if (authors[i] == null) { - throw new IOException("Author elements must have values."); - } - } - - for (int i = 0; i < scriptNodes.length; i++) { - scripts[i] = scriptNodes[i].getValue(); - if (scripts[i] == null) { - throw new IOException("Script elements must have values."); - } - } - - for (int i = 0; i < dependencyNodes.length; i++) { - dependencies[i] = dependencyNodes[i].getValue(); - if (dependencies[i] == null) { - throw new IOException("Dependency elements must have values."); - } - } - - return new PluginMetaData(id, base, name, description, authors, scripts, dependencies, version); + for (int i = 0; i < authorNodes.length; i++) { + authors[i] = authorNodes[i].getValue(); + if (authors[i] == null) { + throw new IOException("Author elements must have values."); + } } + for (int i = 0; i < scriptNodes.length; i++) { + scripts[i] = scriptNodes[i].getValue(); + if (scripts[i] == null) { + throw new IOException("Script elements must have values."); + } + } + + for (int i = 0; i < dependencyNodes.length; i++) { + dependencies[i] = dependencyNodes[i].getValue(); + if (dependencies[i] == null) { + throw new IOException("Dependency elements must have values."); + } + } + + return new PluginMetaData(id, base, name, description, authors, scripts, dependencies, version); + } + } \ No newline at end of file diff --git a/src/org/apollo/io/RsaKeyParser.java b/src/org/apollo/io/RsaKeyParser.java index 090ce913..129ea333 100644 --- a/src/org/apollo/io/RsaKeyParser.java +++ b/src/org/apollo/io/RsaKeyParser.java @@ -16,51 +16,51 @@ import org.xml.sax.SAXException; */ public final class RsaKeyParser { - /** - * The source {@link InputStream}. - */ - private final InputStream is; + /** + * The source {@link InputStream}. + */ + private final InputStream is; - /** - * The {@link XmlParser} instance. - */ - private final XmlParser parser; + /** + * The {@link XmlParser} instance. + */ + private final XmlParser parser; - /** - * Creates the RSA specification parser. - * - * @param is The source {@link InputStream}. - * @throws SAXException If a SAX error occurs. - */ - public RsaKeyParser(InputStream is) throws SAXException { - this.is = is; - parser = new XmlParser(); + /** + * Creates the RSA specification parser. + * + * @param is The source {@link InputStream}. + * @throws SAXException If a SAX error occurs. + */ + public RsaKeyParser(InputStream is) throws SAXException { + this.is = is; + parser = new XmlParser(); + } + + /** + * Parses the {@code rsa.xml} file. + * + * @throws SAXException If a SAX error occurs. + * @throws IOException + */ + public void parse() throws SAXException, IOException { + XmlNode rootNode = parser.parse(is); + if (!rootNode.getName().equals("rsa")) { + throw new IOException("Root node name is not 'rsa'."); } - /** - * Parses the {@code rsa.xml} file. - * - * @throws SAXException If a SAX error occurs. - * @throws IOException - */ - public void parse() throws SAXException, IOException { - XmlNode rootNode = parser.parse(is); - if (!rootNode.getName().equals("rsa")) { - throw new IOException("Root node name is not 'rsa'."); - } - - XmlNode modulusNode = rootNode.getChild("modulus"); - if (modulusNode == null) { - throw new IOException("No node named 'modulus' beneath root node."); - } - - XmlNode exponentNode = rootNode.getChild("private-exponent"); - if (exponentNode == null) { - throw new IOException("No node named 'private-exponent' beneath root node."); - } - - NetworkConstants.RSA_MODULUS = new BigInteger(modulusNode.getValue()); - NetworkConstants.RSA_EXPONENT = new BigInteger(exponentNode.getValue()); + XmlNode modulusNode = rootNode.getChild("modulus"); + if (modulusNode == null) { + throw new IOException("No node named 'modulus' beneath root node."); } + XmlNode exponentNode = rootNode.getChild("private-exponent"); + if (exponentNode == null) { + throw new IOException("No node named 'private-exponent' beneath root node."); + } + + NetworkConstants.RSA_MODULUS = new BigInteger(modulusNode.getValue()); + NetworkConstants.RSA_EXPONENT = new BigInteger(exponentNode.getValue()); + } + } \ No newline at end of file diff --git a/src/org/apollo/io/player/PlayerLoader.java b/src/org/apollo/io/player/PlayerLoader.java index ff14e622..1f6f84da 100644 --- a/src/org/apollo/io/player/PlayerLoader.java +++ b/src/org/apollo/io/player/PlayerLoader.java @@ -10,13 +10,13 @@ import org.apollo.security.PlayerCredentials; */ public interface PlayerLoader { - /** - * Loads a player. - * - * @param credentials The player's credentials. - * @return The {@link PlayerLoaderResponse}. - * @throws Exception If an error occurs. - */ - public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws Exception; + /** + * Loads a player. + * + * @param credentials The player's credentials. + * @return The {@link PlayerLoaderResponse}. + * @throws Exception If an error occurs. + */ + public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws Exception; } \ No newline at end of file diff --git a/src/org/apollo/io/player/PlayerLoaderResponse.java b/src/org/apollo/io/player/PlayerLoaderResponse.java index 77a8244c..5fd5f4c1 100644 --- a/src/org/apollo/io/player/PlayerLoaderResponse.java +++ b/src/org/apollo/io/player/PlayerLoaderResponse.java @@ -10,61 +10,61 @@ import org.apollo.net.codec.login.LoginConstants; */ public final class PlayerLoaderResponse { - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * The status code. - */ - private final int status; + /** + * The status code. + */ + private final int status; - /** - * Creates a {@link PlayerLoaderResponse} with only a status code. - * - * @param status The status code. - * @throws IllegalArgumentException If the status code needs a {@link Player}. - */ - public PlayerLoaderResponse(int status) { - if (status == LoginConstants.STATUS_OK || status == LoginConstants.STATUS_RECONNECTION_OK) { - throw new IllegalArgumentException("Player required for this status code."); - } - this.status = status; - player = null; + /** + * Creates a {@link PlayerLoaderResponse} with only a status code. + * + * @param status The status code. + * @throws IllegalArgumentException If the status code needs a {@link Player}. + */ + public PlayerLoaderResponse(int status) { + if (status == LoginConstants.STATUS_OK || status == LoginConstants.STATUS_RECONNECTION_OK) { + throw new IllegalArgumentException("Player required for this status code."); } + this.status = status; + player = null; + } - /** - * Creates a {@link PlayerLoaderResponse} with a status code and player. - * - * @param status The status code. - * @param player The player. - * @throws IllegalArgumentException If the status code does not need {@link Player}. - */ - public PlayerLoaderResponse(int status, Player player) { - if (status != LoginConstants.STATUS_OK && status != LoginConstants.STATUS_RECONNECTION_OK) { - throw new IllegalArgumentException("Player not required for this status code."); - } - this.status = status; - this.player = player; + /** + * Creates a {@link PlayerLoaderResponse} with a status code and player. + * + * @param status The status code. + * @param player The player. + * @throws IllegalArgumentException If the status code does not need {@link Player}. + */ + public PlayerLoaderResponse(int status, Player player) { + if (status != LoginConstants.STATUS_OK && status != LoginConstants.STATUS_RECONNECTION_OK) { + throw new IllegalArgumentException("Player not required for this status code."); } + this.status = status; + this.player = player; + } - /** - * Gets the player. - * - * @return The player, or {@code null} if there is no player in this response. - */ - public Player getPlayer() { - return player; - } + /** + * Gets the player. + * + * @return The player, or {@code null} if there is no player in this response. + */ + public Player getPlayer() { + return player; + } - /** - * Gets the status code. - * - * @return The status code. - */ - public int getStatus() { - return status; - } + /** + * Gets the status code. + * + * @return The status code. + */ + public int getStatus() { + return status; + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/PlayerSaver.java b/src/org/apollo/io/player/PlayerSaver.java index 1a2def5d..137be887 100644 --- a/src/org/apollo/io/player/PlayerSaver.java +++ b/src/org/apollo/io/player/PlayerSaver.java @@ -10,12 +10,12 @@ import org.apollo.game.model.entity.Player; */ public interface PlayerSaver { - /** - * Saves a player. - * - * @param player The player to save. - * @throws Exception If an error occurs. - */ - public void savePlayer(Player player) throws Exception; + /** + * Saves a player. + * + * @param player The player to save. + * @throws Exception If an error occurs. + */ + public void savePlayer(Player player) throws Exception; } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/BinaryPlayerLoader.java b/src/org/apollo/io/player/impl/BinaryPlayerLoader.java index 71a326a6..1f9b198a 100644 --- a/src/org/apollo/io/player/impl/BinaryPlayerLoader.java +++ b/src/org/apollo/io/player/impl/BinaryPlayerLoader.java @@ -34,135 +34,135 @@ import com.lambdaworks.crypto.SCryptUtil; */ public final class BinaryPlayerLoader implements PlayerLoader { - /** - * The default spawn position. - */ - private static final Position SPAWN_POSITION = new Position(3093, 3104); + /** + * The default spawn position. + */ + private static final Position SPAWN_POSITION = new Position(3093, 3104); - @Override - public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws IOException { - File file = BinaryPlayerUtil.getFile(credentials.getUsername()); - if (!file.exists()) { - Player player = new Player(credentials, SPAWN_POSITION); - player.getBank().add(995, 25); // 25 coins - return new PlayerLoaderResponse(LoginConstants.STATUS_OK, player); - } - - try (DataInputStream in = new DataInputStream(new FileInputStream(file))) { - // read credentials and privileges - String name = StreamUtil.readString(in); - String pass = StreamUtil.readString(in); - - if (!name.equalsIgnoreCase(credentials.getUsername()) || !SCryptUtil.check(credentials.getPassword(), pass)) { - return new PlayerLoaderResponse(LoginConstants.STATUS_INVALID_CREDENTIALS); - } - - // set the credentials password to the scrypted one - credentials.setPassword(pass); - - PrivilegeLevel privilegeLevel = PrivilegeLevel.valueOf(in.readByte()); - boolean members = in.readBoolean(); - - // read settings - PrivacyState chatPrivacy = PrivacyState.valueOf(in.readByte(), true); - PrivacyState friendPrivacy = PrivacyState.valueOf(in.readByte(), false); - PrivacyState tradePrivacy = PrivacyState.valueOf(in.readByte(), false); - int runEnergy = in.readByte(); - ScreenBrightness brightness = ScreenBrightness.valueOf(in.readByte()); - - // read position - int x = in.readUnsignedShort(); - int y = in.readUnsignedShort(); - int height = in.readUnsignedByte(); - - // read appearance - boolean designed = in.readBoolean(); - - int genderIntValue = in.readUnsignedByte(); - Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; - int[] style = new int[7]; - for (int i = 0; i < style.length; i++) { - style[i] = in.readUnsignedByte(); - } - int[] colors = new int[5]; - for (int i = 0; i < colors.length; i++) { - colors[i] = in.readUnsignedByte(); - } - - Player player = new Player(credentials, new Position(x, y, height)); - player.setPrivilegeLevel(privilegeLevel); - player.setMembers(members); - player.setChatPrivacy(chatPrivacy); - player.setFriendPrivacy(friendPrivacy); - player.setTradePrivacy(tradePrivacy); - player.setRunEnergy(runEnergy); - player.setScreenBrightness(brightness); - - player.setNew(designed); - player.setAppearance(new Appearance(gender, style, colors)); - - // read inventories - readInventory(in, player.getInventory()); - readInventory(in, player.getEquipment()); - readInventory(in, player.getBank()); - - // read skills - int size = in.readUnsignedByte(); - SkillSet skills = player.getSkillSet(); - skills.stopFiringEvents(); - try { - for (int i = 0; i < size; i++) { - int level = in.readUnsignedByte(); - double experience = in.readDouble(); - skills.setSkill(i, new Skill(experience, level, SkillSet.getLevelForExperience(experience))); - } - } finally { - skills.calculateCombatLevel(); - skills.startFiringEvents(); - } - - int friendCount = in.readByte(); - List friends = new ArrayList(friendCount); - for (int i = 0; i < friendCount; i++) { - friends.add(NameUtil.decodeBase37(in.readLong())); - } - player.setFriendUsernames(friends); - - int ignoreCount = in.readByte(); - List ignores = new ArrayList(ignoreCount); - for (int i = 0; i < ignoreCount; i++) { - ignores.add(NameUtil.decodeBase37(in.readLong())); - } - player.setIgnoredUsernames(ignores); - - return new PlayerLoaderResponse(LoginConstants.STATUS_OK, player); - } + @Override + public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws IOException { + File file = BinaryPlayerUtil.getFile(credentials.getUsername()); + if (!file.exists()) { + Player player = new Player(credentials, SPAWN_POSITION); + player.getBank().add(995, 25); // 25 coins + return new PlayerLoaderResponse(LoginConstants.STATUS_OK, player); } - /** - * Reads an inventory from the input stream. - * - * @param in The input stream. - * @param inventory The inventory. - * @throws IOException If an I/O error occurs. - */ - private void readInventory(DataInputStream in, Inventory inventory) throws IOException { - int capacity = in.readUnsignedShort(); + try (DataInputStream in = new DataInputStream(new FileInputStream(file))) { + // read credentials and privileges + String name = StreamUtil.readString(in); + String pass = StreamUtil.readString(in); - inventory.stopFiringEvents(); - try { - for (int slot = 0; slot < capacity; slot++) { - int id = in.readUnsignedShort(); - int amount = in.readInt(); - if (id != 0) { - inventory.set(slot, new Item(id - 1, amount)); - } else { - inventory.reset(slot); - } - } - } finally { - inventory.startFiringEvents(); + if (!name.equalsIgnoreCase(credentials.getUsername()) || !SCryptUtil.check(credentials.getPassword(), pass)) { + return new PlayerLoaderResponse(LoginConstants.STATUS_INVALID_CREDENTIALS); + } + + // set the credentials password to the scrypted one + credentials.setPassword(pass); + + PrivilegeLevel privilegeLevel = PrivilegeLevel.valueOf(in.readByte()); + boolean members = in.readBoolean(); + + // read settings + PrivacyState chatPrivacy = PrivacyState.valueOf(in.readByte(), true); + PrivacyState friendPrivacy = PrivacyState.valueOf(in.readByte(), false); + PrivacyState tradePrivacy = PrivacyState.valueOf(in.readByte(), false); + int runEnergy = in.readByte(); + ScreenBrightness brightness = ScreenBrightness.valueOf(in.readByte()); + + // read position + int x = in.readUnsignedShort(); + int y = in.readUnsignedShort(); + int height = in.readUnsignedByte(); + + // read appearance + boolean designed = in.readBoolean(); + + int genderIntValue = in.readUnsignedByte(); + Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; + int[] style = new int[7]; + for (int i = 0; i < style.length; i++) { + style[i] = in.readUnsignedByte(); + } + int[] colors = new int[5]; + for (int i = 0; i < colors.length; i++) { + colors[i] = in.readUnsignedByte(); + } + + Player player = new Player(credentials, new Position(x, y, height)); + player.setPrivilegeLevel(privilegeLevel); + player.setMembers(members); + player.setChatPrivacy(chatPrivacy); + player.setFriendPrivacy(friendPrivacy); + player.setTradePrivacy(tradePrivacy); + player.setRunEnergy(runEnergy); + player.setScreenBrightness(brightness); + + player.setNew(designed); + player.setAppearance(new Appearance(gender, style, colors)); + + // read inventories + readInventory(in, player.getInventory()); + readInventory(in, player.getEquipment()); + readInventory(in, player.getBank()); + + // read skills + int size = in.readUnsignedByte(); + SkillSet skills = player.getSkillSet(); + skills.stopFiringEvents(); + try { + for (int i = 0; i < size; i++) { + int level = in.readUnsignedByte(); + double experience = in.readDouble(); + skills.setSkill(i, new Skill(experience, level, SkillSet.getLevelForExperience(experience))); } + } finally { + skills.calculateCombatLevel(); + skills.startFiringEvents(); + } + + int friendCount = in.readByte(); + List friends = new ArrayList<>(friendCount); + for (int i = 0; i < friendCount; i++) { + friends.add(NameUtil.decodeBase37(in.readLong())); + } + player.setFriendUsernames(friends); + + int ignoreCount = in.readByte(); + List ignores = new ArrayList<>(ignoreCount); + for (int i = 0; i < ignoreCount; i++) { + ignores.add(NameUtil.decodeBase37(in.readLong())); + } + player.setIgnoredUsernames(ignores); + + return new PlayerLoaderResponse(LoginConstants.STATUS_OK, player); } + } + + /** + * Reads an inventory from the input stream. + * + * @param in The input stream. + * @param inventory The inventory. + * @throws IOException If an I/O error occurs. + */ + private void readInventory(DataInputStream in, Inventory inventory) throws IOException { + int capacity = in.readUnsignedShort(); + + inventory.stopFiringEvents(); + try { + for (int slot = 0; slot < capacity; slot++) { + int id = in.readUnsignedShort(); + int amount = in.readInt(); + if (id != 0) { + inventory.set(slot, new Item(id - 1, amount)); + } else { + inventory.reset(slot); + } + } + } finally { + inventory.startFiringEvents(); + } + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/BinaryPlayerSaver.java b/src/org/apollo/io/player/impl/BinaryPlayerSaver.java index e694bcc6..ca55881b 100644 --- a/src/org/apollo/io/player/impl/BinaryPlayerSaver.java +++ b/src/org/apollo/io/player/impl/BinaryPlayerSaver.java @@ -25,121 +25,121 @@ import org.apollo.util.StreamUtil; */ public final class BinaryPlayerSaver implements PlayerSaver { - @Override - public void savePlayer(Player player) throws IOException { - File file = BinaryPlayerUtil.getFile(player.getUsername()); + @Override + public void savePlayer(Player player) throws IOException { + File file = BinaryPlayerUtil.getFile(player.getUsername()); - try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { - // write credentials and privileges - StreamUtil.writeString(out, player.getUsername()); - StreamUtil.writeString(out, player.getCredentials().getHashedPassword()); - out.writeByte(player.getPrivilegeLevel().toInteger()); - out.writeBoolean(player.isMembers()); + try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { + // write credentials and privileges + StreamUtil.writeString(out, player.getUsername()); + StreamUtil.writeString(out, player.getCredentials().getHashedPassword()); + out.writeByte(player.getPrivilegeLevel().toInteger()); + out.writeBoolean(player.isMembers()); - // write settings - out.writeByte(player.getChatPrivacy().toInteger(true)); - out.writeByte(player.getFriendPrivacy().toInteger(false)); - out.writeByte(player.getTradePrivacy().toInteger(false)); - out.writeByte(player.getRunEnergy()); - out.writeByte(player.getScreenBrightness().toInteger()); + // write settings + out.writeByte(player.getChatPrivacy().toInteger(true)); + out.writeByte(player.getFriendPrivacy().toInteger(false)); + out.writeByte(player.getTradePrivacy().toInteger(false)); + out.writeByte(player.getRunEnergy()); + out.writeByte(player.getScreenBrightness().toInteger()); - // write position - Position position = player.getPosition(); - out.writeShort(position.getX()); - out.writeShort(position.getY()); - out.writeByte(position.getHeight()); + // write position + Position position = player.getPosition(); + out.writeShort(position.getX()); + out.writeShort(position.getY()); + out.writeByte(position.getHeight()); - // write appearance - out.writeBoolean(player.isNew()); - Appearance appearance = player.getAppearance(); - out.writeByte(appearance.getGender().toInteger()); - int[] style = appearance.getStyle(); - for (int element : style) { - out.writeByte(element); - } - int[] colors = appearance.getColors(); - for (int color : colors) { - out.writeByte(color); - } - out.flush(); + // write appearance + out.writeBoolean(player.isNew()); + Appearance appearance = player.getAppearance(); + out.writeByte(appearance.getGender().toInteger()); + int[] style = appearance.getStyle(); + for (int element : style) { + out.writeByte(element); + } + int[] colors = appearance.getColors(); + for (int color : colors) { + out.writeByte(color); + } + out.flush(); - // write inventories - writeInventory(out, player.getInventory()); - writeInventory(out, player.getEquipment()); - writeInventory(out, player.getBank()); + // write inventories + writeInventory(out, player.getInventory()); + writeInventory(out, player.getEquipment()); + writeInventory(out, player.getBank()); - // write skills - SkillSet skills = player.getSkillSet(); - out.writeByte(skills.size()); - for (int id = 0; id < skills.size(); id++) { - Skill skill = skills.getSkill(id); - out.writeByte(skill.getCurrentLevel()); - out.writeDouble(skill.getExperience()); - } + // write skills + SkillSet skills = player.getSkillSet(); + out.writeByte(skills.size()); + for (int id = 0; id < skills.size(); id++) { + Skill skill = skills.getSkill(id); + out.writeByte(skill.getCurrentLevel()); + out.writeDouble(skill.getExperience()); + } - List usernames = player.getFriendUsernames(); - out.writeByte(usernames.size()); - for (String username : usernames) { - out.writeLong(NameUtil.encodeBase37(username)); - } + List usernames = player.getFriendUsernames(); + out.writeByte(usernames.size()); + for (String username : usernames) { + out.writeLong(NameUtil.encodeBase37(username)); + } - usernames = player.getIgnoredUsernames(); - out.writeByte(usernames.size()); - for (String username : usernames) { - out.writeLong(NameUtil.encodeBase37(username)); - } + usernames = player.getIgnoredUsernames(); + out.writeByte(usernames.size()); + for (String username : usernames) { + out.writeLong(NameUtil.encodeBase37(username)); + } - for (Entry attribute : player.getAttributes()) { - saveAttribute(out, attribute); - } - } + for (Entry attribute : player.getAttributes()) { + saveAttribute(out, attribute); + } } + } - /** - * Writes an attribute to the specified output stream. - * - * @param out The output stream. - * @param attribute The attribute. - * @throws IOException If an I/O error occurs. - */ - private void saveAttribute(DataOutputStream out, Entry attribute) throws IOException { - StreamUtil.writeString(out, attribute.getKey()); - Object value = attribute.getValue(); - if (value instanceof String) { - out.writeByte(0); - StreamUtil.writeString(out, (String) value); - } else if (value instanceof Integer) { - out.writeByte(1); - out.writeInt((Integer) value); - } else if (value instanceof Boolean) { - out.writeByte(2); - out.writeByte(((Boolean) value) ? 1 : 0); - } else { - throw new IllegalArgumentException("Undefined attribute type " + value + "."); - } + /** + * Writes an attribute to the specified output stream. + * + * @param out The output stream. + * @param attribute The attribute. + * @throws IOException If an I/O error occurs. + */ + private void saveAttribute(DataOutputStream out, Entry attribute) throws IOException { + StreamUtil.writeString(out, attribute.getKey()); + Object value = attribute.getValue(); + if (value instanceof String) { + out.writeByte(0); + StreamUtil.writeString(out, (String) value); + } else if (value instanceof Integer) { + out.writeByte(1); + out.writeInt((Integer) value); + } else if (value instanceof Boolean) { + out.writeByte(2); + out.writeByte(((Boolean) value) ? 1 : 0); + } else { + throw new IllegalArgumentException("Undefined attribute type " + value + "."); } + } - /** - * Writes an inventory to the specified output stream. - * - * @param out The output stream. - * @param inventory The inventory. - * @throws IOException If an I/O error occurs. - */ - private void writeInventory(DataOutputStream out, Inventory inventory) throws IOException { - int capacity = inventory.capacity(); - out.writeShort(capacity); + /** + * Writes an inventory to the specified output stream. + * + * @param out The output stream. + * @param inventory The inventory. + * @throws IOException If an I/O error occurs. + */ + private void writeInventory(DataOutputStream out, Inventory inventory) throws IOException { + int capacity = inventory.capacity(); + out.writeShort(capacity); - for (int slot = 0; slot < capacity; slot++) { - Item item = inventory.get(slot); - if (item != null) { - out.writeShort(item.getId() + 1); - out.writeInt(item.getAmount()); - } else { - out.writeShort(0); - out.writeInt(0); - } - } + for (int slot = 0; slot < capacity; slot++) { + Item item = inventory.get(slot); + if (item != null) { + out.writeShort(item.getId() + 1); + out.writeInt(item.getAmount()); + } else { + out.writeShort(0); + out.writeInt(0); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/BinaryPlayerUtil.java b/src/org/apollo/io/player/impl/BinaryPlayerUtil.java index 85ce31b5..e815ef1f 100644 --- a/src/org/apollo/io/player/impl/BinaryPlayerUtil.java +++ b/src/org/apollo/io/player/impl/BinaryPlayerUtil.java @@ -11,36 +11,36 @@ import org.apollo.util.NameUtil; */ public final class BinaryPlayerUtil { - /** - * The saved games directory. - */ - private static final File SAVED_GAMES_DIRECTORY = new File("data/savedGames"); + /** + * The saved games directory. + */ + private static final File SAVED_GAMES_DIRECTORY = new File("data/savedGames"); - /** - * Creates the saved games directory if it does not exist. - */ - static { - if (!SAVED_GAMES_DIRECTORY.exists()) { - SAVED_GAMES_DIRECTORY.mkdir(); - } + /** + * Creates the saved games directory if it does not exist. + */ + static { + if (!SAVED_GAMES_DIRECTORY.exists()) { + SAVED_GAMES_DIRECTORY.mkdir(); } + } - /** - * Gets the save {@link File} for the specified player. - * - * @param username The username of the player. - * @return The file. - */ - public static File getFile(String username) { - username = NameUtil.decodeBase37(NameUtil.encodeBase37(username)); - return new File(SAVED_GAMES_DIRECTORY, username + ".dat"); - } + /** + * Gets the save {@link File} for the specified player. + * + * @param username The username of the player. + * @return The file. + */ + public static File getFile(String username) { + username = NameUtil.decodeBase37(NameUtil.encodeBase37(username)); + return new File(SAVED_GAMES_DIRECTORY, username + ".dat"); + } - /** - * Default private constructor to prevent instantiation. - */ - private BinaryPlayerUtil() { + /** + * Default private constructor to prevent instantiation. + */ + private BinaryPlayerUtil() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/DiscardPlayerSaver.java b/src/org/apollo/io/player/impl/DiscardPlayerSaver.java index cc00e839..591d6353 100644 --- a/src/org/apollo/io/player/impl/DiscardPlayerSaver.java +++ b/src/org/apollo/io/player/impl/DiscardPlayerSaver.java @@ -10,9 +10,9 @@ import org.apollo.io.player.PlayerSaver; */ public final class DiscardPlayerSaver implements PlayerSaver { - @Override - public void savePlayer(Player player) { - /* discard player */ - } + @Override + public void savePlayer(Player player) { + /* discard player */ + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/DummyPlayerLoader.java b/src/org/apollo/io/player/impl/DummyPlayerLoader.java index 069da700..ed51b0c5 100644 --- a/src/org/apollo/io/player/impl/DummyPlayerLoader.java +++ b/src/org/apollo/io/player/impl/DummyPlayerLoader.java @@ -15,20 +15,20 @@ import org.apollo.security.PlayerCredentials; */ public final class DummyPlayerLoader implements PlayerLoader { - /** - * The default spawn position for players loaded by this loader. - */ - private static final Position DEFAULT_POSITION = new Position(3093, 3104); + /** + * The default spawn position for players loaded by this loader. + */ + private static final Position DEFAULT_POSITION = new Position(3093, 3104); - @Override - public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) { - int status = LoginConstants.STATUS_OK; + @Override + public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) { + int status = LoginConstants.STATUS_OK; - Player player = new Player(credentials, DEFAULT_POSITION); - player.setPrivilegeLevel(PrivilegeLevel.ADMINISTRATOR); - player.setMembers(true); + Player player = new Player(credentials, DEFAULT_POSITION); + player.setPrivilegeLevel(PrivilegeLevel.ADMINISTRATOR); + player.setMembers(true); - return new PlayerLoaderResponse(status, player); - } + return new PlayerLoaderResponse(status, player); + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/JdbcPlayerLoader.java b/src/org/apollo/io/player/impl/JdbcPlayerLoader.java index 6005be4e..5e45d53b 100644 --- a/src/org/apollo/io/player/impl/JdbcPlayerLoader.java +++ b/src/org/apollo/io/player/impl/JdbcPlayerLoader.java @@ -6,9 +6,9 @@ import org.apollo.security.PlayerCredentials; public final class JdbcPlayerLoader implements PlayerLoader { - @Override - public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws Exception { - return null; - } + @Override + public PlayerLoaderResponse loadPlayer(PlayerCredentials credentials) throws Exception { + return null; + } } \ No newline at end of file diff --git a/src/org/apollo/io/player/impl/JdbcPlayerSaver.java b/src/org/apollo/io/player/impl/JdbcPlayerSaver.java index 3098b324..6fad6ba1 100644 --- a/src/org/apollo/io/player/impl/JdbcPlayerSaver.java +++ b/src/org/apollo/io/player/impl/JdbcPlayerSaver.java @@ -5,9 +5,9 @@ import org.apollo.io.player.PlayerSaver; public final class JdbcPlayerSaver implements PlayerSaver { - @Override - public void savePlayer(Player player) throws Exception { + @Override + public void savePlayer(Player player) throws Exception { - } + } } \ No newline at end of file diff --git a/src/org/apollo/login/LoginService.java b/src/org/apollo/login/LoginService.java index b60a29c7..1c5a46e5 100644 --- a/src/org/apollo/login/LoginService.java +++ b/src/org/apollo/login/LoginService.java @@ -28,101 +28,101 @@ import org.xml.sax.SAXException; */ public final class LoginService extends Service { - /** - * The {@link ExecutorService} to which workers are submitted. - */ - private final ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("LoginService")); + /** + * The {@link ExecutorService} to which workers are submitted. + */ + private final ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("LoginService")); - /** - * The current {@link PlayerLoader}. - */ - private PlayerLoader loader; + /** + * The current {@link PlayerLoader}. + */ + private PlayerLoader loader; - /** - * The current {@link PlayerSaver}. - */ - private PlayerSaver saver; + /** + * The current {@link PlayerSaver}. + */ + private PlayerSaver saver; - /** - * Creates the login service. - * - * @throws Exception If an error occurs. - */ - public LoginService() throws Exception { - init(); + /** + * Creates the login service. + * + * @throws Exception If an error occurs. + */ + public LoginService() throws Exception { + init(); + } + + /** + * Initialises the login service. + * + * @throws SAXException If there is an error parsing the XML file. + * @throws IOException If there is an error accessing the file. + * @throws ClassNotFoundException If the player loader/saver implementation could not be found. + * @throws IllegalAccessException If the player loader/saver implementation could not be accessed. + * @throws InstantiationException If the player loader/saver implementation could not be instantiated. + */ + private void init() throws SAXException, IOException, ClassNotFoundException, InstantiationException, + IllegalAccessException { + XmlParser parser = new XmlParser(); + XmlNode rootNode; + + try (InputStream is = new FileInputStream("data/login.xml")) { + rootNode = parser.parse(is); } - /** - * Initialises the login service. - * - * @throws SAXException If there is an error parsing the XML file. - * @throws IOException If there is an error accessing the file. - * @throws ClassNotFoundException If the player loader/saver implementation could not be found. - * @throws IllegalAccessException If the player loader/saver implementation could not be accessed. - * @throws InstantiationException If the player loader/saver implementation could not be instantiated. - */ - private void init() throws SAXException, IOException, ClassNotFoundException, InstantiationException, - IllegalAccessException { - XmlParser parser = new XmlParser(); - XmlNode rootNode; - - try (InputStream is = new FileInputStream("data/login.xml")) { - rootNode = parser.parse(is); - } - - if (!rootNode.getName().equals("login")) { - throw new IOException("Unexpected root node name."); - } - - XmlNode loaderNode = rootNode.getChild("loader"); - if (loaderNode == null || !loaderNode.hasValue()) { - throw new IOException("No loader child node or value."); - } - - XmlNode saverNode = rootNode.getChild("saver"); - if (saverNode == null || !saverNode.hasValue()) { - throw new IOException("No saver child node or value."); - } - - Class loaderClazz = Class.forName(loaderNode.getValue()); - Class saverClazz = Class.forName(saverNode.getValue()); - - loader = (PlayerLoader) loaderClazz.newInstance(); - saver = (PlayerSaver) saverClazz.newInstance(); + if (!rootNode.getName().equals("login")) { + throw new IOException("Unexpected root node name."); } - /** - * Starts the login service. - */ - @Override - public void start() { - /* empty - here for consistency with other services */ + XmlNode loaderNode = rootNode.getChild("loader"); + if (loaderNode == null || !loaderNode.hasValue()) { + throw new IOException("No loader child node or value."); } - /** - * Submits a login request. - * - * @param session The session submitting this request. - * @param request The login request. - */ - public void submitLoadRequest(LoginSession session, LoginRequest request) { - Release release = session.getRelease(); - if (release.getReleaseNumber() != request.getReleaseNumber()) { - // TODO check archive 0 CRCs - session.handlePlayerLoaderResponse(request, new PlayerLoaderResponse(LoginConstants.STATUS_GAME_UPDATED)); - } else { - executor.submit(new PlayerLoaderWorker(loader, session, request)); - } + XmlNode saverNode = rootNode.getChild("saver"); + if (saverNode == null || !saverNode.hasValue()) { + throw new IOException("No saver child node or value."); } - /** - * Submits a save request. - * - * @param session The session submitting this request. - * @param player The player to save. - */ - public void submitSaveRequest(GameSession session, Player player) { - executor.submit(new PlayerSaverWorker(saver, session, player)); + Class loaderClazz = Class.forName(loaderNode.getValue()); + Class saverClazz = Class.forName(saverNode.getValue()); + + loader = (PlayerLoader) loaderClazz.newInstance(); + saver = (PlayerSaver) saverClazz.newInstance(); + } + + /** + * Starts the login service. + */ + @Override + public void start() { + /* empty - here for consistency with other services */ + } + + /** + * Submits a login request. + * + * @param session The session submitting this request. + * @param request The login request. + */ + public void submitLoadRequest(LoginSession session, LoginRequest request) { + Release release = session.getRelease(); + if (release.getReleaseNumber() != request.getReleaseNumber()) { + // TODO check archive 0 CRCs + session.handlePlayerLoaderResponse(request, new PlayerLoaderResponse(LoginConstants.STATUS_GAME_UPDATED)); + } else { + executor.submit(new PlayerLoaderWorker(loader, session, request)); } + } + + /** + * Submits a save request. + * + * @param session The session submitting this request. + * @param player The player to save. + */ + public void submitSaveRequest(GameSession session, Player player) { + executor.submit(new PlayerSaverWorker(saver, session, player)); + } } \ No newline at end of file diff --git a/src/org/apollo/login/PlayerLoaderWorker.java b/src/org/apollo/login/PlayerLoaderWorker.java index 92fd66cb..c235e042 100644 --- a/src/org/apollo/login/PlayerLoaderWorker.java +++ b/src/org/apollo/login/PlayerLoaderWorker.java @@ -16,49 +16,49 @@ import org.apollo.net.session.LoginSession; */ public final class PlayerLoaderWorker implements Runnable { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(PlayerLoaderWorker.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(PlayerLoaderWorker.class.getName()); - /** - * The player loader. - */ - private final PlayerLoader loader; + /** + * The player loader. + */ + private final PlayerLoader loader; - /** - * The request. - */ - private final LoginRequest request; + /** + * The request. + */ + private final LoginRequest request; - /** - * The session that submitted the request. - */ - private final LoginSession session; + /** + * The session that submitted the request. + */ + private final LoginSession session; - /** - * Creates a {@link PlayerLoaderWorker} which will do the work for a single player load request. - * - * @param loader The current player loader. - * @param session The {@link LoginSession} which initiated the request. - * @param request The {@link LoginRequest} object. - */ - public PlayerLoaderWorker(PlayerLoader loader, LoginSession session, LoginRequest request) { - this.loader = loader; - this.session = session; - this.request = request; - } - - @Override - public void run() { - try { - PlayerLoaderResponse response = loader.loadPlayer(request.getCredentials()); - session.handlePlayerLoaderResponse(request, response); - } catch (Exception e) { - logger.log(Level.SEVERE, "Unable to load player's game.", e); - session.handlePlayerLoaderResponse(request, new PlayerLoaderResponse( - LoginConstants.STATUS_COULD_NOT_COMPLETE)); - } + /** + * Creates a {@link PlayerLoaderWorker} which will do the work for a single player load request. + * + * @param loader The current player loader. + * @param session The {@link LoginSession} which initiated the request. + * @param request The {@link LoginRequest} object. + */ + public PlayerLoaderWorker(PlayerLoader loader, LoginSession session, LoginRequest request) { + this.loader = loader; + this.session = session; + this.request = request; + } + + @Override + public void run() { + try { + PlayerLoaderResponse response = loader.loadPlayer(request.getCredentials()); + session.handlePlayerLoaderResponse(request, response); + } catch (Exception e) { + logger.log(Level.SEVERE, "Unable to load player's game.", e); + session.handlePlayerLoaderResponse(request, new PlayerLoaderResponse( + LoginConstants.STATUS_COULD_NOT_COMPLETE)); } + } } \ No newline at end of file diff --git a/src/org/apollo/login/PlayerSaverWorker.java b/src/org/apollo/login/PlayerSaverWorker.java index 2a0e369a..4e9b0f08 100644 --- a/src/org/apollo/login/PlayerSaverWorker.java +++ b/src/org/apollo/login/PlayerSaverWorker.java @@ -14,48 +14,48 @@ import org.apollo.net.session.GameSession; */ public final class PlayerSaverWorker implements Runnable { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(PlayerSaverWorker.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(PlayerSaverWorker.class.getName()); - /** - * The player to save. - */ - private final Player player; + /** + * The player to save. + */ + private final Player player; - /** - * The player saver. - */ - private final PlayerSaver saver; + /** + * The player saver. + */ + private final PlayerSaver saver; - /** - * The game session. - */ - private final GameSession session; + /** + * The game session. + */ + private final GameSession session; - /** - * Creates the player saver worker. - * - * @param saver The player saver. - * @param session The game session. - * @param player The player to save. - */ - public PlayerSaverWorker(PlayerSaver saver, GameSession session, Player player) { - this.saver = saver; - this.session = session; - this.player = player; - } - - @Override - public void run() { - try { - saver.savePlayer(player); - session.handlePlayerSaverResponse(true); - } catch (Exception e) { - logger.log(Level.SEVERE, "Unable to save player's game.", e); - session.handlePlayerSaverResponse(false); - } + /** + * Creates the player saver worker. + * + * @param saver The player saver. + * @param session The game session. + * @param player The player to save. + */ + public PlayerSaverWorker(PlayerSaver saver, GameSession session, Player player) { + this.saver = saver; + this.session = session; + this.player = player; + } + + @Override + public void run() { + try { + saver.savePlayer(player); + session.handlePlayerSaverResponse(true); + } catch (Exception e) { + logger.log(Level.SEVERE, "Unable to save player's game.", e); + session.handlePlayerSaverResponse(false); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/ApolloHandler.java b/src/org/apollo/net/ApolloHandler.java index 864e4e5b..94f596a1 100644 --- a/src/org/apollo/net/ApolloHandler.java +++ b/src/org/apollo/net/ApolloHandler.java @@ -25,63 +25,63 @@ import org.apollo.net.session.UpdateSession; @Sharable public final class ApolloHandler extends ChannelInboundHandlerAdapter { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(ApolloHandler.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(ApolloHandler.class.getName()); - /** - * The server context. - */ - private final ServerContext serverContext; + /** + * The server context. + */ + private final ServerContext serverContext; - /** - * Creates the Apollo event handler. - * - * @param context The server context. - */ - public ApolloHandler(ServerContext context) { - serverContext = context; + /** + * Creates the Apollo event handler. + * + * @param context The server context. + */ + public ApolloHandler(ServerContext context) { + serverContext = context; + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + Channel channel = ctx.channel(); + Session session = ctx.attr(NetworkConstants.SESSION_KEY).getAndRemove(); + if (session != null) { + session.destroy(); } + logger.info("Channel disconnected: " + channel); + channel.close(); + } - @Override - public void channelInactive(ChannelHandlerContext ctx) { - Channel channel = ctx.channel(); - Session session = ctx.attr(NetworkConstants.SESSION_KEY).getAndRemove(); - if (session != null) { - session.destroy(); - } - logger.info("Channel disconnected: " + channel); - channel.close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { - logger.log(Level.WARNING, "Exception occured for channel: " + ctx.channel() + ", closing...", e); - ctx.channel().close(); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) { - if (ctx.attr(NetworkConstants.SESSION_KEY).get() == null) { - if (msg instanceof HttpRequest || msg instanceof JagGrabRequest) { - new UpdateSession(ctx.channel(), serverContext).messageReceived(msg); - } else { - HandshakeMessage handshakeMessage = (HandshakeMessage) msg; - switch (handshakeMessage.getServiceId()) { - case HandshakeConstants.SERVICE_GAME: - ctx.attr(NetworkConstants.SESSION_KEY).set(new LoginSession(ctx, serverContext)); - break; - case HandshakeConstants.SERVICE_UPDATE: - ctx.attr(NetworkConstants.SESSION_KEY).set(new UpdateSession(ctx.channel(), serverContext)); - break; - default: - throw new IllegalStateException("Invalid service id."); - } - } - } else { - ctx.attr(NetworkConstants.SESSION_KEY).get().messageReceived(msg); + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { + logger.log(Level.WARNING, "Exception occured for channel: " + ctx.channel() + ", closing...", e); + ctx.channel().close(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + if (ctx.attr(NetworkConstants.SESSION_KEY).get() == null) { + if (msg instanceof HttpRequest || msg instanceof JagGrabRequest) { + new UpdateSession(ctx.channel(), serverContext).messageReceived(msg); + } else { + HandshakeMessage handshakeMessage = (HandshakeMessage) msg; + switch (handshakeMessage.getServiceId()) { + case HandshakeConstants.SERVICE_GAME: + ctx.attr(NetworkConstants.SESSION_KEY).set(new LoginSession(ctx, serverContext)); + break; + case HandshakeConstants.SERVICE_UPDATE: + ctx.attr(NetworkConstants.SESSION_KEY).set(new UpdateSession(ctx.channel(), serverContext)); + break; + default: + throw new IllegalStateException("Invalid service id."); } + } + } else { + ctx.attr(NetworkConstants.SESSION_KEY).get().messageReceived(msg); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/HttpChannelInitializer.java b/src/org/apollo/net/HttpChannelInitializer.java index b75c61b5..aea62b6f 100644 --- a/src/org/apollo/net/HttpChannelInitializer.java +++ b/src/org/apollo/net/HttpChannelInitializer.java @@ -15,39 +15,39 @@ import io.netty.handler.timeout.IdleStateHandler; */ public final class HttpChannelInitializer extends ChannelInitializer { - /** - * The maximum length of a request, in bytes. - */ - private static final int MAX_REQUEST_LENGTH = 8192; + /** + * The maximum length of a request, in bytes. + */ + private static final int MAX_REQUEST_LENGTH = 8192; - /** - * The server event handler. - */ - private final ApolloHandler handler; + /** + * The server event handler. + */ + private final ApolloHandler handler; - /** - * Creates the HTTP pipeline factory. - * - * @param handler The file server event handler. - */ - public HttpChannelInitializer(ApolloHandler handler) { - this.handler = handler; - } + /** + * Creates the HTTP pipeline factory. + * + * @param handler The file server event handler. + */ + public HttpChannelInitializer(ApolloHandler handler) { + this.handler = handler; + } - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); + @Override + protected void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); - // decoders - pipeline.addLast("decoder", new HttpRequestDecoder()); - pipeline.addLast("chunker", new HttpObjectAggregator(MAX_REQUEST_LENGTH)); + // decoders + pipeline.addLast("decoder", new HttpRequestDecoder()); + pipeline.addLast("chunker", new HttpObjectAggregator(MAX_REQUEST_LENGTH)); - // encoders - pipeline.addLast("encoder", new HttpResponseEncoder()); + // encoders + pipeline.addLast("encoder", new HttpResponseEncoder()); - // handler - pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); - pipeline.addLast("handler", handler); - } + // handler + pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); + pipeline.addLast("handler", handler); + } } \ No newline at end of file diff --git a/src/org/apollo/net/JagGrabChannelInitializer.java b/src/org/apollo/net/JagGrabChannelInitializer.java index a70dff20..09a1dfc6 100644 --- a/src/org/apollo/net/JagGrabChannelInitializer.java +++ b/src/org/apollo/net/JagGrabChannelInitializer.java @@ -21,57 +21,57 @@ import org.apollo.net.codec.jaggrab.JagGrabResponseEncoder; */ public final class JagGrabChannelInitializer extends ChannelInitializer { - /** - * A buffer with two line feed (LF) characters in it. - */ - private static final ByteBuf DOUBLE_LINE_FEED_DELIMITER = Unpooled.buffer(2); + /** + * A buffer with two line feed (LF) characters in it. + */ + private static final ByteBuf DOUBLE_LINE_FEED_DELIMITER = Unpooled.buffer(2); - /** - * The character set used in the request. - */ - private static final Charset JAGGRAB_CHARSET = Charset.forName("US-ASCII"); + /** + * The character set used in the request. + */ + private static final Charset JAGGRAB_CHARSET = Charset.forName("US-ASCII"); - /** - * The maximum length of a request, in bytes. - */ - private static final int MAX_REQUEST_LENGTH = 8192; + /** + * The maximum length of a request, in bytes. + */ + private static final int MAX_REQUEST_LENGTH = 8192; - /** - * Populates the double line feed buffer. - */ - static { - DOUBLE_LINE_FEED_DELIMITER.writeByte(10).writeByte(10); - } + /** + * Populates the double line feed buffer. + */ + static { + DOUBLE_LINE_FEED_DELIMITER.writeByte(10).writeByte(10); + } - /** - * The file server event handler. - */ - private final ApolloHandler handler; + /** + * The file server event handler. + */ + private final ApolloHandler handler; - /** - * Creates a {@code JAGGRAB} pipeline factory. - * - * @param handler The file server event handler. - */ - public JagGrabChannelInitializer(ApolloHandler handler) { - this.handler = handler; - } + /** + * Creates a {@code JAGGRAB} pipeline factory. + * + * @param handler The file server event handler. + */ + public JagGrabChannelInitializer(ApolloHandler handler) { + this.handler = handler; + } - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); - // decoders - pipeline.addLast("framer", new DelimiterBasedFrameDecoder(MAX_REQUEST_LENGTH, DOUBLE_LINE_FEED_DELIMITER)); - pipeline.addLast("string-decoder", new StringDecoder(JAGGRAB_CHARSET)); - pipeline.addLast("jaggrab-decoder", new JagGrabRequestDecoder()); + // decoders + pipeline.addLast("framer", new DelimiterBasedFrameDecoder(MAX_REQUEST_LENGTH, DOUBLE_LINE_FEED_DELIMITER)); + pipeline.addLast("string-decoder", new StringDecoder(JAGGRAB_CHARSET)); + pipeline.addLast("jaggrab-decoder", new JagGrabRequestDecoder()); - // encoders - pipeline.addLast("jaggrab-encoder", new JagGrabResponseEncoder()); + // encoders + pipeline.addLast("jaggrab-encoder", new JagGrabResponseEncoder()); - // handler - pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); - pipeline.addLast("handler", handler); - } + // handler + pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); + pipeline.addLast("handler", handler); + } } \ No newline at end of file diff --git a/src/org/apollo/net/NetworkConstants.java b/src/org/apollo/net/NetworkConstants.java index 0c13c117..cb635ac3 100644 --- a/src/org/apollo/net/NetworkConstants.java +++ b/src/org/apollo/net/NetworkConstants.java @@ -13,51 +13,51 @@ import org.apollo.net.session.Session; */ public final class NetworkConstants { - /** - * The service port. - */ - public static final int SERVICE_PORT = 43594; + /** + * The service port. + */ + public static final int SERVICE_PORT = 43594; - /** - * The JAGGRAB port. - */ - public static final int JAGGRAB_PORT = 43595; + /** + * The JAGGRAB port. + */ + public static final int JAGGRAB_PORT = 43595; - /** - * The HTTP port. - */ - public static final int HTTP_PORT = 80; + /** + * The HTTP port. + */ + public static final int HTTP_PORT = 80; - /** - * The number of seconds before a connection becomes idle. - */ - public static final int IDLE_TIME = 15; + /** + * The number of seconds before a connection becomes idle. + */ + public static final int IDLE_TIME = 15; - /** - * The terminator of a string. - */ - public static final int STRING_TERMINATOR = 10; + /** + * The terminator of a string. + */ + public static final int STRING_TERMINATOR = 10; - /** - * The exponent used when decrypting the RSA block. - */ - public static BigInteger RSA_EXPONENT; + /** + * The exponent used when decrypting the RSA block. + */ + public static BigInteger RSA_EXPONENT; - /** - * The modulus used when decrypting the RSA block. - */ - public static BigInteger RSA_MODULUS; + /** + * The modulus used when decrypting the RSA block. + */ + public static BigInteger RSA_MODULUS; - /** - * The {@link Session} {@link AttributeKey}. - */ - public static final AttributeKey SESSION_KEY = AttributeKey.valueOf("session"); + /** + * The {@link Session} {@link AttributeKey}. + */ + public static final AttributeKey SESSION_KEY = AttributeKey.valueOf("session"); - /** - * Default private constructor to prevent instantiation by other classes. - */ - private NetworkConstants() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private NetworkConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/net/ServiceChannelInitializer.java b/src/org/apollo/net/ServiceChannelInitializer.java index bc5a2d2a..51436050 100644 --- a/src/org/apollo/net/ServiceChannelInitializer.java +++ b/src/org/apollo/net/ServiceChannelInitializer.java @@ -14,26 +14,26 @@ import org.apollo.net.codec.handshake.HandshakeDecoder; */ public final class ServiceChannelInitializer extends ChannelInitializer { - /** - * The network event handler. - */ - private final ApolloHandler handler; + /** + * The network event handler. + */ + private final ApolloHandler handler; - /** - * Creates the service pipeline factory. - * - * @param handler The networking event handler. - */ - public ServiceChannelInitializer(ApolloHandler handler) { - this.handler = handler; - } + /** + * Creates the service pipeline factory. + * + * @param handler The networking event handler. + */ + public ServiceChannelInitializer(ApolloHandler handler) { + this.handler = handler; + } - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast("handshakeDecoder", new HandshakeDecoder()); - pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); - pipeline.addLast("handler", handler); - } + @Override + protected void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast("handshakeDecoder", new HandshakeDecoder()); + pipeline.addLast("timeout", new IdleStateHandler(NetworkConstants.IDLE_TIME, 0, 0)); + pipeline.addLast("handler", handler); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/AccessMode.java b/src/org/apollo/net/codec/game/AccessMode.java index b98be20f..76574576 100644 --- a/src/org/apollo/net/codec/game/AccessMode.java +++ b/src/org/apollo/net/codec/game/AccessMode.java @@ -7,14 +7,14 @@ package org.apollo.net.codec.game; */ public enum AccessMode { - /** - * When in bit access mode, bits can be written and packed into bytes. - */ - BIT_ACCESS, + /** + * When in bit access mode, bits can be written and packed into bytes. + */ + BIT_ACCESS, - /** - * When in byte access modes, bytes are written directly to the buffer. - */ - BYTE_ACCESS; + /** + * When in byte access modes, bytes are written directly to the buffer. + */ + BYTE_ACCESS; } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/DataConstants.java b/src/org/apollo/net/codec/game/DataConstants.java index a1ec9c61..3b1788b6 100644 --- a/src/org/apollo/net/codec/game/DataConstants.java +++ b/src/org/apollo/net/codec/game/DataConstants.java @@ -7,25 +7,25 @@ package org.apollo.net.codec.game; */ public final class DataConstants { - /** - * An array of bit masks. The element {@code n} is equal to {@code 2n - 1}. - */ - public static final int[] BIT_MASK = new int[32]; + /** + * An array of bit masks. The element {@code n} is equal to {@code 2n - 1}. + */ + public static final int[] BIT_MASK = new int[32]; - /** - * Initializes the {@link #BIT_MASK} array. - */ - static { - for (int i = 0; i < BIT_MASK.length; i++) { - BIT_MASK[i] = (1 << i) - 1; - } + /** + * Initializes the {@link #BIT_MASK} array. + */ + static { + for (int i = 0; i < BIT_MASK.length; i++) { + BIT_MASK[i] = (1 << i) - 1; } + } - /** - * Default private constructor to prevent instantiation. - */ - private DataConstants() { + /** + * Default private constructor to prevent instantiation. + */ + private DataConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/DataOrder.java b/src/org/apollo/net/codec/game/DataOrder.java index 186333f4..8922036e 100644 --- a/src/org/apollo/net/codec/game/DataOrder.java +++ b/src/org/apollo/net/codec/game/DataOrder.java @@ -7,24 +7,24 @@ package org.apollo.net.codec.game; */ public enum DataOrder { - /** - * Most significant byte to least significant byte. - */ - BIG, + /** + * Most significant byte to least significant byte. + */ + BIG, - /** - * Also known as the V2 order. - */ - INVERSED_MIDDLE, + /** + * Also known as the V2 order. + */ + INVERSED_MIDDLE, - /** - * Least significant byte to most significant byte. - */ - LITTLE, + /** + * Least significant byte to most significant byte. + */ + LITTLE, - /** - * Also known as the V1 order. - */ - MIDDLE; + /** + * Also known as the V1 order. + */ + MIDDLE; } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/DataTransformation.java b/src/org/apollo/net/codec/game/DataTransformation.java index 6b62e208..5d1c897a 100644 --- a/src/org/apollo/net/codec/game/DataTransformation.java +++ b/src/org/apollo/net/codec/game/DataTransformation.java @@ -7,24 +7,24 @@ package org.apollo.net.codec.game; */ public enum DataTransformation { - /** - * Adds 128 to the value when it is written, takes 128 from the value when it is read (also known as type-A). - */ - ADD, + /** + * Adds 128 to the value when it is written, takes 128 from the value when it is read (also known as type-A). + */ + ADD, - /** - * Negates the value (also known as type-C). - */ - NEGATE, + /** + * Negates the value (also known as type-C). + */ + NEGATE, - /** - * No transformation is done. - */ - NONE, + /** + * No transformation is done. + */ + NONE, - /** - * Subtracts the value from 128 (also known as type-S). - */ - SUBTRACT; + /** + * Subtracts the value from 128 (also known as type-S). + */ + SUBTRACT; } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/DataType.java b/src/org/apollo/net/codec/game/DataType.java index d78c823f..be5a7563 100644 --- a/src/org/apollo/net/codec/game/DataType.java +++ b/src/org/apollo/net/codec/game/DataType.java @@ -7,52 +7,52 @@ package org.apollo.net.codec.game; */ public enum DataType { - /** - * A byte. - */ - BYTE(1), + /** + * A byte. + */ + BYTE(1), - /** - * An integer. - */ - INT(4), + /** + * An integer. + */ + INT(4), - /** - * A long. - */ - LONG(8), + /** + * A long. + */ + LONG(8), - /** - * A short. - */ - SHORT(2), + /** + * A short. + */ + SHORT(2), - /** - * A 'tri byte' - a group of three bytes. - */ - TRI_BYTE(3); + /** + * A 'tri byte' - a group of three bytes. + */ + TRI_BYTE(3); - /** - * The number of bytes this type occupies. - */ - private final int bytes; + /** + * The number of bytes this type occupies. + */ + private final int bytes; - /** - * Creates a data type. - * - * @param bytes The number of bytes it occupies. - */ - private DataType(int bytes) { - this.bytes = bytes; - } + /** + * Creates a data type. + * + * @param bytes The number of bytes it occupies. + */ + private DataType(int bytes) { + this.bytes = bytes; + } - /** - * Gets the number of bytes the data type occupies. - * - * @return The number of bytes. - */ - public int getBytes() { - return bytes; - } + /** + * Gets the number of bytes the data type occupies. + * + * @return The number of bytes. + */ + public int getBytes() { + return bytes; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GameDecoderState.java b/src/org/apollo/net/codec/game/GameDecoderState.java index b69a2ec5..e7ec440e 100644 --- a/src/org/apollo/net/codec/game/GameDecoderState.java +++ b/src/org/apollo/net/codec/game/GameDecoderState.java @@ -7,22 +7,22 @@ package org.apollo.net.codec.game; */ public enum GameDecoderState { - /** - * The game length state waits for the packet length. Once it has been received, it sets the state to the payload - * state. - */ - GAME_LENGTH, + /** + * The game length state waits for the packet length. Once it has been received, it sets the state to the payload + * state. + */ + GAME_LENGTH, - /** - * The game opcode state waits for an encrypted opcode. It decrypts it, and will either set the next state to the - * length (if the packet is variably- sized) or the payload (if it is not variably-sized) state. - */ - GAME_OPCODE, + /** + * The game opcode state waits for an encrypted opcode. It decrypts it, and will either set the next state to the + * length (if the packet is variably- sized) or the payload (if it is not variably-sized) state. + */ + GAME_OPCODE, - /** - * The payload state will wait for the whole packet to be received. Then, it will pass a {@link GamePacket} object - * to Netty and reset the state back to the game opcode state, ready for the next packet. - */ - GAME_PAYLOAD; + /** + * The payload state will wait for the whole packet to be received. Then, it will pass a {@link GamePacket} object + * to Netty and reset the state back to the game opcode state, ready for the next packet. + */ + GAME_PAYLOAD; } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GameEventDecoder.java b/src/org/apollo/net/codec/game/GameEventDecoder.java index 3f512a80..41504f25 100644 --- a/src/org/apollo/net/codec/game/GameEventDecoder.java +++ b/src/org/apollo/net/codec/game/GameEventDecoder.java @@ -16,28 +16,28 @@ import org.apollo.net.release.Release; */ public final class GameEventDecoder extends MessageToMessageDecoder { - /** - * The current release. - */ - private final Release release; + /** + * The current release. + */ + private final Release release; - /** - * Creates the game event decoder with the specified release. - * - * @param release The release. - */ - public GameEventDecoder(Release release) { - this.release = release; - } + /** + * Creates the game event decoder with the specified release. + * + * @param release The release. + */ + public GameEventDecoder(Release release) { + this.release = release; + } - @Override - protected void decode(ChannelHandlerContext ctx, GamePacket packet, List out) { - EventDecoder decoder = release.getEventDecoder(packet.getOpcode()); - if (decoder != null) { - out.add(decoder.decode(packet)); - } else { - System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + "."); - } + @Override + protected void decode(ChannelHandlerContext ctx, GamePacket packet, List out) { + EventDecoder decoder = release.getEventDecoder(packet.getOpcode()); + if (decoder != null) { + out.add(decoder.decode(packet)); + } else { + System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + "."); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GameEventEncoder.java b/src/org/apollo/net/codec/game/GameEventEncoder.java index 59ee928c..86d2e223 100644 --- a/src/org/apollo/net/codec/game/GameEventEncoder.java +++ b/src/org/apollo/net/codec/game/GameEventEncoder.java @@ -16,27 +16,27 @@ import org.apollo.net.release.Release; */ public final class GameEventEncoder extends MessageToMessageEncoder { - /** - * The current release. - */ - private final Release release; + /** + * The current release. + */ + private final Release release; - /** - * Creates the game event encoder with the specified release. - * - * @param release The release. - */ - public GameEventEncoder(Release release) { - this.release = release; - } + /** + * Creates the game event encoder with the specified release. + * + * @param release The release. + */ + public GameEventEncoder(Release release) { + this.release = release; + } - @SuppressWarnings("unchecked") - @Override - protected void encode(ChannelHandlerContext ctx, Event event, List out) { - EventEncoder encoder = (EventEncoder) release.getEventEncoder(event.getClass()); - if (encoder != null) { - out.add(encoder.encode(event)); - } + @SuppressWarnings("unchecked") + @Override + protected void encode(ChannelHandlerContext ctx, Event event, List out) { + EventEncoder encoder = (EventEncoder) release.getEventEncoder(event.getClass()); + if (encoder != null) { + out.add(encoder.encode(event)); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GamePacket.java b/src/org/apollo/net/codec/game/GamePacket.java index d93a70fc..c9fa971c 100644 --- a/src/org/apollo/net/codec/game/GamePacket.java +++ b/src/org/apollo/net/codec/game/GamePacket.java @@ -11,74 +11,74 @@ import org.apollo.net.meta.PacketType; */ public final class GamePacket { - /** - * The length. - */ - private final int length; + /** + * The length. + */ + private final int length; - /** - * The opcode. - */ - private final int opcode; + /** + * The opcode. + */ + private final int opcode; - /** - * The payload. - */ - private final ByteBuf payload; + /** + * The payload. + */ + private final ByteBuf payload; - /** - * The packet type. - */ - private final PacketType type; + /** + * The packet type. + */ + private final PacketType type; - /** - * Creates the game packet. - * - * @param opcode The opcode. - * @param type The packet type. - * @param payload The payload. - */ - public GamePacket(int opcode, PacketType type, ByteBuf payload) { - this.opcode = opcode; - this.type = type; - length = payload.readableBytes(); - this.payload = payload; - } + /** + * Creates the game packet. + * + * @param opcode The opcode. + * @param type The packet type. + * @param payload The payload. + */ + public GamePacket(int opcode, PacketType type, ByteBuf payload) { + this.opcode = opcode; + this.type = type; + length = payload.readableBytes(); + this.payload = payload; + } - /** - * Gets the payload length. - * - * @return The payload length. - */ - public int getLength() { - return length; - } + /** + * Gets the payload length. + * + * @return The payload length. + */ + public int getLength() { + return length; + } - /** - * Gets the opcode. - * - * @return The opcode. - */ - public int getOpcode() { - return opcode; - } + /** + * Gets the opcode. + * + * @return The opcode. + */ + public int getOpcode() { + return opcode; + } - /** - * Gets the payload. - * - * @return The payload. - */ - public ByteBuf getPayload() { - return payload; - } + /** + * Gets the payload. + * + * @return The payload. + */ + public ByteBuf getPayload() { + return payload; + } - /** - * Gets the packet type. - * - * @return The packet type. - */ - public PacketType getType() { - return type; - } + /** + * Gets the packet type. + * + * @return The packet type. + */ + public PacketType getType() { + return type; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GamePacketBuilder.java b/src/org/apollo/net/codec/game/GamePacketBuilder.java index 740dd10e..5ea2c29a 100644 --- a/src/org/apollo/net/codec/game/GamePacketBuilder.java +++ b/src/org/apollo/net/codec/game/GamePacketBuilder.java @@ -13,439 +13,439 @@ import org.apollo.net.meta.PacketType; */ public final class GamePacketBuilder { - /** - * The current bit index. - */ - private int bitIndex; + /** + * The current bit index. + */ + private int bitIndex; - /** - * The buffer. - */ - private final ByteBuf buffer = Unpooled.buffer(); + /** + * The buffer. + */ + private final ByteBuf buffer = Unpooled.buffer(); - /** - * The current mode. - */ - private AccessMode mode = AccessMode.BYTE_ACCESS; + /** + * The current mode. + */ + private AccessMode mode = AccessMode.BYTE_ACCESS; - /** - * The opcode. - */ - private final int opcode; + /** + * The opcode. + */ + private final int opcode; - /** - * The {@link PacketType}. - */ - private final PacketType type; + /** + * The {@link PacketType}. + */ + private final PacketType type; - /** - * Creates a raw {@link GamePacketBuilder}. - */ - public GamePacketBuilder() { - opcode = -1; - type = PacketType.RAW; + /** + * Creates a raw {@link GamePacketBuilder}. + */ + public GamePacketBuilder() { + opcode = -1; + type = PacketType.RAW; + } + + /** + * Creates the {@link GamePacketBuilder} for a {@link PacketType#FIXED} packet with the specified opcode. + * + * @param opcode The opcode. + */ + public GamePacketBuilder(int opcode) { + this(opcode, PacketType.FIXED); + } + + /** + * Creates the {@link GamePacketBuilder} for the specified packet type and opcode. + * + * @param opcode The opcode. + * @param type The packet type. + */ + public GamePacketBuilder(int opcode, PacketType type) { + this.opcode = opcode; + this.type = type; + } + + /** + * Checks that this builder is in the bit access mode. + * + * @throws IllegalStateException If the builder is not in bit access mode. + */ + private void checkBitAccess() { + if (mode != AccessMode.BIT_ACCESS) { + throw new IllegalStateException("For bit-based calls to work, the mode must be bit access."); } + } - /** - * Creates the {@link GamePacketBuilder} for a {@link PacketType#FIXED} packet with the specified opcode. - * - * @param opcode The opcode. - */ - public GamePacketBuilder(int opcode) { - this(opcode, PacketType.FIXED); + /** + * Checks that this builder is in the byte access mode. + * + * @throws IllegalStateException If the builder is not in byte access mode. + */ + private void checkByteAccess() { + if (mode != AccessMode.BYTE_ACCESS) { + throw new IllegalStateException("For byte-based calls to work, the mode must be byte access."); } + } - /** - * Creates the {@link GamePacketBuilder} for the specified packet type and opcode. - * - * @param opcode The opcode. - * @param type The packet type. - */ - public GamePacketBuilder(int opcode, PacketType type) { - this.opcode = opcode; - this.type = type; - } + /** + * Gets the current length of the builder's buffer. + * + * @return The length of the buffer. + */ + public int getLength() { + checkByteAccess(); + return buffer.writerIndex(); + } - /** - * Checks that this builder is in the bit access mode. - * - * @throws IllegalStateException If the builder is not in bit access mode. - */ - private void checkBitAccess() { - if (mode != AccessMode.BIT_ACCESS) { - throw new IllegalStateException("For bit-based calls to work, the mode must be bit access."); - } - } - - /** - * Checks that this builder is in the byte access mode. - * - * @throws IllegalStateException If the builder is not in byte access mode. - */ - private void checkByteAccess() { - if (mode != AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("For byte-based calls to work, the mode must be byte access."); - } - } - - /** - * Gets the current length of the builder's buffer. - * - * @return The length of the buffer. - */ - public int getLength() { - checkByteAccess(); - return buffer.writerIndex(); - } - - /** - * Puts a standard data type with the specified value, byte order and transformation. - * - * @param type The data type. - * @param order The byte order. - * @param transformation The transformation. - * @param value The value. - * @throws IllegalArgumentException If the type, order, or transformation is unknown. - */ - public void put(DataType type, DataOrder order, DataTransformation transformation, Number value) { - checkByteAccess(); - long longValue = value.longValue(); - int length = type.getBytes(); - if (order == DataOrder.BIG) { - for (int i = length - 1; i >= 0; i--) { - if (i == 0 && transformation != DataTransformation.NONE) { - if (transformation == DataTransformation.ADD) { - buffer.writeByte((byte) (longValue + 128)); - } else if (transformation == DataTransformation.NEGATE) { - buffer.writeByte((byte) -longValue); - } else if (transformation == DataTransformation.SUBTRACT) { - buffer.writeByte((byte) (128 - longValue)); - } else { - throw new IllegalArgumentException("Unknown transformation."); - } - } else { - buffer.writeByte((byte) (longValue >> i * 8)); - } - } - } else if (order == DataOrder.LITTLE) { - for (int i = 0; i < length; i++) { - if (i == 0 && transformation != DataTransformation.NONE) { - if (transformation == DataTransformation.ADD) { - buffer.writeByte((byte) (longValue + 128)); - } else if (transformation == DataTransformation.NEGATE) { - buffer.writeByte((byte) -longValue); - } else if (transformation == DataTransformation.SUBTRACT) { - buffer.writeByte((byte) (128 - longValue)); - } else { - throw new IllegalArgumentException("Unknown transformation."); - } - } else { - buffer.writeByte((byte) (longValue >> i * 8)); - } - } - } else if (order == DataOrder.MIDDLE) { - if (transformation != DataTransformation.NONE) { - throw new IllegalArgumentException("Middle endian cannot be transformed."); - } - if (type != DataType.INT) { - throw new IllegalArgumentException("Middle endian can only be used with an integer,"); - } - buffer.writeByte((byte) (longValue >> 8)); - buffer.writeByte((byte) longValue); - buffer.writeByte((byte) (longValue >> 24)); - buffer.writeByte((byte) (longValue >> 16)); - } else if (order == DataOrder.INVERSED_MIDDLE) { - if (transformation != DataTransformation.NONE) { - throw new IllegalArgumentException("Inversed middle endian cannot be transformed,"); - } - if (type != DataType.INT) { - throw new IllegalArgumentException("Inversed middle endian can only be used with an integer,"); - } - buffer.writeByte((byte) (longValue >> 16)); - buffer.writeByte((byte) (longValue >> 24)); - buffer.writeByte((byte) longValue); - buffer.writeByte((byte) (longValue >> 8)); + /** + * Puts a standard data type with the specified value, byte order and transformation. + * + * @param type The data type. + * @param order The byte order. + * @param transformation The transformation. + * @param value The value. + * @throws IllegalArgumentException If the type, order, or transformation is unknown. + */ + public void put(DataType type, DataOrder order, DataTransformation transformation, Number value) { + checkByteAccess(); + long longValue = value.longValue(); + int length = type.getBytes(); + if (order == DataOrder.BIG) { + for (int i = length - 1; i >= 0; i--) { + if (i == 0 && transformation != DataTransformation.NONE) { + if (transformation == DataTransformation.ADD) { + buffer.writeByte((byte) (longValue + 128)); + } else if (transformation == DataTransformation.NEGATE) { + buffer.writeByte((byte) -longValue); + } else if (transformation == DataTransformation.SUBTRACT) { + buffer.writeByte((byte) (128 - longValue)); + } else { + throw new IllegalArgumentException("Unknown transformation."); + } } else { - throw new IllegalArgumentException("Unknown order."); + buffer.writeByte((byte) (longValue >> i * 8)); } - } - - /** - * Puts a standard data type with the specified value and byte order. - * - * @param type The data type. - * @param order The byte order. - * @param value The value. - */ - public void put(DataType type, DataOrder order, Number value) { - put(type, order, DataTransformation.NONE, value); - } - - /** - * Puts a standard data type with the specified value and transformation. - * - * @param type The type. - * @param transformation The transformation. - * @param value The value. - */ - public void put(DataType type, DataTransformation transformation, Number value) { - put(type, DataOrder.BIG, transformation, value); - } - - /** - * Puts a standard data type with the specified value. - * - * @param type The data type. - * @param value The value. - */ - public void put(DataType type, Number value) { - put(type, DataOrder.BIG, DataTransformation.NONE, value); - } - - /** - * Puts a single bit into the buffer. If {@code flag} is {@code true}, the value of the bit is {@code 1}. If - * {@code flag} is {@code false}, the value of the bit is {@code 0}. - * - * @param flag The flag. - */ - public void putBit(boolean flag) { - putBit(flag ? 1 : 0); - } - - /** - * Puts a single bit into the buffer with the value {@code value}. - * - * @param value The value. - */ - public void putBit(int value) { - putBits(1, value); - } - - /** - * Puts {@code numBits} into the buffer with the value {@code value}. - * - * @param numBits The number of bits to put into the buffer. - * @param value The value. - * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. - */ - public void putBits(int numBits, int value) { - if (numBits < 0 || numBits > 32) { - throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive."); - } - - checkBitAccess(); - - int bytePos = bitIndex >> 3; - int bitOffset = 8 - (bitIndex & 7); - bitIndex += numBits; - - int requiredSpace = bytePos - buffer.writerIndex() + 1; - requiredSpace += (numBits + 7) / 8; - buffer.ensureWritable(requiredSpace); - - for (; numBits > bitOffset; bitOffset = 8) { - int tmp = buffer.getByte(bytePos); - tmp &= ~DataConstants.BIT_MASK[bitOffset]; - tmp |= value >> numBits - bitOffset & DataConstants.BIT_MASK[bitOffset]; - buffer.setByte(bytePos++, tmp); - numBits -= bitOffset; - } - if (numBits == bitOffset) { - int tmp = buffer.getByte(bytePos); - tmp &= ~DataConstants.BIT_MASK[bitOffset]; - tmp |= value & DataConstants.BIT_MASK[bitOffset]; - buffer.setByte(bytePos, tmp); + } + } else if (order == DataOrder.LITTLE) { + for (int i = 0; i < length; i++) { + if (i == 0 && transformation != DataTransformation.NONE) { + if (transformation == DataTransformation.ADD) { + buffer.writeByte((byte) (longValue + 128)); + } else if (transformation == DataTransformation.NEGATE) { + buffer.writeByte((byte) -longValue); + } else if (transformation == DataTransformation.SUBTRACT) { + buffer.writeByte((byte) (128 - longValue)); + } else { + throw new IllegalArgumentException("Unknown transformation."); + } } else { - int tmp = buffer.getByte(bytePos); - tmp &= ~(DataConstants.BIT_MASK[numBits] << bitOffset - numBits); - tmp |= (value & DataConstants.BIT_MASK[numBits]) << bitOffset - numBits; - buffer.setByte(bytePos, tmp); + buffer.writeByte((byte) (longValue >> i * 8)); } + } + } else if (order == DataOrder.MIDDLE) { + if (transformation != DataTransformation.NONE) { + throw new IllegalArgumentException("Middle endian cannot be transformed."); + } + if (type != DataType.INT) { + throw new IllegalArgumentException("Middle endian can only be used with an integer,"); + } + buffer.writeByte((byte) (longValue >> 8)); + buffer.writeByte((byte) longValue); + buffer.writeByte((byte) (longValue >> 24)); + buffer.writeByte((byte) (longValue >> 16)); + } else if (order == DataOrder.INVERSED_MIDDLE) { + if (transformation != DataTransformation.NONE) { + throw new IllegalArgumentException("Inversed middle endian cannot be transformed,"); + } + if (type != DataType.INT) { + throw new IllegalArgumentException("Inversed middle endian can only be used with an integer,"); + } + buffer.writeByte((byte) (longValue >> 16)); + buffer.writeByte((byte) (longValue >> 24)); + buffer.writeByte((byte) longValue); + buffer.writeByte((byte) (longValue >> 8)); + } else { + throw new IllegalArgumentException("Unknown order."); + } + } + + /** + * Puts a standard data type with the specified value and byte order. + * + * @param type The data type. + * @param order The byte order. + * @param value The value. + */ + public void put(DataType type, DataOrder order, Number value) { + put(type, order, DataTransformation.NONE, value); + } + + /** + * Puts a standard data type with the specified value and transformation. + * + * @param type The type. + * @param transformation The transformation. + * @param value The value. + */ + public void put(DataType type, DataTransformation transformation, Number value) { + put(type, DataOrder.BIG, transformation, value); + } + + /** + * Puts a standard data type with the specified value. + * + * @param type The data type. + * @param value The value. + */ + public void put(DataType type, Number value) { + put(type, DataOrder.BIG, DataTransformation.NONE, value); + } + + /** + * Puts a single bit into the buffer. If {@code flag} is {@code true}, the value of the bit is {@code 1}. If + * {@code flag} is {@code false}, the value of the bit is {@code 0}. + * + * @param flag The flag. + */ + public void putBit(boolean flag) { + putBit(flag ? 1 : 0); + } + + /** + * Puts a single bit into the buffer with the value {@code value}. + * + * @param value The value. + */ + public void putBit(int value) { + putBits(1, value); + } + + /** + * Puts {@code numBits} into the buffer with the value {@code value}. + * + * @param numBits The number of bits to put into the buffer. + * @param value The value. + * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. + */ + public void putBits(int numBits, int value) { + if (numBits < 0 || numBits > 32) { + throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive."); } - /** - * Puts the specified byte array into the buffer. - * - * @param bytes The byte array. - */ - public void putBytes(byte[] bytes) { - buffer.writeBytes(bytes); - } + checkBitAccess(); - /** - * Puts the bytes from the specified buffer into this packet's buffer. - * - * @param buffer The source {@link ByteBuf}. - */ - public void putBytes(ByteBuf buffer) { - byte[] bytes = new byte[buffer.readableBytes()]; - buffer.markReaderIndex(); - try { - buffer.readBytes(bytes); - } finally { - buffer.resetReaderIndex(); - } - putBytes(bytes); - } + int bytePos = bitIndex >> 3; + int bitOffset = 8 - (bitIndex & 7); + bitIndex += numBits; - /** - * Puts the bytes into the buffer with the specified transformation. - * - * @param transformation The transformation. - * @param bytes The byte array. - */ - public void putBytes(DataTransformation transformation, byte[] bytes) { - if (transformation == DataTransformation.NONE) { - putBytes(bytes); - } else { - for (byte b : bytes) { - put(DataType.BYTE, transformation, b); - } - } - } + int requiredSpace = bytePos - buffer.writerIndex() + 1; + requiredSpace += (numBits + 7) / 8; + buffer.ensureWritable(requiredSpace); - /** - * Puts the specified byte array into the buffer in reverse. - * - * @param bytes The byte array. - */ - public void putBytesReverse(byte[] bytes) { - checkByteAccess(); - for (int i = bytes.length - 1; i >= 0; i--) { - buffer.writeByte(bytes[i]); - } + for (; numBits > bitOffset; bitOffset = 8) { + int tmp = buffer.getByte(bytePos); + tmp &= ~DataConstants.BIT_MASK[bitOffset]; + tmp |= value >> numBits - bitOffset & DataConstants.BIT_MASK[bitOffset]; + buffer.setByte(bytePos++, tmp); + numBits -= bitOffset; } + if (numBits == bitOffset) { + int tmp = buffer.getByte(bytePos); + tmp &= ~DataConstants.BIT_MASK[bitOffset]; + tmp |= value & DataConstants.BIT_MASK[bitOffset]; + buffer.setByte(bytePos, tmp); + } else { + int tmp = buffer.getByte(bytePos); + tmp &= ~(DataConstants.BIT_MASK[numBits] << bitOffset - numBits); + tmp |= (value & DataConstants.BIT_MASK[numBits]) << bitOffset - numBits; + buffer.setByte(bytePos, tmp); + } + } - /** - * Puts the bytes from the specified buffer into this packet's buffer, in reverse. - * - * @param buffer The source {@link ByteBuf}. - */ - public void putBytesReverse(ByteBuf buffer) { - byte[] bytes = new byte[buffer.readableBytes()]; - buffer.markReaderIndex(); - try { - buffer.readBytes(bytes); - } finally { - buffer.resetReaderIndex(); - } - putBytesReverse(bytes); - } + /** + * Puts the specified byte array into the buffer. + * + * @param bytes The byte array. + */ + public void putBytes(byte[] bytes) { + buffer.writeBytes(bytes); + } - /** - * Puts the specified byte array into the buffer in reverse with the specified transformation. - * - * @param transformation The transformation. - * @param bytes The byte array. - */ - public void putBytesReverse(DataTransformation transformation, byte[] bytes) { - if (transformation == DataTransformation.NONE) { - putBytesReverse(bytes); - } else { - for (int i = bytes.length - 1; i >= 0; i--) { - put(DataType.BYTE, transformation, bytes[i]); - } - } + /** + * Puts the bytes from the specified buffer into this packet's buffer. + * + * @param buffer The source {@link ByteBuf}. + */ + public void putBytes(ByteBuf buffer) { + byte[] bytes = new byte[buffer.readableBytes()]; + buffer.markReaderIndex(); + try { + buffer.readBytes(bytes); + } finally { + buffer.resetReaderIndex(); } + putBytes(bytes); + } - /** - * Puts a raw builder. Both builders (this and parameter) must be in byte access mode. - * - * @param builder The builder. - * @throws IllegalArgumentException If the builder is not raw. - */ - public void putRawBuilder(GamePacketBuilder builder) { - checkByteAccess(); - if (builder.type != PacketType.RAW) { - throw new IllegalArgumentException("Builder must be raw."); - } - builder.checkByteAccess(); - putBytes(builder.buffer); + /** + * Puts the bytes into the buffer with the specified transformation. + * + * @param transformation The transformation. + * @param bytes The byte array. + */ + public void putBytes(DataTransformation transformation, byte[] bytes) { + if (transformation == DataTransformation.NONE) { + putBytes(bytes); + } else { + for (byte b : bytes) { + put(DataType.BYTE, transformation, b); + } } + } - /** - * Puts a raw builder in reverse. Both builders (this and parameter) must be in byte access mode. - * - * @param builder The builder. - * @throws IllegalArgumentException If the builder is not raw. - */ - public void putRawBuilderReverse(GamePacketBuilder builder) { - checkByteAccess(); - if (builder.type != PacketType.RAW) { - throw new IllegalArgumentException("Builder must be raw."); - } - builder.checkByteAccess(); - putBytesReverse(builder.buffer); + /** + * Puts the specified byte array into the buffer in reverse. + * + * @param bytes The byte array. + */ + public void putBytesReverse(byte[] bytes) { + checkByteAccess(); + for (int i = bytes.length - 1; i >= 0; i--) { + buffer.writeByte(bytes[i]); } + } - /** - * Puts a smart into the buffer. - * - * @param value The value. - */ - public void putSmart(int value) { - checkByteAccess(); - if (value < 128) { - buffer.writeByte(value); - } else { - buffer.writeShort(value); - } + /** + * Puts the bytes from the specified buffer into this packet's buffer, in reverse. + * + * @param buffer The source {@link ByteBuf}. + */ + public void putBytesReverse(ByteBuf buffer) { + byte[] bytes = new byte[buffer.readableBytes()]; + buffer.markReaderIndex(); + try { + buffer.readBytes(bytes); + } finally { + buffer.resetReaderIndex(); } + putBytesReverse(bytes); + } - /** - * Puts a string into the buffer. - * - * @param str The string. - */ - public void putString(String str) { - checkByteAccess(); - char[] chars = str.toCharArray(); - for (char c : chars) { - buffer.writeByte((byte) c); - } - buffer.writeByte(NetworkConstants.STRING_TERMINATOR); + /** + * Puts the specified byte array into the buffer in reverse with the specified transformation. + * + * @param transformation The transformation. + * @param bytes The byte array. + */ + public void putBytesReverse(DataTransformation transformation, byte[] bytes) { + if (transformation == DataTransformation.NONE) { + putBytesReverse(bytes); + } else { + for (int i = bytes.length - 1; i >= 0; i--) { + put(DataType.BYTE, transformation, bytes[i]); + } } + } - /** - * Switches this builder's mode to the bit access mode. - * - * @throws IllegalStateException If the builder is already in bit access mode. - */ - public void switchToBitAccess() { - if (mode == AccessMode.BIT_ACCESS) { - throw new IllegalStateException("Already in bit access mode."); - } - mode = AccessMode.BIT_ACCESS; - bitIndex = buffer.writerIndex() * 8; + /** + * Puts a raw builder. Both builders (this and parameter) must be in byte access mode. + * + * @param builder The builder. + * @throws IllegalArgumentException If the builder is not raw. + */ + public void putRawBuilder(GamePacketBuilder builder) { + checkByteAccess(); + if (builder.type != PacketType.RAW) { + throw new IllegalArgumentException("Builder must be raw."); } + builder.checkByteAccess(); + putBytes(builder.buffer); + } - /** - * Switches this builder's mode to the byte access mode. - * - * @throws IllegalStateException If the builder is already in byte access mode. - */ - public void switchToByteAccess() { - if (mode == AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("Already in byte access mode."); - } - mode = AccessMode.BYTE_ACCESS; - buffer.writerIndex((bitIndex + 7) / 8); + /** + * Puts a raw builder in reverse. Both builders (this and parameter) must be in byte access mode. + * + * @param builder The builder. + * @throws IllegalArgumentException If the builder is not raw. + */ + public void putRawBuilderReverse(GamePacketBuilder builder) { + checkByteAccess(); + if (builder.type != PacketType.RAW) { + throw new IllegalArgumentException("Builder must be raw."); } + builder.checkByteAccess(); + putBytesReverse(builder.buffer); + } - /** - * Creates a {@link GamePacket} based on the current contents of this builder. - * - * @return The {@link GamePacket}. - * @throws IllegalStateException If the builder is not in byte access mode, or if the packet is raw. - */ - public GamePacket toGamePacket() { - if (type == PacketType.RAW) { - throw new IllegalStateException("Raw packets cannot be converted to a game packet."); - } - if (mode != AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("Must be in byte access mode to convert to a packet."); - } - return new GamePacket(opcode, type, buffer); + /** + * Puts a smart into the buffer. + * + * @param value The value. + */ + public void putSmart(int value) { + checkByteAccess(); + if (value < 128) { + buffer.writeByte(value); + } else { + buffer.writeShort(value); } + } + + /** + * Puts a string into the buffer. + * + * @param str The string. + */ + public void putString(String str) { + checkByteAccess(); + char[] chars = str.toCharArray(); + for (char c : chars) { + buffer.writeByte((byte) c); + } + buffer.writeByte(NetworkConstants.STRING_TERMINATOR); + } + + /** + * Switches this builder's mode to the bit access mode. + * + * @throws IllegalStateException If the builder is already in bit access mode. + */ + public void switchToBitAccess() { + if (mode == AccessMode.BIT_ACCESS) { + throw new IllegalStateException("Already in bit access mode."); + } + mode = AccessMode.BIT_ACCESS; + bitIndex = buffer.writerIndex() * 8; + } + + /** + * Switches this builder's mode to the byte access mode. + * + * @throws IllegalStateException If the builder is already in byte access mode. + */ + public void switchToByteAccess() { + if (mode == AccessMode.BYTE_ACCESS) { + throw new IllegalStateException("Already in byte access mode."); + } + mode = AccessMode.BYTE_ACCESS; + buffer.writerIndex((bitIndex + 7) / 8); + } + + /** + * Creates a {@link GamePacket} based on the current contents of this builder. + * + * @return The {@link GamePacket}. + * @throws IllegalStateException If the builder is not in byte access mode, or if the packet is raw. + */ + public GamePacket toGamePacket() { + if (type == PacketType.RAW) { + throw new IllegalStateException("Raw packets cannot be converted to a game packet."); + } + if (mode != AccessMode.BYTE_ACCESS) { + throw new IllegalStateException("Must be in byte access mode to convert to a packet."); + } + return new GamePacket(opcode, type, buffer); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GamePacketDecoder.java b/src/org/apollo/net/codec/game/GamePacketDecoder.java index ce32ec47..bc2b8a54 100644 --- a/src/org/apollo/net/codec/game/GamePacketDecoder.java +++ b/src/org/apollo/net/codec/game/GamePacketDecoder.java @@ -21,134 +21,134 @@ import org.apollo.util.StatefulFrameDecoder; */ public final class GamePacketDecoder extends StatefulFrameDecoder { - /** - * The current length. - */ - private int length; + /** + * The current length. + */ + private int length; - /** - * The current opcode. - */ - private int opcode; + /** + * The current opcode. + */ + private int opcode; - /** - * The random number generator. - */ - private final IsaacRandom random; + /** + * The random number generator. + */ + private final IsaacRandom random; - /** - * The current release. - */ - private final Release release; + /** + * The current release. + */ + private final Release release; - /** - * The packet type. - */ - private PacketType type; + /** + * The packet type. + */ + private PacketType type; - /** - * Creates the {@link GamePacketDecoder}. - * - * @param random The random number generator. - * @param release The current release. - */ - public GamePacketDecoder(IsaacRandom random, Release release) { - super(GameDecoderState.GAME_OPCODE); - this.random = random; - this.release = release; + /** + * Creates the {@link GamePacketDecoder}. + * + * @param random The random number generator. + * @param release The current release. + */ + public GamePacketDecoder(IsaacRandom random, Release release) { + super(GameDecoderState.GAME_OPCODE); + this.random = random; + this.release = release; + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out, GameDecoderState state) + throws IOException { + switch (state) { + case GAME_OPCODE: + decodeOpcode(ctx, in, out); + break; + case GAME_LENGTH: + decodeLength(ctx, in, out); + break; + case GAME_PAYLOAD: + decodePayload(ctx, in, out); + break; + default: + throw new IllegalStateException("Invalid game decoder state."); } + } - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out, GameDecoderState state) - throws IOException { - switch (state) { - case GAME_OPCODE: - decodeOpcode(ctx, in, out); - break; - case GAME_LENGTH: - decodeLength(ctx, in, out); - break; - case GAME_PAYLOAD: - decodePayload(ctx, in, out); - break; - default: - throw new IllegalStateException("Invalid game decoder state."); + /** + * Decodes in the length state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws Exception If an error occurs. + */ + private Object decodeLength(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + if (buffer.isReadable()) { + length = buffer.readUnsignedByte(); + if (length != 0) { + setState(GameDecoderState.GAME_PAYLOAD); + } + } + return null; + } + + /** + * Decodes in the opcode state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws IOException If a received opcode or packet type is illegal. + */ + private void decodeOpcode(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws IOException { + if (buffer.isReadable()) { + int encryptedOpcode = buffer.readUnsignedByte(); + opcode = encryptedOpcode - random.nextInt() & 0xFF; + + PacketMetaData metaData = release.getIncomingPacketMetaData(opcode); + if (metaData == null) { + throw new IOException("Illegal opcode: " + opcode + "."); + } + + type = metaData.getType(); + switch (type) { + case FIXED: + length = metaData.getLength(); + if (length == 0) { + setState(GameDecoderState.GAME_OPCODE); + out.add(new GamePacket(opcode, type, Unpooled.EMPTY_BUFFER)); + } else { + setState(GameDecoderState.GAME_PAYLOAD); } + break; + case VARIABLE_BYTE: + setState(GameDecoderState.GAME_LENGTH); + break; + default: + throw new IOException("Illegal packet type: " + type + "."); + } } + } - /** - * Decodes in the length state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws Exception If an error occurs. - */ - private Object decodeLength(ChannelHandlerContext ctx, ByteBuf buffer, List out) { - if (buffer.isReadable()) { - length = buffer.readUnsignedByte(); - if (length != 0) { - setState(GameDecoderState.GAME_PAYLOAD); - } - } - return null; - } - - /** - * Decodes in the opcode state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws IOException If a received opcode or packet type is illegal. - */ - private void decodeOpcode(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws IOException { - if (buffer.isReadable()) { - int encryptedOpcode = buffer.readUnsignedByte(); - opcode = encryptedOpcode - random.nextInt() & 0xFF; - - PacketMetaData metaData = release.getIncomingPacketMetaData(opcode); - if (metaData == null) { - throw new IOException("Illegal opcode: " + opcode + "."); - } - - type = metaData.getType(); - switch (type) { - case FIXED: - length = metaData.getLength(); - if (length == 0) { - setState(GameDecoderState.GAME_OPCODE); - out.add(new GamePacket(opcode, type, Unpooled.EMPTY_BUFFER)); - } else { - setState(GameDecoderState.GAME_PAYLOAD); - } - break; - case VARIABLE_BYTE: - setState(GameDecoderState.GAME_LENGTH); - break; - default: - throw new IOException("Illegal packet type: " + type + "."); - } - } - } - - /** - * Decodes in the payload state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws Exception If an error occurs. - */ - private void decodePayload(ChannelHandlerContext ctx, ByteBuf buffer, List out) { - if (buffer.readableBytes() >= length) { - ByteBuf payload = buffer.readBytes(length); - setState(GameDecoderState.GAME_OPCODE); - out.add(new GamePacket(opcode, type, payload)); - } + /** + * Decodes in the payload state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws Exception If an error occurs. + */ + private void decodePayload(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + if (buffer.readableBytes() >= length) { + ByteBuf payload = buffer.readBytes(length); + setState(GameDecoderState.GAME_OPCODE); + out.add(new GamePacket(opcode, type, payload)); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GamePacketEncoder.java b/src/org/apollo/net/codec/game/GamePacketEncoder.java index 3468cd94..e893b71c 100644 --- a/src/org/apollo/net/codec/game/GamePacketEncoder.java +++ b/src/org/apollo/net/codec/game/GamePacketEncoder.java @@ -18,48 +18,48 @@ import org.apollo.net.meta.PacketType; */ public final class GamePacketEncoder extends MessageToMessageEncoder { - /** - * The random number generator. - */ - private final IsaacRandom random; + /** + * The random number generator. + */ + private final IsaacRandom random; - /** - * Creates the {@link GamePacketEncoder}. - * - * @param random The random number generator. - */ - public GamePacketEncoder(IsaacRandom random) { - this.random = random; + /** + * Creates the {@link GamePacketEncoder}. + * + * @param random The random number generator. + */ + public GamePacketEncoder(IsaacRandom random) { + this.random = random; + } + + @Override + protected void encode(ChannelHandlerContext ctx, GamePacket msg, List out) throws Exception { + GamePacket packet = (GamePacket) msg; + PacketType type = packet.getType(); + int headerLength = 1; + int payloadLength = packet.getLength(); + if (type == PacketType.VARIABLE_BYTE) { + headerLength++; + if (payloadLength >= 256) { + throw new Exception("Payload too long for variable byte packet."); + } + } else if (type == PacketType.VARIABLE_SHORT) { + headerLength += 2; + if (payloadLength >= 65536) { + throw new Exception("Payload too long for variable short packet."); + } } - @Override - protected void encode(ChannelHandlerContext ctx, GamePacket msg, List out) throws Exception { - GamePacket packet = (GamePacket) msg; - PacketType type = packet.getType(); - int headerLength = 1; - int payloadLength = packet.getLength(); - if (type == PacketType.VARIABLE_BYTE) { - headerLength++; - if (payloadLength >= 256) { - throw new Exception("Payload too long for variable byte packet."); - } - } else if (type == PacketType.VARIABLE_SHORT) { - headerLength += 2; - if (payloadLength >= 65536) { - throw new Exception("Payload too long for variable short packet."); - } - } - - ByteBuf buffer = Unpooled.buffer(headerLength + payloadLength); - buffer.writeByte(packet.getOpcode() + random.nextInt() & 0xFF); - if (type == PacketType.VARIABLE_BYTE) { - buffer.writeByte(payloadLength); - } else if (type == PacketType.VARIABLE_SHORT) { - buffer.writeShort(payloadLength); - } - buffer.writeBytes(packet.getPayload()); - - out.add(buffer); + ByteBuf buffer = Unpooled.buffer(headerLength + payloadLength); + buffer.writeByte(packet.getOpcode() + random.nextInt() & 0xFF); + if (type == PacketType.VARIABLE_BYTE) { + buffer.writeByte(payloadLength); + } else if (type == PacketType.VARIABLE_SHORT) { + buffer.writeShort(payloadLength); } + buffer.writeBytes(packet.getPayload()); + + out.add(buffer); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/game/GamePacketReader.java b/src/org/apollo/net/codec/game/GamePacketReader.java index 08aaa2b1..28be0d16 100644 --- a/src/org/apollo/net/codec/game/GamePacketReader.java +++ b/src/org/apollo/net/codec/game/GamePacketReader.java @@ -11,418 +11,418 @@ import org.apollo.util.BufferUtil; */ public final class GamePacketReader { - /** - * The current bit index. - */ - private int bitIndex; + /** + * The current bit index. + */ + private int bitIndex; - /** - * The buffer. - */ - private final ByteBuf buffer; + /** + * The buffer. + */ + private final ByteBuf buffer; - /** - * The current mode. - */ - private AccessMode mode = AccessMode.BYTE_ACCESS; + /** + * The current mode. + */ + private AccessMode mode = AccessMode.BYTE_ACCESS; - /** - * Creates the reader. - * - * @param packet The packet. - */ - public GamePacketReader(GamePacket packet) { - buffer = packet.getPayload(); + /** + * Creates the reader. + * + * @param packet The packet. + */ + public GamePacketReader(GamePacket packet) { + buffer = packet.getPayload(); + } + + /** + * Checks that this reader is in the bit access mode. + * + * @throws IllegalStateException If the reader is not in bit access mode. + */ + private void checkBitAccess() { + if (mode != AccessMode.BIT_ACCESS) { + throw new IllegalStateException("For bit-based calls to work, the mode must be bit access."); } + } - /** - * Checks that this reader is in the bit access mode. - * - * @throws IllegalStateException If the reader is not in bit access mode. - */ - private void checkBitAccess() { - if (mode != AccessMode.BIT_ACCESS) { - throw new IllegalStateException("For bit-based calls to work, the mode must be bit access."); - } + /** + * Checks that this reader is in the byte access mode. + * + * @throws IllegalStateException If the reader is not in byte access mode. + */ + private void checkByteAccess() { + if (mode != AccessMode.BYTE_ACCESS) { + throw new IllegalStateException("For byte-based calls to work, the mode must be byte access."); } + } - /** - * Checks that this reader is in the byte access mode. - * - * @throws IllegalStateException If the reader is not in byte access mode. - */ - private void checkByteAccess() { - if (mode != AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("For byte-based calls to work, the mode must be byte access."); - } - } - - /** - * Reads a standard data type from the buffer with the specified order and transformation. - * - * @param type The data type. - * @param order The data order. - * @param transformation The data transformation. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - private long get(DataType type, DataOrder order, DataTransformation transformation) { - checkByteAccess(); - long longValue = 0; - int length = type.getBytes(); - if (order == DataOrder.BIG) { - for (int i = length - 1; i >= 0; i--) { - if (i == 0 && transformation != DataTransformation.NONE) { - if (transformation == DataTransformation.ADD) { - longValue |= buffer.readByte() - 128 & 0xFFL; - } else if (transformation == DataTransformation.NEGATE) { - longValue |= -buffer.readByte() & 0xFFL; - } else if (transformation == DataTransformation.SUBTRACT) { - longValue |= 128 - buffer.readByte() & 0xFFL; - } else { - throw new IllegalArgumentException("Unknown transformation."); - } - } else { - longValue |= (buffer.readByte() & 0xFFL) << i * 8; - } - } - } else if (order == DataOrder.LITTLE) { - for (int i = 0; i < length; i++) { - if (i == 0 && transformation != DataTransformation.NONE) { - if (transformation == DataTransformation.ADD) { - longValue |= buffer.readByte() - 128 & 0xFFL; - } else if (transformation == DataTransformation.NEGATE) { - longValue |= -buffer.readByte() & 0xFFL; - } else if (transformation == DataTransformation.SUBTRACT) { - longValue |= 128 - buffer.readByte() & 0xFFL; - } else { - throw new IllegalArgumentException("Unknown transformation."); - } - } else { - longValue |= (buffer.readByte() & 0xFFL) << i * 8; - } - } - } else if (order == DataOrder.MIDDLE) { - if (transformation != DataTransformation.NONE) { - throw new IllegalArgumentException("Middle endian cannot be transformed."); - } - if (type != DataType.INT) { - throw new IllegalArgumentException("Middle endian can only be used with an integer."); - } - longValue |= (buffer.readByte() & 0xFF) << 8; - longValue |= buffer.readByte() & 0xFF; - longValue |= (buffer.readByte() & 0xFF) << 24; - longValue |= (buffer.readByte() & 0xFF) << 16; - } else if (order == DataOrder.INVERSED_MIDDLE) { - if (transformation != DataTransformation.NONE) { - throw new IllegalArgumentException("Inversed middle endian cannot be transformed."); - } - if (type != DataType.INT) { - throw new IllegalArgumentException("Inversed middle endian can only be used with an integer."); - } - longValue |= (buffer.readByte() & 0xFF) << 16; - longValue |= (buffer.readByte() & 0xFF) << 24; - longValue |= buffer.readByte() & 0xFF; - longValue |= (buffer.readByte() & 0xFF) << 8; + /** + * Reads a standard data type from the buffer with the specified order and transformation. + * + * @param type The data type. + * @param order The data order. + * @param transformation The data transformation. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + private long get(DataType type, DataOrder order, DataTransformation transformation) { + checkByteAccess(); + long longValue = 0; + int length = type.getBytes(); + if (order == DataOrder.BIG) { + for (int i = length - 1; i >= 0; i--) { + if (i == 0 && transformation != DataTransformation.NONE) { + if (transformation == DataTransformation.ADD) { + longValue |= buffer.readByte() - 128 & 0xFFL; + } else if (transformation == DataTransformation.NEGATE) { + longValue |= -buffer.readByte() & 0xFFL; + } else if (transformation == DataTransformation.SUBTRACT) { + longValue |= 128 - buffer.readByte() & 0xFFL; + } else { + throw new IllegalArgumentException("Unknown transformation."); + } } else { - throw new IllegalArgumentException("Unknown order."); + longValue |= (buffer.readByte() & 0xFFL) << i * 8; } - return longValue; - } - - /** - * Gets a bit from the buffer. - * - * @return The value. - * @throws IllegalStateException If the reader is not in bit access mode. - */ - public int getBit() { - return getBits(1); - } - - /** - * Gets {@code numBits} from the buffer. - * - * @param numBits The number of bits. - * @return The value. - * @throws IllegalStateException If the reader is not in bit access mode. - * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. - */ - public int getBits(int numBits) { - if (numBits < 0 || numBits > 32) { - throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive."); - } - - checkBitAccess(); - - int bytePos = bitIndex >> 3; - int bitOffset = 8 - (bitIndex & 7); - int value = 0; - bitIndex += numBits; - - for (; numBits > bitOffset; bitOffset = 8) { - value += (buffer.getByte(bytePos++) & DataConstants.BIT_MASK[bitOffset]) << numBits - bitOffset; - numBits -= bitOffset; - } - if (numBits == bitOffset) { - value += buffer.getByte(bytePos) & DataConstants.BIT_MASK[bitOffset]; + } + } else if (order == DataOrder.LITTLE) { + for (int i = 0; i < length; i++) { + if (i == 0 && transformation != DataTransformation.NONE) { + if (transformation == DataTransformation.ADD) { + longValue |= buffer.readByte() - 128 & 0xFFL; + } else if (transformation == DataTransformation.NEGATE) { + longValue |= -buffer.readByte() & 0xFFL; + } else if (transformation == DataTransformation.SUBTRACT) { + longValue |= 128 - buffer.readByte() & 0xFFL; + } else { + throw new IllegalArgumentException("Unknown transformation."); + } } else { - value += buffer.getByte(bytePos) >> bitOffset - numBits & DataConstants.BIT_MASK[numBits]; + longValue |= (buffer.readByte() & 0xFFL) << i * 8; } - return value; + } + } else if (order == DataOrder.MIDDLE) { + if (transformation != DataTransformation.NONE) { + throw new IllegalArgumentException("Middle endian cannot be transformed."); + } + if (type != DataType.INT) { + throw new IllegalArgumentException("Middle endian can only be used with an integer."); + } + longValue |= (buffer.readByte() & 0xFF) << 8; + longValue |= buffer.readByte() & 0xFF; + longValue |= (buffer.readByte() & 0xFF) << 24; + longValue |= (buffer.readByte() & 0xFF) << 16; + } else if (order == DataOrder.INVERSED_MIDDLE) { + if (transformation != DataTransformation.NONE) { + throw new IllegalArgumentException("Inversed middle endian cannot be transformed."); + } + if (type != DataType.INT) { + throw new IllegalArgumentException("Inversed middle endian can only be used with an integer."); + } + longValue |= (buffer.readByte() & 0xFF) << 16; + longValue |= (buffer.readByte() & 0xFF) << 24; + longValue |= buffer.readByte() & 0xFF; + longValue |= (buffer.readByte() & 0xFF) << 8; + } else { + throw new IllegalArgumentException("Unknown order."); + } + return longValue; + } + + /** + * Gets a bit from the buffer. + * + * @return The value. + * @throws IllegalStateException If the reader is not in bit access mode. + */ + public int getBit() { + return getBits(1); + } + + /** + * Gets {@code numBits} from the buffer. + * + * @param numBits The number of bits. + * @return The value. + * @throws IllegalStateException If the reader is not in bit access mode. + * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. + */ + public int getBits(int numBits) { + if (numBits < 0 || numBits > 32) { + throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive."); } - /** - * Gets bytes. - * - * @param bytes The target byte array. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public void getBytes(byte[] bytes) { - checkByteAccess(); - for (int i = 0; i < bytes.length; i++) { - bytes[i] = buffer.readByte(); - } - } + checkBitAccess(); - /** - * Gets bytes with the specified transformation. - * - * @param transformation The transformation. - * @param bytes The target byte array. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public void getBytes(DataTransformation transformation, byte[] bytes) { - if (transformation == DataTransformation.NONE) { - getBytesReverse(bytes); - } else { - for (int i = 0; i < bytes.length; i++) { - bytes[i] = (byte) getSigned(DataType.BYTE, transformation); - } - } - } + int bytePos = bitIndex >> 3; + int bitOffset = 8 - (bitIndex & 7); + int value = 0; + bitIndex += numBits; - /** - * Gets bytes in reverse. - * - * @param bytes The target byte array. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public void getBytesReverse(byte[] bytes) { - checkByteAccess(); - for (int i = bytes.length - 1; i >= 0; i--) { - bytes[i] = buffer.readByte(); - } + for (; numBits > bitOffset; bitOffset = 8) { + value += (buffer.getByte(bytePos++) & DataConstants.BIT_MASK[bitOffset]) << numBits - bitOffset; + numBits -= bitOffset; } + if (numBits == bitOffset) { + value += buffer.getByte(bytePos) & DataConstants.BIT_MASK[bitOffset]; + } else { + value += buffer.getByte(bytePos) >> bitOffset - numBits & DataConstants.BIT_MASK[numBits]; + } + return value; + } - /** - * Gets bytes in reverse with the specified transformation. - * - * @param transformation The transformation. - * @param bytes The target byte array. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public void getBytesReverse(DataTransformation transformation, byte[] bytes) { - if (transformation == DataTransformation.NONE) { - getBytesReverse(bytes); - } else { - for (int i = bytes.length - 1; i >= 0; i--) { - bytes[i] = (byte) getSigned(DataType.BYTE, transformation); - } - } + /** + * Gets bytes. + * + * @param bytes The target byte array. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public void getBytes(byte[] bytes) { + checkByteAccess(); + for (int i = 0; i < bytes.length; i++) { + bytes[i] = buffer.readByte(); } + } - /** - * Gets the length of this reader. - * - * @return The length of this reader. - */ - public int getLength() { - checkByteAccess(); - return buffer.writableBytes(); + /** + * Gets bytes with the specified transformation. + * + * @param transformation The transformation. + * @param bytes The target byte array. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public void getBytes(DataTransformation transformation, byte[] bytes) { + if (transformation == DataTransformation.NONE) { + getBytesReverse(bytes); + } else { + for (int i = 0; i < bytes.length; i++) { + bytes[i] = (byte) getSigned(DataType.BYTE, transformation); + } } + } - /** - * Gets a signed data type from the buffer. - * - * @param type The data type. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public long getSigned(DataType type) { - return getSigned(type, DataOrder.BIG, DataTransformation.NONE); + /** + * Gets bytes in reverse. + * + * @param bytes The target byte array. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public void getBytesReverse(byte[] bytes) { + checkByteAccess(); + for (int i = bytes.length - 1; i >= 0; i--) { + bytes[i] = buffer.readByte(); } + } - /** - * Gets a signed data type from the buffer with the specified order. - * - * @param type The data type. - * @param order The byte order. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getSigned(DataType type, DataOrder order) { - return getSigned(type, order, DataTransformation.NONE); + /** + * Gets bytes in reverse with the specified transformation. + * + * @param transformation The transformation. + * @param bytes The target byte array. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public void getBytesReverse(DataTransformation transformation, byte[] bytes) { + if (transformation == DataTransformation.NONE) { + getBytesReverse(bytes); + } else { + for (int i = bytes.length - 1; i >= 0; i--) { + bytes[i] = (byte) getSigned(DataType.BYTE, transformation); + } } + } - /** - * Gets a signed data type from the buffer with the specified order and transformation. - * - * @param type The data type. - * @param order The byte order. - * @param transformation The data transformation. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getSigned(DataType type, DataOrder order, DataTransformation transformation) { - long longValue = get(type, order, transformation); - if (type != DataType.LONG) { - int max = (int) (Math.pow(2, type.getBytes() * 8 - 1) - 1); - if (longValue > max) { - longValue -= (max + 1) * 2; - } - } - return longValue; - } + /** + * Gets the length of this reader. + * + * @return The length of this reader. + */ + public int getLength() { + checkByteAccess(); + return buffer.writableBytes(); + } - /** - * Gets a signed data type from the buffer with the specified transformation. - * - * @param type The data type. - * @param transformation The data transformation. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getSigned(DataType type, DataTransformation transformation) { - return getSigned(type, DataOrder.BIG, transformation); - } + /** + * Gets a signed data type from the buffer. + * + * @param type The data type. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public long getSigned(DataType type) { + return getSigned(type, DataOrder.BIG, DataTransformation.NONE); + } - /** - * Gets a signed smart from the buffer. - * - * @return The smart. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public int getSignedSmart() { - checkByteAccess(); - int peek = buffer.getByte(buffer.readerIndex()); - if (peek < 128) { - return buffer.readByte() - 64; - } else { - return buffer.readShort() - 49152; - } - } + /** + * Gets a signed data type from the buffer with the specified order. + * + * @param type The data type. + * @param order The byte order. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getSigned(DataType type, DataOrder order) { + return getSigned(type, order, DataTransformation.NONE); + } - /** - * Gets a string from the buffer. - * - * @return The string. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public String getString() { - checkByteAccess(); - return BufferUtil.readString(buffer); + /** + * Gets a signed data type from the buffer with the specified order and transformation. + * + * @param type The data type. + * @param order The byte order. + * @param transformation The data transformation. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getSigned(DataType type, DataOrder order, DataTransformation transformation) { + long longValue = get(type, order, transformation); + if (type != DataType.LONG) { + int max = (int) (Math.pow(2, type.getBytes() * 8 - 1) - 1); + if (longValue > max) { + longValue -= (max + 1) * 2; + } } + return longValue; + } - /** - * Gets an unsigned data type from the buffer. - * - * @param type The data type. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public long getUnsigned(DataType type) { - return getUnsigned(type, DataOrder.BIG, DataTransformation.NONE); - } + /** + * Gets a signed data type from the buffer with the specified transformation. + * + * @param type The data type. + * @param transformation The data transformation. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getSigned(DataType type, DataTransformation transformation) { + return getSigned(type, DataOrder.BIG, transformation); + } - /** - * Gets an unsigned data type from the buffer with the specified order. - * - * @param type The data type. - * @param order The byte order. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getUnsigned(DataType type, DataOrder order) { - return getUnsigned(type, order, DataTransformation.NONE); + /** + * Gets a signed smart from the buffer. + * + * @return The smart. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public int getSignedSmart() { + checkByteAccess(); + int peek = buffer.getByte(buffer.readerIndex()); + if (peek < 128) { + return buffer.readByte() - 64; + } else { + return buffer.readShort() - 49152; } + } - /** - * Gets an unsigned data type from the buffer with the specified order and transformation. - * - * @param type The data type. - * @param order The byte order. - * @param transformation The data transformation. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getUnsigned(DataType type, DataOrder order, DataTransformation transformation) { - long longValue = get(type, order, transformation); - if (type == DataType.LONG) { - throw new IllegalArgumentException("Due to java restrictions, longs must be read as signed types."); - } - return longValue & 0xFFFFFFFFFFFFFFFFL; - } + /** + * Gets a string from the buffer. + * + * @return The string. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public String getString() { + checkByteAccess(); + return BufferUtil.readString(buffer); + } - /** - * Gets an unsigned data type from the buffer with the specified transformation. - * - * @param type The data type. - * @param transformation The data transformation. - * @return The value. - * @throws IllegalStateException If this reader is not in byte access mode. - * @throws IllegalArgumentException If the combination is invalid. - */ - public long getUnsigned(DataType type, DataTransformation transformation) { - return getUnsigned(type, DataOrder.BIG, transformation); - } + /** + * Gets an unsigned data type from the buffer. + * + * @param type The data type. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public long getUnsigned(DataType type) { + return getUnsigned(type, DataOrder.BIG, DataTransformation.NONE); + } - /** - * Gets an unsigned smart from the buffer. - * - * @return The smart. - * @throws IllegalStateException If this reader is not in byte access mode. - */ - public int getUnsignedSmart() { - checkByteAccess(); - int peek = buffer.getByte(buffer.readerIndex()); - if (peek < 128) { - return buffer.readByte(); - } else { - return buffer.readShort() - 32768; - } - } + /** + * Gets an unsigned data type from the buffer with the specified order. + * + * @param type The data type. + * @param order The byte order. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getUnsigned(DataType type, DataOrder order) { + return getUnsigned(type, order, DataTransformation.NONE); + } - /** - * Switches this builder's mode to the bit access mode. - * - * @throws IllegalStateException If the builder is already in bit access mode. - */ - public void switchToBitAccess() { - if (mode == AccessMode.BIT_ACCESS) { - throw new IllegalStateException("Already in bit access mode."); - } - mode = AccessMode.BIT_ACCESS; - bitIndex = buffer.readerIndex() * 8; + /** + * Gets an unsigned data type from the buffer with the specified order and transformation. + * + * @param type The data type. + * @param order The byte order. + * @param transformation The data transformation. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getUnsigned(DataType type, DataOrder order, DataTransformation transformation) { + long longValue = get(type, order, transformation); + if (type == DataType.LONG) { + throw new IllegalArgumentException("Due to java restrictions, longs must be read as signed types."); } + return longValue & 0xFFFFFFFFFFFFFFFFL; + } - /** - * Switches this builder's mode to the byte access mode. - * - * @throws IllegalStateException If the builder is already in byte access mode. - */ - public void switchToByteAccess() { - if (mode == AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("Already in byte access mode."); - } - mode = AccessMode.BYTE_ACCESS; - buffer.readerIndex((bitIndex + 7) / 8); + /** + * Gets an unsigned data type from the buffer with the specified transformation. + * + * @param type The data type. + * @param transformation The data transformation. + * @return The value. + * @throws IllegalStateException If this reader is not in byte access mode. + * @throws IllegalArgumentException If the combination is invalid. + */ + public long getUnsigned(DataType type, DataTransformation transformation) { + return getUnsigned(type, DataOrder.BIG, transformation); + } + + /** + * Gets an unsigned smart from the buffer. + * + * @return The smart. + * @throws IllegalStateException If this reader is not in byte access mode. + */ + public int getUnsignedSmart() { + checkByteAccess(); + int peek = buffer.getByte(buffer.readerIndex()); + if (peek < 128) { + return buffer.readByte(); + } else { + return buffer.readShort() - 32768; } + } + + /** + * Switches this builder's mode to the bit access mode. + * + * @throws IllegalStateException If the builder is already in bit access mode. + */ + public void switchToBitAccess() { + if (mode == AccessMode.BIT_ACCESS) { + throw new IllegalStateException("Already in bit access mode."); + } + mode = AccessMode.BIT_ACCESS; + bitIndex = buffer.readerIndex() * 8; + } + + /** + * Switches this builder's mode to the byte access mode. + * + * @throws IllegalStateException If the builder is already in byte access mode. + */ + public void switchToByteAccess() { + if (mode == AccessMode.BYTE_ACCESS) { + throw new IllegalStateException("Already in byte access mode."); + } + mode = AccessMode.BYTE_ACCESS; + buffer.readerIndex((bitIndex + 7) / 8); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/handshake/HandshakeConstants.java b/src/org/apollo/net/codec/handshake/HandshakeConstants.java index e3cdffc4..6c71c383 100644 --- a/src/org/apollo/net/codec/handshake/HandshakeConstants.java +++ b/src/org/apollo/net/codec/handshake/HandshakeConstants.java @@ -7,21 +7,21 @@ package org.apollo.net.codec.handshake; */ public final class HandshakeConstants { - /** - * The id of the game service. - */ - public static final int SERVICE_GAME = 14; + /** + * The id of the game service. + */ + public static final int SERVICE_GAME = 14; - /** - * The id of the update service. - */ - public static final int SERVICE_UPDATE = 15; + /** + * The id of the update service. + */ + public static final int SERVICE_UPDATE = 15; - /** - * Default private constructor to prevent instantiation by other classes. - */ - private HandshakeConstants() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private HandshakeConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/handshake/HandshakeDecoder.java b/src/org/apollo/net/codec/handshake/HandshakeDecoder.java index 9025e7a0..e4b7e3e1 100644 --- a/src/org/apollo/net/codec/handshake/HandshakeDecoder.java +++ b/src/org/apollo/net/codec/handshake/HandshakeDecoder.java @@ -19,35 +19,35 @@ import org.apollo.net.codec.update.UpdateEncoder; */ public final class HandshakeDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { - if (buffer.isReadable()) { - int id = buffer.readUnsignedByte(); + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + if (buffer.isReadable()) { + int id = buffer.readUnsignedByte(); - switch (id) { - case HandshakeConstants.SERVICE_GAME: - ctx.pipeline().addFirst("loginEncoder", new LoginEncoder()); - ctx.pipeline().addAfter("handshakeDecoder", "loginDecoder", new LoginDecoder()); - break; - case HandshakeConstants.SERVICE_UPDATE: - ctx.pipeline().addFirst("updateEncoder", new UpdateEncoder()); - ctx.pipeline().addBefore("handler", "updateDecoder", new UpdateDecoder()); - ByteBuf buf = ctx.alloc().buffer(8); - buf.writeLong(0); - ctx.channel().writeAndFlush(buf); - break; - default: - throw new IllegalArgumentException("Invalid service id."); - } + switch (id) { + case HandshakeConstants.SERVICE_GAME: + ctx.pipeline().addFirst("loginEncoder", new LoginEncoder()); + ctx.pipeline().addAfter("handshakeDecoder", "loginDecoder", new LoginDecoder()); + break; + case HandshakeConstants.SERVICE_UPDATE: + ctx.pipeline().addFirst("updateEncoder", new UpdateEncoder()); + ctx.pipeline().addBefore("handler", "updateDecoder", new UpdateDecoder()); + ByteBuf buf = ctx.alloc().buffer(8); + buf.writeLong(0); + ctx.channel().writeAndFlush(buf); + break; + default: + throw new IllegalArgumentException("Invalid service id."); + } - ctx.pipeline().remove(this); - HandshakeMessage message = new HandshakeMessage(id); + ctx.pipeline().remove(this); + HandshakeMessage message = new HandshakeMessage(id); - out.add(message); - if (buffer.isReadable()) { - out.add(buffer.readBytes(buffer.readableBytes())); - } - } + out.add(message); + if (buffer.isReadable()) { + out.add(buffer.readBytes(buffer.readableBytes())); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/handshake/HandshakeMessage.java b/src/org/apollo/net/codec/handshake/HandshakeMessage.java index bc82a468..1950f97f 100644 --- a/src/org/apollo/net/codec/handshake/HandshakeMessage.java +++ b/src/org/apollo/net/codec/handshake/HandshakeMessage.java @@ -7,27 +7,27 @@ package org.apollo.net.codec.handshake; */ public final class HandshakeMessage { - /** - * The service id. - */ - private final int serviceId; + /** + * The service id. + */ + private final int serviceId; - /** - * Creates the handshake message. - * - * @param serviceId The service id. - */ - public HandshakeMessage(int serviceId) { - this.serviceId = serviceId; - } + /** + * Creates the handshake message. + * + * @param serviceId The service id. + */ + public HandshakeMessage(int serviceId) { + this.serviceId = serviceId; + } - /** - * Gets the service id. - * - * @return The service id. - */ - public int getServiceId() { - return serviceId; - } + /** + * Gets the service id. + * + * @return The service id. + */ + public int getServiceId() { + return serviceId; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/jaggrab/JagGrabRequest.java b/src/org/apollo/net/codec/jaggrab/JagGrabRequest.java index a3f65d2c..5eb46aa6 100644 --- a/src/org/apollo/net/codec/jaggrab/JagGrabRequest.java +++ b/src/org/apollo/net/codec/jaggrab/JagGrabRequest.java @@ -7,27 +7,27 @@ package org.apollo.net.codec.jaggrab; */ public final class JagGrabRequest { - /** - * The path to the file. - */ - private final String filePath; + /** + * The path to the file. + */ + private final String filePath; - /** - * Creates the request. - * - * @param filePath The file path. - */ - public JagGrabRequest(String filePath) { - this.filePath = filePath; - } + /** + * Creates the request. + * + * @param filePath The file path. + */ + public JagGrabRequest(String filePath) { + this.filePath = filePath; + } - /** - * Gets the file path. - * - * @return The file path. - */ - public String getFilePath() { - return filePath; - } + /** + * Gets the file path. + * + * @return The file path. + */ + public String getFilePath() { + return filePath; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/jaggrab/JagGrabRequestDecoder.java b/src/org/apollo/net/codec/jaggrab/JagGrabRequestDecoder.java index a18c0caf..838b6506 100644 --- a/src/org/apollo/net/codec/jaggrab/JagGrabRequestDecoder.java +++ b/src/org/apollo/net/codec/jaggrab/JagGrabRequestDecoder.java @@ -12,14 +12,14 @@ import java.util.List; */ public final class JagGrabRequestDecoder extends MessageToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext ctx, String request, List out) { - if (request.startsWith("JAGGRAB /")) { - String filePath = request.substring(8).trim(); - out.add(new JagGrabRequest(filePath)); - } else { - throw new IllegalArgumentException("Corrupted request line."); - } + @Override + protected void decode(ChannelHandlerContext ctx, String request, List out) { + if (request.startsWith("JAGGRAB /")) { + String filePath = request.substring(8).trim(); + out.add(new JagGrabRequest(filePath)); + } else { + throw new IllegalArgumentException("Corrupted request line."); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/jaggrab/JagGrabResponse.java b/src/org/apollo/net/codec/jaggrab/JagGrabResponse.java index a9e52da6..f9a92ae4 100644 --- a/src/org/apollo/net/codec/jaggrab/JagGrabResponse.java +++ b/src/org/apollo/net/codec/jaggrab/JagGrabResponse.java @@ -9,27 +9,27 @@ import io.netty.buffer.ByteBuf; */ public final class JagGrabResponse { - /** - * The file data. - */ - private final ByteBuf fileData; + /** + * The file data. + */ + private final ByteBuf fileData; - /** - * Creates the response. - * - * @param fileData The file data. - */ - public JagGrabResponse(ByteBuf fileData) { - this.fileData = fileData; - } + /** + * Creates the response. + * + * @param fileData The file data. + */ + public JagGrabResponse(ByteBuf fileData) { + this.fileData = fileData; + } - /** - * Gets the file data. - * - * @return The file data. - */ - public ByteBuf getFileData() { - return fileData; - } + /** + * Gets the file data. + * + * @return The file data. + */ + public ByteBuf getFileData() { + return fileData; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/jaggrab/JagGrabResponseEncoder.java b/src/org/apollo/net/codec/jaggrab/JagGrabResponseEncoder.java index 1a8de5c3..73b31162 100644 --- a/src/org/apollo/net/codec/jaggrab/JagGrabResponseEncoder.java +++ b/src/org/apollo/net/codec/jaggrab/JagGrabResponseEncoder.java @@ -12,9 +12,9 @@ import java.util.List; */ public final class JagGrabResponseEncoder extends MessageToMessageEncoder { - @Override - protected void encode(ChannelHandlerContext ctx, JagGrabResponse response, List out) { - out.add(response.getFileData()); - } + @Override + protected void encode(ChannelHandlerContext ctx, JagGrabResponse response, List out) { + out.add(response.getFileData()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginConstants.java b/src/org/apollo/net/codec/login/LoginConstants.java index d74604ea..b3da8d93 100644 --- a/src/org/apollo/net/codec/login/LoginConstants.java +++ b/src/org/apollo/net/codec/login/LoginConstants.java @@ -7,121 +7,121 @@ package org.apollo.net.codec.login; */ public final class LoginConstants { - /** - * Exchange data login status. - */ - public static final int STATUS_EXCHANGE_DATA = 0; + /** + * Exchange data login status. + */ + public static final int STATUS_EXCHANGE_DATA = 0; - /** - * Delay for 2 seconds login status. - */ - public static final int STATUS_DELAY = 1; + /** + * Delay for 2 seconds login status. + */ + public static final int STATUS_DELAY = 1; - /** - * OK login status. - */ - public static final int STATUS_OK = 2; + /** + * OK login status. + */ + public static final int STATUS_OK = 2; - /** - * Invalid credentials login status. - */ - public static final int STATUS_INVALID_CREDENTIALS = 3; + /** + * Invalid credentials login status. + */ + public static final int STATUS_INVALID_CREDENTIALS = 3; - /** - * Account disabled login status. - */ - public static final int STATUS_ACCOUNT_DISABLED = 4; + /** + * Account disabled login status. + */ + public static final int STATUS_ACCOUNT_DISABLED = 4; - /** - * Account online login status. - */ - public static final int STATUS_ACCOUNT_ONLINE = 5; + /** + * Account online login status. + */ + public static final int STATUS_ACCOUNT_ONLINE = 5; - /** - * Game updated login status. - */ - public static final int STATUS_GAME_UPDATED = 6; + /** + * Game updated login status. + */ + public static final int STATUS_GAME_UPDATED = 6; - /** - * Server full login status. - */ - public static final int STATUS_SERVER_FULL = 7; + /** + * Server full login status. + */ + public static final int STATUS_SERVER_FULL = 7; - /** - * Login server offline login status. - */ - public static final int STATUS_LOGIN_SERVER_OFFLINE = 8; + /** + * Login server offline login status. + */ + public static final int STATUS_LOGIN_SERVER_OFFLINE = 8; - /** - * Too many connections login status. - */ - public static final int STATUS_TOO_MANY_CONNECTIONS = 9; + /** + * Too many connections login status. + */ + public static final int STATUS_TOO_MANY_CONNECTIONS = 9; - /** - * Bad session id login status. - */ - public static final int STATUS_BAD_SESSION_ID = 10; + /** + * Bad session id login status. + */ + public static final int STATUS_BAD_SESSION_ID = 10; - /** - * Login server rejected session login status. - */ - public static final int STATUS_LOGIN_SERVER_REJECTED_SESSION = 11; + /** + * Login server rejected session login status. + */ + public static final int STATUS_LOGIN_SERVER_REJECTED_SESSION = 11; - /** - * Members account required login status. - */ - public static final int STATUS_MEMBERS_ACCOUNT_REQUIRED = 12; + /** + * Members account required login status. + */ + public static final int STATUS_MEMBERS_ACCOUNT_REQUIRED = 12; - /** - * Could not complete login status. - */ - public static final int STATUS_COULD_NOT_COMPLETE = 13; + /** + * Could not complete login status. + */ + public static final int STATUS_COULD_NOT_COMPLETE = 13; - /** - * Server updating login status. - */ - public static final int STATUS_UPDATING = 14; + /** + * Server updating login status. + */ + public static final int STATUS_UPDATING = 14; - /** - * Reconnection OK login status. - */ - public static final int STATUS_RECONNECTION_OK = 15; + /** + * Reconnection OK login status. + */ + public static final int STATUS_RECONNECTION_OK = 15; - /** - * Too many login attempts login status. - */ - public static final int STATUS_TOO_MANY_LOGINS = 16; + /** + * Too many login attempts login status. + */ + public static final int STATUS_TOO_MANY_LOGINS = 16; - /** - * Standing in members area on free world status. - */ - public static final int STATUS_IN_MEMBERS_AREA = 17; + /** + * Standing in members area on free world status. + */ + public static final int STATUS_IN_MEMBERS_AREA = 17; - /** - * Invalid login server status. - */ - public static final int STATUS_INVALID_LOGIN_SERVER = 20; + /** + * Invalid login server status. + */ + public static final int STATUS_INVALID_LOGIN_SERVER = 20; - /** - * Profile transfer login status. - */ - public static final int STATUS_PROFILE_TRANSFER = 21; + /** + * Profile transfer login status. + */ + public static final int STATUS_PROFILE_TRANSFER = 21; - /** - * Standard login type id. - */ - public static final int TYPE_STANDARD = 16; + /** + * Standard login type id. + */ + public static final int TYPE_STANDARD = 16; - /** - * Reconnection login type id. - */ - public static final int TYPE_RECONNECTION = 18; + /** + * Reconnection login type id. + */ + public static final int TYPE_RECONNECTION = 18; - /** - * Default private constructor to prevent instantiation. - */ - private LoginConstants() { + /** + * Default private constructor to prevent instantiation. + */ + private LoginConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginDecoder.java b/src/org/apollo/net/codec/login/LoginDecoder.java index ed381ecb..292f91e8 100644 --- a/src/org/apollo/net/codec/login/LoginDecoder.java +++ b/src/org/apollo/net/codec/login/LoginDecoder.java @@ -25,190 +25,190 @@ import org.apollo.util.StatefulFrameDecoder; */ public final class LoginDecoder extends StatefulFrameDecoder { - /** - * The secure random number generator. - */ - private static final SecureRandom random = new SecureRandom(); + /** + * The secure random number generator. + */ + private static final SecureRandom random = new SecureRandom(); - /** - * The login packet length. - */ - private int loginLength; + /** + * The login packet length. + */ + private int loginLength; - /** - * The reconnecting flag. - */ - private boolean reconnecting; + /** + * The reconnecting flag. + */ + private boolean reconnecting; - /** - * The server-side session key. - */ - private long serverSeed; + /** + * The server-side session key. + */ + private long serverSeed; - /** - * The username hash. - */ - private int usernameHash; + /** + * The username hash. + */ + private int usernameHash; - /** - * Creates the login decoder with the default initial state. - */ - public LoginDecoder() { - super(LoginDecoderState.LOGIN_HANDSHAKE, true); + /** + * Creates the login decoder with the default initial state. + */ + public LoginDecoder() { + super(LoginDecoderState.LOGIN_HANDSHAKE, true); + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out, LoginDecoderState state) + throws Exception { + switch (state) { + case LOGIN_HANDSHAKE: + decodeHandshake(ctx, in, out); + break; + case LOGIN_HEADER: + decodeHeader(ctx, in, out); + break; + case LOGIN_PAYLOAD: + decodePayload(ctx, in, out); + break; + default: + throw new IllegalStateException("Invalid login decoder state."); } + } - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out, LoginDecoderState state) - throws Exception { - switch (state) { - case LOGIN_HANDSHAKE: - decodeHandshake(ctx, in, out); - break; - case LOGIN_HEADER: - decodeHeader(ctx, in, out); - break; - case LOGIN_PAYLOAD: - decodePayload(ctx, in, out); - break; - default: - throw new IllegalStateException("Invalid login decoder state."); - } + /** + * Decodes in the handshake state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws Exception If an error occurs. + */ + private void decodeHandshake(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + if (buffer.isReadable()) { + usernameHash = buffer.readUnsignedByte(); + serverSeed = random.nextLong(); + + ByteBuf response = ctx.alloc().buffer(17); + response.writeByte(LoginConstants.STATUS_EXCHANGE_DATA); + response.writeLong(0); + response.writeLong(serverSeed); + ctx.channel().writeAndFlush(response); + + setState(LoginDecoderState.LOGIN_HEADER); } + } - /** - * Decodes in the handshake state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws Exception If an error occurs. - */ - private void decodeHandshake(ChannelHandlerContext ctx, ByteBuf buffer, List out) { - if (buffer.isReadable()) { - usernameHash = buffer.readUnsignedByte(); - serverSeed = random.nextLong(); + /** + * Decodes in the header state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws IOException If the login type sent by the client is invalid. + */ + private void decodeHeader(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws IOException { + if (buffer.readableBytes() >= 2) { + int loginType = buffer.readUnsignedByte(); - ByteBuf response = ctx.alloc().buffer(17); - response.writeByte(LoginConstants.STATUS_EXCHANGE_DATA); - response.writeLong(0); - response.writeLong(serverSeed); - ctx.channel().writeAndFlush(response); + if (loginType != LoginConstants.TYPE_STANDARD && loginType != LoginConstants.TYPE_RECONNECTION) { + throw new IOException("Invalid login type."); + } - setState(LoginDecoderState.LOGIN_HEADER); - } + reconnecting = loginType == LoginConstants.TYPE_RECONNECTION; + loginLength = buffer.readUnsignedByte(); + + setState(LoginDecoderState.LOGIN_PAYLOAD); } + } - /** - * Decodes in the header state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws IOException If the login type sent by the client is invalid. - */ - private void decodeHeader(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws IOException { - if (buffer.readableBytes() >= 2) { - int loginType = buffer.readUnsignedByte(); + /** + * Decodes in the payload state. + * + * @param ctx The channel handler context. + * @param channel The channel. + * @param buffer The buffer. + * @return The frame, or {@code null}. + * @throws Exception If an error occurs. + */ + private void decodePayload(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws Exception { + if (buffer.readableBytes() >= loginLength) { + ByteBuf payload = buffer.readBytes(loginLength); + int clientVersion = 255 - payload.readUnsignedByte(); - if (loginType != LoginConstants.TYPE_STANDARD && loginType != LoginConstants.TYPE_RECONNECTION) { - throw new IOException("Invalid login type."); - } + int releaseNumber = payload.readUnsignedShort(); - reconnecting = loginType == LoginConstants.TYPE_RECONNECTION; - loginLength = buffer.readUnsignedByte(); + int lowMemoryFlag = payload.readUnsignedByte(); + if (lowMemoryFlag != 0 && lowMemoryFlag != 1) { + throw new Exception("Invalid value for low memory flag."); + } - setState(LoginDecoderState.LOGIN_PAYLOAD); - } - } - - /** - * Decodes in the payload state. - * - * @param ctx The channel handler context. - * @param channel The channel. - * @param buffer The buffer. - * @return The frame, or {@code null}. - * @throws Exception If an error occurs. - */ - private void decodePayload(ChannelHandlerContext ctx, ByteBuf buffer, List out) throws Exception { - if (buffer.readableBytes() >= loginLength) { - ByteBuf payload = buffer.readBytes(loginLength); - int clientVersion = 255 - payload.readUnsignedByte(); - - int releaseNumber = payload.readUnsignedShort(); - - int lowMemoryFlag = payload.readUnsignedByte(); - if (lowMemoryFlag != 0 && lowMemoryFlag != 1) { - throw new Exception("Invalid value for low memory flag."); - } - - boolean lowMemory = lowMemoryFlag == 1; - - int[] archiveCrcs = new int[FileSystemConstants.ARCHIVE_COUNT]; - for (int i = 0; i < 9; i++) { - archiveCrcs[i] = payload.readInt(); - } - - int securePayloadLength = payload.readUnsignedByte(); - if (securePayloadLength != loginLength - 41) { - throw new Exception("Secure payload length mismatch."); - } - - ByteBuf securePayload = payload.readBytes(securePayloadLength); - - BigInteger bigInteger = new BigInteger(securePayload.array()); - bigInteger = bigInteger.modPow(NetworkConstants.RSA_EXPONENT, NetworkConstants.RSA_MODULUS); - - securePayload = Unpooled.wrappedBuffer(bigInteger.toByteArray()); - - int secureId = securePayload.readUnsignedByte(); - if (secureId != 10) { - throw new Exception("Invalid secure payload id."); - } - - long clientSeed = securePayload.readLong(); - long reportedServerSeed = securePayload.readLong(); - if (reportedServerSeed != serverSeed) { - throw new Exception("Server seed mismatch."); - } - - int uid = securePayload.readInt(); - - String username = BufferUtil.readString(securePayload); - String password = BufferUtil.readString(securePayload); - - if (password.length() < 6 || password.length() > 20) { - throw new Exception("Invalid password."); - } else if (username.isEmpty() || username.length() > 12) { - throw new Exception("Invalid username."); - } - - int[] seed = new int[4]; - seed[0] = (int) (clientSeed >> 32); - seed[1] = (int) clientSeed; - seed[2] = (int) (serverSeed >> 32); - seed[3] = (int) serverSeed; - - IsaacRandom decodingRandom = new IsaacRandom(seed); - for (int i = 0; i < seed.length; i++) { - seed[i] += 50; - } - - IsaacRandom encodingRandom = new IsaacRandom(seed); - - PlayerCredentials credentials = new PlayerCredentials(username, password, usernameHash, uid); - IsaacRandomPair randomPair = new IsaacRandomPair(encodingRandom, decodingRandom); - - LoginRequest request = new LoginRequest(credentials, randomPair, reconnecting, lowMemory, releaseNumber, - archiveCrcs, clientVersion); - - out.add(request); - if (buffer.isReadable()) { - out.add(buffer.readBytes(buffer.readableBytes())); - } - } + boolean lowMemory = lowMemoryFlag == 1; + + int[] archiveCrcs = new int[FileSystemConstants.ARCHIVE_COUNT]; + for (int i = 0; i < 9; i++) { + archiveCrcs[i] = payload.readInt(); + } + + int securePayloadLength = payload.readUnsignedByte(); + if (securePayloadLength != loginLength - 41) { + throw new Exception("Secure payload length mismatch."); + } + + ByteBuf securePayload = payload.readBytes(securePayloadLength); + + BigInteger bigInteger = new BigInteger(securePayload.array()); + bigInteger = bigInteger.modPow(NetworkConstants.RSA_EXPONENT, NetworkConstants.RSA_MODULUS); + + securePayload = Unpooled.wrappedBuffer(bigInteger.toByteArray()); + + int secureId = securePayload.readUnsignedByte(); + if (secureId != 10) { + throw new Exception("Invalid secure payload id."); + } + + long clientSeed = securePayload.readLong(); + long reportedServerSeed = securePayload.readLong(); + if (reportedServerSeed != serverSeed) { + throw new Exception("Server seed mismatch."); + } + + int uid = securePayload.readInt(); + + String username = BufferUtil.readString(securePayload); + String password = BufferUtil.readString(securePayload); + + if (password.length() < 6 || password.length() > 20) { + throw new Exception("Invalid password."); + } else if (username.isEmpty() || username.length() > 12) { + throw new Exception("Invalid username."); + } + + int[] seed = new int[4]; + seed[0] = (int) (clientSeed >> 32); + seed[1] = (int) clientSeed; + seed[2] = (int) (serverSeed >> 32); + seed[3] = (int) serverSeed; + + IsaacRandom decodingRandom = new IsaacRandom(seed); + for (int i = 0; i < seed.length; i++) { + seed[i] += 50; + } + + IsaacRandom encodingRandom = new IsaacRandom(seed); + + PlayerCredentials credentials = new PlayerCredentials(username, password, usernameHash, uid); + IsaacRandomPair randomPair = new IsaacRandomPair(encodingRandom, decodingRandom); + + LoginRequest request = new LoginRequest(credentials, randomPair, reconnecting, lowMemory, releaseNumber, + archiveCrcs, clientVersion); + + out.add(request); + if (buffer.isReadable()) { + out.add(buffer.readBytes(buffer.readableBytes())); + } } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginDecoderState.java b/src/org/apollo/net/codec/login/LoginDecoderState.java index ff833557..92c6bc74 100644 --- a/src/org/apollo/net/codec/login/LoginDecoderState.java +++ b/src/org/apollo/net/codec/login/LoginDecoderState.java @@ -7,22 +7,22 @@ package org.apollo.net.codec.login; */ public enum LoginDecoderState { - /** - * The login handshake state will wait for the username hash to be received. Once it is, a server session key will - * be sent to the client and the state will be set to the login header state. - */ - LOGIN_HANDSHAKE, + /** + * The login handshake state will wait for the username hash to be received. Once it is, a server session key will + * be sent to the client and the state will be set to the login header state. + */ + LOGIN_HANDSHAKE, - /** - * The login header state will wait for the login type and payload length to be received. These are saved, and then - * the state will be set to the login payload state. - */ - LOGIN_HEADER, + /** + * The login header state will wait for the login type and payload length to be received. These are saved, and then + * the state will be set to the login payload state. + */ + LOGIN_HEADER, - /** - * The login payload state will wait for all login information (such as client release number, username and - * password). - */ - LOGIN_PAYLOAD; + /** + * The login payload state will wait for all login information (such as client release number, username and + * password). + */ + LOGIN_PAYLOAD; } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginEncoder.java b/src/org/apollo/net/codec/login/LoginEncoder.java index 477a1382..b930c9cc 100644 --- a/src/org/apollo/net/codec/login/LoginEncoder.java +++ b/src/org/apollo/net/codec/login/LoginEncoder.java @@ -13,19 +13,19 @@ import java.util.List; */ public final class LoginEncoder extends MessageToMessageEncoder { - public LoginEncoder() { - super(LoginResponse.class); - } + public LoginEncoder() { + super(LoginResponse.class); + } - @Override - protected void encode(ChannelHandlerContext ctx, LoginResponse response, List out) { - ByteBuf buffer = ctx.alloc().buffer(3); - buffer.writeByte(response.getStatus()); - if (response.getStatus() == LoginConstants.STATUS_OK) { - buffer.writeByte(response.getRights()); - buffer.writeByte(response.isFlagged() ? 1 : 0); - } - out.add(buffer); + @Override + protected void encode(ChannelHandlerContext ctx, LoginResponse response, List out) { + ByteBuf buffer = ctx.alloc().buffer(3); + buffer.writeByte(response.getStatus()); + if (response.getStatus() == LoginConstants.STATUS_OK) { + buffer.writeByte(response.getRights()); + buffer.writeByte(response.isFlagged() ? 1 : 0); } + out.add(buffer); + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginRequest.java b/src/org/apollo/net/codec/login/LoginRequest.java index d2585e2d..f4320281 100644 --- a/src/org/apollo/net/codec/login/LoginRequest.java +++ b/src/org/apollo/net/codec/login/LoginRequest.java @@ -10,123 +10,123 @@ import org.apollo.security.PlayerCredentials; */ public final class LoginRequest { - /** - * The archive CRCs. - */ - private final int[] archiveCrcs; + /** + * The archive CRCs. + */ + private final int[] archiveCrcs; - /** - * The version denoting whether the client has been modified or not. - */ - private final int clientVersion; + /** + * The version denoting whether the client has been modified or not. + */ + private final int clientVersion; - /** - * The player's credentials. - */ - private final PlayerCredentials credentials; + /** + * The player's credentials. + */ + private final PlayerCredentials credentials; - /** - * The low memory flag. - */ - private final boolean lowMemory; + /** + * The low memory flag. + */ + private final boolean lowMemory; - /** - * The pair of random number generators. - */ - private final IsaacRandomPair randomPair; + /** + * The pair of random number generators. + */ + private final IsaacRandomPair randomPair; - /** - * The reconnecting flag. - */ - private final boolean reconnecting; + /** + * The reconnecting flag. + */ + private final boolean reconnecting; - /** - * The release number. - */ - private final int releaseNumber; + /** + * The release number. + */ + private final int releaseNumber; - /** - * Creates a login request. - * - * @param credentials The player credentials. - * @param randomPair The pair of random number generators. - * @param lowMemory The low memory flag. - * @param reconnecting The reconnecting flag. - * @param releaseNumber The release number. - * @param archiveCrcs The archive CRCs. - */ - public LoginRequest(PlayerCredentials credentials, IsaacRandomPair randomPair, boolean lowMemory, - boolean reconnecting, int releaseNumber, int[] archiveCrcs, int clientVersion) { - this.credentials = credentials; - this.randomPair = randomPair; - this.lowMemory = lowMemory; - this.reconnecting = reconnecting; - this.releaseNumber = releaseNumber; - this.archiveCrcs = archiveCrcs; - this.clientVersion = clientVersion; - } + /** + * Creates a login request. + * + * @param credentials The player credentials. + * @param randomPair The pair of random number generators. + * @param lowMemory The low memory flag. + * @param reconnecting The reconnecting flag. + * @param releaseNumber The release number. + * @param archiveCrcs The archive CRCs. + */ + public LoginRequest(PlayerCredentials credentials, IsaacRandomPair randomPair, boolean lowMemory, + boolean reconnecting, int releaseNumber, int[] archiveCrcs, int clientVersion) { + this.credentials = credentials; + this.randomPair = randomPair; + this.lowMemory = lowMemory; + this.reconnecting = reconnecting; + this.releaseNumber = releaseNumber; + this.archiveCrcs = archiveCrcs; + this.clientVersion = clientVersion; + } - /** - * Gets the archive CRCs. - * - * @return The array of archive CRCs. - */ - public int[] getArchiveCrcs() { - return archiveCrcs; - } + /** + * Gets the archive CRCs. + * + * @return The array of archive CRCs. + */ + public int[] getArchiveCrcs() { + return archiveCrcs; + } - /** - * Gets the value denoting the client's (modified) version. - * - * @return The client version. - */ - public int getClientVersion() { - return clientVersion; - } + /** + * Gets the value denoting the client's (modified) version. + * + * @return The client version. + */ + public int getClientVersion() { + return clientVersion; + } - /** - * Gets the player's credentials. - * - * @return The player's credentials. - */ - public PlayerCredentials getCredentials() { - return credentials; - } + /** + * Gets the player's credentials. + * + * @return The player's credentials. + */ + public PlayerCredentials getCredentials() { + return credentials; + } - /** - * Gets the pair of random number generators. - * - * @return The pair of random number generators. - */ - public IsaacRandomPair getRandomPair() { - return randomPair; - } + /** + * Gets the pair of random number generators. + * + * @return The pair of random number generators. + */ + public IsaacRandomPair getRandomPair() { + return randomPair; + } - /** - * Gets the release number. - * - * @return The release number. - */ - public int getReleaseNumber() { - return releaseNumber; - } + /** + * Gets the release number. + * + * @return The release number. + */ + public int getReleaseNumber() { + return releaseNumber; + } - /** - * Checks if this client is in low memory mode. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isLowMemory() { - return lowMemory; - } + /** + * Checks if this client is in low memory mode. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isLowMemory() { + return lowMemory; + } - /** - * Checks if this client is reconnecting. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean isReconnecting() { - return reconnecting; - } + /** + * Checks if this client is reconnecting. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean isReconnecting() { + return reconnecting; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/login/LoginResponse.java b/src/org/apollo/net/codec/login/LoginResponse.java index 426c78c6..fd283cf8 100644 --- a/src/org/apollo/net/codec/login/LoginResponse.java +++ b/src/org/apollo/net/codec/login/LoginResponse.java @@ -7,59 +7,59 @@ package org.apollo.net.codec.login; */ public final class LoginResponse { - /** - * The flagged flag. - */ - private final boolean flagged; + /** + * The flagged flag. + */ + private final boolean flagged; - /** - * The rights level. - */ - private final int rights; + /** + * The rights level. + */ + private final int rights; - /** - * The login status. - */ - private final int status; + /** + * The login status. + */ + private final int status; - /** - * Creates the login response. - * - * @param status The login status. - * @param rights The rights level. - * @param flagged The flagged flag. - */ - public LoginResponse(int status, int rights, boolean flagged) { - this.status = status; - this.rights = rights; - this.flagged = flagged; - } + /** + * Creates the login response. + * + * @param status The login status. + * @param rights The rights level. + * @param flagged The flagged flag. + */ + public LoginResponse(int status, int rights, boolean flagged) { + this.status = status; + this.rights = rights; + this.flagged = flagged; + } - /** - * Gets the rights level. - * - * @return The rights level. - */ - public int getRights() { - return rights; - } + /** + * Gets the rights level. + * + * @return The rights level. + */ + public int getRights() { + return rights; + } - /** - * Gets the status. - * - * @return The status. - */ - public int getStatus() { - return status; - } + /** + * Gets the status. + * + * @return The status. + */ + public int getStatus() { + return status; + } - /** - * Checks if the player should be flagged. - * - * @return The flagged flag. - */ - public boolean isFlagged() { - return flagged; - } + /** + * Checks if the player should be flagged. + * + * @return The flagged flag. + */ + public boolean isFlagged() { + return flagged; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/update/OnDemandRequest.java b/src/org/apollo/net/codec/update/OnDemandRequest.java index 4be18399..b6efb64c 100644 --- a/src/org/apollo/net/codec/update/OnDemandRequest.java +++ b/src/org/apollo/net/codec/update/OnDemandRequest.java @@ -9,124 +9,124 @@ import org.apollo.fs.FileDescriptor; */ public final class OnDemandRequest implements Comparable { + /** + * An enumeration containing the different request priorities. + * + * @author Graham + */ + public enum Priority { + /** - * An enumeration containing the different request priorities. - * - * @author Graham - */ - public enum Priority { - - /** - * High priority - used in-game when data is required immediately but has not yet been received. - */ - HIGH(0), - - /** - * Low priority - used when a file is not required urgently. The client login screen says - * "loading extra files.." when low priority loading is being performed. - */ - LOW(2), - - /** - * Medium priority - used while loading the 'bare minimum' required to run the game. - */ - MEDIUM(1); - - /** - * Converts the integer value to a priority. - * - * @param v The integer value. - * @return The priority. - * @throws IllegalArgumentException If the value is outside of the range 1-3 inclusive. - */ - public static Priority valueOf(int v) { - switch (v) { - case 0: - return HIGH; - case 1: - return MEDIUM; - case 2: - return LOW; - default: - throw new IllegalArgumentException("Priority out of range."); - } - } - - /** - * The integer value. - */ - private final int intValue; - - /** - * Creates a priority. - * - * @param intValue The integer value. - */ - private Priority(int intValue) { - this.intValue = intValue; - } - - /** - * Converts the priority to an integer. - * - * @return The integer value. - */ - public int toInteger() { - return intValue; - } - - } - - /** - * The file descriptor. - */ - private final FileDescriptor fileDescriptor; - - /** - * The request priority. - */ - private final Priority priority; - - /** - * Creates the 'on-demand' request. - * - * @param fileDescriptor The file descriptor. - * @param priority The priority. - */ - public OnDemandRequest(FileDescriptor fileDescriptor, Priority priority) { - this.fileDescriptor = fileDescriptor; - this.priority = priority; - } - - @Override - public int compareTo(OnDemandRequest o) { - int thisPriority = priority.toInteger(); - int otherPriority = o.priority.toInteger(); - - if (thisPriority < otherPriority) { - return 1; - } else if (thisPriority == otherPriority) { - return 0; - } - return -1; - } - - /** - * Gets the file descriptor. - * - * @return The file descriptor. - */ - public FileDescriptor getFileDescriptor() { - return fileDescriptor; - } - - /** - * Gets the priority. + * High priority - used in-game when data is required immediately but has not yet been received. + */ + HIGH(0), + + /** + * Low priority - used when a file is not required urgently. The client login screen says + * "loading extra files.." when low priority loading is being performed. + */ + LOW(2), + + /** + * Medium priority - used while loading the 'bare minimum' required to run the game. + */ + MEDIUM(1); + + /** + * Converts the integer value to a priority. * + * @param v The integer value. * @return The priority. + * @throws IllegalArgumentException If the value is outside of the range 1-3 inclusive. */ - public Priority getPriority() { - return priority; + public static Priority valueOf(int v) { + switch (v) { + case 0: + return HIGH; + case 1: + return MEDIUM; + case 2: + return LOW; + default: + throw new IllegalArgumentException("Priority out of range."); + } } + /** + * The integer value. + */ + private final int intValue; + + /** + * Creates a priority. + * + * @param intValue The integer value. + */ + private Priority(int intValue) { + this.intValue = intValue; + } + + /** + * Converts the priority to an integer. + * + * @return The integer value. + */ + public int toInteger() { + return intValue; + } + + } + + /** + * The file descriptor. + */ + private final FileDescriptor fileDescriptor; + + /** + * The request priority. + */ + private final Priority priority; + + /** + * Creates the 'on-demand' request. + * + * @param fileDescriptor The file descriptor. + * @param priority The priority. + */ + public OnDemandRequest(FileDescriptor fileDescriptor, Priority priority) { + this.fileDescriptor = fileDescriptor; + this.priority = priority; + } + + @Override + public int compareTo(OnDemandRequest o) { + int thisPriority = priority.toInteger(); + int otherPriority = o.priority.toInteger(); + + if (thisPriority < otherPriority) { + return 1; + } else if (thisPriority == otherPriority) { + return 0; + } + return -1; + } + + /** + * Gets the file descriptor. + * + * @return The file descriptor. + */ + public FileDescriptor getFileDescriptor() { + return fileDescriptor; + } + + /** + * Gets the priority. + * + * @return The priority. + */ + public Priority getPriority() { + return priority; + } + } \ No newline at end of file diff --git a/src/org/apollo/net/codec/update/OnDemandResponse.java b/src/org/apollo/net/codec/update/OnDemandResponse.java index a4441603..d7e4fed7 100644 --- a/src/org/apollo/net/codec/update/OnDemandResponse.java +++ b/src/org/apollo/net/codec/update/OnDemandResponse.java @@ -11,75 +11,75 @@ import org.apollo.fs.FileDescriptor; */ public final class OnDemandResponse { - /** - * The chunk data. - */ - private final ByteBuf chunkData; + /** + * The chunk data. + */ + private final ByteBuf chunkData; - /** - * The chunk id. - */ - private final int chunkId; + /** + * The chunk id. + */ + private final int chunkId; - /** - * The file descriptor. - */ - private final FileDescriptor fileDescriptor; + /** + * The file descriptor. + */ + private final FileDescriptor fileDescriptor; - /** - * The file size. - */ - private final int fileSize; + /** + * The file size. + */ + private final int fileSize; - /** - * Creates the 'on-demand' response. - * - * @param fileDescriptor The file descriptor. - * @param fileSize The file size. - * @param chunkId The chunk id. - * @param chunkData The chunk data. - */ - public OnDemandResponse(FileDescriptor fileDescriptor, int fileSize, int chunkId, ByteBuf chunkData) { - this.fileDescriptor = fileDescriptor; - this.fileSize = fileSize; - this.chunkId = chunkId; - this.chunkData = chunkData; - } + /** + * Creates the 'on-demand' response. + * + * @param fileDescriptor The file descriptor. + * @param fileSize The file size. + * @param chunkId The chunk id. + * @param chunkData The chunk data. + */ + public OnDemandResponse(FileDescriptor fileDescriptor, int fileSize, int chunkId, ByteBuf chunkData) { + this.fileDescriptor = fileDescriptor; + this.fileSize = fileSize; + this.chunkId = chunkId; + this.chunkData = chunkData; + } - /** - * Gets the chunk data. - * - * @return The chunk data. - */ - public ByteBuf getChunkData() { - return chunkData; - } + /** + * Gets the chunk data. + * + * @return The chunk data. + */ + public ByteBuf getChunkData() { + return chunkData; + } - /** - * Gets the chunk id. - * - * @return The chunk id. - */ - public int getChunkId() { - return chunkId; - } + /** + * Gets the chunk id. + * + * @return The chunk id. + */ + public int getChunkId() { + return chunkId; + } - /** - * Gets the file descriptor. - * - * @return The file descriptor. - */ - public FileDescriptor getFileDescriptor() { - return fileDescriptor; - } + /** + * Gets the file descriptor. + * + * @return The file descriptor. + */ + public FileDescriptor getFileDescriptor() { + return fileDescriptor; + } - /** - * Gets the file size. - * - * @return The file size. - */ - public int getFileSize() { - return fileSize; - } + /** + * Gets the file size. + * + * @return The file size. + */ + public int getFileSize() { + return fileSize; + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/update/UpdateDecoder.java b/src/org/apollo/net/codec/update/UpdateDecoder.java index fd2e97aa..c174fd18 100644 --- a/src/org/apollo/net/codec/update/UpdateDecoder.java +++ b/src/org/apollo/net/codec/update/UpdateDecoder.java @@ -16,16 +16,16 @@ import org.apollo.net.codec.update.OnDemandRequest.Priority; */ public final class UpdateDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { - if (buffer.readableBytes() >= 4) { - int type = buffer.readUnsignedByte() + 1; - int file = buffer.readUnsignedShort(); - Priority priority = Priority.valueOf(buffer.readUnsignedByte()); + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + if (buffer.readableBytes() >= 4) { + int type = buffer.readUnsignedByte() + 1; + int file = buffer.readUnsignedShort(); + Priority priority = Priority.valueOf(buffer.readUnsignedByte()); - FileDescriptor desc = new FileDescriptor(type, file); - out.add(new OnDemandRequest(desc, priority)); - } + FileDescriptor desc = new FileDescriptor(type, file); + out.add(new OnDemandRequest(desc, priority)); } + } } \ No newline at end of file diff --git a/src/org/apollo/net/codec/update/UpdateEncoder.java b/src/org/apollo/net/codec/update/UpdateEncoder.java index 638844fc..dd974418 100644 --- a/src/org/apollo/net/codec/update/UpdateEncoder.java +++ b/src/org/apollo/net/codec/update/UpdateEncoder.java @@ -15,21 +15,21 @@ import org.apollo.fs.FileDescriptor; */ public final class UpdateEncoder extends MessageToMessageEncoder { - @Override - protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, List out) { - FileDescriptor descriptor = response.getFileDescriptor(); - int fileSize = response.getFileSize(); - int chunkId = response.getChunkId(); - ByteBuf chunkData = response.getChunkData(); + @Override + protected void encode(ChannelHandlerContext ctx, OnDemandResponse response, List out) { + FileDescriptor descriptor = response.getFileDescriptor(); + int fileSize = response.getFileSize(); + int chunkId = response.getChunkId(); + ByteBuf chunkData = response.getChunkData(); - ByteBuf buffer = ctx.alloc().buffer(6 + chunkData.readableBytes()); - buffer.writeByte(descriptor.getType() - 1); - buffer.writeShort(descriptor.getFile()); - buffer.writeShort(fileSize); - buffer.writeByte(chunkId); - buffer.writeBytes(chunkData); + ByteBuf buffer = ctx.alloc().buffer(6 + chunkData.readableBytes()); + buffer.writeByte(descriptor.getType() - 1); + buffer.writeShort(descriptor.getFile()); + buffer.writeShort(fileSize); + buffer.writeByte(chunkId); + buffer.writeBytes(chunkData); - out.add(buffer); - } + out.add(buffer); + } } \ No newline at end of file diff --git a/src/org/apollo/net/meta/PacketMetaData.java b/src/org/apollo/net/meta/PacketMetaData.java index 0742ec46..2a020199 100644 --- a/src/org/apollo/net/meta/PacketMetaData.java +++ b/src/org/apollo/net/meta/PacketMetaData.java @@ -7,80 +7,80 @@ package org.apollo.net.meta; */ public final class PacketMetaData { - /** - * Creates a {@link PacketMetaData} object for a fixed-length packet. - * - * @param length The length of the packet. - * @return The {@link PacketMetaData} object. - * @throws IllegalArgumentException If length is less than 0. - */ - public static PacketMetaData createFixed(int length) { - if (length < 0) { - throw new IllegalArgumentException("Packet length cannot be less than 0."); - } - return new PacketMetaData(PacketType.FIXED, length); + /** + * Creates a {@link PacketMetaData} object for a fixed-length packet. + * + * @param length The length of the packet. + * @return The {@link PacketMetaData} object. + * @throws IllegalArgumentException If length is less than 0. + */ + public static PacketMetaData createFixed(int length) { + if (length < 0) { + throw new IllegalArgumentException("Packet length cannot be less than 0."); } + return new PacketMetaData(PacketType.FIXED, length); + } - /** - * Creates a {@link PacketMetaData} object for a variable byte length packet. - * - * @return The {@link PacketMetaData} object. - */ - public static PacketMetaData createVariableByte() { - return new PacketMetaData(PacketType.VARIABLE_BYTE, 0); + /** + * Creates a {@link PacketMetaData} object for a variable byte length packet. + * + * @return The {@link PacketMetaData} object. + */ + public static PacketMetaData createVariableByte() { + return new PacketMetaData(PacketType.VARIABLE_BYTE, 0); + } + + /** + * Creates a {@link PacketMetaData} object for a variable short length packet. + * + * @return The {@link PacketMetaData} object. + */ + public static PacketMetaData createVariableShort() { + return new PacketMetaData(PacketType.VARIABLE_SHORT, 0); + } + + /** + * The length of this packet. + */ + private final int length; + + /** + * The type of packet. + */ + private final PacketType type; + + /** + * Creates the packet meta data object. This should not be called directy. Use the {@link #createFixed(int)}, + * {@link #createVariableByte()} and {@link #createVariableShort()} methods instead! + * + * @param type The type of packet. + * @param length The length of the packet. + */ + private PacketMetaData(PacketType type, int length) { + this.type = type; + this.length = length; + } + + /** + * Gets the length of this packet. + * + * @return The length of this packet. + * @throws IllegalStateException If the packet is not a fixed-size packet. + */ + public int getLength() { + if (type != PacketType.FIXED) { + throw new IllegalStateException("Can only get the length of a fixed length packet."); } + return length; + } - /** - * Creates a {@link PacketMetaData} object for a variable short length packet. - * - * @return The {@link PacketMetaData} object. - */ - public static PacketMetaData createVariableShort() { - return new PacketMetaData(PacketType.VARIABLE_SHORT, 0); - } - - /** - * The length of this packet. - */ - private final int length; - - /** - * The type of packet. - */ - private final PacketType type; - - /** - * Creates the packet meta data object. This should not be called directy. Use the {@link #createFixed(int)}, - * {@link #createVariableByte()} and {@link #createVariableShort()} methods instead! - * - * @param type The type of packet. - * @param length The length of the packet. - */ - private PacketMetaData(PacketType type, int length) { - this.type = type; - this.length = length; - } - - /** - * Gets the length of this packet. - * - * @return The length of this packet. - * @throws IllegalStateException If the packet is not a fixed-size packet. - */ - public int getLength() { - if (type != PacketType.FIXED) { - throw new IllegalStateException("Can only get the length of a fixed length packet."); - } - return length; - } - - /** - * Gets the type of packet. - * - * @return The type of packet. - */ - public PacketType getType() { - return type; - } + /** + * Gets the type of packet. + * + * @return The type of packet. + */ + public PacketType getType() { + return type; + } } \ No newline at end of file diff --git a/src/org/apollo/net/meta/PacketMetaDataGroup.java b/src/org/apollo/net/meta/PacketMetaDataGroup.java index ab83ce64..3473374e 100644 --- a/src/org/apollo/net/meta/PacketMetaDataGroup.java +++ b/src/org/apollo/net/meta/PacketMetaDataGroup.java @@ -7,60 +7,60 @@ package org.apollo.net.meta; */ public final class PacketMetaDataGroup { - /** - * Creates a {@link PacketMetaDataGroup} from the packet length array. - * - * @param lengthArray The packet length array. - * @return The {@link PacketMetaDataGroup} object. - * @throws IllegalArgumentException If the array length is not 256 or if there is an element in the array with a - * value below -3. - */ - public static PacketMetaDataGroup createFromArray(int[] lengthArray) { - if (lengthArray.length != 256) { - throw new IllegalArgumentException("Array length must be 256."); - } - PacketMetaDataGroup grp = new PacketMetaDataGroup(); - for (int i = 0; i < lengthArray.length; i++) { - int length = lengthArray[i]; - PacketMetaData metaData = null; - if (length < -3) { - throw new IllegalArgumentException("No packet length can have a value less than -3."); - } else if (length == -2) { - metaData = PacketMetaData.createVariableShort(); - } else if (length == -1) { - metaData = PacketMetaData.createVariableByte(); - } else { - metaData = PacketMetaData.createFixed(length); - } - grp.packets[i] = metaData; - } - return grp; + /** + * Creates a {@link PacketMetaDataGroup} from the packet length array. + * + * @param lengthArray The packet length array. + * @return The {@link PacketMetaDataGroup} object. + * @throws IllegalArgumentException If the array length is not 256 or if there is an element in the array with a + * value below -3. + */ + public static PacketMetaDataGroup createFromArray(int[] lengthArray) { + if (lengthArray.length != 256) { + throw new IllegalArgumentException("Array length must be 256."); } - - /** - * The array of {@link PacketMetaData} objects. - */ - private final PacketMetaData[] packets = new PacketMetaData[256]; - - /** - * This constructor should not be called directly. Use the {@link #createFromArray(int[])} method instead. - */ - private PacketMetaDataGroup() { - + PacketMetaDataGroup grp = new PacketMetaDataGroup(); + for (int i = 0; i < lengthArray.length; i++) { + int length = lengthArray[i]; + PacketMetaData metaData = null; + if (length < -3) { + throw new IllegalArgumentException("No packet length can have a value less than -3."); + } else if (length == -2) { + metaData = PacketMetaData.createVariableShort(); + } else if (length == -1) { + metaData = PacketMetaData.createVariableByte(); + } else { + metaData = PacketMetaData.createFixed(length); + } + grp.packets[i] = metaData; } + return grp; + } - /** - * Gets the meta data for the specified packet. - * - * @param opcode The opcode of the packet. - * @return The {@link PacketMetaData}, or {@code null} if the packet does not exist. - * @throws IllegalArgumentException If the opcode is not in the range 0 to 255. - */ - public PacketMetaData getMetaData(int opcode) { - if (opcode < 0 || opcode >= packets.length) { - throw new IllegalArgumentException("Opcode is out of bounds."); - } - return packets[opcode]; + /** + * The array of {@link PacketMetaData} objects. + */ + private final PacketMetaData[] packets = new PacketMetaData[256]; + + /** + * This constructor should not be called directly. Use the {@link #createFromArray(int[])} method instead. + */ + private PacketMetaDataGroup() { + + } + + /** + * Gets the meta data for the specified packet. + * + * @param opcode The opcode of the packet. + * @return The {@link PacketMetaData}, or {@code null} if the packet does not exist. + * @throws IllegalArgumentException If the opcode is not in the range 0 to 255. + */ + public PacketMetaData getMetaData(int opcode) { + if (opcode < 0 || opcode >= packets.length) { + throw new IllegalArgumentException("Opcode is out of bounds."); } + return packets[opcode]; + } } \ No newline at end of file diff --git a/src/org/apollo/net/meta/PacketType.java b/src/org/apollo/net/meta/PacketType.java index 67cb9b41..c2745d96 100644 --- a/src/org/apollo/net/meta/PacketType.java +++ b/src/org/apollo/net/meta/PacketType.java @@ -7,24 +7,24 @@ package org.apollo.net.meta; */ public enum PacketType { - /** - * A packet where the length is known by both the client and server already. - */ - FIXED, + /** + * A packet where the length is known by both the client and server already. + */ + FIXED, - /** - * A packet with no header. - */ - RAW, + /** + * A packet with no header. + */ + RAW, - /** - * A packet where the length is sent to its destination with it as a byte. - */ - VARIABLE_BYTE, + /** + * A packet where the length is sent to its destination with it as a byte. + */ + VARIABLE_BYTE, - /** - * A packet where the length is sent to its destination with it as a short. - */ - VARIABLE_SHORT; + /** + * A packet where the length is sent to its destination with it as a short. + */ + VARIABLE_SHORT; } \ No newline at end of file diff --git a/src/org/apollo/net/release/EventDecoder.java b/src/org/apollo/net/release/EventDecoder.java index 5ceee0a8..4b2ea918 100644 --- a/src/org/apollo/net/release/EventDecoder.java +++ b/src/org/apollo/net/release/EventDecoder.java @@ -12,12 +12,12 @@ import org.apollo.net.codec.game.GamePacket; */ public abstract class EventDecoder { - /** - * Decodes the specified packet into an event. - * - * @param packet The packet. - * @return The event. - */ - public abstract E decode(GamePacket packet); + /** + * Decodes the specified packet into an event. + * + * @param packet The packet. + * @return The event. + */ + public abstract E decode(GamePacket packet); } \ No newline at end of file diff --git a/src/org/apollo/net/release/EventEncoder.java b/src/org/apollo/net/release/EventEncoder.java index 91bb632c..a50f71af 100644 --- a/src/org/apollo/net/release/EventEncoder.java +++ b/src/org/apollo/net/release/EventEncoder.java @@ -11,12 +11,12 @@ import org.apollo.net.codec.game.GamePacket; */ public abstract class EventEncoder { - /** - * Encodes the specified event into a packet. - * - * @param event The event. - * @return The packet. - */ - public abstract GamePacket encode(E event); + /** + * Encodes the specified event into a packet. + * + * @param event The event. + * @return The packet. + */ + public abstract GamePacket encode(E event); } \ No newline at end of file diff --git a/src/org/apollo/net/release/Release.java b/src/org/apollo/net/release/Release.java index c4470b5f..8f1dab0a 100644 --- a/src/org/apollo/net/release/Release.java +++ b/src/org/apollo/net/release/Release.java @@ -14,101 +14,101 @@ import org.apollo.net.meta.PacketMetaDataGroup; */ public abstract class Release { - /** - * The decoders. - */ - private final EventDecoder[] decoders = new EventDecoder[256]; + /** + * The decoders. + */ + private final EventDecoder[] decoders = new EventDecoder[256]; - /** - * The encoders. - */ - private final Map, EventEncoder> encoders = new HashMap, EventEncoder>(); + /** + * The encoders. + */ + private final Map, EventEncoder> encoders = new HashMap, EventEncoder>(); - /** - * The incoming packet meta data. - */ - private final PacketMetaDataGroup incomingPacketMetaData; + /** + * The incoming packet meta data. + */ + private final PacketMetaDataGroup incomingPacketMetaData; - /** - * The release number, e.g. {@code 317}. - */ - private final int releaseNumber; + /** + * The release number, e.g. {@code 317}. + */ + private final int releaseNumber; - /** - * Creates the release. - * - * @param releaseNumber The release number. - * @param incomingPacketMetaData The incoming packet meta data. - */ - public Release(int releaseNumber, PacketMetaDataGroup incomingPacketMetaData) { - this.releaseNumber = releaseNumber; - this.incomingPacketMetaData = incomingPacketMetaData; + /** + * Creates the release. + * + * @param releaseNumber The release number. + * @param incomingPacketMetaData The incoming packet meta data. + */ + public Release(int releaseNumber, PacketMetaDataGroup incomingPacketMetaData) { + this.releaseNumber = releaseNumber; + this.incomingPacketMetaData = incomingPacketMetaData; + } + + /** + * Gets the {@link EventDecoder} for the specified opcode. + * + * @param opcode The opcode. + * @return The {@link EventDecoder}. + */ + public final EventDecoder getEventDecoder(int opcode) { + if (opcode < 0 || opcode >= decoders.length) { + throw new IndexOutOfBoundsException("Opcode is out of bounds."); } + return decoders[opcode]; + } - /** - * Gets the {@link EventDecoder} for the specified opcode. - * - * @param opcode The opcode. - * @return The {@link EventDecoder}. - */ - public final EventDecoder getEventDecoder(int opcode) { - if (opcode < 0 || opcode >= decoders.length) { - throw new IndexOutOfBoundsException("Opcode is out of bounds."); - } - return decoders[opcode]; - } + /** + * Gets an {@link EventEncoder} for the specified event type. + * + * @param type The type of event. + * @return The {@link EventEncoder}. + */ + @SuppressWarnings("unchecked") + public EventEncoder getEventEncoder(Class type) { + return (EventEncoder) encoders.get(type); + } - /** - * Gets an {@link EventEncoder} for the specified event type. - * - * @param type The type of event. - * @return The {@link EventEncoder}. - */ - @SuppressWarnings("unchecked") - public EventEncoder getEventEncoder(Class type) { - return (EventEncoder) encoders.get(type); - } + /** + * Gets meta data for the specified incoming packet. + * + * @param opcode The opcode of the incoming packet. + * @return The {@link PacketMetaData} object. + */ + public final PacketMetaData getIncomingPacketMetaData(int opcode) { + return incomingPacketMetaData.getMetaData(opcode); + } - /** - * Gets meta data for the specified incoming packet. - * - * @param opcode The opcode of the incoming packet. - * @return The {@link PacketMetaData} object. - */ - public final PacketMetaData getIncomingPacketMetaData(int opcode) { - return incomingPacketMetaData.getMetaData(opcode); - } + /** + * Gets the release number. + * + * @return The release number. + */ + public final int getReleaseNumber() { + return releaseNumber; + } - /** - * Gets the release number. - * - * @return The release number. - */ - public final int getReleaseNumber() { - return releaseNumber; - } + /** + * Registers a {@link EventEncoder} for the specified event type. + * + * @param type The event type. + * @param encoder The {@link EventEncoder}. + */ + public final void register(Class type, EventEncoder encoder) { + encoders.put(type, encoder); + } - /** - * Registers a {@link EventEncoder} for the specified event type. - * - * @param type The event type. - * @param encoder The {@link EventEncoder}. - */ - public final void register(Class type, EventEncoder encoder) { - encoders.put(type, encoder); - } - - /** - * Registers a {@link EventDecoder} for the specified opcode. - * - * @param opcode The opcode, between 0 and 255 inclusive. - * @param decoder The {@link EventDecoder}. - */ - public final void register(int opcode, EventDecoder decoder) { - if (opcode < 0 || opcode >= decoders.length) { - throw new IndexOutOfBoundsException("Opcode is out of bounds."); - } - decoders[opcode] = decoder; + /** + * Registers a {@link EventDecoder} for the specified opcode. + * + * @param opcode The opcode, between 0 and 255 inclusive. + * @param decoder The {@link EventDecoder}. + */ + public final void register(int opcode, EventDecoder decoder) { + if (opcode < 0 || opcode >= decoders.length) { + throw new IndexOutOfBoundsException("Opcode is out of bounds."); } + decoders[opcode] = decoder; + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/AddFriendEventDecoder.java b/src/org/apollo/net/release/r317/AddFriendEventDecoder.java index 43106bd7..9a2fe982 100644 --- a/src/org/apollo/net/release/r317/AddFriendEventDecoder.java +++ b/src/org/apollo/net/release/r317/AddFriendEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class AddFriendEventDecoder extends EventDecoder { - @Override - public AddFriendEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new AddFriendEvent(username); - } + @Override + public AddFriendEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new AddFriendEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/AddGlobalTileItemEventEncoder.java b/src/org/apollo/net/release/r317/AddGlobalTileItemEventEncoder.java index e43f6d39..37d32648 100644 --- a/src/org/apollo/net/release/r317/AddGlobalTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r317/AddGlobalTileItemEventEncoder.java @@ -14,14 +14,14 @@ import org.apollo.net.release.EventEncoder; */ public final class AddGlobalTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(AddGlobalTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(215); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, event.getPositionOffset()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getIndex()); - builder.put(DataType.SHORT, event.getAmount()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(AddGlobalTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(215); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, event.getPositionOffset()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getIndex()); + builder.put(DataType.SHORT, event.getAmount()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/AddIgnoreEventDecoder.java b/src/org/apollo/net/release/r317/AddIgnoreEventDecoder.java index 3b78d133..debc9a28 100644 --- a/src/org/apollo/net/release/r317/AddIgnoreEventDecoder.java +++ b/src/org/apollo/net/release/r317/AddIgnoreEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class AddIgnoreEventDecoder extends EventDecoder { - @Override - public AddIgnoreEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new AddIgnoreEvent(username); - } + @Override + public AddIgnoreEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new AddIgnoreEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/AddTileItemEventEncoder.java b/src/org/apollo/net/release/r317/AddTileItemEventEncoder.java index f7d96521..ecf98307 100644 --- a/src/org/apollo/net/release/r317/AddTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r317/AddTileItemEventEncoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventEncoder; */ public final class AddTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(AddTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(44); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); - builder.put(DataType.SHORT, event.getAmount()); - builder.put(DataType.BYTE, event.getPositionOffset()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(AddTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(44); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); + builder.put(DataType.SHORT, event.getAmount()); + builder.put(DataType.BYTE, event.getPositionOffset()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ArrowKeyEventDecoder.java b/src/org/apollo/net/release/r317/ArrowKeyEventDecoder.java index 49cf8984..f15b3145 100644 --- a/src/org/apollo/net/release/r317/ArrowKeyEventDecoder.java +++ b/src/org/apollo/net/release/r317/ArrowKeyEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ArrowKeyEventDecoder extends EventDecoder { - @Override - public ArrowKeyEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int roll = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int yaw = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new ArrowKeyEvent(roll, yaw); - } + @Override + public ArrowKeyEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int roll = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int yaw = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new ArrowKeyEvent(roll, yaw); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ButtonEventDecoder.java b/src/org/apollo/net/release/r317/ButtonEventDecoder.java index 14e56120..32003267 100644 --- a/src/org/apollo/net/release/r317/ButtonEventDecoder.java +++ b/src/org/apollo/net/release/r317/ButtonEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ButtonEventDecoder extends EventDecoder { - @Override - public ButtonEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new ButtonEvent(interfaceId); - } + @Override + public ButtonEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + return new ButtonEvent(interfaceId); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ChatEventDecoder.java b/src/org/apollo/net/release/r317/ChatEventDecoder.java index 4a66464f..2cf6f6d8 100644 --- a/src/org/apollo/net/release/r317/ChatEventDecoder.java +++ b/src/org/apollo/net/release/r317/ChatEventDecoder.java @@ -15,26 +15,26 @@ import org.apollo.util.TextUtil; */ public final class ChatEventDecoder extends EventDecoder { - @Override - public ChatEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ChatEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int effects = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.SUBTRACT); - int color = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.SUBTRACT); - int length = packet.getLength() - 2; + int effects = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.SUBTRACT); + int color = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.SUBTRACT); + int length = packet.getLength() - 2; - byte[] originalCompressed = new byte[length]; - reader.getBytesReverse(DataTransformation.ADD, originalCompressed); + byte[] originalCompressed = new byte[length]; + reader.getBytesReverse(DataTransformation.ADD, originalCompressed); - String uncompressed = TextUtil.uncompress(originalCompressed, length); - uncompressed = TextUtil.filterInvalidCharacters(uncompressed); - uncompressed = TextUtil.capitalize(uncompressed); + String uncompressed = TextUtil.uncompress(originalCompressed, length); + uncompressed = TextUtil.filterInvalidCharacters(uncompressed); + uncompressed = TextUtil.capitalize(uncompressed); - byte[] recompressed = new byte[length]; - TextUtil.compress(uncompressed, recompressed); - // in case invalid data gets sent, this effectively verifies it + byte[] recompressed = new byte[length]; + TextUtil.compress(uncompressed, recompressed); + // in case invalid data gets sent, this effectively verifies it - return new ChatEvent(uncompressed, recompressed, color, effects); - } + return new ChatEvent(uncompressed, recompressed, color, effects); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/CloseInterfaceEventEncoder.java b/src/org/apollo/net/release/r317/CloseInterfaceEventEncoder.java index df1c404c..a8db40cb 100644 --- a/src/org/apollo/net/release/r317/CloseInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r317/CloseInterfaceEventEncoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventEncoder; */ public final class CloseInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(CloseInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(219); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(CloseInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(219); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ClosedInterfaceEventDecoder.java b/src/org/apollo/net/release/r317/ClosedInterfaceEventDecoder.java index 24004950..4be0903d 100644 --- a/src/org/apollo/net/release/r317/ClosedInterfaceEventDecoder.java +++ b/src/org/apollo/net/release/r317/ClosedInterfaceEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class ClosedInterfaceEventDecoder extends EventDecoder { - @Override - public ClosedInterfaceEvent decode(GamePacket packet) { - return new ClosedInterfaceEvent(); - } + @Override + public ClosedInterfaceEvent decode(GamePacket packet) { + return new ClosedInterfaceEvent(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/CommandEventDecoder.java b/src/org/apollo/net/release/r317/CommandEventDecoder.java index 5ced5885..ecb9ad86 100644 --- a/src/org/apollo/net/release/r317/CommandEventDecoder.java +++ b/src/org/apollo/net/release/r317/CommandEventDecoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventDecoder; */ public final class CommandEventDecoder extends EventDecoder { - @Override - public CommandEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - return new CommandEvent(reader.getString()); - } + @Override + public CommandEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + return new CommandEvent(reader.getString()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ConfigEventEncoder.java b/src/org/apollo/net/release/r317/ConfigEventEncoder.java index ac28c4a3..aded2f8a 100644 --- a/src/org/apollo/net/release/r317/ConfigEventEncoder.java +++ b/src/org/apollo/net/release/r317/ConfigEventEncoder.java @@ -15,24 +15,24 @@ import org.apollo.net.release.EventEncoder; */ public final class ConfigEventEncoder extends EventEncoder { - @Override - public GamePacket encode(ConfigEvent event) { - GamePacketBuilder builder; - int value = event.getValue(); + @Override + public GamePacket encode(ConfigEvent event) { + GamePacketBuilder builder; + int value = event.getValue(); - if (value > Byte.MIN_VALUE && value < Byte.MAX_VALUE) { - builder = new GamePacketBuilder(36); + if (value > Byte.MIN_VALUE && value < Byte.MAX_VALUE) { + builder = new GamePacketBuilder(36); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); - builder.put(DataType.BYTE, value & 0xFF); - } else { - builder = new GamePacketBuilder(87); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); + builder.put(DataType.BYTE, value & 0xFF); + } else { + builder = new GamePacketBuilder(87); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); - builder.put(DataType.INT, DataOrder.MIDDLE, value); - } - - return builder.toGamePacket(); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); + builder.put(DataType.INT, DataOrder.MIDDLE, value); } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/DialogueContinueEventEncoder.java b/src/org/apollo/net/release/r317/DialogueContinueEventEncoder.java index b70a8ca5..4186996b 100644 --- a/src/org/apollo/net/release/r317/DialogueContinueEventEncoder.java +++ b/src/org/apollo/net/release/r317/DialogueContinueEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ final class DialogueContinueEventDecoder extends EventDecoder { - @Override - public DialogueContinueEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new DialogueContinueEvent(interfaceId); - } + @Override + public DialogueContinueEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + return new DialogueContinueEvent(interfaceId); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/DisplayCrossbonesEventEncoder.java b/src/org/apollo/net/release/r317/DisplayCrossbonesEventEncoder.java index 8797fb0d..e0b45673 100644 --- a/src/org/apollo/net/release/r317/DisplayCrossbonesEventEncoder.java +++ b/src/org/apollo/net/release/r317/DisplayCrossbonesEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class DisplayCrossbonesEventEncoder extends EventEncoder { - @Override - public GamePacket encode(DisplayCrossbonesEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(61); - builder.put(DataType.BYTE, event.isDisplayed() ? 1 : 0); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(DisplayCrossbonesEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(61); + builder.put(DataType.BYTE, event.isDisplayed() ? 1 : 0); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/DisplayTabInterfaceEventEncoder.java b/src/org/apollo/net/release/r317/DisplayTabInterfaceEventEncoder.java index ad75a49d..5756da55 100644 --- a/src/org/apollo/net/release/r317/DisplayTabInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r317/DisplayTabInterfaceEventEncoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventEncoder; */ final class DisplayTabInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(DisplayTabInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(106); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getTab()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(DisplayTabInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(106); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getTab()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/EnterAmountEventEncoder.java b/src/org/apollo/net/release/r317/EnterAmountEventEncoder.java index 3b6dc958..43c11c79 100644 --- a/src/org/apollo/net/release/r317/EnterAmountEventEncoder.java +++ b/src/org/apollo/net/release/r317/EnterAmountEventEncoder.java @@ -14,9 +14,9 @@ import org.apollo.net.release.EventEncoder; */ public final class EnterAmountEventEncoder extends EventEncoder { - @Override - public GamePacket encode(EnterAmountEvent event) { - return new GamePacket(27, PacketType.FIXED, Unpooled.EMPTY_BUFFER); - } + @Override + public GamePacket encode(EnterAmountEvent event) { + return new GamePacket(27, PacketType.FIXED, Unpooled.EMPTY_BUFFER); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/EnteredAmountEventDecoder.java b/src/org/apollo/net/release/r317/EnteredAmountEventDecoder.java index e77bd209..5d52a37f 100644 --- a/src/org/apollo/net/release/r317/EnteredAmountEventDecoder.java +++ b/src/org/apollo/net/release/r317/EnteredAmountEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class EnteredAmountEventDecoder extends EventDecoder { - @Override - public EnteredAmountEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int amount = (int) reader.getUnsigned(DataType.INT); - return new EnteredAmountEvent(amount); - } + @Override + public EnteredAmountEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int amount = (int) reader.getUnsigned(DataType.INT); + return new EnteredAmountEvent(amount); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FifthItemActionEventDecoder.java b/src/org/apollo/net/release/r317/FifthItemActionEventDecoder.java index d6109c1b..e2e6858c 100644 --- a/src/org/apollo/net/release/r317/FifthItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FifthItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FifthItemActionEventDecoder extends EventDecoder { - @Override - public FifthItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FifthItemActionEvent(interfaceId, id, slot); - } + @Override + public FifthItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FifthItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FifthItemOptionEventDecoder.java b/src/org/apollo/net/release/r317/FifthItemOptionEventDecoder.java index b214049c..66b82e55 100644 --- a/src/org/apollo/net/release/r317/FifthItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FifthItemOptionEventDecoder.java @@ -14,15 +14,15 @@ import org.apollo.net.release.EventDecoder; */ final class FifthItemOptionEventDecoder extends EventDecoder { - @Override - public FifthItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FifthItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FifthItemOptionEvent(interfaceId, id, slot); - } + return new FifthItemOptionEvent(interfaceId, id, slot); + } } diff --git a/src/org/apollo/net/release/r317/FifthPlayerActionEventDecoder.java b/src/org/apollo/net/release/r317/FifthPlayerActionEventDecoder.java index ac7942a7..53969fb3 100644 --- a/src/org/apollo/net/release/r317/FifthPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FifthPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FifthPlayerActionEventDecoder extends EventDecoder { - @Override - public FifthPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FifthPlayerActionEvent(index); - } + @Override + public FifthPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FifthPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FirstItemActionEventDecoder.java b/src/org/apollo/net/release/r317/FirstItemActionEventDecoder.java index c818ddfa..f9cd9a86 100644 --- a/src/org/apollo/net/release/r317/FirstItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FirstItemActionEventDecoder.java @@ -14,13 +14,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstItemActionEventDecoder extends EventDecoder { - @Override - public FirstItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FirstItemActionEvent(interfaceId, id, slot); - } + @Override + public FirstItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new FirstItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FirstItemOptionEventDecoder.java b/src/org/apollo/net/release/r317/FirstItemOptionEventDecoder.java index 6d27117e..8c8e743b 100644 --- a/src/org/apollo/net/release/r317/FirstItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FirstItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class FirstItemOptionEventDecoder extends EventDecoder { - @Override - public FirstItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FirstItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); + int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); - return new FirstItemOptionEvent(interfaceId, id, slot); - } + return new FirstItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FirstNpcActionEventDecoder.java b/src/org/apollo/net/release/r317/FirstNpcActionEventDecoder.java index 0eeda0c6..059e0e02 100644 --- a/src/org/apollo/net/release/r317/FirstNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FirstNpcActionEventDecoder.java @@ -11,11 +11,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstNpcActionEventDecoder extends EventDecoder { - @Override - public FirstNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); - return new FirstNpcActionEvent(index); - } + @Override + public FirstNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); + return new FirstNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FirstObjectActionEventDecoder.java b/src/org/apollo/net/release/r317/FirstObjectActionEventDecoder.java index 0ae24bc4..6112c121 100644 --- a/src/org/apollo/net/release/r317/FirstObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FirstObjectActionEventDecoder.java @@ -16,13 +16,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstObjectActionEventDecoder extends EventDecoder { - @Override - public FirstObjectActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT); - int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FirstObjectActionEvent(id, new Position(x, y)); - } + @Override + public FirstObjectActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT); + int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new FirstObjectActionEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FirstPlayerActionEventDecoder.java b/src/org/apollo/net/release/r317/FirstPlayerActionEventDecoder.java index 6a70e584..52062bd0 100644 --- a/src/org/apollo/net/release/r317/FirstPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FirstPlayerActionEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstPlayerActionEventDecoder extends EventDecoder { - @Override - public FirstPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT); - return new FirstPlayerActionEvent(index); - } + @Override + public FirstPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT); + return new FirstPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FocusUpdateEventDecoder.java b/src/org/apollo/net/release/r317/FocusUpdateEventDecoder.java index 1de2e1ea..15e1f045 100644 --- a/src/org/apollo/net/release/r317/FocusUpdateEventDecoder.java +++ b/src/org/apollo/net/release/r317/FocusUpdateEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FocusUpdateEventDecoder extends EventDecoder { - @Override - public FocusUpdateEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - boolean focused = (byte) reader.getUnsigned(DataType.BYTE) == 1; - return new FocusUpdateEvent(focused); - } + @Override + public FocusUpdateEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + boolean focused = (byte) reader.getUnsigned(DataType.BYTE) == 1; + return new FocusUpdateEvent(focused); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ForwardPrivateMessageEventEncoder.java b/src/org/apollo/net/release/r317/ForwardPrivateMessageEventEncoder.java index 8464b2cb..eef5dc59 100644 --- a/src/org/apollo/net/release/r317/ForwardPrivateMessageEventEncoder.java +++ b/src/org/apollo/net/release/r317/ForwardPrivateMessageEventEncoder.java @@ -17,20 +17,20 @@ import org.apollo.util.NameUtil; */ public final class ForwardPrivateMessageEventEncoder extends EventEncoder { - /** - * The amount of messages sent globally, offset by a random variable x, {@code 0 <= x < 100,000,000}. - */ - private static AtomicInteger messageCounter = new AtomicInteger((int) (Math.random() * 100_000_000)); + /** + * The amount of messages sent globally, offset by a random variable x, {@code 0 <= x < 100,000,000}. + */ + private static AtomicInteger messageCounter = new AtomicInteger((int) (Math.random() * 100_000_000)); - @Override - public GamePacket encode(ForwardPrivateMessageEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(196, PacketType.VARIABLE_BYTE); + @Override + public GamePacket encode(ForwardPrivateMessageEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(196, PacketType.VARIABLE_BYTE); - builder.put(DataType.LONG, NameUtil.encodeBase37(event.getSenderUsername())); - builder.put(DataType.INT, messageCounter.incrementAndGet()); - builder.put(DataType.BYTE, event.getSenderPrivilege().toInteger()); - builder.putBytes(event.getCompressedMessage()); - return builder.toGamePacket(); - } + builder.put(DataType.LONG, NameUtil.encodeBase37(event.getSenderUsername())); + builder.put(DataType.INT, messageCounter.incrementAndGet()); + builder.put(DataType.BYTE, event.getSenderPrivilege().toInteger()); + builder.putBytes(event.getCompressedMessage()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FourthItemActionEventDecoder.java b/src/org/apollo/net/release/r317/FourthItemActionEventDecoder.java index 28260843..2e6a73ec 100644 --- a/src/org/apollo/net/release/r317/FourthItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FourthItemActionEventDecoder.java @@ -14,13 +14,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FourthItemActionEventDecoder extends EventDecoder { - @Override - public FourthItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FourthItemActionEvent(interfaceId, id, slot); - } + @Override + public FourthItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new FourthItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FourthItemOptionEventDecoder.java b/src/org/apollo/net/release/r317/FourthItemOptionEventDecoder.java index ff4e9fde..428050ef 100644 --- a/src/org/apollo/net/release/r317/FourthItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FourthItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class FourthItemOptionEventDecoder extends EventDecoder { - @Override - public FourthItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FourthItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int slot = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FourthItemOptionEvent(interfaceId, id, slot); - } + return new FourthItemOptionEvent(interfaceId, id, slot); + } } diff --git a/src/org/apollo/net/release/r317/FourthPlayerActionEventDecoder.java b/src/org/apollo/net/release/r317/FourthPlayerActionEventDecoder.java index e0b52aa6..465f3036 100644 --- a/src/org/apollo/net/release/r317/FourthPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/FourthPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FourthPlayerActionEventDecoder extends EventDecoder { - @Override - public FourthPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FourthPlayerActionEvent(index); - } + @Override + public FourthPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FourthPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/FriendServerStatusEventEncoder.java b/src/org/apollo/net/release/r317/FriendServerStatusEventEncoder.java index 73ec2fdc..58c5152a 100644 --- a/src/org/apollo/net/release/r317/FriendServerStatusEventEncoder.java +++ b/src/org/apollo/net/release/r317/FriendServerStatusEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class FriendServerStatusEventEncoder extends EventEncoder { - @Override - public GamePacket encode(FriendServerStatusEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(221); - builder.put(DataType.BYTE, event.getStatusCode()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(FriendServerStatusEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(221); + builder.put(DataType.BYTE, event.getStatusCode()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/IdAssignmentEventEncoder.java b/src/org/apollo/net/release/r317/IdAssignmentEventEncoder.java index d16e7e16..266a4562 100644 --- a/src/org/apollo/net/release/r317/IdAssignmentEventEncoder.java +++ b/src/org/apollo/net/release/r317/IdAssignmentEventEncoder.java @@ -15,12 +15,12 @@ import org.apollo.net.release.EventEncoder; */ public final class IdAssignmentEventEncoder extends EventEncoder { - @Override - public GamePacket encode(IdAssignmentEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(249); - builder.put(DataType.BYTE, DataTransformation.ADD, event.isMembers() ? 1 : 0); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(IdAssignmentEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(249); + builder.put(DataType.BYTE, DataTransformation.ADD, event.isMembers() ? 1 : 0); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/IgnoreListEventEncoder.java b/src/org/apollo/net/release/r317/IgnoreListEventEncoder.java index 445a08c6..ed4cddb0 100644 --- a/src/org/apollo/net/release/r317/IgnoreListEventEncoder.java +++ b/src/org/apollo/net/release/r317/IgnoreListEventEncoder.java @@ -17,16 +17,16 @@ import org.apollo.util.NameUtil; */ public final class IgnoreListEventEncoder extends EventEncoder { - @Override - public GamePacket encode(IgnoreListEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(214, PacketType.VARIABLE_SHORT); + @Override + public GamePacket encode(IgnoreListEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(214, PacketType.VARIABLE_SHORT); - List usernames = event.getUsernames(); - for (String username : usernames) { - builder.put(DataType.LONG, NameUtil.encodeBase37(username)); - } - - return builder.toGamePacket(); + List usernames = event.getUsernames(); + for (String username : usernames) { + builder.put(DataType.LONG, NameUtil.encodeBase37(username)); } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ItemOnItemEventDecoder.java b/src/org/apollo/net/release/r317/ItemOnItemEventDecoder.java index 847b1238..a0f704c7 100644 --- a/src/org/apollo/net/release/r317/ItemOnItemEventDecoder.java +++ b/src/org/apollo/net/release/r317/ItemOnItemEventDecoder.java @@ -15,20 +15,20 @@ import org.apollo.net.release.EventDecoder; */ final class ItemOnItemEventDecoder extends EventDecoder { - @Override - public ItemOnItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ItemOnItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int targetSlot = (int) reader.getUnsigned(DataType.SHORT); - int usedSlot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int targetSlot = (int) reader.getUnsigned(DataType.SHORT); + int usedSlot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int targetId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int targetInterface = (int) reader.getUnsigned(DataType.SHORT); + int targetId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int targetInterface = (int) reader.getUnsigned(DataType.SHORT); - int usedId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); - int usedInterface = (int) reader.getUnsigned(DataType.SHORT); + int usedId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE); + int usedInterface = (int) reader.getUnsigned(DataType.SHORT); - return new ItemOnItemEvent(usedInterface, usedId, usedSlot, targetInterface, targetId, targetSlot); - } + return new ItemOnItemEvent(usedInterface, usedId, usedSlot, targetInterface, targetId, targetSlot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ItemOnObjectEventDecoder.java b/src/org/apollo/net/release/r317/ItemOnObjectEventDecoder.java index d9056643..5d1f15c9 100644 --- a/src/org/apollo/net/release/r317/ItemOnObjectEventDecoder.java +++ b/src/org/apollo/net/release/r317/ItemOnObjectEventDecoder.java @@ -15,18 +15,18 @@ import org.apollo.net.release.EventDecoder; */ public final class ItemOnObjectEventDecoder extends EventDecoder { - @Override - public ItemOnObjectEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ItemOnObjectEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - int objectId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int itemId = (int) reader.getUnsigned(DataType.SHORT); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int objectId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int itemId = (int) reader.getUnsigned(DataType.SHORT); - return new ItemOnObjectEvent(interfaceId, itemId, slot, objectId, x, y); - } + return new ItemOnObjectEvent(interfaceId, itemId, slot, objectId, x, y); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/KeepAliveEventDecoder.java b/src/org/apollo/net/release/r317/KeepAliveEventDecoder.java index 9fd00822..66ac8318 100644 --- a/src/org/apollo/net/release/r317/KeepAliveEventDecoder.java +++ b/src/org/apollo/net/release/r317/KeepAliveEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class KeepAliveEventDecoder extends EventDecoder { - @Override - public KeepAliveEvent decode(GamePacket packet) { - return new KeepAliveEvent(); - } + @Override + public KeepAliveEvent decode(GamePacket packet) { + return new KeepAliveEvent(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/LogoutEventEncoder.java b/src/org/apollo/net/release/r317/LogoutEventEncoder.java index 19844bfc..8053bc20 100644 --- a/src/org/apollo/net/release/r317/LogoutEventEncoder.java +++ b/src/org/apollo/net/release/r317/LogoutEventEncoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventEncoder; */ public final class LogoutEventEncoder extends EventEncoder { - @Override - public GamePacket encode(LogoutEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(109); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(LogoutEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(109); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/MagicOnItemEventDecoder.java b/src/org/apollo/net/release/r317/MagicOnItemEventDecoder.java index ae17675e..a1081fa4 100644 --- a/src/org/apollo/net/release/r317/MagicOnItemEventDecoder.java +++ b/src/org/apollo/net/release/r317/MagicOnItemEventDecoder.java @@ -14,16 +14,16 @@ import org.apollo.net.release.EventDecoder; */ final class MagicOnItemEventDecoder extends EventDecoder { - @Override - public MagicOnItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public MagicOnItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - int spell = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int spell = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new MagicOnItemEvent(interfaceId, id, slot, spell); - } + return new MagicOnItemEvent(interfaceId, id, slot, spell); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/MobAnimationResetEventEncoder.java b/src/org/apollo/net/release/r317/MobAnimationResetEventEncoder.java index cc90bcca..04a0eb2c 100644 --- a/src/org/apollo/net/release/r317/MobAnimationResetEventEncoder.java +++ b/src/org/apollo/net/release/r317/MobAnimationResetEventEncoder.java @@ -12,9 +12,9 @@ import org.apollo.net.release.EventEncoder; */ public final class MobAnimationResetEventEncoder extends EventEncoder { - @Override - public GamePacket encode(MobAnimationResetEvent event) { - return new GamePacketBuilder(1).toGamePacket(); - } + @Override + public GamePacket encode(MobAnimationResetEvent event) { + return new GamePacketBuilder(1).toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/MouseClickEventDecoder.java b/src/org/apollo/net/release/r317/MouseClickEventDecoder.java index 0377324d..97516599 100644 --- a/src/org/apollo/net/release/r317/MouseClickEventDecoder.java +++ b/src/org/apollo/net/release/r317/MouseClickEventDecoder.java @@ -13,25 +13,25 @@ import org.apollo.net.release.EventDecoder; */ public final class MouseClickEventDecoder extends EventDecoder { - @Override - public MouseClickEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int read; - if (reader.getLength() == 2) { - read = (int) reader.getUnsigned(DataType.SHORT); - int clickCount = (read >> 12); - int dX = (read >> 6) & 0x3f; - int dY = read & 0x3f; - return new MouseClickEvent(clickCount, dX, dY, true); - } else if (reader.getLength() == 3) { - read = (int) reader.getUnsigned(DataType.TRI_BYTE) & ~0x800000; - } else { - read = (int) reader.getUnsigned(DataType.INT) & ~0xc0000000; - } - int clickCount = (read >> 19); - int x = (read & 0x7f) % 765; - int y = (read & 0x7f) / 765; - return new MouseClickEvent(clickCount, x, y, false); + @Override + public MouseClickEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int read; + if (reader.getLength() == 2) { + read = (int) reader.getUnsigned(DataType.SHORT); + int clickCount = (read >> 12); + int dX = (read >> 6) & 0x3f; + int dY = read & 0x3f; + return new MouseClickEvent(clickCount, dX, dY, true); + } else if (reader.getLength() == 3) { + read = (int) reader.getUnsigned(DataType.TRI_BYTE) & ~0x800000; + } else { + read = (int) reader.getUnsigned(DataType.INT) & ~0xc0000000; } + int clickCount = (read >> 19); + int x = (read & 0x7f) % 765; + int y = (read & 0x7f) / 765; + return new MouseClickEvent(clickCount, x, y, false); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/NpcSynchronizationEventEncoder.java b/src/org/apollo/net/release/r317/NpcSynchronizationEventEncoder.java index 3720ceb6..5e70d9a6 100644 --- a/src/org/apollo/net/release/r317/NpcSynchronizationEventEncoder.java +++ b/src/org/apollo/net/release/r317/NpcSynchronizationEventEncoder.java @@ -33,269 +33,269 @@ import org.apollo.net.release.EventEncoder; */ public final class NpcSynchronizationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(NpcSynchronizationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(65, PacketType.VARIABLE_SHORT); - builder.switchToBitAccess(); + @Override + public GamePacket encode(NpcSynchronizationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(65, PacketType.VARIABLE_SHORT); + builder.switchToBitAccess(); - GamePacketBuilder blockBuilder = new GamePacketBuilder(); - builder.putBits(8, event.getLocalNpcCount()); + GamePacketBuilder blockBuilder = new GamePacketBuilder(); + builder.putBits(8, event.getLocalNpcCount()); - for (SynchronizationSegment segment : event.getSegments()) { - SegmentType type = segment.getType(); - if (type == SegmentType.REMOVE_MOB) { - putRemoveMobUpdate(builder); - } else if (type == SegmentType.ADD_MOB) { - putAddNpcUpdate((AddNpcSegment) segment, event, builder); - putBlocks(segment, blockBuilder); - } else { - putMovementUpdate(segment, event, builder); - putBlocks(segment, blockBuilder); - } - } - - if (blockBuilder.getLength() > 0) { - builder.putBits(14, 16383); - builder.switchToByteAccess(); - builder.putRawBuilder(blockBuilder); - } else { - builder.switchToByteAccess(); - } - - return builder.toGamePacket(); + for (SynchronizationSegment segment : event.getSegments()) { + SegmentType type = segment.getType(); + if (type == SegmentType.REMOVE_MOB) { + putRemoveMobUpdate(builder); + } else if (type == SegmentType.ADD_MOB) { + putAddNpcUpdate((AddNpcSegment) segment, event, builder); + putBlocks(segment, blockBuilder); + } else { + putMovementUpdate(segment, event, builder); + putBlocks(segment, blockBuilder); + } } - /** - * Puts an add npc update. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putAddNpcUpdate(AddNpcSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - Position npc = event.getPosition(); - Position other = seg.getPosition(); - builder.putBits(14, seg.getIndex()); - builder.putBits(5, other.getY() - npc.getY()); - builder.putBits(5, other.getX() - npc.getX()); - builder.putBits(1, 0); // discard walking queue - builder.putBits(12, seg.getNpcId()); - builder.putBits(1, updateRequired ? 1 : 0); + if (blockBuilder.getLength() > 0) { + builder.putBits(14, 16383); + builder.switchToByteAccess(); + builder.putRawBuilder(blockBuilder); + } else { + builder.switchToByteAccess(); } - /** - * Puts an animation block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { - Animation animation = block.getAnimation(); - builder.put(DataType.SHORT, DataOrder.LITTLE, animation.getId()); - builder.put(DataType.BYTE, animation.getDelay()); + return builder.toGamePacket(); + } + + /** + * Puts an add npc update. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putAddNpcUpdate(AddNpcSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + Position npc = event.getPosition(); + Position other = seg.getPosition(); + builder.putBits(14, seg.getIndex()); + builder.putBits(5, other.getY() - npc.getY()); + builder.putBits(5, other.getX() - npc.getX()); + builder.putBits(1, 0); // discard walking queue + builder.putBits(12, seg.getNpcId()); + builder.putBits(1, updateRequired ? 1 : 0); + } + + /** + * Puts an animation block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { + Animation animation = block.getAnimation(); + builder.put(DataType.SHORT, DataOrder.LITTLE, animation.getId()); + builder.put(DataType.BYTE, animation.getDelay()); + } + + /** + * Puts the blocks for the specified segment. + * + * @param segment The segment. + * @param builder The block builder. + */ + private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { + SynchronizationBlockSet blockSet = segment.getBlockSet(); + if (blockSet.size() > 0) { + int mask = 0; + + if (blockSet.contains(AnimationBlock.class)) { + mask |= 0x10; + } + + if (blockSet.contains(HitUpdateBlock.class)) { + mask |= 0x8; + } + + if (blockSet.contains(GraphicBlock.class)) { + mask |= 0x80; + } + + if (blockSet.contains(InteractingMobBlock.class)) { + mask |= 0x20; + } + + if (blockSet.contains(ForceChatBlock.class)) { + mask |= 0x1; + } + + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + mask |= 0x40; + } + + if (blockSet.contains(TransformBlock.class)) { + mask |= 0x2; + } + + if (blockSet.contains(TurnToPositionBlock.class)) { + mask |= 0x4; + } + + builder.put(DataType.BYTE, mask); + + if (blockSet.contains(AnimationBlock.class)) { + putAnimationBlock(blockSet.get(AnimationBlock.class), builder); + } + + if (blockSet.contains(HitUpdateBlock.class)) { + putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); + } + + if (blockSet.contains(GraphicBlock.class)) { + putGraphicBlock(blockSet.get(GraphicBlock.class), builder); + } + + if (blockSet.contains(InteractingMobBlock.class)) { + putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); + } + + if (blockSet.contains(ForceChatBlock.class)) { + putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); + } + + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); + } + + if (blockSet.contains(TransformBlock.class)) { + putTransformBlock(blockSet.get(TransformBlock.class), builder); + } + + if (blockSet.contains(TurnToPositionBlock.class)) { + putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); + } } + } - /** - * Puts the blocks for the specified segment. - * - * @param segment The segment. - * @param builder The block builder. - */ - private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { - SynchronizationBlockSet blockSet = segment.getBlockSet(); - if (blockSet.size() > 0) { - int mask = 0; + /** + * Puts a force chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { + builder.putString(block.getMessage()); + } - if (blockSet.contains(AnimationBlock.class)) { - mask |= 0x10; - } + /** + * Puts a graphic block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { + Graphic graphic = block.getGraphic(); + builder.put(DataType.SHORT, graphic.getId()); + builder.put(DataType.INT, graphic.getDelay()); + } - if (blockSet.contains(HitUpdateBlock.class)) { - mask |= 0x8; - } + /** + * Puts a hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getType()); + builder.put(DataType.BYTE, DataTransformation.ADD, block.getCurrentHealth()); + builder.put(DataType.BYTE, block.getMaximumHealth()); + } - if (blockSet.contains(GraphicBlock.class)) { - mask |= 0x80; - } + /** + * Puts an interacting mob block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, block.getInteractingMobIndex()); + } - if (blockSet.contains(InteractingMobBlock.class)) { - mask |= 0x20; - } - - if (blockSet.contains(ForceChatBlock.class)) { - mask |= 0x1; - } - - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - mask |= 0x40; - } - - if (blockSet.contains(TransformBlock.class)) { - mask |= 0x2; - } - - if (blockSet.contains(TurnToPositionBlock.class)) { - mask |= 0x4; - } - - builder.put(DataType.BYTE, mask); - - if (blockSet.contains(AnimationBlock.class)) { - putAnimationBlock(blockSet.get(AnimationBlock.class), builder); - } - - if (blockSet.contains(HitUpdateBlock.class)) { - putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); - } - - if (blockSet.contains(GraphicBlock.class)) { - putGraphicBlock(blockSet.get(GraphicBlock.class), builder); - } - - if (blockSet.contains(InteractingMobBlock.class)) { - putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); - } - - if (blockSet.contains(ForceChatBlock.class)) { - putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); - } - - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); - } - - if (blockSet.contains(TransformBlock.class)) { - putTransformBlock(blockSet.get(TransformBlock.class), builder); - } - - if (blockSet.contains(TurnToPositionBlock.class)) { - putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); - } - } - } - - /** - * Puts a force chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { - builder.putString(block.getMessage()); - } - - /** - * Puts a graphic block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { - Graphic graphic = block.getGraphic(); - builder.put(DataType.SHORT, graphic.getId()); - builder.put(DataType.INT, graphic.getDelay()); - } - - /** - * Puts a hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getType()); - builder.put(DataType.BYTE, DataTransformation.ADD, block.getCurrentHealth()); - builder.put(DataType.BYTE, block.getMaximumHealth()); - } - - /** - * Puts an interacting mob block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, block.getInteractingMobIndex()); - } - - /** - * Puts a movement update for the specified segment. - * - * @param segment The segment. - * @param event The event. - * @param builder The builder. - */ - private void putMovementUpdate(SynchronizationSegment segment, NpcSynchronizationEvent event, - GamePacketBuilder builder) { - boolean updateRequired = segment.getBlockSet().size() > 0; - if (segment.getType() == SegmentType.RUN) { - Direction[] directions = ((MovementSegment) segment).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 2); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(3, directions[1].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else if (segment.getType() == SegmentType.WALK) { - Direction[] directions = ((MovementSegment) segment).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 1); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else { - if (updateRequired) { - builder.putBits(1, 1); - builder.putBits(2, 0); - } else { - builder.putBits(1, 0); - } - } - } - - /** - * Puts a remove mob update. - * - * @param builder The builder. - */ - private void putRemoveMobUpdate(GamePacketBuilder builder) { + /** + * Puts a movement update for the specified segment. + * + * @param segment The segment. + * @param event The event. + * @param builder The builder. + */ + private void putMovementUpdate(SynchronizationSegment segment, NpcSynchronizationEvent event, + GamePacketBuilder builder) { + boolean updateRequired = segment.getBlockSet().size() > 0; + if (segment.getType() == SegmentType.RUN) { + Direction[] directions = ((MovementSegment) segment).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 2); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(3, directions[1].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else if (segment.getType() == SegmentType.WALK) { + Direction[] directions = ((MovementSegment) segment).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 1); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else { + if (updateRequired) { builder.putBits(1, 1); - builder.putBits(2, 3); + builder.putBits(2, 0); + } else { + builder.putBits(1, 0); + } } + } - /** - * Puts a second hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getCurrentHealth()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); - } + /** + * Puts a remove mob update. + * + * @param builder The builder. + */ + private void putRemoveMobUpdate(GamePacketBuilder builder) { + builder.putBits(1, 1); + builder.putBits(2, 3); + } - /** - * Puts a transform block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTransformBlock(TransformBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, block.getId()); - } + /** + * Puts a second hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getCurrentHealth()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); + } - /** - * Puts a turn to position block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { - Position position = block.getPosition(); - builder.put(DataType.SHORT, DataOrder.LITTLE, position.getX() * 2 + 1); - builder.put(DataType.SHORT, DataOrder.LITTLE, position.getY() * 2 + 1); - } + /** + * Puts a transform block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTransformBlock(TransformBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, block.getId()); + } + + /** + * Puts a turn to position block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { + Position position = block.getPosition(); + builder.put(DataType.SHORT, DataOrder.LITTLE, position.getX() * 2 + 1); + builder.put(DataType.SHORT, DataOrder.LITTLE, position.getY() * 2 + 1); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/OpenDialogueInterfaceEventEncoder.java b/src/org/apollo/net/release/r317/OpenDialogueInterfaceEventEncoder.java index acabd337..effaa587 100644 --- a/src/org/apollo/net/release/r317/OpenDialogueInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r317/OpenDialogueInterfaceEventEncoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenDialogueInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenDialogueInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(164); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenDialogueInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(164); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/OpenInterfaceEventEncoder.java b/src/org/apollo/net/release/r317/OpenInterfaceEventEncoder.java index 7d536b2e..c6974ea1 100644 --- a/src/org/apollo/net/release/r317/OpenInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r317/OpenInterfaceEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(97); - builder.put(DataType.SHORT, event.getId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(97); + builder.put(DataType.SHORT, event.getId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/OpenInterfaceSidebarEventEncoder.java b/src/org/apollo/net/release/r317/OpenInterfaceSidebarEventEncoder.java index 22a21e47..08f5ef2e 100644 --- a/src/org/apollo/net/release/r317/OpenInterfaceSidebarEventEncoder.java +++ b/src/org/apollo/net/release/r317/OpenInterfaceSidebarEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenInterfaceSidebarEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenInterfaceSidebarEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(248); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); - builder.put(DataType.SHORT, event.getSidebarId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenInterfaceSidebarEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(248); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); + builder.put(DataType.SHORT, event.getSidebarId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PlayerDesignEventDecoder.java b/src/org/apollo/net/release/r317/PlayerDesignEventDecoder.java index 89c7bc20..f1b4572e 100644 --- a/src/org/apollo/net/release/r317/PlayerDesignEventDecoder.java +++ b/src/org/apollo/net/release/r317/PlayerDesignEventDecoder.java @@ -15,25 +15,25 @@ import org.apollo.net.release.EventDecoder; */ public final class PlayerDesignEventDecoder extends EventDecoder { - @Override - public PlayerDesignEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PlayerDesignEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int genderIntValue = (int) reader.getUnsigned(DataType.BYTE); + int genderIntValue = (int) reader.getUnsigned(DataType.BYTE); - int[] style = new int[7]; - for (int i = 0; i < style.length; i++) { - style[i] = (int) reader.getUnsigned(DataType.BYTE); - } - - int[] color = new int[5]; - for (int i = 0; i < color.length; i++) { - color[i] = (int) reader.getUnsigned(DataType.BYTE); - } - - Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; - - return new PlayerDesignEvent(new Appearance(gender, style, color)); + int[] style = new int[7]; + for (int i = 0; i < style.length; i++) { + style[i] = (int) reader.getUnsigned(DataType.BYTE); } + int[] color = new int[5]; + for (int i = 0; i < color.length; i++) { + color[i] = (int) reader.getUnsigned(DataType.BYTE); + } + + Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; + + return new PlayerDesignEvent(new Appearance(gender, style, color)); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PlayerSynchronizationEventEncoder.java b/src/org/apollo/net/release/r317/PlayerSynchronizationEventEncoder.java index 05bf876b..96e4ede0 100644 --- a/src/org/apollo/net/release/r317/PlayerSynchronizationEventEncoder.java +++ b/src/org/apollo/net/release/r317/PlayerSynchronizationEventEncoder.java @@ -43,419 +43,419 @@ import org.apollo.net.release.EventEncoder; */ public final class PlayerSynchronizationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(PlayerSynchronizationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(81, PacketType.VARIABLE_SHORT); - builder.switchToBitAccess(); + @Override + public GamePacket encode(PlayerSynchronizationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(81, PacketType.VARIABLE_SHORT); + builder.switchToBitAccess(); - GamePacketBuilder blockBuilder = new GamePacketBuilder(); + GamePacketBuilder blockBuilder = new GamePacketBuilder(); - putMovementUpdate(event.getSegment(), event, builder); - putBlocks(event.getSegment(), blockBuilder); + putMovementUpdate(event.getSegment(), event, builder); + putBlocks(event.getSegment(), blockBuilder); - builder.putBits(8, event.getLocalPlayers()); + builder.putBits(8, event.getLocalPlayers()); - for (SynchronizationSegment segment : event.getSegments()) { - SegmentType type = segment.getType(); - if (type == SegmentType.REMOVE_MOB) { - putRemovePlayerUpdate(builder); - } else if (type == SegmentType.ADD_MOB) { - putAddPlayerUpdate((AddPlayerSegment) segment, event, builder); - putBlocks(segment, blockBuilder); - } else { - putMovementUpdate(segment, event, builder); - putBlocks(segment, blockBuilder); - } - } + for (SynchronizationSegment segment : event.getSegments()) { + SegmentType type = segment.getType(); + if (type == SegmentType.REMOVE_MOB) { + putRemovePlayerUpdate(builder); + } else if (type == SegmentType.ADD_MOB) { + putAddPlayerUpdate((AddPlayerSegment) segment, event, builder); + putBlocks(segment, blockBuilder); + } else { + putMovementUpdate(segment, event, builder); + putBlocks(segment, blockBuilder); + } + } - if (blockBuilder.getLength() > 0) { - builder.putBits(11, 2047); - builder.switchToByteAccess(); - builder.putRawBuilder(blockBuilder); + if (blockBuilder.getLength() > 0) { + builder.putBits(11, 2047); + builder.switchToByteAccess(); + builder.putRawBuilder(blockBuilder); + } else { + builder.switchToByteAccess(); + } + + return builder.toGamePacket(); + } + + /** + * Puts an add player update. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putAddPlayerUpdate(AddPlayerSegment seg, PlayerSynchronizationEvent event, GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + Position player = event.getPosition(); + Position other = seg.getPosition(); + builder.putBits(11, seg.getIndex()); + builder.putBits(1, updateRequired ? 1 : 0); + builder.putBits(1, 1); // discard walking queue? + builder.putBits(5, other.getY() - player.getY()); + builder.putBits(5, other.getX() - player.getX()); + } + + /** + * Puts an animation block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { + Animation animation = block.getAnimation(); + builder.put(DataType.SHORT, DataOrder.LITTLE, animation.getId()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, animation.getDelay()); + } + + /** + * Puts an appearance block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAppearanceBlock(AppearanceBlock block, GamePacketBuilder builder) { + Appearance appearance = block.getAppearance(); + GamePacketBuilder playerProperties = new GamePacketBuilder(); + + playerProperties.put(DataType.BYTE, appearance.getGender().toInteger()); + playerProperties.put(DataType.BYTE, 0); + + if (block.appearingAsNpc()) { + playerProperties.put(DataType.BYTE, 255); + playerProperties.put(DataType.BYTE, 255); + playerProperties.put(DataType.SHORT, block.getNpcId()); + } else { + Inventory equipment = block.getEquipment(); + int[] style = appearance.getStyle(); + Item item, chest, helm; + + for (int slot = 0; slot < 4; slot++) { + if ((item = equipment.get(slot)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); } else { - builder.switchToByteAccess(); + playerProperties.put(DataType.BYTE, 0); } + } - return builder.toGamePacket(); - } + if ((chest = equipment.get(EquipmentConstants.CHEST)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + chest.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[2]); + } - /** - * Puts an add player update. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putAddPlayerUpdate(AddPlayerSegment seg, PlayerSynchronizationEvent event, GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - Position player = event.getPosition(); - Position other = seg.getPosition(); - builder.putBits(11, seg.getIndex()); - builder.putBits(1, updateRequired ? 1 : 0); - builder.putBits(1, 1); // discard walking queue? - builder.putBits(5, other.getY() - player.getY()); - builder.putBits(5, other.getX() - player.getX()); - } - - /** - * Puts an animation block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { - Animation animation = block.getAnimation(); - builder.put(DataType.SHORT, DataOrder.LITTLE, animation.getId()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, animation.getDelay()); - } - - /** - * Puts an appearance block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAppearanceBlock(AppearanceBlock block, GamePacketBuilder builder) { - Appearance appearance = block.getAppearance(); - GamePacketBuilder playerProperties = new GamePacketBuilder(); - - playerProperties.put(DataType.BYTE, appearance.getGender().toInteger()); + if ((item = equipment.get(EquipmentConstants.SHIELD)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { playerProperties.put(DataType.BYTE, 0); + } - if (block.appearingAsNpc()) { - playerProperties.put(DataType.BYTE, 255); - playerProperties.put(DataType.BYTE, 255); - playerProperties.put(DataType.SHORT, block.getNpcId()); + if (chest != null) { + EquipmentDefinition def = EquipmentDefinition.lookup(chest.getId()); + if (def != null && !def.isFullBody()) { + playerProperties.put(DataType.SHORT, 0x100 + style[3]); } else { - Inventory equipment = block.getEquipment(); - int[] style = appearance.getStyle(); - Item item, chest, helm; - - for (int slot = 0; slot < 4; slot++) { - if ((item = equipment.get(slot)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } - - if ((chest = equipment.get(EquipmentConstants.CHEST)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + chest.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[2]); - } - - if ((item = equipment.get(EquipmentConstants.SHIELD)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.BYTE, 0); - } - - if (chest != null) { - EquipmentDefinition def = EquipmentDefinition.lookup(chest.getId()); - if (def != null && !def.isFullBody()) { - playerProperties.put(DataType.SHORT, 0x100 + style[3]); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[3]); - } - - if ((item = equipment.get(EquipmentConstants.LEGS)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[5]); - } - - if ((helm = equipment.get(EquipmentConstants.HAT)) != null) { - EquipmentDefinition def = EquipmentDefinition.lookup(helm.getId()); - if (def != null && !def.isFullHat() && !def.isFullMask()) { - playerProperties.put(DataType.SHORT, 0x100 + style[0]); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[0]); - } - - if ((item = equipment.get(EquipmentConstants.HANDS)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[4]); - } - - if ((item = equipment.get(EquipmentConstants.FEET)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[6]); - } - - EquipmentDefinition def = null; - if (helm != null) { - def = EquipmentDefinition.lookup(helm.getId()); - } - if (def != null && (def.isFullHat() || def.isFullMask()) || appearance.getGender() == Gender.FEMALE) { - playerProperties.put(DataType.BYTE, 0); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[1]); - } + playerProperties.put(DataType.BYTE, 0); } + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[3]); + } - int[] colors = appearance.getColors(); - for (int color : colors) { - playerProperties.put(DataType.BYTE, color); - } + if ((item = equipment.get(EquipmentConstants.LEGS)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[5]); + } - playerProperties.put(DataType.SHORT, 0x328); // stand - playerProperties.put(DataType.SHORT, 0x337); // stand turn - playerProperties.put(DataType.SHORT, 0x333); // walk - playerProperties.put(DataType.SHORT, 0x334); // turn 180 - playerProperties.put(DataType.SHORT, 0x335); // turn 90 cw - playerProperties.put(DataType.SHORT, 0x336); // turn 90 ccw - playerProperties.put(DataType.SHORT, 0x338); // run - - playerProperties.put(DataType.LONG, block.getName()); - playerProperties.put(DataType.BYTE, block.getCombatLevel()); - playerProperties.put(DataType.SHORT, block.getSkillLevel()); - - builder.put(DataType.BYTE, DataTransformation.NEGATE, playerProperties.getLength()); - - builder.putRawBuilder(playerProperties); - } - - /** - * Puts the blocks for the specified segment. - * - * @param segment The segment. - * @param builder The block builder. - */ - private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { - SynchronizationBlockSet blockSet = segment.getBlockSet(); - if (blockSet.size() > 0) { - int mask = 0; - - if (blockSet.contains(ForceMovementBlock.class)) { - mask |= 0x400; - } - if (blockSet.contains(GraphicBlock.class)) { - mask |= 0x100; - } - if (blockSet.contains(AnimationBlock.class)) { - mask |= 0x8; - } - if (blockSet.contains(ForceChatBlock.class)) { - mask |= 0x4; - } - if (blockSet.contains(ChatBlock.class)) { - mask |= 0x80; - } - if (blockSet.contains(InteractingMobBlock.class)) { - mask |= 0x1; - } - if (blockSet.contains(AppearanceBlock.class)) { - mask |= 0x10; - } - if (blockSet.contains(TurnToPositionBlock.class)) { - mask |= 0x2; - } - if (blockSet.contains(HitUpdateBlock.class)) { - mask |= 0x20; - } - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - mask |= 0x200; - } - - if (mask >= 0x100) { - mask |= 0x40; - builder.put(DataType.SHORT, DataOrder.LITTLE, mask); - } else { - builder.put(DataType.BYTE, mask); - } - - if (blockSet.contains(ForceMovementBlock.class)) { - putForceMovementBlock(blockSet.get(ForceMovementBlock.class), builder); - } - if (blockSet.contains(GraphicBlock.class)) { - putGraphicBlock(blockSet.get(GraphicBlock.class), builder); - } - if (blockSet.contains(AnimationBlock.class)) { - putAnimationBlock(blockSet.get(AnimationBlock.class), builder); - } - if (blockSet.contains(ForceChatBlock.class)) { - putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); - } - if (blockSet.contains(ChatBlock.class)) { - putChatBlock(blockSet.get(ChatBlock.class), builder); - } - if (blockSet.contains(InteractingMobBlock.class)) { - putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); - } - if (blockSet.contains(AppearanceBlock.class)) { - putAppearanceBlock(blockSet.get(AppearanceBlock.class), builder); - } - if (blockSet.contains(TurnToPositionBlock.class)) { - putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); - } - if (blockSet.contains(HitUpdateBlock.class)) { - putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); - } - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); - } - } - } - - /** - * Puts a chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putChatBlock(ChatBlock block, GamePacketBuilder builder) { - byte[] bytes = block.getCompressedMessage(); - builder.put(DataType.SHORT, DataOrder.LITTLE, block.getTextColor() << 8 | block.getTextEffects()); - builder.put(DataType.BYTE, block.getPrivilegeLevel().toInteger()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, bytes.length); - builder.putBytesReverse(bytes); - } - - /** - * Puts a force chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { - builder.putString(block.getMessage()); - } - - /** - * Puts a force movement block in the specified builder. - * - * @param forceMovementBlock The block. - * @param builder The builder. - */ - private void putForceMovementBlock(ForceMovementBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getInitialX()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getInitialY()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalX()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalY()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, block.getTravelDurationX()); - builder.put(DataType.SHORT, DataTransformation.ADD, block.getTravelDurationY()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDirection().toInteger()); - } - - /** - * Puts a graphic block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { - Graphic graphic = block.getGraphic(); - builder.put(DataType.SHORT, DataOrder.LITTLE, graphic.getId()); - builder.put(DataType.INT, graphic.getHeight() << 16 | graphic.getDelay() & 0xFFFF); - } - - /** - * Puts a hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.ADD, block.getType()); - builder.put(DataType.BYTE, block.getCurrentHealth()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); - } - - /** - * Puts an interacting mob block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, DataOrder.LITTLE, block.getInteractingMobIndex()); - } - - /** - * Puts a movement update for the specified segment. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putMovementUpdate(SynchronizationSegment seg, PlayerSynchronizationEvent event, - GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - if (seg.getType() == SegmentType.TELEPORT) { - Position position = ((TeleportSegment) seg).getDestination(); - builder.putBits(1, 1); - builder.putBits(2, 3); - builder.putBits(2, position.getHeight()); - builder.putBits(1, event.hasRegionChanged() ? 0 : 1); - builder.putBits(1, updateRequired ? 1 : 0); - builder.putBits(7, position.getLocalY(event.getLastKnownRegion())); - builder.putBits(7, position.getLocalX(event.getLastKnownRegion())); - } else if (seg.getType() == SegmentType.RUN) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 2); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(3, directions[1].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else if (seg.getType() == SegmentType.WALK) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 1); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); + if ((helm = equipment.get(EquipmentConstants.HAT)) != null) { + EquipmentDefinition def = EquipmentDefinition.lookup(helm.getId()); + if (def != null && !def.isFullHat() && !def.isFullMask()) { + playerProperties.put(DataType.SHORT, 0x100 + style[0]); } else { - if (updateRequired) { - builder.putBits(1, 1); - builder.putBits(2, 0); - } else { - builder.putBits(1, 0); - } + playerProperties.put(DataType.BYTE, 0); } + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[0]); + } + + if ((item = equipment.get(EquipmentConstants.HANDS)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[4]); + } + + if ((item = equipment.get(EquipmentConstants.FEET)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[6]); + } + + EquipmentDefinition def = null; + if (helm != null) { + def = EquipmentDefinition.lookup(helm.getId()); + } + if (def != null && (def.isFullHat() || def.isFullMask()) || appearance.getGender() == Gender.FEMALE) { + playerProperties.put(DataType.BYTE, 0); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[1]); + } } - /** - * Puts a remove player update. - * - * @param builder The builder. - */ - private void putRemovePlayerUpdate(GamePacketBuilder builder) { + int[] colors = appearance.getColors(); + for (int color : colors) { + playerProperties.put(DataType.BYTE, color); + } + + playerProperties.put(DataType.SHORT, 0x328); // stand + playerProperties.put(DataType.SHORT, 0x337); // stand turn + playerProperties.put(DataType.SHORT, 0x333); // walk + playerProperties.put(DataType.SHORT, 0x334); // turn 180 + playerProperties.put(DataType.SHORT, 0x335); // turn 90 cw + playerProperties.put(DataType.SHORT, 0x336); // turn 90 ccw + playerProperties.put(DataType.SHORT, 0x338); // run + + playerProperties.put(DataType.LONG, block.getName()); + playerProperties.put(DataType.BYTE, block.getCombatLevel()); + playerProperties.put(DataType.SHORT, block.getSkillLevel()); + + builder.put(DataType.BYTE, DataTransformation.NEGATE, playerProperties.getLength()); + + builder.putRawBuilder(playerProperties); + } + + /** + * Puts the blocks for the specified segment. + * + * @param segment The segment. + * @param builder The block builder. + */ + private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { + SynchronizationBlockSet blockSet = segment.getBlockSet(); + if (blockSet.size() > 0) { + int mask = 0; + + if (blockSet.contains(ForceMovementBlock.class)) { + mask |= 0x400; + } + if (blockSet.contains(GraphicBlock.class)) { + mask |= 0x100; + } + if (blockSet.contains(AnimationBlock.class)) { + mask |= 0x8; + } + if (blockSet.contains(ForceChatBlock.class)) { + mask |= 0x4; + } + if (blockSet.contains(ChatBlock.class)) { + mask |= 0x80; + } + if (blockSet.contains(InteractingMobBlock.class)) { + mask |= 0x1; + } + if (blockSet.contains(AppearanceBlock.class)) { + mask |= 0x10; + } + if (blockSet.contains(TurnToPositionBlock.class)) { + mask |= 0x2; + } + if (blockSet.contains(HitUpdateBlock.class)) { + mask |= 0x20; + } + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + mask |= 0x200; + } + + if (mask >= 0x100) { + mask |= 0x40; + builder.put(DataType.SHORT, DataOrder.LITTLE, mask); + } else { + builder.put(DataType.BYTE, mask); + } + + if (blockSet.contains(ForceMovementBlock.class)) { + putForceMovementBlock(blockSet.get(ForceMovementBlock.class), builder); + } + if (blockSet.contains(GraphicBlock.class)) { + putGraphicBlock(blockSet.get(GraphicBlock.class), builder); + } + if (blockSet.contains(AnimationBlock.class)) { + putAnimationBlock(blockSet.get(AnimationBlock.class), builder); + } + if (blockSet.contains(ForceChatBlock.class)) { + putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); + } + if (blockSet.contains(ChatBlock.class)) { + putChatBlock(blockSet.get(ChatBlock.class), builder); + } + if (blockSet.contains(InteractingMobBlock.class)) { + putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); + } + if (blockSet.contains(AppearanceBlock.class)) { + putAppearanceBlock(blockSet.get(AppearanceBlock.class), builder); + } + if (blockSet.contains(TurnToPositionBlock.class)) { + putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); + } + if (blockSet.contains(HitUpdateBlock.class)) { + putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); + } + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); + } + } + } + + /** + * Puts a chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putChatBlock(ChatBlock block, GamePacketBuilder builder) { + byte[] bytes = block.getCompressedMessage(); + builder.put(DataType.SHORT, DataOrder.LITTLE, block.getTextColor() << 8 | block.getTextEffects()); + builder.put(DataType.BYTE, block.getPrivilegeLevel().toInteger()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, bytes.length); + builder.putBytesReverse(bytes); + } + + /** + * Puts a force chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { + builder.putString(block.getMessage()); + } + + /** + * Puts a force movement block in the specified builder. + * + * @param forceMovementBlock The block. + * @param builder The builder. + */ + private void putForceMovementBlock(ForceMovementBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getInitialX()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getInitialY()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalX()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalY()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, block.getTravelDurationX()); + builder.put(DataType.SHORT, DataTransformation.ADD, block.getTravelDurationY()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDirection().toInteger()); + } + + /** + * Puts a graphic block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { + Graphic graphic = block.getGraphic(); + builder.put(DataType.SHORT, DataOrder.LITTLE, graphic.getId()); + builder.put(DataType.INT, graphic.getHeight() << 16 | graphic.getDelay() & 0xFFFF); + } + + /** + * Puts a hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.ADD, block.getType()); + builder.put(DataType.BYTE, block.getCurrentHealth()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); + } + + /** + * Puts an interacting mob block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, DataOrder.LITTLE, block.getInteractingMobIndex()); + } + + /** + * Puts a movement update for the specified segment. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putMovementUpdate(SynchronizationSegment seg, PlayerSynchronizationEvent event, + GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + if (seg.getType() == SegmentType.TELEPORT) { + Position position = ((TeleportSegment) seg).getDestination(); + builder.putBits(1, 1); + builder.putBits(2, 3); + builder.putBits(2, position.getHeight()); + builder.putBits(1, event.hasRegionChanged() ? 0 : 1); + builder.putBits(1, updateRequired ? 1 : 0); + builder.putBits(7, position.getLocalY(event.getLastKnownRegion())); + builder.putBits(7, position.getLocalX(event.getLastKnownRegion())); + } else if (seg.getType() == SegmentType.RUN) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 2); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(3, directions[1].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else if (seg.getType() == SegmentType.WALK) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 1); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else { + if (updateRequired) { builder.putBits(1, 1); - builder.putBits(2, 3); + builder.putBits(2, 0); + } else { + builder.putBits(1, 0); + } } + } - /** - * Puts a Second Hit Update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); - builder.put(DataType.BYTE, block.getCurrentHealth()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); - } + /** + * Puts a remove player update. + * + * @param builder The builder. + */ + private void putRemovePlayerUpdate(GamePacketBuilder builder) { + builder.putBits(1, 1); + builder.putBits(2, 3); + } - /** - * Puts a Turn To Position block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { - Position pos = block.getPosition(); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, pos.getX() * 2 + 1); - builder.put(DataType.SHORT, DataOrder.LITTLE, pos.getY() * 2 + 1); - } + /** + * Puts a Second Hit Update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); + builder.put(DataType.BYTE, block.getCurrentHealth()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); + } + + /** + * Puts a Turn To Position block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { + Position pos = block.getPosition(); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, pos.getX() * 2 + 1); + builder.put(DataType.SHORT, DataOrder.LITTLE, pos.getY() * 2 + 1); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PositionEventEncoder.java b/src/org/apollo/net/release/r317/PositionEventEncoder.java index 81fe67a6..635b08dd 100644 --- a/src/org/apollo/net/release/r317/PositionEventEncoder.java +++ b/src/org/apollo/net/release/r317/PositionEventEncoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventEncoder; */ final class PositionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(PositionEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(85); - Position base = event.getBase(), pos = event.getPosition(); + @Override + public GamePacket encode(PositionEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(85); + Position base = event.getBase(), pos = event.getPosition(); - builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalY(base)); - builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalX(base)); + builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalY(base)); + builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalX(base)); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PrivacyOptionEventDecoder.java b/src/org/apollo/net/release/r317/PrivacyOptionEventDecoder.java index 911d02a8..791b3eb5 100644 --- a/src/org/apollo/net/release/r317/PrivacyOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/PrivacyOptionEventDecoder.java @@ -13,15 +13,15 @@ import org.apollo.net.release.EventDecoder; */ public final class PrivacyOptionEventDecoder extends EventDecoder { - @Override - public PrivacyOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PrivacyOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int publicChatState = (int) reader.getUnsigned(DataType.BYTE); - int privateChatState = (int) reader.getUnsigned(DataType.BYTE); - int tradeChatState = (int) reader.getUnsigned(DataType.BYTE); + int publicChatState = (int) reader.getUnsigned(DataType.BYTE); + int privateChatState = (int) reader.getUnsigned(DataType.BYTE); + int tradeChatState = (int) reader.getUnsigned(DataType.BYTE); - return new PrivacyOptionEvent(publicChatState, privateChatState, tradeChatState); - } + return new PrivacyOptionEvent(publicChatState, privateChatState, tradeChatState); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PrivacyOptionEventEncoder.java b/src/org/apollo/net/release/r317/PrivacyOptionEventEncoder.java index 08459cfb..9f2aaf1f 100644 --- a/src/org/apollo/net/release/r317/PrivacyOptionEventEncoder.java +++ b/src/org/apollo/net/release/r317/PrivacyOptionEventEncoder.java @@ -13,15 +13,15 @@ import org.apollo.net.release.EventEncoder; */ public final class PrivacyOptionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(final PrivacyOptionEvent event) { - final GamePacketBuilder builder = new GamePacketBuilder(206); + @Override + public GamePacket encode(final PrivacyOptionEvent event) { + final GamePacketBuilder builder = new GamePacketBuilder(206); - builder.put(DataType.BYTE, event.getChatPrivacy().toInteger(true)); - builder.put(DataType.BYTE, event.getFriendPrivacy().toInteger(true)); - builder.put(DataType.BYTE, event.getTradePrivacy().toInteger(true)); + builder.put(DataType.BYTE, event.getChatPrivacy().toInteger(true)); + builder.put(DataType.BYTE, event.getFriendPrivacy().toInteger(true)); + builder.put(DataType.BYTE, event.getTradePrivacy().toInteger(true)); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/PrivateMessageEventDecoder.java b/src/org/apollo/net/release/r317/PrivateMessageEventDecoder.java index 026d6a65..620efaf0 100644 --- a/src/org/apollo/net/release/r317/PrivateMessageEventDecoder.java +++ b/src/org/apollo/net/release/r317/PrivateMessageEventDecoder.java @@ -15,24 +15,24 @@ import org.apollo.util.TextUtil; */ public final class PrivateMessageEventDecoder extends EventDecoder { - @Override - public PrivateMessageEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PrivateMessageEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - int length = packet.getLength() - 8; + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + int length = packet.getLength() - 8; - byte[] originalCompressed = new byte[length]; - reader.getBytes(originalCompressed); + byte[] originalCompressed = new byte[length]; + reader.getBytes(originalCompressed); - String uncompressed = TextUtil.uncompress(originalCompressed, length); - uncompressed = TextUtil.filterInvalidCharacters(uncompressed); - uncompressed = TextUtil.capitalize(uncompressed); + String uncompressed = TextUtil.uncompress(originalCompressed, length); + uncompressed = TextUtil.filterInvalidCharacters(uncompressed); + uncompressed = TextUtil.capitalize(uncompressed); - byte[] recompressed = new byte[length]; - TextUtil.compress(uncompressed, recompressed); - - return new PrivateMessageEvent(username, new String(uncompressed), recompressed); - } + byte[] recompressed = new byte[length]; + TextUtil.compress(uncompressed, recompressed); + + return new PrivateMessageEvent(username, new String(uncompressed), recompressed); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/RegionChangeEventEncoder.java b/src/org/apollo/net/release/r317/RegionChangeEventEncoder.java index 677c7a7f..a69271f1 100644 --- a/src/org/apollo/net/release/r317/RegionChangeEventEncoder.java +++ b/src/org/apollo/net/release/r317/RegionChangeEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class RegionChangeEventEncoder extends EventEncoder { - @Override - public GamePacket encode(RegionChangeEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(73); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getPosition().getCentralSectorX()); - builder.put(DataType.SHORT, event.getPosition().getCentralSectorY()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(RegionChangeEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(73); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getPosition().getCentralSectorX()); + builder.put(DataType.SHORT, event.getPosition().getCentralSectorY()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/Release317.java b/src/org/apollo/net/release/r317/Release317.java index 506c1d40..d80d4af5 100644 --- a/src/org/apollo/net/release/r317/Release317.java +++ b/src/org/apollo/net/release/r317/Release317.java @@ -47,157 +47,157 @@ import org.apollo.net.release.Release; */ public final class Release317 extends Release { - /** - * The incoming packet lengths array. - */ - public static final int[] PACKET_LENGTHS = { 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 8, 0, 6, 2, 2, 0, // 10 - 0, 2, 0, 6, 0, 12, 0, 0, 0, 0, // 20 - 0, 0, 0, 0, 0, 8, 4, 0, 0, 2, // 30 - 2, 6, 0, 6, 0, -1, 0, 0, 0, 0, // 40 - 0, 0, 0, 12, 0, 0, 0, 0, 8, 0, // 50 - 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, // 60 - 6, 0, 2, 2, 8, 6, 0, -1, 0, 6, // 70 - 0, 0, 0, 0, 0, 1, 4, 6, 0, 0, // 80 - 0, 0, 0, 0, 0, 3, 0, 0, -1, 0, // 90 - 0, 13, 0, -1, 0, 0, 0, 0, 0, 0, // 100 - 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, // 110 - 1, 0, 6, 0, 0, 0, -1, 0, 2, 6, // 120 - 0, 4, 6, 8, 0, 6, 0, 0, 0, 2, // 130 - 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, // 140 - 0, 0, 1, 2, 0, 2, 6, 0, 0, 0, // 150 - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, // 160 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 - 0, 8, 0, 3, 0, 2, 0, 0, 8, 1, // 180 - 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, // 190 - 2, 0, 0, 0, 0, 0, 0, 0, 4, 0, // 200 - 4, 0, 0, 0, 7, 8, 0, 0, 10, 0, // 210 - 0, 0, 0, 0, 0, 0, -1, 0, 6, 0, // 220 - 1, 0, 0, 0, 6, 0, 6, 8, 1, 0, // 230 - 0, 4, 0, 0, 0, 0, -1, 0, -1, 4, // 240 - 0, 0, 6, 6, 0, 0, // 250 - }; + /** + * The incoming packet lengths array. + */ + public static final int[] PACKET_LENGTHS = { 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, // 0 + 0, 0, 0, 0, 8, 0, 6, 2, 2, 0, // 10 + 0, 2, 0, 6, 0, 12, 0, 0, 0, 0, // 20 + 0, 0, 0, 0, 0, 8, 4, 0, 0, 2, // 30 + 2, 6, 0, 6, 0, -1, 0, 0, 0, 0, // 40 + 0, 0, 0, 12, 0, 0, 0, 0, 8, 0, // 50 + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, // 60 + 6, 0, 2, 2, 8, 6, 0, -1, 0, 6, // 70 + 0, 0, 0, 0, 0, 1, 4, 6, 0, 0, // 80 + 0, 0, 0, 0, 0, 3, 0, 0, -1, 0, // 90 + 0, 13, 0, -1, 0, 0, 0, 0, 0, 0, // 100 + 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, // 110 + 1, 0, 6, 0, 0, 0, -1, 0, 2, 6, // 120 + 0, 4, 6, 8, 0, 6, 0, 0, 0, 2, // 130 + 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, // 140 + 0, 0, 1, 2, 0, 2, 6, 0, 0, 0, // 150 + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, // 160 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 + 0, 8, 0, 3, 0, 2, 0, 0, 8, 1, // 180 + 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, // 190 + 2, 0, 0, 0, 0, 0, 0, 0, 4, 0, // 200 + 4, 0, 0, 0, 7, 8, 0, 0, 10, 0, // 210 + 0, 0, 0, 0, 0, 0, -1, 0, 6, 0, // 220 + 1, 0, 0, 0, 6, 0, 6, 8, 1, 0, // 230 + 0, 4, 0, 0, 0, 0, -1, 0, -1, 4, // 240 + 0, 0, 6, 6, 0, 0, // 250 + }; - /** - * Creates and initialises this release. - */ - public Release317() { - super(317, PacketMetaDataGroup.createFromArray(PACKET_LENGTHS)); - init(); - } + /** + * Creates and initialises this release. + */ + public Release317() { + super(317, PacketMetaDataGroup.createFromArray(PACKET_LENGTHS)); + init(); + } - /** - * Initialises this release by registering encoders and decoders. - */ - private void init() { - // register decoders - WalkEventDecoder walkEventDecoder = new WalkEventDecoder(); - register(248, walkEventDecoder); - register(164, walkEventDecoder); - register(98, walkEventDecoder); + /** + * Initialises this release by registering encoders and decoders. + */ + private void init() { + // register decoders + WalkEventDecoder walkEventDecoder = new WalkEventDecoder(); + register(248, walkEventDecoder); + register(164, walkEventDecoder); + register(98, walkEventDecoder); - register(0, new KeepAliveEventDecoder()); - register(101, new PlayerDesignEventDecoder()); - register(4, new ChatEventDecoder()); - register(103, new CommandEventDecoder()); - register(214, new SwitchItemEventDecoder()); + register(0, new KeepAliveEventDecoder()); + register(101, new PlayerDesignEventDecoder()); + register(4, new ChatEventDecoder()); + register(103, new CommandEventDecoder()); + register(214, new SwitchItemEventDecoder()); - register(132, new FirstObjectActionEventDecoder()); - register(252, new SecondObjectActionEventDecoder()); - register(70, new ThirdObjectActionEventDecoder()); + register(132, new FirstObjectActionEventDecoder()); + register(252, new SecondObjectActionEventDecoder()); + register(70, new ThirdObjectActionEventDecoder()); - register(122, new FirstItemOptionEventDecoder()); - register(41, new SecondItemOptionEventDecoder()); - register(16, new ThirdItemOptionEventDecoder()); - register(75, new FourthItemOptionEventDecoder()); - register(87, new FifthItemOptionEventDecoder()); + register(122, new FirstItemOptionEventDecoder()); + register(41, new SecondItemOptionEventDecoder()); + register(16, new ThirdItemOptionEventDecoder()); + register(75, new FourthItemOptionEventDecoder()); + register(87, new FifthItemOptionEventDecoder()); - register(145, new FirstItemActionEventDecoder()); - register(117, new SecondItemActionEventDecoder()); - register(43, new ThirdItemActionEventDecoder()); - register(129, new FourthItemActionEventDecoder()); - register(135, new FifthItemActionEventDecoder()); + register(145, new FirstItemActionEventDecoder()); + register(117, new SecondItemActionEventDecoder()); + register(43, new ThirdItemActionEventDecoder()); + register(129, new FourthItemActionEventDecoder()); + register(135, new FifthItemActionEventDecoder()); - register(185, new ButtonEventDecoder()); - register(130, new ClosedInterfaceEventDecoder()); - register(208, new EnteredAmountEventDecoder()); - register(40, new DialogueContinueEventDecoder()); + register(185, new ButtonEventDecoder()); + register(130, new ClosedInterfaceEventDecoder()); + register(208, new EnteredAmountEventDecoder()); + register(40, new DialogueContinueEventDecoder()); - register(53, new ItemOnItemEventDecoder()); - register(237, new MagicOnItemEventDecoder()); + register(53, new ItemOnItemEventDecoder()); + register(237, new MagicOnItemEventDecoder()); - register(3, new FocusUpdateEventDecoder()); - register(241, new MouseClickEventDecoder()); - register(86, new ArrowKeyEventDecoder()); - register(95, new PrivacyOptionEventDecoder()); + register(3, new FocusUpdateEventDecoder()); + register(241, new MouseClickEventDecoder()); + register(86, new ArrowKeyEventDecoder()); + register(95, new PrivacyOptionEventDecoder()); - SpamPacketEventDecoder spamEventDecoder = new SpamPacketEventDecoder(); - register(77, spamEventDecoder); - register(78, spamEventDecoder); - register(165, spamEventDecoder); - register(189, spamEventDecoder); - register(210, spamEventDecoder); - register(226, spamEventDecoder); - register(121, spamEventDecoder); + SpamPacketEventDecoder spamEventDecoder = new SpamPacketEventDecoder(); + register(77, spamEventDecoder); + register(78, spamEventDecoder); + register(165, spamEventDecoder); + register(189, spamEventDecoder); + register(210, spamEventDecoder); + register(226, spamEventDecoder); + register(121, spamEventDecoder); - register(155, new FirstNpcActionEventDecoder()); - register(17, new SecondNpcActionEventDecoder()); - register(21, new ThirdNpcActionEventDecoder()); - register(236, new TakeTileItemEventDecoder()); - register(192, new ItemOnObjectEventDecoder()); + register(155, new FirstNpcActionEventDecoder()); + register(17, new SecondNpcActionEventDecoder()); + register(21, new ThirdNpcActionEventDecoder()); + register(236, new TakeTileItemEventDecoder()); + register(192, new ItemOnObjectEventDecoder()); - register(128, new FirstPlayerActionEventDecoder()); - register(153, new SecondPlayerActionEventDecoder()); - register(73, new ThirdPlayerActionEventDecoder()); - register(139, new FourthPlayerActionEventDecoder()); - register(39, new FifthPlayerActionEventDecoder()); + register(128, new FirstPlayerActionEventDecoder()); + register(153, new SecondPlayerActionEventDecoder()); + register(73, new ThirdPlayerActionEventDecoder()); + register(139, new FourthPlayerActionEventDecoder()); + register(39, new FifthPlayerActionEventDecoder()); - register(188, new AddFriendEventDecoder()); - register(133, new AddIgnoreEventDecoder()); - register(215, new RemoveFriendEventDecoder()); - register(74, new RemoveIgnoreEventDecoder()); - register(126, new PrivateMessageEventDecoder()); + register(188, new AddFriendEventDecoder()); + register(133, new AddIgnoreEventDecoder()); + register(215, new RemoveFriendEventDecoder()); + register(74, new RemoveIgnoreEventDecoder()); + register(126, new PrivateMessageEventDecoder()); - // register encoders - register(IdAssignmentEvent.class, new IdAssignmentEventEncoder()); - register(RegionChangeEvent.class, new RegionChangeEventEncoder()); - register(ServerMessageEvent.class, new ServerMessageEventEncoder()); - register(PlayerSynchronizationEvent.class, new PlayerSynchronizationEventEncoder()); - register(OpenInterfaceEvent.class, new OpenInterfaceEventEncoder()); - register(CloseInterfaceEvent.class, new CloseInterfaceEventEncoder()); - register(SwitchTabInterfaceEvent.class, new SwitchTabInterfaceEventEncoder()); - register(LogoutEvent.class, new LogoutEventEncoder()); - register(UpdateItemsEvent.class, new UpdateItemsEventEncoder()); - register(UpdateSlottedItemsEvent.class, new UpdateSlottedItemsEventEncoder()); - register(UpdateSkillEvent.class, new UpdateSkillEventEncoder()); - register(OpenInterfaceSidebarEvent.class, new OpenInterfaceSidebarEventEncoder()); - register(EnterAmountEvent.class, new EnterAmountEventEncoder()); - register(SetWidgetTextEvent.class, new SetWidgetTextEventEncoder()); - register(NpcSynchronizationEvent.class, new NpcSynchronizationEventEncoder()); - register(SetWidgetVisibilityEvent.class, new SetWidgetVisibilityEventEncoder()); - register(SetWidgetItemModelEvent.class, new SetWidgetItemModelEventEncoder()); - register(SetWidgetNpcModelEvent.class, new SetWidgetNpcModelEventEncoder()); - register(SetWidgetPlayerModelEvent.class, new SetWidgetPlayerModelEventEncoder()); - register(SetWidgetModelAnimationEvent.class, new SetWidgetModelAnimationEventEncoder()); - register(ConfigEvent.class, new ConfigEventEncoder()); - register(DisplayTabInterfaceEvent.class, new DisplayTabInterfaceEventEncoder()); - register(PositionEvent.class, new PositionEventEncoder()); - register(UpdateRunEnergyEvent.class, new UpdateRunEnergyEventEncoder()); - register(PrivacyOptionEvent.class, new PrivacyOptionEventEncoder()); - register(OpenDialogueInterfaceEvent.class, new OpenDialogueInterfaceEventEncoder()); - register(UpdateWeightEvent.class, new UpdateWeightEventEncoder()); - register(SetPlayerActionEvent.class, new SetPlayerActionEventEncoder()); - register(DisplayCrossbonesEvent.class, new DisplayCrossbonesEventEncoder()); + // register encoders + register(IdAssignmentEvent.class, new IdAssignmentEventEncoder()); + register(RegionChangeEvent.class, new RegionChangeEventEncoder()); + register(ServerMessageEvent.class, new ServerMessageEventEncoder()); + register(PlayerSynchronizationEvent.class, new PlayerSynchronizationEventEncoder()); + register(OpenInterfaceEvent.class, new OpenInterfaceEventEncoder()); + register(CloseInterfaceEvent.class, new CloseInterfaceEventEncoder()); + register(SwitchTabInterfaceEvent.class, new SwitchTabInterfaceEventEncoder()); + register(LogoutEvent.class, new LogoutEventEncoder()); + register(UpdateItemsEvent.class, new UpdateItemsEventEncoder()); + register(UpdateSlottedItemsEvent.class, new UpdateSlottedItemsEventEncoder()); + register(UpdateSkillEvent.class, new UpdateSkillEventEncoder()); + register(OpenInterfaceSidebarEvent.class, new OpenInterfaceSidebarEventEncoder()); + register(EnterAmountEvent.class, new EnterAmountEventEncoder()); + register(SetWidgetTextEvent.class, new SetWidgetTextEventEncoder()); + register(NpcSynchronizationEvent.class, new NpcSynchronizationEventEncoder()); + register(SetWidgetVisibilityEvent.class, new SetWidgetVisibilityEventEncoder()); + register(SetWidgetItemModelEvent.class, new SetWidgetItemModelEventEncoder()); + register(SetWidgetNpcModelEvent.class, new SetWidgetNpcModelEventEncoder()); + register(SetWidgetPlayerModelEvent.class, new SetWidgetPlayerModelEventEncoder()); + register(SetWidgetModelAnimationEvent.class, new SetWidgetModelAnimationEventEncoder()); + register(ConfigEvent.class, new ConfigEventEncoder()); + register(DisplayTabInterfaceEvent.class, new DisplayTabInterfaceEventEncoder()); + register(PositionEvent.class, new PositionEventEncoder()); + register(UpdateRunEnergyEvent.class, new UpdateRunEnergyEventEncoder()); + register(PrivacyOptionEvent.class, new PrivacyOptionEventEncoder()); + register(OpenDialogueInterfaceEvent.class, new OpenDialogueInterfaceEventEncoder()); + register(UpdateWeightEvent.class, new UpdateWeightEventEncoder()); + register(SetPlayerActionEvent.class, new SetPlayerActionEventEncoder()); + register(DisplayCrossbonesEvent.class, new DisplayCrossbonesEventEncoder()); - register(AddGlobalTileItemEvent.class, new AddGlobalTileItemEventEncoder()); - register(AddTileItemEvent.class, new AddTileItemEventEncoder()); - register(UpdateTileItemEvent.class, new UpdateTileItemEventEncoder()); - register(RemoveTileItemEvent.class, new RemoveTileItemEventEncoder()); + register(AddGlobalTileItemEvent.class, new AddGlobalTileItemEventEncoder()); + register(AddTileItemEvent.class, new AddTileItemEventEncoder()); + register(UpdateTileItemEvent.class, new UpdateTileItemEventEncoder()); + register(RemoveTileItemEvent.class, new RemoveTileItemEventEncoder()); - register(ForwardPrivateMessageEvent.class, new ForwardPrivateMessageEventEncoder()); - register(FriendServerStatusEvent.class, new FriendServerStatusEventEncoder()); - register(IgnoreListEvent.class, new IgnoreListEventEncoder()); - register(SendFriendEvent.class, new SendFriendEventEncoder()); - } + register(ForwardPrivateMessageEvent.class, new ForwardPrivateMessageEventEncoder()); + register(FriendServerStatusEvent.class, new FriendServerStatusEventEncoder()); + register(IgnoreListEvent.class, new IgnoreListEventEncoder()); + register(SendFriendEvent.class, new SendFriendEventEncoder()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/RemoveFriendEventDecoder.java b/src/org/apollo/net/release/r317/RemoveFriendEventDecoder.java index 94cde280..dbe8cb77 100644 --- a/src/org/apollo/net/release/r317/RemoveFriendEventDecoder.java +++ b/src/org/apollo/net/release/r317/RemoveFriendEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class RemoveFriendEventDecoder extends EventDecoder { - @Override - public RemoveFriendEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new RemoveFriendEvent(username); - } + @Override + public RemoveFriendEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new RemoveFriendEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/RemoveIgnoreEventDecoder.java b/src/org/apollo/net/release/r317/RemoveIgnoreEventDecoder.java index 6569f654..80a82a03 100644 --- a/src/org/apollo/net/release/r317/RemoveIgnoreEventDecoder.java +++ b/src/org/apollo/net/release/r317/RemoveIgnoreEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class RemoveIgnoreEventDecoder extends EventDecoder { - @Override - public RemoveIgnoreEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new RemoveIgnoreEvent(username); - } + @Override + public RemoveIgnoreEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new RemoveIgnoreEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/RemoveTileItemEventEncoder.java b/src/org/apollo/net/release/r317/RemoveTileItemEventEncoder.java index 1ef41f1d..0e8e70ff 100644 --- a/src/org/apollo/net/release/r317/RemoveTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r317/RemoveTileItemEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class RemoveTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(RemoveTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(156); - builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); - builder.put(DataType.SHORT, event.getId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(RemoveTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(156); + builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); + builder.put(DataType.SHORT, event.getId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SecondItemActionEventDecoder.java b/src/org/apollo/net/release/r317/SecondItemActionEventDecoder.java index f93d0294..ad555771 100644 --- a/src/org/apollo/net/release/r317/SecondItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/SecondItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondItemActionEventDecoder extends EventDecoder { - @Override - public SecondItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SecondItemActionEvent(interfaceId, id, slot); - } + @Override + public SecondItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SecondItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SecondItemOptionEventDecoder.java b/src/org/apollo/net/release/r317/SecondItemOptionEventDecoder.java index df1c93cc..50f4c309 100644 --- a/src/org/apollo/net/release/r317/SecondItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/SecondItemOptionEventDecoder.java @@ -14,13 +14,13 @@ import org.apollo.net.release.EventDecoder; */ final class SecondItemOptionEventDecoder extends EventDecoder { - @Override - public SecondItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new SecondItemOptionEvent(interfaceId, id, slot); - } + @Override + public SecondItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new SecondItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SecondNpcActionEventDecoder.java b/src/org/apollo/net/release/r317/SecondNpcActionEventDecoder.java index 442c08c2..ec300cab 100644 --- a/src/org/apollo/net/release/r317/SecondNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/SecondNpcActionEventDecoder.java @@ -11,11 +11,11 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondNpcActionEventDecoder extends EventDecoder { - @Override - public SecondNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new SecondNpcActionEvent(index); - } + @Override + public SecondNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + return new SecondNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SecondObjectActionEventDecoder.java b/src/org/apollo/net/release/r317/SecondObjectActionEventDecoder.java index af849044..90b519df 100644 --- a/src/org/apollo/net/release/r317/SecondObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/SecondObjectActionEventDecoder.java @@ -16,13 +16,13 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondObjectActionEventDecoder extends EventDecoder { - @Override - public SecondObjectActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int x = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new SecondObjectActionEvent(id, new Position(x, y)); - } + @Override + public SecondObjectActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int x = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new SecondObjectActionEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SecondPlayerActionEventDecoder.java b/src/org/apollo/net/release/r317/SecondPlayerActionEventDecoder.java index 00269a3f..54a13987 100644 --- a/src/org/apollo/net/release/r317/SecondPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/SecondPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondPlayerActionEventDecoder extends EventDecoder { - @Override - public SecondPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SecondPlayerActionEvent(index); - } + @Override + public SecondPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SecondPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SendFriendEventEncoder.java b/src/org/apollo/net/release/r317/SendFriendEventEncoder.java index 375567c9..65ca9fbd 100644 --- a/src/org/apollo/net/release/r317/SendFriendEventEncoder.java +++ b/src/org/apollo/net/release/r317/SendFriendEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.util.NameUtil; */ public final class SendFriendEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SendFriendEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(50); - builder.put(DataType.LONG, NameUtil.encodeBase37(event.getUsername())); - builder.put(DataType.BYTE, event.getWorld()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SendFriendEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(50); + builder.put(DataType.LONG, NameUtil.encodeBase37(event.getUsername())); + builder.put(DataType.BYTE, event.getWorld()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ServerMessageEventEncoder.java b/src/org/apollo/net/release/r317/ServerMessageEventEncoder.java index 6fff772f..324307dd 100644 --- a/src/org/apollo/net/release/r317/ServerMessageEventEncoder.java +++ b/src/org/apollo/net/release/r317/ServerMessageEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class ServerMessageEventEncoder extends EventEncoder { - @Override - public GamePacket encode(ServerMessageEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(253, PacketType.VARIABLE_BYTE); - builder.putString(event.getMessage()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(ServerMessageEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(253, PacketType.VARIABLE_BYTE); + builder.putString(event.getMessage()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SetPlayerActionEventEncoder.java b/src/org/apollo/net/release/r317/SetPlayerActionEventEncoder.java index 06c7eff5..1cbdc900 100644 --- a/src/org/apollo/net/release/r317/SetPlayerActionEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetPlayerActionEventEncoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventEncoder; */ public final class SetPlayerActionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetPlayerActionEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(104, PacketType.VARIABLE_BYTE); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getSlot()); - builder.put(DataType.BYTE, DataTransformation.ADD, event.isPrimaryAction() ? 0 : 1); - builder.putString(event.getText()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SetPlayerActionEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(104, PacketType.VARIABLE_BYTE); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getSlot()); + builder.put(DataType.BYTE, DataTransformation.ADD, event.isPrimaryAction() ? 0 : 1); + builder.putString(event.getText()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SetWidgetItemModelEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetItemModelEventEncoder.java index 338029b9..bd2f33c2 100644 --- a/src/org/apollo/net/release/r317/SetWidgetItemModelEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetItemModelEventEncoder.java @@ -14,15 +14,15 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetItemModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetItemModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(246); + @Override + public GamePacket encode(SetWidgetItemModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(246); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); - builder.put(DataType.SHORT, event.getZoom()); - builder.put(DataType.SHORT, event.getModelId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); + builder.put(DataType.SHORT, event.getZoom()); + builder.put(DataType.SHORT, event.getModelId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r317/SetWidgetModelAnimationEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetModelAnimationEventEncoder.java index 63432589..03b356a0 100644 --- a/src/org/apollo/net/release/r317/SetWidgetModelAnimationEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetModelAnimationEventEncoder.java @@ -13,14 +13,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetModelAnimationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetModelAnimationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(200); + @Override + public GamePacket encode(SetWidgetModelAnimationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(200); - builder.put(DataType.SHORT, event.getInterfaceId() & 0xFFFF); - builder.put(DataType.SHORT, event.getAnimation()); + builder.put(DataType.SHORT, event.getInterfaceId() & 0xFFFF); + builder.put(DataType.SHORT, event.getAnimation()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SetWidgetNpcModelEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetNpcModelEventEncoder.java index 01d47a7d..87a107c0 100644 --- a/src/org/apollo/net/release/r317/SetWidgetNpcModelEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetNpcModelEventEncoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetNpcModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetNpcModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(75); + @Override + public GamePacket encode(SetWidgetNpcModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(75); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getModelId()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getModelId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r317/SetWidgetPlayerModelEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetPlayerModelEventEncoder.java index d66a781b..4b467b21 100644 --- a/src/org/apollo/net/release/r317/SetWidgetPlayerModelEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetPlayerModelEventEncoder.java @@ -15,11 +15,11 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetPlayerModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetPlayerModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(185); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SetWidgetPlayerModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(185); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SetWidgetTextEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetTextEventEncoder.java index 63a65e77..aa506eb3 100644 --- a/src/org/apollo/net/release/r317/SetWidgetTextEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetTextEventEncoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventEncoder; */ public final class SetWidgetTextEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetTextEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(126, PacketType.VARIABLE_SHORT); - builder.putString(event.getText()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); + @Override + public GamePacket encode(SetWidgetTextEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(126, PacketType.VARIABLE_SHORT); + builder.putString(event.getText()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SetWidgetVisibilityEventEncoder.java b/src/org/apollo/net/release/r317/SetWidgetVisibilityEventEncoder.java index f8644c96..6511631a 100644 --- a/src/org/apollo/net/release/r317/SetWidgetVisibilityEventEncoder.java +++ b/src/org/apollo/net/release/r317/SetWidgetVisibilityEventEncoder.java @@ -13,14 +13,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetVisibilityEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetVisibilityEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(171); + @Override + public GamePacket encode(SetWidgetVisibilityEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(171); - builder.put(DataType.BYTE, event.isVisible() ? 0 : 1); - builder.put(DataType.SHORT, event.getWidgetId()); + builder.put(DataType.BYTE, event.isVisible() ? 0 : 1); + builder.put(DataType.SHORT, event.getWidgetId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SpamPacketEventDecoder.java b/src/org/apollo/net/release/r317/SpamPacketEventDecoder.java index 29e2a1dd..51b9746d 100644 --- a/src/org/apollo/net/release/r317/SpamPacketEventDecoder.java +++ b/src/org/apollo/net/release/r317/SpamPacketEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class SpamPacketEventDecoder extends EventDecoder { - @Override - public SpamPacketEvent decode(GamePacket packet) { - return new SpamPacketEvent(packet.getPayload().array()); - } + @Override + public SpamPacketEvent decode(GamePacket packet) { + return new SpamPacketEvent(packet.getPayload().array()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SwitchItemEventDecoder.java b/src/org/apollo/net/release/r317/SwitchItemEventDecoder.java index a0e17da0..50e72d2f 100644 --- a/src/org/apollo/net/release/r317/SwitchItemEventDecoder.java +++ b/src/org/apollo/net/release/r317/SwitchItemEventDecoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventDecoder; */ public final class SwitchItemEventDecoder extends EventDecoder { - @Override - public SwitchItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - boolean inserting = reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE) == 1; - int oldSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int newSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SwitchItemEvent(interfaceId, inserting, oldSlot, newSlot); - } + @Override + public SwitchItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + boolean inserting = reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE) == 1; + int oldSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int newSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SwitchItemEvent(interfaceId, inserting, oldSlot, newSlot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/SwitchTabInterfaceEventEncoder.java b/src/org/apollo/net/release/r317/SwitchTabInterfaceEventEncoder.java index 5651fb80..4f5cf932 100644 --- a/src/org/apollo/net/release/r317/SwitchTabInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r317/SwitchTabInterfaceEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class SwitchTabInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SwitchTabInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(71); - builder.put(DataType.SHORT, event.getInterfaceId()); - builder.put(DataType.BYTE, DataTransformation.ADD, event.getTabId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SwitchTabInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(71); + builder.put(DataType.SHORT, event.getInterfaceId()); + builder.put(DataType.BYTE, DataTransformation.ADD, event.getTabId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/TakeTileItemEventDecoder.java b/src/org/apollo/net/release/r317/TakeTileItemEventDecoder.java index 24f0dde8..fc0bd4dc 100644 --- a/src/org/apollo/net/release/r317/TakeTileItemEventDecoder.java +++ b/src/org/apollo/net/release/r317/TakeTileItemEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class TakeTileItemEventDecoder extends EventDecoder { - @Override - public TakeTileItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new TakeTileItemEvent(id, new Position(x, y)); - } + @Override + public TakeTileItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new TakeTileItemEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ThirdItemActionEventDecoder.java b/src/org/apollo/net/release/r317/ThirdItemActionEventDecoder.java index e2082abf..c1656014 100644 --- a/src/org/apollo/net/release/r317/ThirdItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/ThirdItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdItemActionEventDecoder extends EventDecoder { - @Override - public ThirdItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new ThirdItemActionEvent(interfaceId, id, slot); - } + @Override + public ThirdItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new ThirdItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ThirdItemOptionEventDecoder.java b/src/org/apollo/net/release/r317/ThirdItemOptionEventDecoder.java index cadf96ea..08e0bcaa 100644 --- a/src/org/apollo/net/release/r317/ThirdItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r317/ThirdItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class ThirdItemOptionEventDecoder extends EventDecoder { - @Override - public ThirdItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ThirdItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int slot = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int interfaceId = (int) reader.getSigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new ThirdItemOptionEvent(interfaceId, id, slot); - } + return new ThirdItemOptionEvent(interfaceId, id, slot); + } } diff --git a/src/org/apollo/net/release/r317/ThirdNpcActionEventDecoder.java b/src/org/apollo/net/release/r317/ThirdNpcActionEventDecoder.java index 510be22e..a44820ed 100644 --- a/src/org/apollo/net/release/r317/ThirdNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/ThirdNpcActionEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdNpcActionEventDecoder extends EventDecoder { - @Override - public ThirdNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getSigned(DataType.SHORT); - return new ThirdNpcActionEvent(index); - } + @Override + public ThirdNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getSigned(DataType.SHORT); + return new ThirdNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ThirdObjectActionEventDecoder.java b/src/org/apollo/net/release/r317/ThirdObjectActionEventDecoder.java index f7c06d65..18fe4014 100644 --- a/src/org/apollo/net/release/r317/ThirdObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/ThirdObjectActionEventDecoder.java @@ -16,14 +16,14 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdObjectActionEventDecoder extends EventDecoder { - @Override - public ThirdObjectActionEvent decode(GamePacket packet) { - // TODO ripped out of some Winterlove-based server, so probably wrong - GamePacketReader reader = new GamePacketReader(packet); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int y = (int) reader.getUnsigned(DataType.SHORT); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new ThirdObjectActionEvent(id, new Position(x, y)); - } + @Override + public ThirdObjectActionEvent decode(GamePacket packet) { + // TODO ripped out of some Winterlove-based server, so probably wrong + GamePacketReader reader = new GamePacketReader(packet); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int y = (int) reader.getUnsigned(DataType.SHORT); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + return new ThirdObjectActionEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/ThirdPlayerActionEventDecoder.java b/src/org/apollo/net/release/r317/ThirdPlayerActionEventDecoder.java index 6797c45e..b81ef067 100644 --- a/src/org/apollo/net/release/r317/ThirdPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r317/ThirdPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdPlayerActionEventDecoder extends EventDecoder { - @Override - public ThirdPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new ThirdPlayerActionEvent(index); - } + @Override + public ThirdPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new ThirdPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateItemsEventEncoder.java b/src/org/apollo/net/release/r317/UpdateItemsEventEncoder.java index 22762a6f..65455421 100644 --- a/src/org/apollo/net/release/r317/UpdateItemsEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateItemsEventEncoder.java @@ -17,30 +17,30 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateItemsEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateItemsEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(53, PacketType.VARIABLE_SHORT); + @Override + public GamePacket encode(UpdateItemsEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(53, PacketType.VARIABLE_SHORT); - Item[] items = event.getItems(); + Item[] items = event.getItems(); - builder.put(DataType.SHORT, event.getInterfaceId()); - builder.put(DataType.SHORT, items.length); + builder.put(DataType.SHORT, event.getInterfaceId()); + builder.put(DataType.SHORT, items.length); - for (Item item : items) { - int id = item == null ? -1 : item.getId(); - int amount = item == null ? 0 : item.getAmount(); + for (Item item : items) { + int id = item == null ? -1 : item.getId(); + int amount = item == null ? 0 : item.getAmount(); - if (amount > 254) { - builder.put(DataType.BYTE, 255); - builder.put(DataType.INT, DataOrder.INVERSED_MIDDLE, amount); - } else { - builder.put(DataType.BYTE, amount); - } + if (amount > 254) { + builder.put(DataType.BYTE, 255); + builder.put(DataType.INT, DataOrder.INVERSED_MIDDLE, amount); + } else { + builder.put(DataType.BYTE, amount); + } - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, id + 1); - } - - return builder.toGamePacket(); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, id + 1); } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateRunEnergyEventEncoder.java b/src/org/apollo/net/release/r317/UpdateRunEnergyEventEncoder.java index 2657a99e..6790a04a 100644 --- a/src/org/apollo/net/release/r317/UpdateRunEnergyEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateRunEnergyEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateRunEnergyEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateRunEnergyEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(110); - builder.put(DataType.BYTE, event.getEnergy()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateRunEnergyEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(110); + builder.put(DataType.BYTE, event.getEnergy()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateSkillEventEncoder.java b/src/org/apollo/net/release/r317/UpdateSkillEventEncoder.java index a2545ec2..6acdd3ff 100644 --- a/src/org/apollo/net/release/r317/UpdateSkillEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateSkillEventEncoder.java @@ -15,16 +15,16 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateSkillEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateSkillEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(134); - Skill skill = event.getSkill(); + @Override + public GamePacket encode(UpdateSkillEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(134); + Skill skill = event.getSkill(); - builder.put(DataType.BYTE, event.getId()); - builder.put(DataType.INT, DataOrder.MIDDLE, (int) skill.getExperience()); - builder.put(DataType.BYTE, skill.getCurrentLevel()); + builder.put(DataType.BYTE, event.getId()); + builder.put(DataType.INT, DataOrder.MIDDLE, (int) skill.getExperience()); + builder.put(DataType.BYTE, skill.getCurrentLevel()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateSlottedItemsEventEncoder.java b/src/org/apollo/net/release/r317/UpdateSlottedItemsEventEncoder.java index 9422aa72..c8aa606f 100644 --- a/src/org/apollo/net/release/r317/UpdateSlottedItemsEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateSlottedItemsEventEncoder.java @@ -16,31 +16,31 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateSlottedItemsEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateSlottedItemsEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(34, PacketType.VARIABLE_SHORT); - SlottedItem[] items = event.getSlottedItems(); + @Override + public GamePacket encode(UpdateSlottedItemsEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(34, PacketType.VARIABLE_SHORT); + SlottedItem[] items = event.getSlottedItems(); - builder.put(DataType.SHORT, event.getInterfaceId()); + builder.put(DataType.SHORT, event.getInterfaceId()); - for (SlottedItem slottedItem : items) { - builder.putSmart(slottedItem.getSlot()); + for (SlottedItem slottedItem : items) { + builder.putSmart(slottedItem.getSlot()); - Item item = slottedItem.getItem(); - int id = item == null ? -1 : item.getId(); - int amount = item == null ? 0 : item.getAmount(); + Item item = slottedItem.getItem(); + int id = item == null ? -1 : item.getId(); + int amount = item == null ? 0 : item.getAmount(); - builder.put(DataType.SHORT, id + 1); + builder.put(DataType.SHORT, id + 1); - if (amount > 254) { - builder.put(DataType.BYTE, 255); - builder.put(DataType.INT, amount); - } else { - builder.put(DataType.BYTE, amount); - } - } - - return builder.toGamePacket(); + if (amount > 254) { + builder.put(DataType.BYTE, 255); + builder.put(DataType.INT, amount); + } else { + builder.put(DataType.BYTE, amount); + } } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateTileItemEventEncoder.java b/src/org/apollo/net/release/r317/UpdateTileItemEventEncoder.java index 257ba7d9..e25299cb 100644 --- a/src/org/apollo/net/release/r317/UpdateTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateTileItemEventEncoder.java @@ -13,14 +13,14 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(84); - builder.put(DataType.BYTE, event.getPositionOffset()); - builder.put(DataType.SHORT, event.getId()); - builder.put(DataType.SHORT, event.getPreviousAmount()); - builder.put(DataType.SHORT, event.getAmount()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(84); + builder.put(DataType.BYTE, event.getPositionOffset()); + builder.put(DataType.SHORT, event.getId()); + builder.put(DataType.SHORT, event.getPreviousAmount()); + builder.put(DataType.SHORT, event.getAmount()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/UpdateWeightEventEncoder.java b/src/org/apollo/net/release/r317/UpdateWeightEventEncoder.java index ccdb8d2d..fae40dcb 100644 --- a/src/org/apollo/net/release/r317/UpdateWeightEventEncoder.java +++ b/src/org/apollo/net/release/r317/UpdateWeightEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateWeightEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateWeightEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(240); - builder.put(DataType.SHORT, event.getWeight()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateWeightEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(240); + builder.put(DataType.SHORT, event.getWeight()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r317/WalkEventDecoder.java b/src/org/apollo/net/release/r317/WalkEventDecoder.java index 2e0c8473..70939e0b 100644 --- a/src/org/apollo/net/release/r317/WalkEventDecoder.java +++ b/src/org/apollo/net/release/r317/WalkEventDecoder.java @@ -16,33 +16,33 @@ import org.apollo.net.release.EventDecoder; */ public final class WalkEventDecoder extends EventDecoder { - @Override - public WalkEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public WalkEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int length = packet.getLength(); - if (packet.getOpcode() == 248) { - length -= 14; // strip off anti-cheat data - } - - int steps = (length - 5) / 2; - int[][] path = new int[steps][2]; - - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - for (int i = 0; i < steps; i++) { - path[i][0] = (int) reader.getSigned(DataType.BYTE); - path[i][1] = (int) reader.getSigned(DataType.BYTE); - } - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - boolean run = reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE) == 1; - - Position[] positions = new Position[steps + 1]; - positions[0] = new Position(x, y); - for (int i = 0; i < steps; i++) { - positions[i + 1] = new Position(path[i][0] + x, path[i][1] + y); - } - - return new WalkEvent(positions, run); + int length = packet.getLength(); + if (packet.getOpcode() == 248) { + length -= 14; // strip off anti-cheat data } + int steps = (length - 5) / 2; + int[][] path = new int[steps][2]; + + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + for (int i = 0; i < steps; i++) { + path[i][0] = (int) reader.getSigned(DataType.BYTE); + path[i][1] = (int) reader.getSigned(DataType.BYTE); + } + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + boolean run = reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE) == 1; + + Position[] positions = new Position[steps + 1]; + positions[0] = new Position(x, y); + for (int i = 0; i < steps; i++) { + positions[i + 1] = new Position(path[i][0] + x, path[i][1] + y); + } + + return new WalkEvent(positions, run); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/AddFriendEventDecoder.java b/src/org/apollo/net/release/r377/AddFriendEventDecoder.java index 76867f11..c715f95c 100644 --- a/src/org/apollo/net/release/r377/AddFriendEventDecoder.java +++ b/src/org/apollo/net/release/r377/AddFriendEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class AddFriendEventDecoder extends EventDecoder { - @Override - public AddFriendEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new AddFriendEvent(username); - } + @Override + public AddFriendEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new AddFriendEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/AddGlobalTileItemEventEncoder.java b/src/org/apollo/net/release/r377/AddGlobalTileItemEventEncoder.java index 4737b912..fc977e92 100644 --- a/src/org/apollo/net/release/r377/AddGlobalTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r377/AddGlobalTileItemEventEncoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventEncoder; */ public final class AddGlobalTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(AddGlobalTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(106); - builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getAmount()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getIndex()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(AddGlobalTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(106); + builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getAmount()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getIndex()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/AddIgnoreEventDecoder.java b/src/org/apollo/net/release/r377/AddIgnoreEventDecoder.java index b3f56782..c95a2884 100644 --- a/src/org/apollo/net/release/r377/AddIgnoreEventDecoder.java +++ b/src/org/apollo/net/release/r377/AddIgnoreEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class AddIgnoreEventDecoder extends EventDecoder { - @Override - public AddIgnoreEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new AddIgnoreEvent(username); - } + @Override + public AddIgnoreEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new AddIgnoreEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/AddTileItemEventEncoder.java b/src/org/apollo/net/release/r377/AddTileItemEventEncoder.java index eb965d18..a1e4f43b 100644 --- a/src/org/apollo/net/release/r377/AddTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r377/AddTileItemEventEncoder.java @@ -14,13 +14,13 @@ import org.apollo.net.release.EventEncoder; */ public final class AddTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(AddTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(107); - builder.put(DataType.SHORT, event.getId()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getPositionOffset()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getAmount()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(AddTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(107); + builder.put(DataType.SHORT, event.getId()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getPositionOffset()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getAmount()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ArrowKeyEventDecoder.java b/src/org/apollo/net/release/r377/ArrowKeyEventDecoder.java index 7b987f5b..f7c4ddb7 100644 --- a/src/org/apollo/net/release/r377/ArrowKeyEventDecoder.java +++ b/src/org/apollo/net/release/r377/ArrowKeyEventDecoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventDecoder; */ public final class ArrowKeyEventDecoder extends EventDecoder { - @Override - public ArrowKeyEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int roll = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int yaw = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new ArrowKeyEvent(roll, yaw); - } + @Override + public ArrowKeyEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int roll = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int yaw = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new ArrowKeyEvent(roll, yaw); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ButtonEventDecoder.java b/src/org/apollo/net/release/r377/ButtonEventDecoder.java index bc126118..40a106b4 100644 --- a/src/org/apollo/net/release/r377/ButtonEventDecoder.java +++ b/src/org/apollo/net/release/r377/ButtonEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ButtonEventDecoder extends EventDecoder { - @Override - public ButtonEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new ButtonEvent(interfaceId); - } + @Override + public ButtonEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + return new ButtonEvent(interfaceId); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ChatEventDecoder.java b/src/org/apollo/net/release/r377/ChatEventDecoder.java index 8b63d088..7f52b1d1 100644 --- a/src/org/apollo/net/release/r377/ChatEventDecoder.java +++ b/src/org/apollo/net/release/r377/ChatEventDecoder.java @@ -15,26 +15,26 @@ import org.apollo.util.TextUtil; */ public final class ChatEventDecoder extends EventDecoder { - @Override - public ChatEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ChatEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int color = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE); - int effects = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.ADD); + int color = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.NEGATE); + int effects = (int) reader.getUnsigned(DataType.BYTE, DataTransformation.ADD); - int length = packet.getLength() - 2; + int length = packet.getLength() - 2; - byte[] originalCompressed = new byte[length]; - reader.getBytes(originalCompressed); + byte[] originalCompressed = new byte[length]; + reader.getBytes(originalCompressed); - String uncompressed = TextUtil.uncompress(originalCompressed, length); - uncompressed = TextUtil.filterInvalidCharacters(uncompressed); - uncompressed = TextUtil.capitalize(uncompressed); + String uncompressed = TextUtil.uncompress(originalCompressed, length); + uncompressed = TextUtil.filterInvalidCharacters(uncompressed); + uncompressed = TextUtil.capitalize(uncompressed); - byte[] recompressed = new byte[length]; - TextUtil.compress(uncompressed, recompressed); // in case invalid data gets sent, this effectively verifies it + byte[] recompressed = new byte[length]; + TextUtil.compress(uncompressed, recompressed); // in case invalid data gets sent, this effectively verifies it - return new ChatEvent(uncompressed, recompressed, color, effects); - } + return new ChatEvent(uncompressed, recompressed, color, effects); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/CloseInterfaceEventEncoder.java b/src/org/apollo/net/release/r377/CloseInterfaceEventEncoder.java index 0a74ae24..f6108e55 100644 --- a/src/org/apollo/net/release/r377/CloseInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r377/CloseInterfaceEventEncoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventEncoder; */ public final class CloseInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(CloseInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(29); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(CloseInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(29); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ClosedInterfaceEventDecoder.java b/src/org/apollo/net/release/r377/ClosedInterfaceEventDecoder.java index 8de0c730..d29746ec 100644 --- a/src/org/apollo/net/release/r377/ClosedInterfaceEventDecoder.java +++ b/src/org/apollo/net/release/r377/ClosedInterfaceEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class ClosedInterfaceEventDecoder extends EventDecoder { - @Override - public ClosedInterfaceEvent decode(GamePacket packet) { - return new ClosedInterfaceEvent(); - } + @Override + public ClosedInterfaceEvent decode(GamePacket packet) { + return new ClosedInterfaceEvent(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/CommandEventDecoder.java b/src/org/apollo/net/release/r377/CommandEventDecoder.java index 57f06fa5..80a1e63c 100644 --- a/src/org/apollo/net/release/r377/CommandEventDecoder.java +++ b/src/org/apollo/net/release/r377/CommandEventDecoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventDecoder; */ public final class CommandEventDecoder extends EventDecoder { - @Override - public CommandEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - return new CommandEvent(reader.getString()); - } + @Override + public CommandEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + return new CommandEvent(reader.getString()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ConfigEventEncoder.java b/src/org/apollo/net/release/r377/ConfigEventEncoder.java index 46513736..e54f884f 100644 --- a/src/org/apollo/net/release/r377/ConfigEventEncoder.java +++ b/src/org/apollo/net/release/r377/ConfigEventEncoder.java @@ -16,24 +16,24 @@ import org.apollo.net.release.EventEncoder; */ final class ConfigEventEncoder extends EventEncoder { - @Override - public GamePacket encode(ConfigEvent event) { - GamePacketBuilder builder; - int value = event.getValue(); + @Override + public GamePacket encode(ConfigEvent event) { + GamePacketBuilder builder; + int value = event.getValue(); - if (value > Byte.MIN_VALUE && value < Byte.MAX_VALUE) { - builder = new GamePacketBuilder(182); + if (value > Byte.MIN_VALUE && value < Byte.MAX_VALUE) { + builder = new GamePacketBuilder(182); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, value & 0xFF); - } else { - builder = new GamePacketBuilder(115); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, value & 0xFF); + } else { + builder = new GamePacketBuilder(115); - builder.put(DataType.INT, DataOrder.INVERSED_MIDDLE, value); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); - } - - return builder.toGamePacket(); + builder.put(DataType.INT, DataOrder.INVERSED_MIDDLE, value); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/DialogueContinueEventDecoder.java b/src/org/apollo/net/release/r377/DialogueContinueEventDecoder.java index ea241b5e..123851b5 100644 --- a/src/org/apollo/net/release/r377/DialogueContinueEventDecoder.java +++ b/src/org/apollo/net/release/r377/DialogueContinueEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ final class DialogueContinueEventDecoder extends EventDecoder { - @Override - public DialogueContinueEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new DialogueContinueEvent(interfaceId); - } + @Override + public DialogueContinueEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + return new DialogueContinueEvent(interfaceId); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/DisplayCrossbonesEventEncoder.java b/src/org/apollo/net/release/r377/DisplayCrossbonesEventEncoder.java index 31b29b96..30f85a72 100644 --- a/src/org/apollo/net/release/r377/DisplayCrossbonesEventEncoder.java +++ b/src/org/apollo/net/release/r377/DisplayCrossbonesEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class DisplayCrossbonesEventEncoder extends EventEncoder { - @Override - public GamePacket encode(DisplayCrossbonesEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(233); - builder.put(DataType.BYTE, event.isDisplayed() ? 1 : 0); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(DisplayCrossbonesEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(233); + builder.put(DataType.BYTE, event.isDisplayed() ? 1 : 0); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/DisplayTabInterfaceEventEncoder.java b/src/org/apollo/net/release/r377/DisplayTabInterfaceEventEncoder.java index 8f90018c..ad321d66 100644 --- a/src/org/apollo/net/release/r377/DisplayTabInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r377/DisplayTabInterfaceEventEncoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventEncoder; */ final class DisplayTabInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(DisplayTabInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(252); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getTab()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(DisplayTabInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(252); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getTab()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/EnterAmountEventEncoder.java b/src/org/apollo/net/release/r377/EnterAmountEventEncoder.java index 904fd994..7e01faa6 100644 --- a/src/org/apollo/net/release/r377/EnterAmountEventEncoder.java +++ b/src/org/apollo/net/release/r377/EnterAmountEventEncoder.java @@ -14,9 +14,9 @@ import org.apollo.net.release.EventEncoder; */ public final class EnterAmountEventEncoder extends EventEncoder { - @Override - public GamePacket encode(EnterAmountEvent event) { - return new GamePacket(58, PacketType.FIXED, Unpooled.EMPTY_BUFFER); - } + @Override + public GamePacket encode(EnterAmountEvent event) { + return new GamePacket(58, PacketType.FIXED, Unpooled.EMPTY_BUFFER); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/EnteredAmountEventDecoder.java b/src/org/apollo/net/release/r377/EnteredAmountEventDecoder.java index 6ee7ed4f..3ef0f783 100644 --- a/src/org/apollo/net/release/r377/EnteredAmountEventDecoder.java +++ b/src/org/apollo/net/release/r377/EnteredAmountEventDecoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventDecoder; */ public final class EnteredAmountEventDecoder extends EventDecoder { - @Override - public EnteredAmountEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int amount = (int) reader.getUnsigned(DataType.INT); - return new EnteredAmountEvent(amount); - } + @Override + public EnteredAmountEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int amount = (int) reader.getUnsigned(DataType.INT); + return new EnteredAmountEvent(amount); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FifthItemActionEventDecoder.java b/src/org/apollo/net/release/r377/FifthItemActionEventDecoder.java index 18b78ac6..de9f6610 100644 --- a/src/org/apollo/net/release/r377/FifthItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FifthItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FifthItemActionEventDecoder extends EventDecoder { - @Override - public FifthItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FifthItemActionEvent(interfaceId, id, slot); - } + @Override + public FifthItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FifthItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FifthItemOptionEventDecoder.java b/src/org/apollo/net/release/r377/FifthItemOptionEventDecoder.java index ff3a01db..fd04fe8c 100644 --- a/src/org/apollo/net/release/r377/FifthItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FifthItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class FifthItemOptionEventDecoder extends EventDecoder { - @Override - public FifthItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FifthItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new FifthItemOptionEvent(interfaceId, id, slot); - } + return new FifthItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FifthPlayerActionEventDecoder.java b/src/org/apollo/net/release/r377/FifthPlayerActionEventDecoder.java index 24a54060..2a5314d4 100644 --- a/src/org/apollo/net/release/r377/FifthPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FifthPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FifthPlayerActionEventDecoder extends EventDecoder { - @Override - public FifthPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FifthPlayerActionEvent(index); - } + @Override + public FifthPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new FifthPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FirstItemActionEventDecoder.java b/src/org/apollo/net/release/r377/FirstItemActionEventDecoder.java index 7ac4cf4d..c5bb8748 100644 --- a/src/org/apollo/net/release/r377/FirstItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FirstItemActionEventDecoder.java @@ -14,13 +14,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstItemActionEventDecoder extends EventDecoder { - @Override - public FirstItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - int slot = (int) reader.getUnsigned(DataType.SHORT); - return new FirstItemActionEvent(interfaceId, id, slot); - } + @Override + public FirstItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int slot = (int) reader.getUnsigned(DataType.SHORT); + return new FirstItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FirstItemOptionEventDecoder.java b/src/org/apollo/net/release/r377/FirstItemOptionEventDecoder.java index 9c7c6548..0324c988 100644 --- a/src/org/apollo/net/release/r377/FirstItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FirstItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class FirstItemOptionEventDecoder extends EventDecoder { - @Override - public FirstItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FirstItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FirstItemOptionEvent(interfaceId, id, slot); - } + return new FirstItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FirstNpcActionEventDecoder.java b/src/org/apollo/net/release/r377/FirstNpcActionEventDecoder.java index 81b9e8d6..89d2fd51 100644 --- a/src/org/apollo/net/release/r377/FirstNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FirstNpcActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstNpcActionEventDecoder extends EventDecoder { - @Override - public FirstNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new FirstNpcActionEvent(index); - } + @Override + public FirstNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new FirstNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FirstObjectActionEventDecoder.java b/src/org/apollo/net/release/r377/FirstObjectActionEventDecoder.java index c56599c9..5201e160 100644 --- a/src/org/apollo/net/release/r377/FirstObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FirstObjectActionEventDecoder.java @@ -16,13 +16,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstObjectActionEventDecoder extends EventDecoder { - @Override - public FirstObjectActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int x = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FirstObjectActionEvent(id, new Position(x, y)); - } + @Override + public FirstObjectActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int x = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FirstObjectActionEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FirstPlayerActionEventDecoder.java b/src/org/apollo/net/release/r377/FirstPlayerActionEventDecoder.java index 5531b7e0..7121a240 100644 --- a/src/org/apollo/net/release/r377/FirstPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FirstPlayerActionEventDecoder.java @@ -15,11 +15,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FirstPlayerActionEventDecoder extends EventDecoder { - @Override - public FirstPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new FirstPlayerActionEvent(index); - } + @Override + public FirstPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + return new FirstPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FocusUpdateEventDecoder.java b/src/org/apollo/net/release/r377/FocusUpdateEventDecoder.java index fe77bd3a..0aee1ac9 100644 --- a/src/org/apollo/net/release/r377/FocusUpdateEventDecoder.java +++ b/src/org/apollo/net/release/r377/FocusUpdateEventDecoder.java @@ -13,10 +13,10 @@ import org.apollo.net.release.EventDecoder; */ public final class FocusUpdateEventDecoder extends EventDecoder { - @Override - public FocusUpdateEvent decode(GamePacket packet) { - GamePacketReader decoder = new GamePacketReader(packet); - return new FocusUpdateEvent(decoder.getUnsigned(DataType.BYTE) == 1); - } + @Override + public FocusUpdateEvent decode(GamePacket packet) { + GamePacketReader decoder = new GamePacketReader(packet); + return new FocusUpdateEvent(decoder.getUnsigned(DataType.BYTE) == 1); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ForwardPrivateMessageEventEncoder.java b/src/org/apollo/net/release/r377/ForwardPrivateMessageEventEncoder.java index 3add324d..23e53afa 100644 --- a/src/org/apollo/net/release/r377/ForwardPrivateMessageEventEncoder.java +++ b/src/org/apollo/net/release/r377/ForwardPrivateMessageEventEncoder.java @@ -17,20 +17,20 @@ import org.apollo.util.NameUtil; */ public final class ForwardPrivateMessageEventEncoder extends EventEncoder { - /** - * The amount of messages sent globally, offset by a random variable x, {@code 0 <= x < 100,000,000}. - */ - private static AtomicInteger messageCounter = new AtomicInteger((int) (Math.random() * 100_000_000)); + /** + * The amount of messages sent globally, offset by a random variable x, {@code 0 <= x < 100,000,000}. + */ + private static AtomicInteger messageCounter = new AtomicInteger((int) (Math.random() * 100_000_000)); - @Override - public GamePacket encode(ForwardPrivateMessageEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(135, PacketType.VARIABLE_BYTE); + @Override + public GamePacket encode(ForwardPrivateMessageEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(135, PacketType.VARIABLE_BYTE); - builder.put(DataType.LONG, NameUtil.encodeBase37(event.getSenderUsername())); - builder.put(DataType.INT, messageCounter.incrementAndGet()); - builder.put(DataType.BYTE, event.getSenderPrivilege().toInteger()); - builder.putBytes(event.getCompressedMessage()); - return builder.toGamePacket(); - } + builder.put(DataType.LONG, NameUtil.encodeBase37(event.getSenderUsername())); + builder.put(DataType.INT, messageCounter.incrementAndGet()); + builder.put(DataType.BYTE, event.getSenderPrivilege().toInteger()); + builder.putBytes(event.getCompressedMessage()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FourthItemActionEventDecoder.java b/src/org/apollo/net/release/r377/FourthItemActionEventDecoder.java index 5beade6d..ceb3d58c 100644 --- a/src/org/apollo/net/release/r377/FourthItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FourthItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class FourthItemActionEventDecoder extends EventDecoder { - @Override - public FourthItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT); - return new FourthItemActionEvent(interfaceId, id, slot); - } + @Override + public FourthItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT); + return new FourthItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FourthItemOptionEventDecoder.java b/src/org/apollo/net/release/r377/FourthItemOptionEventDecoder.java index 16e6d927..9520d59f 100644 --- a/src/org/apollo/net/release/r377/FourthItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FourthItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class FourthItemOptionEventDecoder extends EventDecoder { - @Override - public FourthItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public FourthItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new FourthItemOptionEvent(interfaceId, id, slot); - } + return new FourthItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FourthPlayerActionEventDecoder.java b/src/org/apollo/net/release/r377/FourthPlayerActionEventDecoder.java index f650a533..f8490ec7 100644 --- a/src/org/apollo/net/release/r377/FourthPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/FourthPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class FourthPlayerActionEventDecoder extends EventDecoder { - @Override - public FourthPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new FourthPlayerActionEvent(index); - } + @Override + public FourthPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new FourthPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/FriendServerStatusEventEncoder.java b/src/org/apollo/net/release/r377/FriendServerStatusEventEncoder.java index 2afcf6f5..168dbe5d 100644 --- a/src/org/apollo/net/release/r377/FriendServerStatusEventEncoder.java +++ b/src/org/apollo/net/release/r377/FriendServerStatusEventEncoder.java @@ -13,10 +13,10 @@ import org.apollo.net.release.EventEncoder; */ public final class FriendServerStatusEventEncoder extends EventEncoder { - @Override - public GamePacket encode(FriendServerStatusEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(251); - builder.put(DataType.BYTE, event.getStatusCode()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(FriendServerStatusEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(251); + builder.put(DataType.BYTE, event.getStatusCode()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/IdAssignmentEventEncoder.java b/src/org/apollo/net/release/r377/IdAssignmentEventEncoder.java index 316ab341..98cabe40 100644 --- a/src/org/apollo/net/release/r377/IdAssignmentEventEncoder.java +++ b/src/org/apollo/net/release/r377/IdAssignmentEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class IdAssignmentEventEncoder extends EventEncoder { - @Override - public GamePacket encode(IdAssignmentEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(126); - builder.put(DataType.BYTE, event.isMembers() ? 1 : 0); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(IdAssignmentEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(126); + builder.put(DataType.BYTE, event.isMembers() ? 1 : 0); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/IgnoreListEventEncoder.java b/src/org/apollo/net/release/r377/IgnoreListEventEncoder.java index 2eb289e6..7e96b428 100644 --- a/src/org/apollo/net/release/r377/IgnoreListEventEncoder.java +++ b/src/org/apollo/net/release/r377/IgnoreListEventEncoder.java @@ -16,16 +16,16 @@ import org.apollo.util.NameUtil; */ public final class IgnoreListEventEncoder extends EventEncoder { - @Override - public GamePacket encode(IgnoreListEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(226); + @Override + public GamePacket encode(IgnoreListEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(226); - List usernames = event.getUsernames(); - for (String username : usernames) { - builder.put(DataType.LONG, NameUtil.encodeBase37(username)); - } - - return builder.toGamePacket(); + List usernames = event.getUsernames(); + for (String username : usernames) { + builder.put(DataType.LONG, NameUtil.encodeBase37(username)); } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ItemOnItemEventDecoder.java b/src/org/apollo/net/release/r377/ItemOnItemEventDecoder.java index 9d457a82..a6c8d437 100644 --- a/src/org/apollo/net/release/r377/ItemOnItemEventDecoder.java +++ b/src/org/apollo/net/release/r377/ItemOnItemEventDecoder.java @@ -15,20 +15,20 @@ import org.apollo.net.release.EventDecoder; */ final class ItemOnItemEventDecoder extends EventDecoder { - @Override - public ItemOnItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ItemOnItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int targetId = (int) reader.getUnsigned(DataType.SHORT); - int usedSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int targetId = (int) reader.getUnsigned(DataType.SHORT); + int usedSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int usedId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int targetInterface = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int usedId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int targetInterface = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int targetSlot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int usedInterface = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int targetSlot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int usedInterface = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new ItemOnItemEvent(usedInterface, usedId, usedSlot, targetInterface, targetId, targetSlot); - } + return new ItemOnItemEvent(usedInterface, usedId, usedSlot, targetInterface, targetId, targetSlot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ItemOnObjectEventDecoder.java b/src/org/apollo/net/release/r377/ItemOnObjectEventDecoder.java index e831d7c4..82182d52 100644 --- a/src/org/apollo/net/release/r377/ItemOnObjectEventDecoder.java +++ b/src/org/apollo/net/release/r377/ItemOnObjectEventDecoder.java @@ -15,18 +15,18 @@ import org.apollo.net.release.EventDecoder; */ public final class ItemOnObjectEventDecoder extends EventDecoder { - @Override - public ItemOnObjectEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ItemOnObjectEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int objectId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int itemId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int slot = (int) reader.getUnsigned(DataType.SHORT); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int objectId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int itemId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int slot = (int) reader.getUnsigned(DataType.SHORT); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new ItemOnObjectEvent(interfaceId, itemId, slot, objectId, x, y); - } + return new ItemOnObjectEvent(interfaceId, itemId, slot, objectId, x, y); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/KeepAliveEventDecoder.java b/src/org/apollo/net/release/r377/KeepAliveEventDecoder.java index 9c83f28d..c368a277 100644 --- a/src/org/apollo/net/release/r377/KeepAliveEventDecoder.java +++ b/src/org/apollo/net/release/r377/KeepAliveEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class KeepAliveEventDecoder extends EventDecoder { - @Override - public KeepAliveEvent decode(GamePacket packet) { - return new KeepAliveEvent(); - } + @Override + public KeepAliveEvent decode(GamePacket packet) { + return new KeepAliveEvent(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/LogoutEventEncoder.java b/src/org/apollo/net/release/r377/LogoutEventEncoder.java index 579c55f7..d83d8f26 100644 --- a/src/org/apollo/net/release/r377/LogoutEventEncoder.java +++ b/src/org/apollo/net/release/r377/LogoutEventEncoder.java @@ -12,10 +12,10 @@ import org.apollo.net.release.EventEncoder; */ public final class LogoutEventEncoder extends EventEncoder { - @Override - public GamePacket encode(LogoutEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(5); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(LogoutEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(5); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/MagicOnItemEventDecoder.java b/src/org/apollo/net/release/r377/MagicOnItemEventDecoder.java index a1fd2519..675912bf 100644 --- a/src/org/apollo/net/release/r377/MagicOnItemEventDecoder.java +++ b/src/org/apollo/net/release/r377/MagicOnItemEventDecoder.java @@ -14,16 +14,16 @@ import org.apollo.net.release.EventDecoder; */ final class MagicOnItemEventDecoder extends EventDecoder { - @Override - public MagicOnItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public MagicOnItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int spell = (int) reader.getUnsigned(DataType.SHORT); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int spell = (int) reader.getUnsigned(DataType.SHORT); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new MagicOnItemEvent(interfaceId, id, slot, spell); - } + return new MagicOnItemEvent(interfaceId, id, slot, spell); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/MobAnimationResetEventEncoder.java b/src/org/apollo/net/release/r377/MobAnimationResetEventEncoder.java index 8bc4d517..6e21ca9c 100644 --- a/src/org/apollo/net/release/r377/MobAnimationResetEventEncoder.java +++ b/src/org/apollo/net/release/r377/MobAnimationResetEventEncoder.java @@ -12,9 +12,9 @@ import org.apollo.net.release.EventEncoder; */ public final class MobAnimationResetEventEncoder extends EventEncoder { - @Override - public GamePacket encode(MobAnimationResetEvent event) { - return new GamePacketBuilder(13).toGamePacket(); - } + @Override + public GamePacket encode(MobAnimationResetEvent event) { + return new GamePacketBuilder(13).toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/MouseClickEventDecoder.java b/src/org/apollo/net/release/r377/MouseClickEventDecoder.java index 9689f0ff..3f647bf3 100644 --- a/src/org/apollo/net/release/r377/MouseClickEventDecoder.java +++ b/src/org/apollo/net/release/r377/MouseClickEventDecoder.java @@ -13,26 +13,26 @@ import org.apollo.net.release.EventDecoder; */ public final class MouseClickEventDecoder extends EventDecoder { - @Override - public MouseClickEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int read, clickCount, x, y; + @Override + public MouseClickEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int read, clickCount, x, y; - if (reader.getLength() == 2) { - read = (int) reader.getUnsigned(DataType.SHORT); - clickCount = (read >> 12); - x = (read >> 6) & 0x3f; - y = read & 0x3f; - return new MouseClickEvent(clickCount, x, y, true); - } else if (reader.getLength() == 3) { - read = (int) reader.getUnsigned(DataType.TRI_BYTE) & ~0x800000; - } else { - read = (int) reader.getUnsigned(DataType.INT) & ~0xc0000000; - } - clickCount = (read >> 19); - x = (read & 0x7f) % 765; - y = (read & 0x7f) / 765; - return new MouseClickEvent(clickCount, x, y, false); + if (reader.getLength() == 2) { + read = (int) reader.getUnsigned(DataType.SHORT); + clickCount = (read >> 12); + x = (read >> 6) & 0x3f; + y = read & 0x3f; + return new MouseClickEvent(clickCount, x, y, true); + } else if (reader.getLength() == 3) { + read = (int) reader.getUnsigned(DataType.TRI_BYTE) & ~0x800000; + } else { + read = (int) reader.getUnsigned(DataType.INT) & ~0xc0000000; } + clickCount = (read >> 19); + x = (read & 0x7f) % 765; + y = (read & 0x7f) / 765; + return new MouseClickEvent(clickCount, x, y, false); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/NpcSynchronizationEventEncoder.java b/src/org/apollo/net/release/r377/NpcSynchronizationEventEncoder.java index 9b3414a0..93f54311 100644 --- a/src/org/apollo/net/release/r377/NpcSynchronizationEventEncoder.java +++ b/src/org/apollo/net/release/r377/NpcSynchronizationEventEncoder.java @@ -33,268 +33,268 @@ import org.apollo.net.release.EventEncoder; */ public final class NpcSynchronizationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(NpcSynchronizationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(71, PacketType.VARIABLE_SHORT); - builder.switchToBitAccess(); + @Override + public GamePacket encode(NpcSynchronizationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(71, PacketType.VARIABLE_SHORT); + builder.switchToBitAccess(); - GamePacketBuilder blockBuilder = new GamePacketBuilder(); - builder.putBits(8, event.getLocalNpcCount()); + GamePacketBuilder blockBuilder = new GamePacketBuilder(); + builder.putBits(8, event.getLocalNpcCount()); - for (SynchronizationSegment segment : event.getSegments()) { - SegmentType type = segment.getType(); - if (type == SegmentType.REMOVE_MOB) { - putRemoveNpcUpdate(builder); - } else if (type == SegmentType.ADD_MOB) { - putAddNpcUpdate((AddNpcSegment) segment, event, builder); - putBlocks(segment, blockBuilder); - } else { - putMovementUpdate(segment, event, builder); - putBlocks(segment, blockBuilder); - } - } - - if (blockBuilder.getLength() > 0) { - builder.putBits(14, 16383); - builder.switchToByteAccess(); - builder.putRawBuilder(blockBuilder); - } else { - builder.switchToByteAccess(); - } - - return builder.toGamePacket(); + for (SynchronizationSegment segment : event.getSegments()) { + SegmentType type = segment.getType(); + if (type == SegmentType.REMOVE_MOB) { + putRemoveNpcUpdate(builder); + } else if (type == SegmentType.ADD_MOB) { + putAddNpcUpdate((AddNpcSegment) segment, event, builder); + putBlocks(segment, blockBuilder); + } else { + putMovementUpdate(segment, event, builder); + putBlocks(segment, blockBuilder); + } } - /** - * Puts an add npc update. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putAddNpcUpdate(AddNpcSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - Position npc = event.getPosition(); - Position other = seg.getPosition(); - builder.putBits(14, seg.getIndex()); - builder.putBits(1, updateRequired ? 1 : 0); - builder.putBits(5, other.getY() - npc.getY()); - builder.putBits(5, other.getX() - npc.getX()); - builder.putBits(1, 0); // discard walking queue - builder.putBits(13, seg.getNpcId()); + if (blockBuilder.getLength() > 0) { + builder.putBits(14, 16383); + builder.switchToByteAccess(); + builder.putRawBuilder(blockBuilder); + } else { + builder.switchToByteAccess(); } - /** - * Puts an animation block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { - Animation animation = block.getAnimation(); - builder.put(DataType.SHORT, animation.getId()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, animation.getDelay()); + return builder.toGamePacket(); + } + + /** + * Puts an add npc update. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putAddNpcUpdate(AddNpcSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + Position npc = event.getPosition(); + Position other = seg.getPosition(); + builder.putBits(14, seg.getIndex()); + builder.putBits(1, updateRequired ? 1 : 0); + builder.putBits(5, other.getY() - npc.getY()); + builder.putBits(5, other.getX() - npc.getX()); + builder.putBits(1, 0); // discard walking queue + builder.putBits(13, seg.getNpcId()); + } + + /** + * Puts an animation block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { + Animation animation = block.getAnimation(); + builder.put(DataType.SHORT, animation.getId()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, animation.getDelay()); + } + + /** + * Puts the blocks for the specified segment. + * + * @param segment The segment. + * @param builder The block builder. + */ + private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { + SynchronizationBlockSet blockSet = segment.getBlockSet(); + if (blockSet.size() > 0) { + int mask = 0; + + if (blockSet.contains(TransformBlock.class)) { + mask |= 0x1; + } + + if (blockSet.contains(InteractingMobBlock.class)) { + mask |= 0x40; + } + + if (blockSet.contains(HitUpdateBlock.class)) { + mask |= 0x80; + } + + if (blockSet.contains(GraphicBlock.class)) { + mask |= 0x4; + } + + if (blockSet.contains(ForceChatBlock.class)) { + mask |= 0x20; + } + + if (blockSet.contains(TurnToPositionBlock.class)) { + mask |= 0x8; + } + + if (blockSet.contains(AnimationBlock.class)) { + mask |= 0x2; + } + + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + mask |= 0x10; + } + + builder.put(DataType.BYTE, mask); + + if (blockSet.contains(TransformBlock.class)) { + putTransformBlock(blockSet.get(TransformBlock.class), builder); + } + + if (blockSet.contains(InteractingMobBlock.class)) { + putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); + } + + if (blockSet.contains(HitUpdateBlock.class)) { + putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); + } + + if (blockSet.contains(GraphicBlock.class)) { + putGraphicBlock(blockSet.get(GraphicBlock.class), builder); + } + + if (blockSet.contains(ForceChatBlock.class)) { + putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); + } + + if (blockSet.contains(TurnToPositionBlock.class)) { + putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); + } + + if (blockSet.contains(AnimationBlock.class)) { + putAnimationBlock(blockSet.get(AnimationBlock.class), builder); + } + + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); + } } + } - /** - * Puts the blocks for the specified segment. - * - * @param segment The segment. - * @param builder The block builder. - */ - private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { - SynchronizationBlockSet blockSet = segment.getBlockSet(); - if (blockSet.size() > 0) { - int mask = 0; + /** + * Puts a force chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { + builder.putString(block.getMessage()); + } - if (blockSet.contains(TransformBlock.class)) { - mask |= 0x1; - } + /** + * Puts a graphic block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { + Graphic graphic = block.getGraphic(); + builder.put(DataType.SHORT, graphic.getId()); + builder.put(DataType.INT, DataOrder.MIDDLE, graphic.getDelay()); + } - if (blockSet.contains(InteractingMobBlock.class)) { - mask |= 0x40; - } + /** + * Puts a hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.ADD, block.getType()); + builder.put(DataType.BYTE, block.getCurrentHealth()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getMaximumHealth()); + } - if (blockSet.contains(HitUpdateBlock.class)) { - mask |= 0x80; - } + /** + * Puts an interacting mob block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, DataOrder.LITTLE, block.getInteractingMobIndex()); + } - if (blockSet.contains(GraphicBlock.class)) { - mask |= 0x4; - } - - if (blockSet.contains(ForceChatBlock.class)) { - mask |= 0x20; - } - - if (blockSet.contains(TurnToPositionBlock.class)) { - mask |= 0x8; - } - - if (blockSet.contains(AnimationBlock.class)) { - mask |= 0x2; - } - - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - mask |= 0x10; - } - - builder.put(DataType.BYTE, mask); - - if (blockSet.contains(TransformBlock.class)) { - putTransformBlock(blockSet.get(TransformBlock.class), builder); - } - - if (blockSet.contains(InteractingMobBlock.class)) { - putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); - } - - if (blockSet.contains(HitUpdateBlock.class)) { - putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); - } - - if (blockSet.contains(GraphicBlock.class)) { - putGraphicBlock(blockSet.get(GraphicBlock.class), builder); - } - - if (blockSet.contains(ForceChatBlock.class)) { - putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); - } - - if (blockSet.contains(TurnToPositionBlock.class)) { - putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); - } - - if (blockSet.contains(AnimationBlock.class)) { - putAnimationBlock(blockSet.get(AnimationBlock.class), builder); - } - - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); - } - } - } - - /** - * Puts a force chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { - builder.putString(block.getMessage()); - } - - /** - * Puts a graphic block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { - Graphic graphic = block.getGraphic(); - builder.put(DataType.SHORT, graphic.getId()); - builder.put(DataType.INT, DataOrder.MIDDLE, graphic.getDelay()); - } - - /** - * Puts a hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.ADD, block.getType()); - builder.put(DataType.BYTE, block.getCurrentHealth()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getMaximumHealth()); - } - - /** - * Puts an interacting mob block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, DataOrder.LITTLE, block.getInteractingMobIndex()); - } - - /** - * Puts a movement update for the specified segment. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putMovementUpdate(SynchronizationSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - if (seg.getType() == SegmentType.RUN) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 2); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(3, directions[1].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else if (seg.getType() == SegmentType.WALK) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 1); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else { - if (updateRequired) { - builder.putBits(1, 1); - builder.putBits(2, 0); - } else { - builder.putBits(1, 0); - } - } - } - - /** - * Puts a remove mob update. - * - * @param builder The builder. - */ - private void putRemoveNpcUpdate(GamePacketBuilder builder) { + /** + * Puts a movement update for the specified segment. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putMovementUpdate(SynchronizationSegment seg, NpcSynchronizationEvent event, GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + if (seg.getType() == SegmentType.RUN) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 2); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(3, directions[1].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else if (seg.getType() == SegmentType.WALK) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 1); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else { + if (updateRequired) { builder.putBits(1, 1); - builder.putBits(2, 3); + builder.putBits(2, 0); + } else { + builder.putBits(1, 0); + } } + } - /** - * Puts a second hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); - builder.put(DataType.BYTE, block.getCurrentHealth()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); - } + /** + * Puts a remove mob update. + * + * @param builder The builder. + */ + private void putRemoveNpcUpdate(GamePacketBuilder builder) { + builder.putBits(1, 1); + builder.putBits(2, 3); + } - /** - * Puts a transform block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTransformBlock(TransformBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, DataTransformation.ADD, block.getId()); - } + /** + * Puts a second hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); + builder.put(DataType.BYTE, block.getCurrentHealth()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getMaximumHealth()); + } - /** - * Puts a turn to position block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { - Position position = block.getPosition(); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, position.getX() * 2 + 1); - builder.put(DataType.SHORT, DataOrder.LITTLE, position.getY() * 2 + 1); - } + /** + * Puts a transform block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTransformBlock(TransformBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, DataTransformation.ADD, block.getId()); + } + + /** + * Puts a turn to position block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { + Position position = block.getPosition(); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, position.getX() * 2 + 1); + builder.put(DataType.SHORT, DataOrder.LITTLE, position.getY() * 2 + 1); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/OpenDialogueInterfaceEventEncoder.java b/src/org/apollo/net/release/r377/OpenDialogueInterfaceEventEncoder.java index 9ac686a8..c531063a 100644 --- a/src/org/apollo/net/release/r377/OpenDialogueInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r377/OpenDialogueInterfaceEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenDialogueInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenDialogueInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(109); - builder.put(DataType.SHORT, event.getInterfaceId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenDialogueInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(109); + builder.put(DataType.SHORT, event.getInterfaceId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/OpenInterfaceEventEncoder.java b/src/org/apollo/net/release/r377/OpenInterfaceEventEncoder.java index 6d7611bd..2fb9c4bc 100644 --- a/src/org/apollo/net/release/r377/OpenInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r377/OpenInterfaceEventEncoder.java @@ -15,11 +15,11 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(159); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(159); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/OpenInterfaceSidebarEventEncoder.java b/src/org/apollo/net/release/r377/OpenInterfaceSidebarEventEncoder.java index 6f3277ba..a28fcbf7 100644 --- a/src/org/apollo/net/release/r377/OpenInterfaceSidebarEventEncoder.java +++ b/src/org/apollo/net/release/r377/OpenInterfaceSidebarEventEncoder.java @@ -15,12 +15,12 @@ import org.apollo.net.release.EventEncoder; */ public final class OpenInterfaceSidebarEventEncoder extends EventEncoder { - @Override - public GamePacket encode(OpenInterfaceSidebarEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(128); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getSidebarId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(OpenInterfaceSidebarEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(128); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getSidebarId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PlayerDesignEventDecoder.java b/src/org/apollo/net/release/r377/PlayerDesignEventDecoder.java index 14c18c37..3d2637f9 100644 --- a/src/org/apollo/net/release/r377/PlayerDesignEventDecoder.java +++ b/src/org/apollo/net/release/r377/PlayerDesignEventDecoder.java @@ -15,25 +15,25 @@ import org.apollo.net.release.EventDecoder; */ public final class PlayerDesignEventDecoder extends EventDecoder { - @Override - public PlayerDesignEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PlayerDesignEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int genderIntValue = (int) reader.getUnsigned(DataType.BYTE); + int genderIntValue = (int) reader.getUnsigned(DataType.BYTE); - int[] style = new int[7]; - for (int i = 0; i < style.length; i++) { - style[i] = (int) reader.getUnsigned(DataType.BYTE); - } - - int[] color = new int[5]; - for (int i = 0; i < color.length; i++) { - color[i] = (int) reader.getUnsigned(DataType.BYTE); - } - - Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; - - return new PlayerDesignEvent(new Appearance(gender, style, color)); + int[] style = new int[7]; + for (int i = 0; i < style.length; i++) { + style[i] = (int) reader.getUnsigned(DataType.BYTE); } + int[] color = new int[5]; + for (int i = 0; i < color.length; i++) { + color[i] = (int) reader.getUnsigned(DataType.BYTE); + } + + Gender gender = genderIntValue == Gender.MALE.toInteger() ? Gender.MALE : Gender.FEMALE; + + return new PlayerDesignEvent(new Appearance(gender, style, color)); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PlayerSynchronizationEventEncoder.java b/src/org/apollo/net/release/r377/PlayerSynchronizationEventEncoder.java index ae468587..99f1865e 100644 --- a/src/org/apollo/net/release/r377/PlayerSynchronizationEventEncoder.java +++ b/src/org/apollo/net/release/r377/PlayerSynchronizationEventEncoder.java @@ -43,420 +43,420 @@ import org.apollo.net.release.EventEncoder; */ public final class PlayerSynchronizationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(PlayerSynchronizationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(90, PacketType.VARIABLE_SHORT); - builder.switchToBitAccess(); + @Override + public GamePacket encode(PlayerSynchronizationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(90, PacketType.VARIABLE_SHORT); + builder.switchToBitAccess(); - GamePacketBuilder blockBuilder = new GamePacketBuilder(); + GamePacketBuilder blockBuilder = new GamePacketBuilder(); - putMovementUpdate(event.getSegment(), event, builder); - putBlocks(event.getSegment(), blockBuilder); + putMovementUpdate(event.getSegment(), event, builder); + putBlocks(event.getSegment(), blockBuilder); - builder.putBits(8, event.getLocalPlayers()); + builder.putBits(8, event.getLocalPlayers()); - for (SynchronizationSegment segment : event.getSegments()) { - SegmentType type = segment.getType(); - if (type == SegmentType.REMOVE_MOB) { - putRemovePlayerUpdate(builder); - } else if (type == SegmentType.ADD_MOB) { - putAddPlayerUpdate((AddPlayerSegment) segment, event, builder); - putBlocks(segment, blockBuilder); - } else { - putMovementUpdate(segment, event, builder); - putBlocks(segment, blockBuilder); - } - } + for (SynchronizationSegment segment : event.getSegments()) { + SegmentType type = segment.getType(); + if (type == SegmentType.REMOVE_MOB) { + putRemovePlayerUpdate(builder); + } else if (type == SegmentType.ADD_MOB) { + putAddPlayerUpdate((AddPlayerSegment) segment, event, builder); + putBlocks(segment, blockBuilder); + } else { + putMovementUpdate(segment, event, builder); + putBlocks(segment, blockBuilder); + } + } - if (blockBuilder.getLength() > 0) { - builder.putBits(11, 2047); - builder.switchToByteAccess(); - builder.putRawBuilder(blockBuilder); + if (blockBuilder.getLength() > 0) { + builder.putBits(11, 2047); + builder.switchToByteAccess(); + builder.putRawBuilder(blockBuilder); + } else { + builder.switchToByteAccess(); + } + + return builder.toGamePacket(); + } + + /** + * Puts an add player update. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putAddPlayerUpdate(AddPlayerSegment seg, PlayerSynchronizationEvent event, GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + Position player = event.getPosition(); + Position other = seg.getPosition(); + builder.putBits(11, seg.getIndex()); + builder.putBits(5, other.getX() - player.getX()); + builder.putBits(1, updateRequired ? 1 : 0); + builder.putBits(1, 1); // discard walking queue? + builder.putBits(5, other.getY() - player.getY()); + } + + /** + * Puts an Animation block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { + Animation animation = block.getAnimation(); + builder.put(DataType.SHORT, animation.getId()); + builder.put(DataType.BYTE, DataTransformation.ADD, animation.getDelay()); + } + + /** + * Puts an Appearance block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putAppearanceBlock(AppearanceBlock block, GamePacketBuilder builder) { + Appearance appearance = block.getAppearance(); + GamePacketBuilder playerProperties = new GamePacketBuilder(); + + playerProperties.put(DataType.BYTE, appearance.getGender().toInteger()); + playerProperties.put(DataType.BYTE, block.isSkulled() ? 1 : -1); + playerProperties.put(DataType.BYTE, block.getHeadIcon()); + + if (block.appearingAsNpc()) { + playerProperties.put(DataType.BYTE, 255); + playerProperties.put(DataType.BYTE, 255); + playerProperties.put(DataType.SHORT, block.getNpcId()); + } else { + Inventory equipment = block.getEquipment(); + int[] style = appearance.getStyle(); + Item item, chest, helm; + + for (int slot = 0; slot < 4; slot++) { + if ((item = equipment.get(slot)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); } else { - builder.switchToByteAccess(); + playerProperties.put(DataType.BYTE, 0); } + } - return builder.toGamePacket(); - } + if ((chest = equipment.get(EquipmentConstants.CHEST)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + chest.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[2]); + } - /** - * Puts an add player update. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putAddPlayerUpdate(AddPlayerSegment seg, PlayerSynchronizationEvent event, GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - Position player = event.getPosition(); - Position other = seg.getPosition(); - builder.putBits(11, seg.getIndex()); - builder.putBits(5, other.getX() - player.getX()); - builder.putBits(1, updateRequired ? 1 : 0); - builder.putBits(1, 1); // discard walking queue? - builder.putBits(5, other.getY() - player.getY()); - } + if ((item = equipment.get(EquipmentConstants.SHIELD)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.BYTE, 0); + } - /** - * Puts an Animation block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAnimationBlock(AnimationBlock block, GamePacketBuilder builder) { - Animation animation = block.getAnimation(); - builder.put(DataType.SHORT, animation.getId()); - builder.put(DataType.BYTE, DataTransformation.ADD, animation.getDelay()); - } - - /** - * Puts an Appearance block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putAppearanceBlock(AppearanceBlock block, GamePacketBuilder builder) { - Appearance appearance = block.getAppearance(); - GamePacketBuilder playerProperties = new GamePacketBuilder(); - - playerProperties.put(DataType.BYTE, appearance.getGender().toInteger()); - playerProperties.put(DataType.BYTE, block.isSkulled() ? 1 : -1); - playerProperties.put(DataType.BYTE, block.getHeadIcon()); - - if (block.appearingAsNpc()) { - playerProperties.put(DataType.BYTE, 255); - playerProperties.put(DataType.BYTE, 255); - playerProperties.put(DataType.SHORT, block.getNpcId()); + if (chest != null) { + EquipmentDefinition def = EquipmentDefinition.lookup(chest.getId()); + if (def != null && !def.isFullBody()) { + playerProperties.put(DataType.SHORT, 0x100 + style[3]); } else { - Inventory equipment = block.getEquipment(); - int[] style = appearance.getStyle(); - Item item, chest, helm; - - for (int slot = 0; slot < 4; slot++) { - if ((item = equipment.get(slot)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } - - if ((chest = equipment.get(EquipmentConstants.CHEST)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + chest.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[2]); - } - - if ((item = equipment.get(EquipmentConstants.SHIELD)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.BYTE, 0); - } - - if (chest != null) { - EquipmentDefinition def = EquipmentDefinition.lookup(chest.getId()); - if (def != null && !def.isFullBody()) { - playerProperties.put(DataType.SHORT, 0x100 + style[3]); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[3]); - } - - if ((item = equipment.get(EquipmentConstants.LEGS)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[5]); - } - - if ((helm = equipment.get(EquipmentConstants.HAT)) != null) { - EquipmentDefinition def = EquipmentDefinition.lookup(helm.getId()); - if (def != null && !def.isFullHat() && !def.isFullMask()) { - playerProperties.put(DataType.SHORT, 0x100 + style[0]); - } else { - playerProperties.put(DataType.BYTE, 0); - } - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[0]); - } - - if ((item = equipment.get(EquipmentConstants.HANDS)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[4]); - } - - if ((item = equipment.get(EquipmentConstants.FEET)) != null) { - playerProperties.put(DataType.SHORT, 0x200 + item.getId()); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[6]); - } - - EquipmentDefinition def = null; - if (helm != null) { - def = EquipmentDefinition.lookup(helm.getId()); - } - if (def != null && (def.isFullHat() || def.isFullMask()) || appearance.getGender() == Gender.FEMALE) { - playerProperties.put(DataType.BYTE, 0); - } else { - playerProperties.put(DataType.SHORT, 0x100 + style[1]); - } + playerProperties.put(DataType.BYTE, 0); } + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[3]); + } - int[] colors = appearance.getColors(); - for (int color : colors) { - playerProperties.put(DataType.BYTE, color); - } + if ((item = equipment.get(EquipmentConstants.LEGS)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[5]); + } - playerProperties.put(DataType.SHORT, 0x328); // stand - playerProperties.put(DataType.SHORT, 0x337); // stand turn - playerProperties.put(DataType.SHORT, 0x333); // walk - playerProperties.put(DataType.SHORT, 0x334); // turn 180 - playerProperties.put(DataType.SHORT, 0x335); // turn 90 cw - playerProperties.put(DataType.SHORT, 0x336); // turn 90 ccw - playerProperties.put(DataType.SHORT, 0x338); // run - - playerProperties.put(DataType.LONG, block.getName()); - playerProperties.put(DataType.BYTE, block.getCombatLevel()); - playerProperties.put(DataType.SHORT, block.getSkillLevel()); - - builder.put(DataType.BYTE, playerProperties.getLength()); - builder.putRawBuilderReverse(playerProperties); - } - - /** - * Puts the blocks for the specified segment. - * - * @param segment The segment. - * @param builder The block builder. - */ - private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { - SynchronizationBlockSet blockSet = segment.getBlockSet(); - if (blockSet.size() > 0) { - int mask = 0; - - if (blockSet.contains(AnimationBlock.class)) { - mask |= 0x8; - } - if (blockSet.contains(ForceChatBlock.class)) { - mask |= 0x10; - } - if (blockSet.contains(ForceMovementBlock.class)) { - mask |= 0x100; - } - if (blockSet.contains(InteractingMobBlock.class)) { - mask |= 0x1; - } - if (blockSet.contains(TurnToPositionBlock.class)) { - mask |= 0x2; - } - if (blockSet.contains(GraphicBlock.class)) { - mask |= 0x200; - } - if (blockSet.contains(AppearanceBlock.class)) { - mask |= 0x4; - } - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - mask |= 0x400; - } - if (blockSet.contains(ChatBlock.class)) { - mask |= 0x40; - } - if (blockSet.contains(HitUpdateBlock.class)) { - mask |= 0x80; - } - - if (mask >= 0x100) { - mask |= 0x20; - builder.put(DataType.SHORT, DataOrder.LITTLE, mask); - } else { - builder.put(DataType.BYTE, mask); - } - - if (blockSet.contains(AnimationBlock.class)) { - putAnimationBlock(blockSet.get(AnimationBlock.class), builder); - } - if (blockSet.contains(ForceChatBlock.class)) { - putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); - } - if (blockSet.contains(ForceMovementBlock.class)) { - putForceMovementBlock(blockSet.get(ForceMovementBlock.class), builder); - } - if (blockSet.contains(InteractingMobBlock.class)) { - putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); - } - if (blockSet.contains(TurnToPositionBlock.class)) { - putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); - } - if (blockSet.contains(GraphicBlock.class)) { - putGraphicBlock(blockSet.get(GraphicBlock.class), builder); - } - if (blockSet.contains(AppearanceBlock.class)) { - putAppearanceBlock(blockSet.get(AppearanceBlock.class), builder); - } - if (blockSet.contains(SecondaryHitUpdateBlock.class)) { - putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); - } - if (blockSet.contains(ChatBlock.class)) { - putChatBlock(blockSet.get(ChatBlock.class), builder); - } - if (blockSet.contains(HitUpdateBlock.class)) { - putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); - } - } - } - - /** - * Puts a chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putChatBlock(ChatBlock block, GamePacketBuilder builder) { - byte[] bytes = block.getCompressedMessage(); - builder.put(DataType.SHORT, DataOrder.LITTLE, block.getTextEffects() << 8 | block.getTextColor()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getPrivilegeLevel().toInteger()); - builder.put(DataType.BYTE, DataTransformation.ADD, bytes.length); - builder.putBytes(DataTransformation.ADD, bytes); - } - - /** - * Puts a force chat block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { - builder.putString(block.getMessage()); - } - - /** - * Puts a force movement block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putForceMovementBlock(ForceMovementBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.ADD, block.getInitialX()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getInitialY()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalX()); - builder.put(DataType.BYTE, block.getFinalY()); - builder.put(DataType.SHORT, block.getTravelDurationX()); - builder.put(DataType.SHORT, DataTransformation.ADD, block.getTravelDurationY()); - builder.put(DataType.BYTE, block.getDirection().toInteger()); - } - - /** - * Puts a graphic block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { - Graphic graphic = block.getGraphic(); - builder.put(DataType.SHORT, DataTransformation.ADD, graphic.getId()); - builder.put(DataType.INT, DataOrder.MIDDLE, graphic.getHeight() << 16 & 0xFFFF0000 | graphic.getDelay() - & 0x0000FFFF); - } - - /** - * Puts a hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getType()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getCurrentHealth()); - builder.put(DataType.BYTE, block.getMaximumHealth()); - } - - /** - * Puts an interacting mob block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { - builder.put(DataType.SHORT, DataTransformation.ADD, block.getInteractingMobIndex()); - } - - /** - * Puts a movement update for the specified segment. - * - * @param seg The segment. - * @param event The event. - * @param builder The builder. - */ - private void putMovementUpdate(SynchronizationSegment seg, PlayerSynchronizationEvent event, - GamePacketBuilder builder) { - boolean updateRequired = seg.getBlockSet().size() > 0; - if (seg.getType() == SegmentType.TELEPORT) { - Position pos = ((TeleportSegment) seg).getDestination(); - builder.putBits(1, 1); - builder.putBits(2, 3); - builder.putBits(1, event.hasRegionChanged() ? 0 : 1); - builder.putBits(2, pos.getHeight()); - builder.putBits(7, pos.getLocalY(event.getLastKnownRegion())); - builder.putBits(7, pos.getLocalX(event.getLastKnownRegion())); - builder.putBits(1, updateRequired ? 1 : 0); - } else if (seg.getType() == SegmentType.RUN) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 2); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(3, directions[1].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); - } else if (seg.getType() == SegmentType.WALK) { - Direction[] directions = ((MovementSegment) seg).getDirections(); - builder.putBits(1, 1); - builder.putBits(2, 1); - builder.putBits(3, directions[0].toInteger()); - builder.putBits(1, updateRequired ? 1 : 0); + if ((helm = equipment.get(EquipmentConstants.HAT)) != null) { + EquipmentDefinition def = EquipmentDefinition.lookup(helm.getId()); + if (def != null && !def.isFullHat() && !def.isFullMask()) { + playerProperties.put(DataType.SHORT, 0x100 + style[0]); } else { - if (updateRequired) { - builder.putBits(1, 1); - builder.putBits(2, 0); - } else { - builder.putBits(1, 0); - } + playerProperties.put(DataType.BYTE, 0); } + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[0]); + } + + if ((item = equipment.get(EquipmentConstants.HANDS)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[4]); + } + + if ((item = equipment.get(EquipmentConstants.FEET)) != null) { + playerProperties.put(DataType.SHORT, 0x200 + item.getId()); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[6]); + } + + EquipmentDefinition def = null; + if (helm != null) { + def = EquipmentDefinition.lookup(helm.getId()); + } + if (def != null && (def.isFullHat() || def.isFullMask()) || appearance.getGender() == Gender.FEMALE) { + playerProperties.put(DataType.BYTE, 0); + } else { + playerProperties.put(DataType.SHORT, 0x100 + style[1]); + } } - /** - * Puts a remove player update. - * - * @param builder The builder. - */ - private void putRemovePlayerUpdate(GamePacketBuilder builder) { + int[] colors = appearance.getColors(); + for (int color : colors) { + playerProperties.put(DataType.BYTE, color); + } + + playerProperties.put(DataType.SHORT, 0x328); // stand + playerProperties.put(DataType.SHORT, 0x337); // stand turn + playerProperties.put(DataType.SHORT, 0x333); // walk + playerProperties.put(DataType.SHORT, 0x334); // turn 180 + playerProperties.put(DataType.SHORT, 0x335); // turn 90 cw + playerProperties.put(DataType.SHORT, 0x336); // turn 90 ccw + playerProperties.put(DataType.SHORT, 0x338); // run + + playerProperties.put(DataType.LONG, block.getName()); + playerProperties.put(DataType.BYTE, block.getCombatLevel()); + playerProperties.put(DataType.SHORT, block.getSkillLevel()); + + builder.put(DataType.BYTE, playerProperties.getLength()); + builder.putRawBuilderReverse(playerProperties); + } + + /** + * Puts the blocks for the specified segment. + * + * @param segment The segment. + * @param builder The block builder. + */ + private void putBlocks(SynchronizationSegment segment, GamePacketBuilder builder) { + SynchronizationBlockSet blockSet = segment.getBlockSet(); + if (blockSet.size() > 0) { + int mask = 0; + + if (blockSet.contains(AnimationBlock.class)) { + mask |= 0x8; + } + if (blockSet.contains(ForceChatBlock.class)) { + mask |= 0x10; + } + if (blockSet.contains(ForceMovementBlock.class)) { + mask |= 0x100; + } + if (blockSet.contains(InteractingMobBlock.class)) { + mask |= 0x1; + } + if (blockSet.contains(TurnToPositionBlock.class)) { + mask |= 0x2; + } + if (blockSet.contains(GraphicBlock.class)) { + mask |= 0x200; + } + if (blockSet.contains(AppearanceBlock.class)) { + mask |= 0x4; + } + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + mask |= 0x400; + } + if (blockSet.contains(ChatBlock.class)) { + mask |= 0x40; + } + if (blockSet.contains(HitUpdateBlock.class)) { + mask |= 0x80; + } + + if (mask >= 0x100) { + mask |= 0x20; + builder.put(DataType.SHORT, DataOrder.LITTLE, mask); + } else { + builder.put(DataType.BYTE, mask); + } + + if (blockSet.contains(AnimationBlock.class)) { + putAnimationBlock(blockSet.get(AnimationBlock.class), builder); + } + if (blockSet.contains(ForceChatBlock.class)) { + putForceChatBlock(blockSet.get(ForceChatBlock.class), builder); + } + if (blockSet.contains(ForceMovementBlock.class)) { + putForceMovementBlock(blockSet.get(ForceMovementBlock.class), builder); + } + if (blockSet.contains(InteractingMobBlock.class)) { + putInteractingMobBlock(blockSet.get(InteractingMobBlock.class), builder); + } + if (blockSet.contains(TurnToPositionBlock.class)) { + putTurnToPositionBlock(blockSet.get(TurnToPositionBlock.class), builder); + } + if (blockSet.contains(GraphicBlock.class)) { + putGraphicBlock(blockSet.get(GraphicBlock.class), builder); + } + if (blockSet.contains(AppearanceBlock.class)) { + putAppearanceBlock(blockSet.get(AppearanceBlock.class), builder); + } + if (blockSet.contains(SecondaryHitUpdateBlock.class)) { + putSecondHitUpdateBlock(blockSet.get(SecondaryHitUpdateBlock.class), builder); + } + if (blockSet.contains(ChatBlock.class)) { + putChatBlock(blockSet.get(ChatBlock.class), builder); + } + if (blockSet.contains(HitUpdateBlock.class)) { + putHitUpdateBlock(blockSet.get(HitUpdateBlock.class), builder); + } + } + } + + /** + * Puts a chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putChatBlock(ChatBlock block, GamePacketBuilder builder) { + byte[] bytes = block.getCompressedMessage(); + builder.put(DataType.SHORT, DataOrder.LITTLE, block.getTextEffects() << 8 | block.getTextColor()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getPrivilegeLevel().toInteger()); + builder.put(DataType.BYTE, DataTransformation.ADD, bytes.length); + builder.putBytes(DataTransformation.ADD, bytes); + } + + /** + * Puts a force chat block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putForceChatBlock(ForceChatBlock block, GamePacketBuilder builder) { + builder.putString(block.getMessage()); + } + + /** + * Puts a force movement block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putForceMovementBlock(ForceMovementBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.ADD, block.getInitialX()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getInitialY()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getFinalX()); + builder.put(DataType.BYTE, block.getFinalY()); + builder.put(DataType.SHORT, block.getTravelDurationX()); + builder.put(DataType.SHORT, DataTransformation.ADD, block.getTravelDurationY()); + builder.put(DataType.BYTE, block.getDirection().toInteger()); + } + + /** + * Puts a graphic block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putGraphicBlock(GraphicBlock block, GamePacketBuilder builder) { + Graphic graphic = block.getGraphic(); + builder.put(DataType.SHORT, DataTransformation.ADD, graphic.getId()); + builder.put(DataType.INT, DataOrder.MIDDLE, graphic.getHeight() << 16 & 0xFFFF0000 | graphic.getDelay() + & 0x0000FFFF); + } + + /** + * Puts a hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putHitUpdateBlock(HitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getType()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getCurrentHealth()); + builder.put(DataType.BYTE, block.getMaximumHealth()); + } + + /** + * Puts an interacting mob block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putInteractingMobBlock(InteractingMobBlock block, GamePacketBuilder builder) { + builder.put(DataType.SHORT, DataTransformation.ADD, block.getInteractingMobIndex()); + } + + /** + * Puts a movement update for the specified segment. + * + * @param seg The segment. + * @param event The event. + * @param builder The builder. + */ + private void putMovementUpdate(SynchronizationSegment seg, PlayerSynchronizationEvent event, + GamePacketBuilder builder) { + boolean updateRequired = seg.getBlockSet().size() > 0; + if (seg.getType() == SegmentType.TELEPORT) { + Position pos = ((TeleportSegment) seg).getDestination(); + builder.putBits(1, 1); + builder.putBits(2, 3); + builder.putBits(1, event.hasRegionChanged() ? 0 : 1); + builder.putBits(2, pos.getHeight()); + builder.putBits(7, pos.getLocalY(event.getLastKnownRegion())); + builder.putBits(7, pos.getLocalX(event.getLastKnownRegion())); + builder.putBits(1, updateRequired ? 1 : 0); + } else if (seg.getType() == SegmentType.RUN) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 2); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(3, directions[1].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else if (seg.getType() == SegmentType.WALK) { + Direction[] directions = ((MovementSegment) seg).getDirections(); + builder.putBits(1, 1); + builder.putBits(2, 1); + builder.putBits(3, directions[0].toInteger()); + builder.putBits(1, updateRequired ? 1 : 0); + } else { + if (updateRequired) { builder.putBits(1, 1); - builder.putBits(2, 3); + builder.putBits(2, 0); + } else { + builder.putBits(1, 0); + } } + } - /** - * Puts a secondary hit update block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { - builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); - builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getCurrentHealth()); - builder.put(DataType.BYTE, block.getMaximumHealth()); - } + /** + * Puts a remove player update. + * + * @param builder The builder. + */ + private void putRemovePlayerUpdate(GamePacketBuilder builder) { + builder.putBits(1, 1); + builder.putBits(2, 3); + } - /** - * Puts a turn to position block into the specified builder. - * - * @param block The block. - * @param builder The builder. - */ - private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { - Position position = block.getPosition(); - builder.put(DataType.SHORT, position.getX() * 2 + 1); - builder.put(DataType.SHORT, position.getY() * 2 + 1); - } + /** + * Puts a secondary hit update block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putSecondHitUpdateBlock(SecondaryHitUpdateBlock block, GamePacketBuilder builder) { + builder.put(DataType.BYTE, DataTransformation.ADD, block.getDamage()); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, block.getType()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, block.getCurrentHealth()); + builder.put(DataType.BYTE, block.getMaximumHealth()); + } + + /** + * Puts a turn to position block into the specified builder. + * + * @param block The block. + * @param builder The builder. + */ + private void putTurnToPositionBlock(TurnToPositionBlock block, GamePacketBuilder builder) { + Position position = block.getPosition(); + builder.put(DataType.SHORT, position.getX() * 2 + 1); + builder.put(DataType.SHORT, position.getY() * 2 + 1); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PositionEventEncoder.java b/src/org/apollo/net/release/r377/PositionEventEncoder.java index f1e9b03f..62f9be25 100644 --- a/src/org/apollo/net/release/r377/PositionEventEncoder.java +++ b/src/org/apollo/net/release/r377/PositionEventEncoder.java @@ -16,15 +16,15 @@ import org.apollo.net.release.EventEncoder; */ public final class PositionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(PositionEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(75); - Position base = event.getBase(), pos = event.getPosition(); + @Override + public GamePacket encode(PositionEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(75); + Position base = event.getBase(), pos = event.getPosition(); - builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalX(base)); - builder.put(DataType.BYTE, DataTransformation.ADD, pos.getLocalY(base)); + builder.put(DataType.BYTE, DataTransformation.NEGATE, pos.getLocalX(base)); + builder.put(DataType.BYTE, DataTransformation.ADD, pos.getLocalY(base)); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PrivacyOptionEventDecoder.java b/src/org/apollo/net/release/r377/PrivacyOptionEventDecoder.java index a423d0c5..c4a2b150 100644 --- a/src/org/apollo/net/release/r377/PrivacyOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/PrivacyOptionEventDecoder.java @@ -13,15 +13,15 @@ import org.apollo.net.release.EventDecoder; */ public final class PrivacyOptionEventDecoder extends EventDecoder { - @Override - public PrivacyOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PrivacyOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int publicChatState = (int) reader.getUnsigned(DataType.BYTE); - int privateChatState = (int) reader.getUnsigned(DataType.BYTE); - int tradeChatState = (int) reader.getUnsigned(DataType.BYTE); + int publicChatState = (int) reader.getUnsigned(DataType.BYTE); + int privateChatState = (int) reader.getUnsigned(DataType.BYTE); + int tradeChatState = (int) reader.getUnsigned(DataType.BYTE); - return new PrivacyOptionEvent(publicChatState, privateChatState, tradeChatState); - } + return new PrivacyOptionEvent(publicChatState, privateChatState, tradeChatState); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PrivacyOptionEventEncoder.java b/src/org/apollo/net/release/r377/PrivacyOptionEventEncoder.java index c6534dca..51688780 100644 --- a/src/org/apollo/net/release/r377/PrivacyOptionEventEncoder.java +++ b/src/org/apollo/net/release/r377/PrivacyOptionEventEncoder.java @@ -13,15 +13,15 @@ import org.apollo.net.release.EventEncoder; */ public final class PrivacyOptionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(final PrivacyOptionEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(201); + @Override + public GamePacket encode(final PrivacyOptionEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(201); - builder.put(DataType.BYTE, event.getChatPrivacy().ordinal()); - builder.put(DataType.BYTE, event.getFriendPrivacy().ordinal()); - builder.put(DataType.BYTE, event.getTradePrivacy().ordinal()); + builder.put(DataType.BYTE, event.getChatPrivacy().ordinal()); + builder.put(DataType.BYTE, event.getFriendPrivacy().ordinal()); + builder.put(DataType.BYTE, event.getTradePrivacy().ordinal()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/PrivateMessageEventDecoder.java b/src/org/apollo/net/release/r377/PrivateMessageEventDecoder.java index 95269e83..813d82f9 100644 --- a/src/org/apollo/net/release/r377/PrivateMessageEventDecoder.java +++ b/src/org/apollo/net/release/r377/PrivateMessageEventDecoder.java @@ -15,24 +15,24 @@ import org.apollo.util.TextUtil; */ public final class PrivateMessageEventDecoder extends EventDecoder { - @Override - public PrivateMessageEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public PrivateMessageEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - int length = packet.getLength() - 8; + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + int length = packet.getLength() - 8; - byte[] originalCompressed = new byte[length]; - reader.getBytes(originalCompressed); + byte[] originalCompressed = new byte[length]; + reader.getBytes(originalCompressed); - String uncompressed = TextUtil.uncompress(originalCompressed, length); - uncompressed = TextUtil.filterInvalidCharacters(uncompressed); - uncompressed = TextUtil.capitalize(uncompressed); + String uncompressed = TextUtil.uncompress(originalCompressed, length); + uncompressed = TextUtil.filterInvalidCharacters(uncompressed); + uncompressed = TextUtil.capitalize(uncompressed); - byte[] recompressed = new byte[length]; - TextUtil.compress(uncompressed, recompressed); + byte[] recompressed = new byte[length]; + TextUtil.compress(uncompressed, recompressed); - return new PrivateMessageEvent(username, new String(uncompressed), recompressed); - } + return new PrivateMessageEvent(username, new String(uncompressed), recompressed); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/RegionChangeEventEncoder.java b/src/org/apollo/net/release/r377/RegionChangeEventEncoder.java index 03fe4e16..f54a9ca3 100644 --- a/src/org/apollo/net/release/r377/RegionChangeEventEncoder.java +++ b/src/org/apollo/net/release/r377/RegionChangeEventEncoder.java @@ -15,12 +15,12 @@ import org.apollo.net.release.EventEncoder; */ public final class RegionChangeEventEncoder extends EventEncoder { - @Override - public GamePacket encode(RegionChangeEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(222); - builder.put(DataType.SHORT, event.getPosition().getCentralSectorY()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getPosition().getCentralSectorX()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(RegionChangeEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(222); + builder.put(DataType.SHORT, event.getPosition().getCentralSectorY()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getPosition().getCentralSectorX()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/Release377.java b/src/org/apollo/net/release/r377/Release377.java index a6dd4392..fe40b583 100644 --- a/src/org/apollo/net/release/r377/Release377.java +++ b/src/org/apollo/net/release/r377/Release377.java @@ -47,152 +47,152 @@ import org.apollo.net.release.Release; */ public final class Release377 extends Release { - /** - * The incoming packet lengths array. - */ - public static final int[] PACKET_LENGTHS = { 0, 12, 0, 6, 6, 0, 0, 0, 2, 0, // 0 - 0, 0, 0, 2, 0, 0, 0, 0, 0, 4, // 10 - 0, 0, 2, 0, 6, 0, 0, 0, -1, 0, // 20 - 0, 4, 0, 0, 0, 0, 8, 0, 0, 0, // 30 - 0, 0, 2, 0, 0, 2, 0, 0, 0, -1, // 40 - 6, 0, 0, 0, 6, 6, -1, 8, 0, 0, // 50 - 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, // 60 - 0, 6, 0, 0, 0, 4, 0, 6, 4, 2, // 70 - 2, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 80 - 0, 6, 0, 0, 0, 4, 0, 0, 0, 0, // 90 - 6, 0, 0, 0, 4, 0, 0, 0, 0, 0, // 100 - 0, 0, 2, 0, 0, 0, 2, 0, 0, 1, // 110 - 8, 0, 0, 7, 0, 0, 1, 0, 0, 0, // 120 - 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, // 130 - 4, 8, 0, 8, 0, 0, 0, 0, 0, 0, // 140 - 0, 0, 12, 0, 0, 0, 0, 4, 6, 0, // 150 - 8, 6, 0, 13, 0, 1, 0, 0, 0, 0, // 160 - 0, -1, 0, 3, 0, 0, 3, 6, 0, 0, // 170 - 0, 6, 0, 0, 10, 0, 0, 1, 0, 0, // 180 - 0, 0, 0, 0, 2, 0, 0, 4, 0, 0, // 190 - 0, 0, 0, 6, 0, 0, 8, 0, 0, 0, // 200 - 8, 12, 0, -1, 0, 0, 0, 8, 0, 0, // 210 - 0, 0, 3, 0, 0, 0, 2, 9, 6, 0, // 220 - 6, 6, 0, 2, 0, 0, 0, 0, 0, 0, // 230 - 0, 6, 0, 0, -1, 2, 0, -1, 0, 0, // 240 - 0, 0, 0, 0, 0, 0 // 250 - }; + /** + * The incoming packet lengths array. + */ + public static final int[] PACKET_LENGTHS = { 0, 12, 0, 6, 6, 0, 0, 0, 2, 0, // 0 + 0, 0, 0, 2, 0, 0, 0, 0, 0, 4, // 10 + 0, 0, 2, 0, 6, 0, 0, 0, -1, 0, // 20 + 0, 4, 0, 0, 0, 0, 8, 0, 0, 0, // 30 + 0, 0, 2, 0, 0, 2, 0, 0, 0, -1, // 40 + 6, 0, 0, 0, 6, 6, -1, 8, 0, 0, // 50 + 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, // 60 + 0, 6, 0, 0, 0, 4, 0, 6, 4, 2, // 70 + 2, 0, 0, 8, 0, 0, 0, 0, 0, 0, // 80 + 0, 6, 0, 0, 0, 4, 0, 0, 0, 0, // 90 + 6, 0, 0, 0, 4, 0, 0, 0, 0, 0, // 100 + 0, 0, 2, 0, 0, 0, 2, 0, 0, 1, // 110 + 8, 0, 0, 7, 0, 0, 1, 0, 0, 0, // 120 + 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, // 130 + 4, 8, 0, 8, 0, 0, 0, 0, 0, 0, // 140 + 0, 0, 12, 0, 0, 0, 0, 4, 6, 0, // 150 + 8, 6, 0, 13, 0, 1, 0, 0, 0, 0, // 160 + 0, -1, 0, 3, 0, 0, 3, 6, 0, 0, // 170 + 0, 6, 0, 0, 10, 0, 0, 1, 0, 0, // 180 + 0, 0, 0, 0, 2, 0, 0, 4, 0, 0, // 190 + 0, 0, 0, 6, 0, 0, 8, 0, 0, 0, // 200 + 8, 12, 0, -1, 0, 0, 0, 8, 0, 0, // 210 + 0, 0, 3, 0, 0, 0, 2, 9, 6, 0, // 220 + 6, 6, 0, 2, 0, 0, 0, 0, 0, 0, // 230 + 0, 6, 0, 0, -1, 2, 0, -1, 0, 0, // 240 + 0, 0, 0, 0, 0, 0 // 250 + }; - /** - * Creates and initialises this release. - */ - public Release377() { - super(377, PacketMetaDataGroup.createFromArray(PACKET_LENGTHS)); - init(); - } + /** + * Creates and initialises this release. + */ + public Release377() { + super(377, PacketMetaDataGroup.createFromArray(PACKET_LENGTHS)); + init(); + } - /** - * Initialises this release by registering encoders and decoders. - */ - private void init() { - // register decoders - WalkEventDecoder walkEventDecoder = new WalkEventDecoder(); - register(213, walkEventDecoder); - register(28, walkEventDecoder); - register(247, walkEventDecoder); + /** + * Initialises this release by registering encoders and decoders. + */ + private void init() { + // register decoders + WalkEventDecoder walkEventDecoder = new WalkEventDecoder(); + register(213, walkEventDecoder); + register(28, walkEventDecoder); + register(247, walkEventDecoder); - register(248, new KeepAliveEventDecoder()); - register(163, new PlayerDesignEventDecoder()); - register(49, new ChatEventDecoder()); - register(56, new CommandEventDecoder()); - register(123, new SwitchItemEventDecoder()); + register(248, new KeepAliveEventDecoder()); + register(163, new PlayerDesignEventDecoder()); + register(49, new ChatEventDecoder()); + register(56, new CommandEventDecoder()); + register(123, new SwitchItemEventDecoder()); - register(181, new FirstObjectActionEventDecoder()); - register(241, new SecondObjectActionEventDecoder()); - register(50, new ThirdObjectActionEventDecoder()); + register(181, new FirstObjectActionEventDecoder()); + register(241, new SecondObjectActionEventDecoder()); + register(50, new ThirdObjectActionEventDecoder()); - register(203, new FirstItemOptionEventDecoder()); - register(24, new SecondItemOptionEventDecoder()); - register(161, new ThirdItemOptionEventDecoder()); - register(228, new FourthItemOptionEventDecoder()); - register(4, new FifthItemOptionEventDecoder()); + register(203, new FirstItemOptionEventDecoder()); + register(24, new SecondItemOptionEventDecoder()); + register(161, new ThirdItemOptionEventDecoder()); + register(228, new FourthItemOptionEventDecoder()); + register(4, new FifthItemOptionEventDecoder()); - register(3, new FirstItemActionEventDecoder()); - register(177, new SecondItemActionEventDecoder()); - register(91, new ThirdItemActionEventDecoder()); - register(231, new FourthItemActionEventDecoder()); - register(158, new FifthItemActionEventDecoder()); + register(3, new FirstItemActionEventDecoder()); + register(177, new SecondItemActionEventDecoder()); + register(91, new ThirdItemActionEventDecoder()); + register(231, new FourthItemActionEventDecoder()); + register(158, new FifthItemActionEventDecoder()); - register(79, new ButtonEventDecoder()); - register(110, new ClosedInterfaceEventDecoder()); - register(75, new EnteredAmountEventDecoder()); - register(226, new DialogueContinueEventDecoder()); + register(79, new ButtonEventDecoder()); + register(110, new ClosedInterfaceEventDecoder()); + register(75, new EnteredAmountEventDecoder()); + register(226, new DialogueContinueEventDecoder()); - register(1, new ItemOnItemEventDecoder()); - register(36, new MagicOnItemEventDecoder()); + register(1, new ItemOnItemEventDecoder()); + register(36, new MagicOnItemEventDecoder()); - register(187, new FocusUpdateEventDecoder()); - register(19, new MouseClickEventDecoder()); - register(140, new ArrowKeyEventDecoder()); - register(176, new PrivacyOptionEventDecoder()); + register(187, new FocusUpdateEventDecoder()); + register(19, new MouseClickEventDecoder()); + register(140, new ArrowKeyEventDecoder()); + register(176, new PrivacyOptionEventDecoder()); - SpamPacketEventDecoder spamEventDecoder = new SpamPacketEventDecoder(); - register(40, spamEventDecoder); - register(244, spamEventDecoder); + SpamPacketEventDecoder spamEventDecoder = new SpamPacketEventDecoder(); + register(40, spamEventDecoder); + register(244, spamEventDecoder); - register(67, new FirstNpcActionEventDecoder()); - register(112, new SecondNpcActionEventDecoder()); - register(13, new ThirdNpcActionEventDecoder()); - register(71, new TakeTileItemEventDecoder()); - register(152, new ItemOnObjectEventDecoder()); + register(67, new FirstNpcActionEventDecoder()); + register(112, new SecondNpcActionEventDecoder()); + register(13, new ThirdNpcActionEventDecoder()); + register(71, new TakeTileItemEventDecoder()); + register(152, new ItemOnObjectEventDecoder()); - register(245, new FirstPlayerActionEventDecoder()); - register(233, new SecondPlayerActionEventDecoder()); - register(194, new ThirdPlayerActionEventDecoder()); - register(116, new FourthPlayerActionEventDecoder()); - register(45, new FifthPlayerActionEventDecoder()); + register(245, new FirstPlayerActionEventDecoder()); + register(233, new SecondPlayerActionEventDecoder()); + register(194, new ThirdPlayerActionEventDecoder()); + register(116, new FourthPlayerActionEventDecoder()); + register(45, new FifthPlayerActionEventDecoder()); - register(120, new AddFriendEventDecoder()); - register(217, new AddIgnoreEventDecoder()); - register(141, new RemoveFriendEventDecoder()); - register(160, new RemoveIgnoreEventDecoder()); - register(227, new PrivateMessageEventDecoder()); + register(120, new AddFriendEventDecoder()); + register(217, new AddIgnoreEventDecoder()); + register(141, new RemoveFriendEventDecoder()); + register(160, new RemoveIgnoreEventDecoder()); + register(227, new PrivateMessageEventDecoder()); - // register encoders - register(IdAssignmentEvent.class, new IdAssignmentEventEncoder()); - register(RegionChangeEvent.class, new RegionChangeEventEncoder()); - register(ServerMessageEvent.class, new ServerMessageEventEncoder()); - register(PlayerSynchronizationEvent.class, new PlayerSynchronizationEventEncoder()); - register(OpenInterfaceEvent.class, new OpenInterfaceEventEncoder()); - register(CloseInterfaceEvent.class, new CloseInterfaceEventEncoder()); - register(SwitchTabInterfaceEvent.class, new SwitchTabInterfaceEventEncoder()); - register(LogoutEvent.class, new LogoutEventEncoder()); - register(UpdateItemsEvent.class, new UpdateItemsEventEncoder()); - register(UpdateSlottedItemsEvent.class, new UpdateSlottedItemsEventEncoder()); - register(UpdateSkillEvent.class, new UpdateSkillEventEncoder()); - register(OpenInterfaceSidebarEvent.class, new OpenInterfaceSidebarEventEncoder()); - register(EnterAmountEvent.class, new EnterAmountEventEncoder()); - register(SetWidgetTextEvent.class, new SetWidgetTextEventEncoder()); - register(NpcSynchronizationEvent.class, new NpcSynchronizationEventEncoder()); - register(SetWidgetVisibilityEvent.class, new SetWidgetVisibilityEventEncoder()); - register(SetWidgetItemModelEvent.class, new SetWidgetItemModelEventEncoder()); - register(SetWidgetNpcModelEvent.class, new SetWidgetNpcModelEventEncoder()); - register(SetWidgetPlayerModelEvent.class, new SetWidgetPlayerModelEventEncoder()); - register(SetWidgetModelAnimationEvent.class, new SetWidgetModelAnimationEventEncoder()); - register(ConfigEvent.class, new ConfigEventEncoder()); - register(DisplayTabInterfaceEvent.class, new DisplayTabInterfaceEventEncoder()); - register(PositionEvent.class, new PositionEventEncoder()); - register(UpdateRunEnergyEvent.class, new UpdateRunEnergyEventEncoder()); - register(PrivacyOptionEvent.class, new PrivacyOptionEventEncoder()); - register(OpenDialogueInterfaceEvent.class, new OpenDialogueInterfaceEventEncoder()); - register(UpdateWeightEvent.class, new UpdateWeightEventEncoder()); - register(SetPlayerActionEvent.class, new SetPlayerActionEventEncoder()); - register(DisplayCrossbonesEvent.class, new DisplayCrossbonesEventEncoder()); + // register encoders + register(IdAssignmentEvent.class, new IdAssignmentEventEncoder()); + register(RegionChangeEvent.class, new RegionChangeEventEncoder()); + register(ServerMessageEvent.class, new ServerMessageEventEncoder()); + register(PlayerSynchronizationEvent.class, new PlayerSynchronizationEventEncoder()); + register(OpenInterfaceEvent.class, new OpenInterfaceEventEncoder()); + register(CloseInterfaceEvent.class, new CloseInterfaceEventEncoder()); + register(SwitchTabInterfaceEvent.class, new SwitchTabInterfaceEventEncoder()); + register(LogoutEvent.class, new LogoutEventEncoder()); + register(UpdateItemsEvent.class, new UpdateItemsEventEncoder()); + register(UpdateSlottedItemsEvent.class, new UpdateSlottedItemsEventEncoder()); + register(UpdateSkillEvent.class, new UpdateSkillEventEncoder()); + register(OpenInterfaceSidebarEvent.class, new OpenInterfaceSidebarEventEncoder()); + register(EnterAmountEvent.class, new EnterAmountEventEncoder()); + register(SetWidgetTextEvent.class, new SetWidgetTextEventEncoder()); + register(NpcSynchronizationEvent.class, new NpcSynchronizationEventEncoder()); + register(SetWidgetVisibilityEvent.class, new SetWidgetVisibilityEventEncoder()); + register(SetWidgetItemModelEvent.class, new SetWidgetItemModelEventEncoder()); + register(SetWidgetNpcModelEvent.class, new SetWidgetNpcModelEventEncoder()); + register(SetWidgetPlayerModelEvent.class, new SetWidgetPlayerModelEventEncoder()); + register(SetWidgetModelAnimationEvent.class, new SetWidgetModelAnimationEventEncoder()); + register(ConfigEvent.class, new ConfigEventEncoder()); + register(DisplayTabInterfaceEvent.class, new DisplayTabInterfaceEventEncoder()); + register(PositionEvent.class, new PositionEventEncoder()); + register(UpdateRunEnergyEvent.class, new UpdateRunEnergyEventEncoder()); + register(PrivacyOptionEvent.class, new PrivacyOptionEventEncoder()); + register(OpenDialogueInterfaceEvent.class, new OpenDialogueInterfaceEventEncoder()); + register(UpdateWeightEvent.class, new UpdateWeightEventEncoder()); + register(SetPlayerActionEvent.class, new SetPlayerActionEventEncoder()); + register(DisplayCrossbonesEvent.class, new DisplayCrossbonesEventEncoder()); - register(AddGlobalTileItemEvent.class, new AddGlobalTileItemEventEncoder()); - register(AddTileItemEvent.class, new AddTileItemEventEncoder()); - register(UpdateTileItemEvent.class, new UpdateTileItemEventEncoder()); - register(RemoveTileItemEvent.class, new RemoveTileItemEventEncoder()); + register(AddGlobalTileItemEvent.class, new AddGlobalTileItemEventEncoder()); + register(AddTileItemEvent.class, new AddTileItemEventEncoder()); + register(UpdateTileItemEvent.class, new UpdateTileItemEventEncoder()); + register(RemoveTileItemEvent.class, new RemoveTileItemEventEncoder()); - register(ForwardPrivateMessageEvent.class, new ForwardPrivateMessageEventEncoder()); - register(FriendServerStatusEvent.class, new FriendServerStatusEventEncoder()); - register(IgnoreListEvent.class, new IgnoreListEventEncoder()); - register(SendFriendEvent.class, new SendFriendEventEncoder()); - } + register(ForwardPrivateMessageEvent.class, new ForwardPrivateMessageEventEncoder()); + register(FriendServerStatusEvent.class, new FriendServerStatusEventEncoder()); + register(IgnoreListEvent.class, new IgnoreListEventEncoder()); + register(SendFriendEvent.class, new SendFriendEventEncoder()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/RemoveFriendEventDecoder.java b/src/org/apollo/net/release/r377/RemoveFriendEventDecoder.java index a24e4144..b8321d4b 100644 --- a/src/org/apollo/net/release/r377/RemoveFriendEventDecoder.java +++ b/src/org/apollo/net/release/r377/RemoveFriendEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class RemoveFriendEventDecoder extends EventDecoder { - @Override - public RemoveFriendEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new RemoveFriendEvent(username); - } + @Override + public RemoveFriendEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new RemoveFriendEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/RemoveIgnoreEventDecoder.java b/src/org/apollo/net/release/r377/RemoveIgnoreEventDecoder.java index 2c289eea..fa3c3ff1 100644 --- a/src/org/apollo/net/release/r377/RemoveIgnoreEventDecoder.java +++ b/src/org/apollo/net/release/r377/RemoveIgnoreEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.util.NameUtil; */ public final class RemoveIgnoreEventDecoder extends EventDecoder { - @Override - public RemoveIgnoreEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); - return new RemoveIgnoreEvent(username); - } + @Override + public RemoveIgnoreEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + String username = NameUtil.decodeBase37(reader.getSigned(DataType.LONG)); + return new RemoveIgnoreEvent(username); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/RemoveTileItemEventEncoder.java b/src/org/apollo/net/release/r377/RemoveTileItemEventEncoder.java index de009b8a..1da69970 100644 --- a/src/org/apollo/net/release/r377/RemoveTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r377/RemoveTileItemEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class RemoveTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(RemoveTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(208); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); - builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(RemoveTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(208); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getId()); + builder.put(DataType.BYTE, DataTransformation.ADD, event.getPositionOffset()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SecondItemActionEventDecoder.java b/src/org/apollo/net/release/r377/SecondItemActionEventDecoder.java index 2fd9e30c..16609c08 100644 --- a/src/org/apollo/net/release/r377/SecondItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/SecondItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondItemActionEventDecoder extends EventDecoder { - @Override - public SecondItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SecondItemActionEvent(interfaceId, id, slot); - } + @Override + public SecondItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SecondItemActionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SecondItemOptionEventDecoder.java b/src/org/apollo/net/release/r377/SecondItemOptionEventDecoder.java index 583a0137..46069474 100644 --- a/src/org/apollo/net/release/r377/SecondItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/SecondItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class SecondItemOptionEventDecoder extends EventDecoder { - @Override - public SecondItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public SecondItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new SecondItemOptionEvent(interfaceId, id, slot); - } + return new SecondItemOptionEvent(interfaceId, id, slot); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SecondNpcActionEventDecoder.java b/src/org/apollo/net/release/r377/SecondNpcActionEventDecoder.java index 2288fe43..41400a82 100644 --- a/src/org/apollo/net/release/r377/SecondNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/SecondNpcActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondNpcActionEventDecoder extends EventDecoder { - @Override - public SecondNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SecondNpcActionEvent(index); - } + @Override + public SecondNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SecondNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SecondObjectActionEventDecoder.java b/src/org/apollo/net/release/r377/SecondObjectActionEventDecoder.java index 2b2edb4f..2d6a4478 100644 --- a/src/org/apollo/net/release/r377/SecondObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/SecondObjectActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondObjectActionEventDecoder extends EventDecoder { - @Override - public SecondObjectActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT); - int x = (int) reader.getUnsigned(DataType.SHORT); - int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new SecondObjectActionEvent(id, new Position(x, y)); - } + @Override + public SecondObjectActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT); + int x = (int) reader.getUnsigned(DataType.SHORT); + int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new SecondObjectActionEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SecondPlayerActionEventDecoder.java b/src/org/apollo/net/release/r377/SecondPlayerActionEventDecoder.java index 11160fcf..44945293 100644 --- a/src/org/apollo/net/release/r377/SecondPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/SecondPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class SecondPlayerActionEventDecoder extends EventDecoder { - @Override - public SecondPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new SecondPlayerActionEvent(index); - } + @Override + public SecondPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new SecondPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SendFriendEventEncoder.java b/src/org/apollo/net/release/r377/SendFriendEventEncoder.java index efb0f60e..d773552d 100644 --- a/src/org/apollo/net/release/r377/SendFriendEventEncoder.java +++ b/src/org/apollo/net/release/r377/SendFriendEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.util.NameUtil; */ public final class SendFriendEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SendFriendEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(78); - builder.put(DataType.LONG, NameUtil.encodeBase37(event.getUsername())); - builder.put(DataType.BYTE, event.getWorld()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SendFriendEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(78); + builder.put(DataType.LONG, NameUtil.encodeBase37(event.getUsername())); + builder.put(DataType.BYTE, event.getWorld()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ServerMessageEventEncoder.java b/src/org/apollo/net/release/r377/ServerMessageEventEncoder.java index 4667bb59..c7e4d1c5 100644 --- a/src/org/apollo/net/release/r377/ServerMessageEventEncoder.java +++ b/src/org/apollo/net/release/r377/ServerMessageEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class ServerMessageEventEncoder extends EventEncoder { - @Override - public GamePacket encode(ServerMessageEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(63, PacketType.VARIABLE_BYTE); - builder.putString(event.getMessage()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(ServerMessageEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(63, PacketType.VARIABLE_BYTE); + builder.putString(event.getMessage()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SetPlayerActionEventEncoder.java b/src/org/apollo/net/release/r377/SetPlayerActionEventEncoder.java index acd89af2..e6a3fd84 100644 --- a/src/org/apollo/net/release/r377/SetPlayerActionEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetPlayerActionEventEncoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventEncoder; */ public final class SetPlayerActionEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetPlayerActionEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(157, PacketType.VARIABLE_BYTE); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getSlot()); - builder.putString(event.getText()); - builder.put(DataType.BYTE, event.isPrimaryAction() ? 0 : 1); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SetPlayerActionEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(157, PacketType.VARIABLE_BYTE); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getSlot()); + builder.putString(event.getText()); + builder.put(DataType.BYTE, event.isPrimaryAction() ? 0 : 1); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SetWidgetItemModelEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetItemModelEventEncoder.java index cfb4a6a6..1efbe587 100644 --- a/src/org/apollo/net/release/r377/SetWidgetItemModelEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetItemModelEventEncoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetItemModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetItemModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(21); + @Override + public GamePacket encode(SetWidgetItemModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(21); - builder.put(DataType.SHORT, event.getZoom()); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getModelId()); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + builder.put(DataType.SHORT, event.getZoom()); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getModelId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SetWidgetModelAnimationEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetModelAnimationEventEncoder.java index 4ce751b5..f9fee285 100644 --- a/src/org/apollo/net/release/r377/SetWidgetModelAnimationEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetModelAnimationEventEncoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetModelAnimationEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetModelAnimationEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(2); + @Override + public GamePacket encode(SetWidgetModelAnimationEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(2); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getAnimation() & 0xFFFF); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getAnimation() & 0xFFFF); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SetWidgetNpcModelEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetNpcModelEventEncoder.java index cd65e9f0..86a09edc 100644 --- a/src/org/apollo/net/release/r377/SetWidgetNpcModelEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetNpcModelEventEncoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetNpcModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetNpcModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(162); + @Override + public GamePacket encode(SetWidgetNpcModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(162); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getModelId()); - builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getModelId()); + builder.put(DataType.SHORT, DataOrder.LITTLE, event.getInterfaceId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r377/SetWidgetPlayerModelEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetPlayerModelEventEncoder.java index 449d22f4..97c6a219 100644 --- a/src/org/apollo/net/release/r377/SetWidgetPlayerModelEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetPlayerModelEventEncoder.java @@ -15,11 +15,11 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetPlayerModelEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetPlayerModelEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(255); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SetWidgetPlayerModelEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(255); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SetWidgetTextEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetTextEventEncoder.java index c2107777..2290a4a4 100644 --- a/src/org/apollo/net/release/r377/SetWidgetTextEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetTextEventEncoder.java @@ -16,12 +16,12 @@ import org.apollo.net.release.EventEncoder; */ public final class SetWidgetTextEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetTextEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(232, PacketType.VARIABLE_SHORT); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); - builder.putString(event.getText()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SetWidgetTextEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(232, PacketType.VARIABLE_SHORT); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, event.getInterfaceId()); + builder.putString(event.getText()); + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r377/SetWidgetVisibilityEventEncoder.java b/src/org/apollo/net/release/r377/SetWidgetVisibilityEventEncoder.java index c1a998f4..c4d56a52 100644 --- a/src/org/apollo/net/release/r377/SetWidgetVisibilityEventEncoder.java +++ b/src/org/apollo/net/release/r377/SetWidgetVisibilityEventEncoder.java @@ -13,14 +13,14 @@ import org.apollo.net.release.EventEncoder; */ final class SetWidgetVisibilityEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SetWidgetVisibilityEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(82); + @Override + public GamePacket encode(SetWidgetVisibilityEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(82); - builder.put(DataType.BYTE, event.isVisible() ? 0 : 1); - builder.put(DataType.SHORT, event.getWidgetId()); + builder.put(DataType.BYTE, event.isVisible() ? 0 : 1); + builder.put(DataType.SHORT, event.getWidgetId()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SpamPacketEventDecoder.java b/src/org/apollo/net/release/r377/SpamPacketEventDecoder.java index 8aae423b..115db465 100644 --- a/src/org/apollo/net/release/r377/SpamPacketEventDecoder.java +++ b/src/org/apollo/net/release/r377/SpamPacketEventDecoder.java @@ -11,9 +11,9 @@ import org.apollo.net.release.EventDecoder; */ public final class SpamPacketEventDecoder extends EventDecoder { - @Override - public SpamPacketEvent decode(GamePacket packet) { - return new SpamPacketEvent(packet.getPayload().array()); - } + @Override + public SpamPacketEvent decode(GamePacket packet) { + return new SpamPacketEvent(packet.getPayload().array()); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/SwitchItemEventDecoder.java b/src/org/apollo/net/release/r377/SwitchItemEventDecoder.java index 07fcc4cc..b6ad5b23 100644 --- a/src/org/apollo/net/release/r377/SwitchItemEventDecoder.java +++ b/src/org/apollo/net/release/r377/SwitchItemEventDecoder.java @@ -15,14 +15,14 @@ import org.apollo.net.release.EventDecoder; */ public final class SwitchItemEventDecoder extends EventDecoder { - @Override - public SwitchItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int newSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - boolean inserting = reader.getUnsigned(DataType.BYTE, DataTransformation.ADD) == 1; - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int oldSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new SwitchItemEvent(interfaceId, inserting, oldSlot, newSlot); - } + @Override + public SwitchItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int newSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + boolean inserting = reader.getUnsigned(DataType.BYTE, DataTransformation.ADD) == 1; + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int oldSlot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new SwitchItemEvent(interfaceId, inserting, oldSlot, newSlot); + } } diff --git a/src/org/apollo/net/release/r377/SwitchTabInterfaceEventEncoder.java b/src/org/apollo/net/release/r377/SwitchTabInterfaceEventEncoder.java index a821dbe8..c7381f03 100644 --- a/src/org/apollo/net/release/r377/SwitchTabInterfaceEventEncoder.java +++ b/src/org/apollo/net/release/r377/SwitchTabInterfaceEventEncoder.java @@ -14,12 +14,12 @@ import org.apollo.net.release.EventEncoder; */ public final class SwitchTabInterfaceEventEncoder extends EventEncoder { - @Override - public GamePacket encode(SwitchTabInterfaceEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(10); - builder.put(DataType.BYTE, DataTransformation.SUBTRACT, event.getTabId()); - builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(SwitchTabInterfaceEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(10); + builder.put(DataType.BYTE, DataTransformation.SUBTRACT, event.getTabId()); + builder.put(DataType.SHORT, DataTransformation.ADD, event.getInterfaceId()); + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r377/TakeTileItemEventDecoder.java b/src/org/apollo/net/release/r377/TakeTileItemEventDecoder.java index 2234cb2d..f09296d0 100644 --- a/src/org/apollo/net/release/r377/TakeTileItemEventDecoder.java +++ b/src/org/apollo/net/release/r377/TakeTileItemEventDecoder.java @@ -16,13 +16,13 @@ import org.apollo.net.release.EventDecoder; */ public final class TakeTileItemEventDecoder extends EventDecoder { - @Override - public TakeTileItemEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - return new TakeTileItemEvent(id, new Position(x, y)); - } + @Override + public TakeTileItemEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + return new TakeTileItemEvent(id, new Position(x, y)); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ThirdItemActionEventDecoder.java b/src/org/apollo/net/release/r377/ThirdItemActionEventDecoder.java index 80c7c4c6..01937999 100644 --- a/src/org/apollo/net/release/r377/ThirdItemActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/ThirdItemActionEventDecoder.java @@ -15,13 +15,13 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdItemActionEventDecoder extends EventDecoder { - @Override - public ThirdItemActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT); - return new ThirdItemActionEvent(interfaceId, id, slot); - } + @Override + public ThirdItemActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT); + return new ThirdItemActionEvent(interfaceId, id, slot); + } } diff --git a/src/org/apollo/net/release/r377/ThirdItemOptionEventDecoder.java b/src/org/apollo/net/release/r377/ThirdItemOptionEventDecoder.java index f106c779..c007c4a0 100644 --- a/src/org/apollo/net/release/r377/ThirdItemOptionEventDecoder.java +++ b/src/org/apollo/net/release/r377/ThirdItemOptionEventDecoder.java @@ -15,15 +15,15 @@ import org.apollo.net.release.EventDecoder; */ final class ThirdItemOptionEventDecoder extends EventDecoder { - @Override - public ThirdItemOptionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public ThirdItemOptionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new ThirdItemOptionEvent(interfaceId, id, slot); - } + return new ThirdItemOptionEvent(interfaceId, id, slot); + } } diff --git a/src/org/apollo/net/release/r377/ThirdNpcActionEventDecoder.java b/src/org/apollo/net/release/r377/ThirdNpcActionEventDecoder.java index 2cd89941..20363334 100644 --- a/src/org/apollo/net/release/r377/ThirdNpcActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/ThirdNpcActionEventDecoder.java @@ -15,11 +15,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdNpcActionEventDecoder extends EventDecoder { - @Override - public ThirdNpcActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new ThirdNpcActionEvent(index); - } + @Override + public ThirdNpcActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + return new ThirdNpcActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/ThirdObjectActionEventDecoder.java b/src/org/apollo/net/release/r377/ThirdObjectActionEventDecoder.java index e6b74f2a..7bb0b338 100644 --- a/src/org/apollo/net/release/r377/ThirdObjectActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/ThirdObjectActionEventDecoder.java @@ -16,13 +16,13 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdObjectActionEventDecoder extends EventDecoder { - @Override - public ThirdObjectActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); - int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - return new ThirdObjectActionEvent(id, new Position(x, y)); - } + @Override + public ThirdObjectActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int y = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD); + int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + return new ThirdObjectActionEvent(id, new Position(x, y)); + } } diff --git a/src/org/apollo/net/release/r377/ThirdPlayerActionEventDecoder.java b/src/org/apollo/net/release/r377/ThirdPlayerActionEventDecoder.java index f5d5bb93..9e1a8ab1 100644 --- a/src/org/apollo/net/release/r377/ThirdPlayerActionEventDecoder.java +++ b/src/org/apollo/net/release/r377/ThirdPlayerActionEventDecoder.java @@ -14,11 +14,11 @@ import org.apollo.net.release.EventDecoder; */ public final class ThirdPlayerActionEventDecoder extends EventDecoder { - @Override - public ThirdPlayerActionEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); - int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); - return new ThirdPlayerActionEvent(index); - } + @Override + public ThirdPlayerActionEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); + int index = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE); + return new ThirdPlayerActionEvent(index); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/UpdateItemsEventEncoder.java b/src/org/apollo/net/release/r377/UpdateItemsEventEncoder.java index c56db2cb..17b86a68 100644 --- a/src/org/apollo/net/release/r377/UpdateItemsEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateItemsEventEncoder.java @@ -17,30 +17,30 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateItemsEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateItemsEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(206, PacketType.VARIABLE_SHORT); + @Override + public GamePacket encode(UpdateItemsEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(206, PacketType.VARIABLE_SHORT); - Item[] items = event.getItems(); + Item[] items = event.getItems(); - builder.put(DataType.SHORT, event.getInterfaceId()); - builder.put(DataType.SHORT, items.length); + builder.put(DataType.SHORT, event.getInterfaceId()); + builder.put(DataType.SHORT, items.length); - for (Item item : items) { - int id = item == null ? -1 : item.getId(); - int amount = item == null ? 0 : item.getAmount(); + for (Item item : items) { + int id = item == null ? -1 : item.getId(); + int amount = item == null ? 0 : item.getAmount(); - builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, id + 1); + builder.put(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD, id + 1); - if (amount > 254) { - builder.put(DataType.BYTE, DataTransformation.NEGATE, 255); - builder.put(DataType.INT, DataOrder.LITTLE, amount); - } else { - builder.put(DataType.BYTE, DataTransformation.NEGATE, amount); - } - } - - return builder.toGamePacket(); + if (amount > 254) { + builder.put(DataType.BYTE, DataTransformation.NEGATE, 255); + builder.put(DataType.INT, DataOrder.LITTLE, amount); + } else { + builder.put(DataType.BYTE, DataTransformation.NEGATE, amount); + } } + return builder.toGamePacket(); + } + } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/UpdateRunEnergyEventEncoder.java b/src/org/apollo/net/release/r377/UpdateRunEnergyEventEncoder.java index e10d8ca3..273ff198 100644 --- a/src/org/apollo/net/release/r377/UpdateRunEnergyEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateRunEnergyEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateRunEnergyEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateRunEnergyEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(125); - builder.put(DataType.BYTE, event.getEnergy()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateRunEnergyEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(125); + builder.put(DataType.BYTE, event.getEnergy()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/UpdateSkillEventEncoder.java b/src/org/apollo/net/release/r377/UpdateSkillEventEncoder.java index 53fc23ba..48f50d09 100644 --- a/src/org/apollo/net/release/r377/UpdateSkillEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateSkillEventEncoder.java @@ -15,16 +15,16 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateSkillEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateSkillEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(49); - Skill skill = event.getSkill(); + @Override + public GamePacket encode(UpdateSkillEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(49); + Skill skill = event.getSkill(); - builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getId()); - builder.put(DataType.BYTE, skill.getCurrentLevel()); - builder.put(DataType.INT, (int) skill.getExperience()); + builder.put(DataType.BYTE, DataTransformation.NEGATE, event.getId()); + builder.put(DataType.BYTE, skill.getCurrentLevel()); + builder.put(DataType.INT, (int) skill.getExperience()); - return builder.toGamePacket(); - } + return builder.toGamePacket(); + } } diff --git a/src/org/apollo/net/release/r377/UpdateSlottedItemsEventEncoder.java b/src/org/apollo/net/release/r377/UpdateSlottedItemsEventEncoder.java index b4e73150..a67a7c3b 100644 --- a/src/org/apollo/net/release/r377/UpdateSlottedItemsEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateSlottedItemsEventEncoder.java @@ -16,31 +16,31 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateSlottedItemsEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateSlottedItemsEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(134, PacketType.VARIABLE_SHORT); - SlottedItem[] items = event.getSlottedItems(); + @Override + public GamePacket encode(UpdateSlottedItemsEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(134, PacketType.VARIABLE_SHORT); + SlottedItem[] items = event.getSlottedItems(); - builder.put(DataType.SHORT, event.getInterfaceId()); + builder.put(DataType.SHORT, event.getInterfaceId()); - for (SlottedItem slottedItem : items) { - builder.putSmart(slottedItem.getSlot()); + for (SlottedItem slottedItem : items) { + builder.putSmart(slottedItem.getSlot()); - Item item = slottedItem.getItem(); - int id = item == null ? -1 : item.getId(); - int amount = item == null ? 0 : item.getAmount(); + Item item = slottedItem.getItem(); + int id = item == null ? -1 : item.getId(); + int amount = item == null ? 0 : item.getAmount(); - builder.put(DataType.SHORT, id + 1); + builder.put(DataType.SHORT, id + 1); - if (amount > 254) { - builder.put(DataType.BYTE, 255); - builder.put(DataType.INT, amount); - } else { - builder.put(DataType.BYTE, amount); - } - } - - return builder.toGamePacket(); + if (amount > 254) { + builder.put(DataType.BYTE, 255); + builder.put(DataType.INT, amount); + } else { + builder.put(DataType.BYTE, amount); + } } + return builder.toGamePacket(); + } + } diff --git a/src/org/apollo/net/release/r377/UpdateTileItemEventEncoder.java b/src/org/apollo/net/release/r377/UpdateTileItemEventEncoder.java index f0f62ca5..e4b9db76 100644 --- a/src/org/apollo/net/release/r377/UpdateTileItemEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateTileItemEventEncoder.java @@ -13,14 +13,14 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateTileItemEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateTileItemEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(121); - builder.put(DataType.BYTE, event.getPositionOffset()); - builder.put(DataType.SHORT, event.getId()); - builder.put(DataType.SHORT, event.getPreviousAmount()); - builder.put(DataType.SHORT, event.getAmount()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateTileItemEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(121); + builder.put(DataType.BYTE, event.getPositionOffset()); + builder.put(DataType.SHORT, event.getId()); + builder.put(DataType.SHORT, event.getPreviousAmount()); + builder.put(DataType.SHORT, event.getAmount()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/UpdateWeightEventEncoder.java b/src/org/apollo/net/release/r377/UpdateWeightEventEncoder.java index dcc1d28b..e9dbff2f 100644 --- a/src/org/apollo/net/release/r377/UpdateWeightEventEncoder.java +++ b/src/org/apollo/net/release/r377/UpdateWeightEventEncoder.java @@ -13,11 +13,11 @@ import org.apollo.net.release.EventEncoder; */ public final class UpdateWeightEventEncoder extends EventEncoder { - @Override - public GamePacket encode(UpdateWeightEvent event) { - GamePacketBuilder builder = new GamePacketBuilder(174); - builder.put(DataType.SHORT, event.getWeight()); - return builder.toGamePacket(); - } + @Override + public GamePacket encode(UpdateWeightEvent event) { + GamePacketBuilder builder = new GamePacketBuilder(174); + builder.put(DataType.SHORT, event.getWeight()); + return builder.toGamePacket(); + } } \ No newline at end of file diff --git a/src/org/apollo/net/release/r377/WalkEventDecoder.java b/src/org/apollo/net/release/r377/WalkEventDecoder.java index 1b6f03f8..f00f7bb6 100644 --- a/src/org/apollo/net/release/r377/WalkEventDecoder.java +++ b/src/org/apollo/net/release/r377/WalkEventDecoder.java @@ -16,34 +16,34 @@ import org.apollo.net.release.EventDecoder; */ public final class WalkEventDecoder extends EventDecoder { - @Override - public WalkEvent decode(GamePacket packet) { - GamePacketReader reader = new GamePacketReader(packet); + @Override + public WalkEvent decode(GamePacket packet) { + GamePacketReader reader = new GamePacketReader(packet); - int length = packet.getLength(); - if (packet.getOpcode() == 213) { - length -= 14; // strip off anti-cheat data - } - - int steps = (length - 5) / 2; - int[][] path = new int[steps][2]; - - int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - boolean run = reader.getUnsigned(DataType.BYTE) == 1; - int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); - - for (int i = 0; i < steps; i++) { - path[i][0] = (int) reader.getSigned(DataType.BYTE); - path[i][1] = (int) reader.getSigned(DataType.BYTE, DataTransformation.SUBTRACT); - } - - Position[] positions = new Position[steps + 1]; - positions[0] = new Position(x, y); - for (int i = 0; i < steps; i++) { - positions[i + 1] = new Position(path[i][0] + x, path[i][1] + y); - } - - return new WalkEvent(positions, run); + int length = packet.getLength(); + if (packet.getOpcode() == 213) { + length -= 14; // strip off anti-cheat data } + int steps = (length - 5) / 2; + int[][] path = new int[steps][2]; + + int x = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + boolean run = reader.getUnsigned(DataType.BYTE) == 1; + int y = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD); + + for (int i = 0; i < steps; i++) { + path[i][0] = (int) reader.getSigned(DataType.BYTE); + path[i][1] = (int) reader.getSigned(DataType.BYTE, DataTransformation.SUBTRACT); + } + + Position[] positions = new Position[steps + 1]; + positions[0] = new Position(x, y); + for (int i = 0; i < steps; i++) { + positions[i + 1] = new Position(path[i][0] + x, path[i][1] + y); + } + + return new WalkEvent(positions, run); + } + } diff --git a/src/org/apollo/net/session/GameSession.java b/src/org/apollo/net/session/GameSession.java index c87ff0fd..9d87507f 100644 --- a/src/org/apollo/net/session/GameSession.java +++ b/src/org/apollo/net/session/GameSession.java @@ -25,109 +25,109 @@ import org.apollo.game.model.entity.Player; */ public final class GameSession extends Session { - /** - * The logger for this class. - */ - private static final Logger logger = Logger.getLogger(GameSession.class.getName()); + /** + * The logger for this class. + */ + private static final Logger logger = Logger.getLogger(GameSession.class.getName()); - /** - * The server context. - */ - private final ServerContext context; + /** + * The server context. + */ + private final ServerContext context; - /** - * The queue of pending {@link Event}s. - */ - private final BlockingQueue eventQueue = new ArrayBlockingQueue(GameConstants.EVENTS_PER_PULSE); + /** + * The queue of pending {@link Event}s. + */ + private final BlockingQueue eventQueue = new ArrayBlockingQueue<>(GameConstants.EVENTS_PER_PULSE); - /** - * The player. - */ - private final Player player; + /** + * The player. + */ + private final Player player; - /** - * Creates a login session for the specified channel. - * - * @param channel The channel. - * @param context The server context. - * @param player The player. - */ - public GameSession(Channel channel, ServerContext context, Player player) { - super(channel); - this.context = context; - this.player = player; + /** + * Creates a login session for the specified channel. + * + * @param channel The channel. + * @param context The server context. + * @param player The player. + */ + public GameSession(Channel channel, ServerContext context, Player player) { + super(channel); + this.context = context; + this.player = player; + } + + @Override + public void destroy() { + context.getService(GameService.class).unregisterPlayer(player); + } + + /** + * Encodes and dispatches the specified event. + * + * @param event The event. + */ + public void dispatchEvent(Event event) { + Channel channel = getChannel(); + if (channel.isActive() && channel.isOpen()) { + ChannelFuture future = channel.writeAndFlush(event); + if (event.getClass() == LogoutEvent.class) { + future.addListener(ChannelFutureListener.CLOSE); + } } + } - @Override - public void destroy() { - context.getService(GameService.class).unregisterPlayer(player); - } + /** + * Handles pending events for this session. + * + * @param chainGroup The event chain group. + */ + @SuppressWarnings("unchecked") + public void handlePendingEvents(EventHandlerChainGroup chainGroup) { + Event event; + while ((event = eventQueue.poll()) != null) { + // this lookup code really sucks! + // TODO improve it! + Class eventType = event.getClass(); + EventHandlerChain chain = (EventHandlerChain) chainGroup.getChain(eventType); - /** - * Encodes and dispatches the specified event. - * - * @param event The event. - */ - public void dispatchEvent(Event event) { - Channel channel = getChannel(); - if (channel.isActive() && channel.isOpen()) { - ChannelFuture future = channel.writeAndFlush(event); - if (event.getClass() == LogoutEvent.class) { - future.addListener(ChannelFutureListener.CLOSE); - } - } - } - - /** - * Handles pending events for this session. - * - * @param chainGroup The event chain group. - */ - @SuppressWarnings("unchecked") - public void handlePendingEvents(EventHandlerChainGroup chainGroup) { - Event event; - while ((event = eventQueue.poll()) != null) { - // this lookup code really sucks! - // TODO improve it! - Class eventType = event.getClass(); - EventHandlerChain chain = (EventHandlerChain) chainGroup.getChain(eventType); - - while (chain == null && eventType != null) { - eventType = (Class) eventType.getSuperclass(); - if (eventType == Event.class) { - eventType = null; - } else { - chain = (EventHandlerChain) chainGroup.getChain(eventType); - } - } - - if (chain != null) { - try { - chain.handle(player, event); - } catch (Exception ex) { - logger.log(Level.SEVERE, "Error handling event: ", ex); - } - } - } - } - - /** - * Handles a player saver response. - * - * @param success A flag indicating if the save was successful. - */ - public void handlePlayerSaverResponse(boolean success) { - context.getService(GameService.class).finalizePlayerUnregistration(player); - } - - @Override - public void messageReceived(Object message) { - Event event = (Event) message; - if (eventQueue.size() >= GameConstants.EVENTS_PER_PULSE) { - logger.warning("Too many events in queue for game session, dropping..."); + while (chain == null && eventType != null) { + eventType = (Class) eventType.getSuperclass(); + if (eventType == Event.class) { + eventType = null; } else { - eventQueue.add(event); + chain = (EventHandlerChain) chainGroup.getChain(eventType); } + } + + if (chain != null) { + try { + chain.handle(player, event); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Error handling event: ", ex); + } + } } + } + + /** + * Handles a player saver response. + * + * @param success A flag indicating if the save was successful. + */ + public void handlePlayerSaverResponse(boolean success) { + context.getService(GameService.class).finalizePlayerUnregistration(player); + } + + @Override + public void messageReceived(Object message) { + Event event = (Event) message; + if (eventQueue.size() >= GameConstants.EVENTS_PER_PULSE) { + logger.warning("Too many events in queue for game session, dropping..."); + } else { + eventQueue.add(event); + } + } } \ No newline at end of file diff --git a/src/org/apollo/net/session/LoginSession.java b/src/org/apollo/net/session/LoginSession.java index 875feca7..ff487a44 100644 --- a/src/org/apollo/net/session/LoginSession.java +++ b/src/org/apollo/net/session/LoginSession.java @@ -30,113 +30,113 @@ import org.apollo.security.IsaacRandomPair; */ public final class LoginSession extends Session { - /** - * The context of the {@link ApolloHandler}. - */ - private final ChannelHandlerContext channelContext; + /** + * The context of the {@link ApolloHandler}. + */ + private final ChannelHandlerContext channelContext; - /** - * The server context. - */ - private final ServerContext serverContext; + /** + * The server context. + */ + private final ServerContext serverContext; - /** - * Creates a login session for the specified channel. - * - * @param ctx The context of the {@link ApolloHandler}. - * @param serverContext The server context. - */ - public LoginSession(ChannelHandlerContext ctx, ServerContext serverContext) { - super(ctx.channel()); - this.channelContext = ctx; - this.serverContext = serverContext; - } + /** + * Creates a login session for the specified channel. + * + * @param ctx The context of the {@link ApolloHandler}. + * @param serverContext The server context. + */ + public LoginSession(ChannelHandlerContext ctx, ServerContext serverContext) { + super(ctx.channel()); + this.channelContext = ctx; + this.serverContext = serverContext; + } - @Override - public void destroy() { + @Override + public void destroy() { - } + } - /** - * Gets the release. - * - * @return The release. - */ - public Release getRelease() { - return serverContext.getRelease(); - } + /** + * Gets the release. + * + * @return The release. + */ + public Release getRelease() { + return serverContext.getRelease(); + } - /** - * Handles a login request. - * - * @param request The login request. - */ - private void handleLoginRequest(LoginRequest request) { - LoginService loginService = serverContext.getService(LoginService.class); - loginService.submitLoadRequest(this, request); - } + /** + * Handles a login request. + * + * @param request The login request. + */ + private void handleLoginRequest(LoginRequest request) { + LoginService loginService = serverContext.getService(LoginService.class); + loginService.submitLoadRequest(this, request); + } - /** - * Handles a response from the login service. - * - * @param request The request this response corresponds to. - * @param response The response. - */ - public void handlePlayerLoaderResponse(LoginRequest request, PlayerLoaderResponse response) { - GameService gameService = serverContext.getService(GameService.class); - Channel channel = getChannel(); + /** + * Handles a response from the login service. + * + * @param request The request this response corresponds to. + * @param response The response. + */ + public void handlePlayerLoaderResponse(LoginRequest request, PlayerLoaderResponse response) { + GameService gameService = serverContext.getService(GameService.class); + Channel channel = getChannel(); - int status = response.getStatus(); - Player player = response.getPlayer(); - int rights = player == null ? 0 : player.getPrivilegeLevel().toInteger(); - boolean log = false; + int status = response.getStatus(); + Player player = response.getPlayer(); + int rights = player == null ? 0 : player.getPrivilegeLevel().toInteger(); + boolean log = false; - if (player != null) { - GameSession session = new GameSession(channel, serverContext, player); - player.setSession(session, false /* TODO */); + if (player != null) { + GameSession session = new GameSession(channel, serverContext, player); + player.setSession(session, false /* TODO */); - RegistrationStatus registrationStatus = gameService.registerPlayer(player); + RegistrationStatus registrationStatus = gameService.registerPlayer(player); - if (registrationStatus != RegistrationStatus.OK) { - player = null; - rights = 0; - if (registrationStatus == RegistrationStatus.ALREADY_ONLINE) { - status = LoginConstants.STATUS_ACCOUNT_ONLINE; - } else { - status = LoginConstants.STATUS_SERVER_FULL; - } - } - } - - ChannelFuture future = channel.writeAndFlush(new LoginResponse(status, rights, log)); - destroy(); - - if (player != null) { - IsaacRandomPair randomPair = request.getRandomPair(); - Release release = serverContext.getRelease(); - - channel.pipeline().addFirst("eventEncoder", new GameEventEncoder(release)); - channel.pipeline().addBefore("eventEncoder", "gameEncoder", - new GamePacketEncoder(randomPair.getEncodingRandom())); - - channel.pipeline().addBefore("handler", "gameDecoder", - new GamePacketDecoder(randomPair.getDecodingRandom(), serverContext.getRelease())); - channel.pipeline().addAfter("gameDecoder", "eventDecoder", new GameEventDecoder(release)); - - channel.pipeline().remove("loginDecoder"); - channel.pipeline().remove("loginEncoder"); - - channelContext.attr(NetworkConstants.SESSION_KEY).set(player.getSession()); + if (registrationStatus != RegistrationStatus.OK) { + player = null; + rights = 0; + if (registrationStatus == RegistrationStatus.ALREADY_ONLINE) { + status = LoginConstants.STATUS_ACCOUNT_ONLINE; } else { - future.addListener(ChannelFutureListener.CLOSE); + status = LoginConstants.STATUS_SERVER_FULL; } + } } - @Override - public void messageReceived(Object message) { - if (message.getClass() == LoginRequest.class) { - handleLoginRequest((LoginRequest) message); - } + ChannelFuture future = channel.writeAndFlush(new LoginResponse(status, rights, log)); + destroy(); + + if (player != null) { + IsaacRandomPair randomPair = request.getRandomPair(); + Release release = serverContext.getRelease(); + + channel.pipeline().addFirst("eventEncoder", new GameEventEncoder(release)); + channel.pipeline().addBefore("eventEncoder", "gameEncoder", + new GamePacketEncoder(randomPair.getEncodingRandom())); + + channel.pipeline().addBefore("handler", "gameDecoder", + new GamePacketDecoder(randomPair.getDecodingRandom(), serverContext.getRelease())); + channel.pipeline().addAfter("gameDecoder", "eventDecoder", new GameEventDecoder(release)); + + channel.pipeline().remove("loginDecoder"); + channel.pipeline().remove("loginEncoder"); + + channelContext.attr(NetworkConstants.SESSION_KEY).set(player.getSession()); + } else { + future.addListener(ChannelFutureListener.CLOSE); } + } + + @Override + public void messageReceived(Object message) { + if (message.getClass() == LoginRequest.class) { + handleLoginRequest((LoginRequest) message); + } + } } \ No newline at end of file diff --git a/src/org/apollo/net/session/Session.java b/src/org/apollo/net/session/Session.java index e2a323ad..05eecb07 100644 --- a/src/org/apollo/net/session/Session.java +++ b/src/org/apollo/net/session/Session.java @@ -10,40 +10,40 @@ import io.netty.channel.ChannelHandlerContext; */ public abstract class Session { - /** - * The channel. - */ - private final Channel channel; + /** + * The channel. + */ + private final Channel channel; - /** - * Creates a session for the specified channel. - * - * @param channel The channel. - */ - public Session(Channel channel) { - this.channel = channel; - } + /** + * Creates a session for the specified channel. + * + * @param channel The channel. + */ + public Session(Channel channel) { + this.channel = channel; + } - /** - * Destroys this session. - */ - public abstract void destroy(); + /** + * Destroys this session. + */ + public abstract void destroy(); - /** - * Gets the channel. - * - * @return The channel. - */ - protected final Channel getChannel() { - return channel; - } + /** + * Gets the channel. + * + * @return The channel. + */ + protected final Channel getChannel() { + return channel; + } - /** - * Processes a message received from the channel. - * - * @param message The message. - * @throws Exception If an error occurs. - */ - public abstract void messageReceived(Object message); + /** + * Processes a message received from the channel. + * + * @param message The message. + * @throws Exception If an error occurs. + */ + public abstract void messageReceived(Object message); } \ No newline at end of file diff --git a/src/org/apollo/net/session/UpdateSession.java b/src/org/apollo/net/session/UpdateSession.java index a4233607..990647f3 100644 --- a/src/org/apollo/net/session/UpdateSession.java +++ b/src/org/apollo/net/session/UpdateSession.java @@ -16,39 +16,39 @@ import org.apollo.update.UpdateService; */ public final class UpdateSession extends Session { - /** - * The server context. - */ - private final ServerContext context; + /** + * The server context. + */ + private final ServerContext context; - /** - * Creates an update session for the specified channel. - * - * @param channel The channel. - * @param context The server context. - */ - public UpdateSession(Channel channel, ServerContext context) { - super(channel); - this.context = context; - } + /** + * Creates an update session for the specified channel. + * + * @param channel The channel. + * @param context The server context. + */ + public UpdateSession(Channel channel, ServerContext context) { + super(channel); + this.context = context; + } - @Override - public void destroy() { - // TODO implement - } + @Override + public void destroy() { + // TODO implement + } - @Override - public void messageReceived(Object message) { - UpdateDispatcher dispatcher = context.getService(UpdateService.class).getDispatcher(); - if (message instanceof OnDemandRequest) { - dispatcher.dispatch(getChannel(), (OnDemandRequest) message); - } else if (message instanceof JagGrabRequest) { - dispatcher.dispatch(getChannel(), (JagGrabRequest) message); - } else if (message instanceof HttpRequest) { - dispatcher.dispatch(getChannel(), (HttpRequest) message); - } else { - throw new IllegalArgumentException("Unknown message type."); - } + @Override + public void messageReceived(Object message) { + UpdateDispatcher dispatcher = context.getService(UpdateService.class).getDispatcher(); + if (message instanceof OnDemandRequest) { + dispatcher.dispatch(getChannel(), (OnDemandRequest) message); + } else if (message instanceof JagGrabRequest) { + dispatcher.dispatch(getChannel(), (JagGrabRequest) message); + } else if (message instanceof HttpRequest) { + dispatcher.dispatch(getChannel(), (HttpRequest) message); + } else { + throw new IllegalArgumentException("Unknown message type."); } + } } \ No newline at end of file diff --git a/src/org/apollo/security/IsaacRandomPair.java b/src/org/apollo/security/IsaacRandomPair.java index c4d14196..b9756795 100644 --- a/src/org/apollo/security/IsaacRandomPair.java +++ b/src/org/apollo/security/IsaacRandomPair.java @@ -10,43 +10,43 @@ import net.burtleburtle.bob.rand.IsaacRandom; */ public final class IsaacRandomPair { - /** - * The random number generator used to decode data. - */ - private final IsaacRandom decodingRandom; + /** + * The random number generator used to decode data. + */ + private final IsaacRandom decodingRandom; - /** - * The random number generator used to encode data. - */ - private final IsaacRandom encodingRandom; + /** + * The random number generator used to encode data. + */ + private final IsaacRandom encodingRandom; - /** - * Creates the pair of random number generators. - * - * @param encodingRandom The random number generator used for encoding. - * @param decodingRandom The random number generator used for decoding. - */ - public IsaacRandomPair(IsaacRandom encodingRandom, IsaacRandom decodingRandom) { - this.encodingRandom = encodingRandom; - this.decodingRandom = decodingRandom; - } + /** + * Creates the pair of random number generators. + * + * @param encodingRandom The random number generator used for encoding. + * @param decodingRandom The random number generator used for decoding. + */ + public IsaacRandomPair(IsaacRandom encodingRandom, IsaacRandom decodingRandom) { + this.encodingRandom = encodingRandom; + this.decodingRandom = decodingRandom; + } - /** - * Gets the random number generator used for decoding. - * - * @return The random number generator used for decoding. - */ - public IsaacRandom getDecodingRandom() { - return decodingRandom; - } + /** + * Gets the random number generator used for decoding. + * + * @return The random number generator used for decoding. + */ + public IsaacRandom getDecodingRandom() { + return decodingRandom; + } - /** - * Gets the random number generator used for encoding. - * - * @return The random number generator used for encoding. - */ - public IsaacRandom getEncodingRandom() { - return encodingRandom; - } + /** + * Gets the random number generator used for encoding. + * + * @return The random number generator used for encoding. + */ + public IsaacRandom getEncodingRandom() { + return encodingRandom; + } } \ No newline at end of file diff --git a/src/org/apollo/security/PlayerCredentials.java b/src/org/apollo/security/PlayerCredentials.java index 6b625190..177729df 100644 --- a/src/org/apollo/security/PlayerCredentials.java +++ b/src/org/apollo/security/PlayerCredentials.java @@ -11,107 +11,108 @@ import com.lambdaworks.crypto.SCryptUtil; */ public final class PlayerCredentials { - /** - * The player's username encoded as a long. - */ - private final long encodedUsername; + /** + * The player's username encoded as a long. + */ + private final long encodedUsername; - /** - * The player's password. - */ - private String password; + /** + * The player's password. + */ + private String password; - /** - * The computer's unique identifier. - */ - private final int uid; + /** + * The computer's unique identifier. + */ + private final int uid; - /** - * The player's username. - */ - private final String username; + /** + * The player's username. + */ + private final String username; - /** - * The hash of the player's username. - */ - private final int usernameHash; + /** + * The hash of the player's username. + */ + private final int usernameHash; - /** - * Creates a new {@link PlayerCredentials} object with the specified name, password and uid. - * - * @param username The player's username. - * @param password The player's password. - * @param usernameHash The hash of the player's username. - * @param uid The computer's uid. - */ - public PlayerCredentials(String username, String password, int usernameHash, int uid) { - this.username = username; - encodedUsername = NameUtil.encodeBase37(username); - this.password = password; - this.usernameHash = usernameHash; - this.uid = uid; - } + /** + * Creates a new {@link PlayerCredentials} object with the specified name, password and uid. + * + * @param username The player's username. + * @param password The player's password. + * @param usernameHash The hash of the player's username. + * @param uid The computer's uid. + */ + public PlayerCredentials(String username, String password, int usernameHash, int uid) { + this.username = username; + encodedUsername = NameUtil.encodeBase37(username); + this.password = password; + this.usernameHash = usernameHash; + this.uid = uid; + } - /** - * Gets the player's username encoded as a long. - * - * @return The username as encoded by {@link NameUtil#encodeBase37(String)}. - */ - public long getEncodedUsername() { - return encodedUsername; - } + /** + * Gets the player's username encoded as a long. + * + * @return The username as encoded by {@link NameUtil#encodeBase37(String)}. + */ + public long getEncodedUsername() { + return encodedUsername; + } - /** - * Gets the hashed password - * @return The password (either the original loaded from file or scrypted) - */ - public String getHashedPassword() { - return password.startsWith("$s0$") ? password : SCryptUtil.scrypt(password, 16384, 8, 1); - } - - /** - * Sets the player's password - * - * @param password The player's new password - */ - public void setPassword(String password) { - this.password = password; - } + /** + * Gets the hashed password + * + * @return The password (either the original loaded from file or scrypted) + */ + public String getHashedPassword() { + return password.startsWith("$s0$") ? password : SCryptUtil.scrypt(password, 16384, 8, 1); + } - /** - * Gets the player's password. - * - * @return The player's password. - */ - public String getPassword() { - return password; - } + /** + * Sets the player's password + * + * @param password The player's new password + */ + public void setPassword(String password) { + this.password = password; + } - /** - * Gets the computer's uid. - * - * @return The computer's uid. - */ - public int getUid() { - return uid; - } + /** + * Gets the player's password. + * + * @return The player's password. + */ + public String getPassword() { + return password; + } - /** - * Gets the player's username. - * - * @return The player's username. - */ - public String getUsername() { - return username; - } + /** + * Gets the computer's uid. + * + * @return The computer's uid. + */ + public int getUid() { + return uid; + } - /** - * Gets the username hash. - * - * @return The username hash. - */ - public int getUsernameHash() { - return usernameHash; - } + /** + * Gets the player's username. + * + * @return The player's username. + */ + public String getUsername() { + return username; + } + + /** + * Gets the username hash. + * + * @return The username hash. + */ + public int getUsernameHash() { + return usernameHash; + } } \ No newline at end of file diff --git a/src/org/apollo/tools/EquipmentConstants.java b/src/org/apollo/tools/EquipmentConstants.java index dad280e9..23fd87a7 100644 --- a/src/org/apollo/tools/EquipmentConstants.java +++ b/src/org/apollo/tools/EquipmentConstants.java @@ -8,95 +8,95 @@ package org.apollo.tools; */ public final class EquipmentConstants { - /** - * Amulets. - */ - public static final String[] AMULETS = { "amulet", "necklace", "Amulet of" }; + /** + * Amulets. + */ + public static final String[] AMULETS = { "amulet", "necklace", "Amulet of" }; - /** - * Arrows. - */ - public static final String[] ARROWS = { "arrow", "arrows", "arrow(p)", "arrow(+)", "arrow(s)", "bolt", "Bolt rack", - "Opal bolts", "Dragon bolts" }; + /** + * Arrows. + */ + public static final String[] ARROWS = { "arrow", "arrows", "arrow(p)", "arrow(+)", "arrow(s)", "bolt", "Bolt rack", + "Opal bolts", "Dragon bolts" }; - /** - * Bodies. - */ - public static final String[] BODY = { "platebody", "chainbody", "robetop", "leathertop", "platemail", "top", - "brassard", "Robe top", "body", "platebody (t)", "platebody (g)", "body(g)", "body_(g)", "chestplate", - "torso", "shirt" }; + /** + * Bodies. + */ + public static final String[] BODY = { "platebody", "chainbody", "robetop", "leathertop", "platemail", "top", + "brassard", "Robe top", "body", "platebody (t)", "platebody (g)", "body(g)", "body_(g)", "chestplate", + "torso", "shirt" }; - /** - * Boots. - */ - public static final String[] BOOTS = { "boots", "Boots" }; + /** + * Boots. + */ + public static final String[] BOOTS = { "boots", "Boots" }; - /** - * Capes. - */ - public static final String[] CAPES = { "cape", "Cape" }; + /** + * Capes. + */ + public static final String[] CAPES = { "cape", "Cape" }; - /** - * Full bodies. - */ - public static final String[] FULL_BODIES = { "top", "shirt", "platebody", "Ahrims robetop", "Karils leathertop", - "brassard", "Robe top", "robetop", "platebody (t)", "platebody (g)", "chestplate", "torso" }; + /** + * Full bodies. + */ + public static final String[] FULL_BODIES = { "top", "shirt", "platebody", "Ahrims robetop", "Karils leathertop", + "brassard", "Robe top", "robetop", "platebody (t)", "platebody (g)", "chestplate", "torso" }; - /** - * Full hats. - */ - public static final String[] FULL_HATS = { "med helm", "coif", "Dharoks helm", "hood", "Initiate helm", "Coif", - "Helm of neitiznot" }; + /** + * Full hats. + */ + public static final String[] FULL_HATS = { "med helm", "coif", "Dharoks helm", "hood", "Initiate helm", "Coif", + "Helm of neitiznot" }; - /** - * Full masks. - */ - public static final String[] FULL_MASKS = { "full helm", "mask", "Veracs helm", "Guthans helm", "Torags helm", - "Karils coif", "full helm (t)", "full helm (g)", "mask" }; + /** + * Full masks. + */ + public static final String[] FULL_MASKS = { "full helm", "mask", "Veracs helm", "Guthans helm", "Torags helm", + "Karils coif", "full helm (t)", "full helm (g)", "mask" }; - /** - * Gloves. - */ - public static final String[] GLOVES = { "gloves", "gauntlets", "Gloves", "vambraces", "vamb", "bracers" }; + /** + * Gloves. + */ + public static final String[] GLOVES = { "gloves", "gauntlets", "Gloves", "vambraces", "vamb", "bracers" }; - /** - * Hats. - */ - public static final String[] HATS = { "tiara", "helm", "hood", "coif", "Coif", "hat", "partyhat", "Hat", - "full helm (t)", "full helm (g)", "hat (t)", "hat (g)", "cav", "boater", "helmet", "mask", - "Helm of neitiznot" }; + /** + * Hats. + */ + public static final String[] HATS = { "tiara", "helm", "hood", "coif", "Coif", "hat", "partyhat", "Hat", + "full helm (t)", "full helm (g)", "hat (t)", "hat (g)", "cav", "boater", "helmet", "mask", + "Helm of neitiznot" }; - /** - * Legs. - */ - public static final String[] LEGS = { "platelegs", "plateskirt", "skirt", "bottoms", "chaps", "platelegs (t)", - "platelegs (g)", "bottom", "skirt", "skirt (g)", "skirt (t)", "chaps (g)", "chaps (t)", "tassets", "legs", - "Flared trousers" }; + /** + * Legs. + */ + public static final String[] LEGS = { "platelegs", "plateskirt", "skirt", "bottoms", "chaps", "platelegs (t)", + "platelegs (g)", "bottom", "skirt", "skirt (g)", "skirt (t)", "chaps (g)", "chaps (t)", "tassets", "legs", + "Flared trousers" }; - /** - * Rings. - */ - public static final String[] RINGS = { "ring", "Ring of" }; + /** + * Rings. + */ + public static final String[] RINGS = { "ring", "Ring of" }; - /** - * Shields. - */ - public static final String[] SHIELDS = { "kiteshield", "sq shield", "Toktz-ket", "books", "book", "kiteshield (t)", - "kiteshield (g)", "kiteshield(h)", "defender", "shield" }; + /** + * Shields. + */ + public static final String[] SHIELDS = { "kiteshield", "sq shield", "Toktz-ket", "books", "book", "kiteshield (t)", + "kiteshield (g)", "kiteshield(h)", "defender", "shield" }; - /** - * Weapons. - */ - public static final String[] WEAPONS = { "scimitar", "longsword", "sword", "longbow", "shortbow", "dagger", "mace", - "halberd", "spear", "Abyssal whip", "axe", "flail", "crossbow", "Torags hammers", "dagger(p)", "dagger(+)", - "dagger(s)", "spear(p)", "spear(+)", "spear(s)", "spear(kp)", "maul", "dart", "dart(p)", "javelin", - "javelin(p)", "knife", "knife(p)", "Longbow", "Shortbow", "Crossbow", "Toktz-xil", "Toktz-mej", - "Tzhaar-ket", "staff", "Staff", "godsword", "c'bow", "Crystal bow", "Dark bow", "Magic butterfly net" }; + /** + * Weapons. + */ + public static final String[] WEAPONS = { "scimitar", "longsword", "sword", "longbow", "shortbow", "dagger", "mace", + "halberd", "spear", "Abyssal whip", "axe", "flail", "crossbow", "Torags hammers", "dagger(p)", "dagger(+)", + "dagger(s)", "spear(p)", "spear(+)", "spear(s)", "spear(kp)", "maul", "dart", "dart(p)", "javelin", + "javelin(p)", "knife", "knife(p)", "Longbow", "Shortbow", "Crossbow", "Toktz-xil", "Toktz-mej", + "Tzhaar-ket", "staff", "Staff", "godsword", "c'bow", "Crystal bow", "Dark bow", "Magic butterfly net" }; - /** - * Default private constructor to prevent instantiation. - */ - private EquipmentConstants() { - } + /** + * Default private constructor to prevent instantiation. + */ + private EquipmentConstants() { + } } \ No newline at end of file diff --git a/src/org/apollo/tools/EquipmentUpdater.java b/src/org/apollo/tools/EquipmentUpdater.java index ce32f421..d64886a7 100644 --- a/src/org/apollo/tools/EquipmentUpdater.java +++ b/src/org/apollo/tools/EquipmentUpdater.java @@ -17,1190 +17,1190 @@ import org.apollo.game.model.def.ItemDefinition; */ public final class EquipmentUpdater { - /** - * Gets the attack requirement. - * - * @param definition The item definition. - * @return The required level. - */ - private static int getAttackRequirement(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - if (name.equals("Black sword")) { - return 10; - } - if (name.equals("Black dagger")) { - return 10; - } - if (name.equals("Black spear")) { - return 10; - } - if (name.equals("Black longsword")) { - return 10; - } - if (name.equals("Black scimitar")) { - return 10; - } - if (name.equals("Black axe")) { - return 10; - } - if (name.equals("Black battleaxe")) { - return 10; - } - if (name.equals("Black mace")) { - return 10; - } - if (name.equals("Black halberd")) { - return 10; - } - if (name.equals("Mithril sword")) { - return 20; - } - if (name.equals("Mithril dagger")) { - return 20; - } - if (name.equals("Mithril spear")) { - return 20; - } - if (name.equals("Mihril longsword")) { - return 20; - } - if (name.equals("Mithril scimitar")) { - return 20; - } - if (name.equals("Mithril axe")) { - return 20; - } - if (name.equals("Mithril battleaxe")) { - return 20; - } - if (name.equals("Mithril mace")) { - return 20; - } - if (name.equals("Mithril halberd")) { - return 20; - } - if (name.equals("Adamant sword")) { - return 30; - } - if (name.equals("Adamant dagger")) { - return 30; - } - if (name.equals("Adamant spear")) { - return 30; - } - if (name.equals("Adamant longsword")) { - return 30; - } - if (name.equals("Adamant scimitar")) { - return 30; - } - if (name.equals("Adamant axe")) { - return 30; - } - if (name.equals("Adamant battleaxe")) { - return 30; - } - if (name.equals("Adamant mace")) { - return 30; - } - if (name.equals("Adamant halberd")) { - return 30; - } - if (name.equals("Rune sword")) { - return 40; - } - if (name.equals("Rune dagger")) { - return 40; - } - if (name.equals("Rune spear")) { - return 40; - } - if (name.equals("Rune longsword")) { - return 40; - } - if (name.equals("Rune scimitar")) { - return 40; - } - if (name.equals("Rune axe")) { - return 40; - } - if (name.equals("Rune battleaxe")) { - return 40; - } - if (name.equals("Rune mace")) { - return 40; - } - if (name.equals("Rune halberd")) { - return 40; - } - if (name.equals("Dragon sword")) { - return 60; - } - if (name.equals("Dragon dagger(s)")) { - return 60; - } - if (name.equals("Dragon dagger")) { - return 60; - } - if (name.startsWith("Dragon spear")) { - return 60; - } - if (name.equals("Dragon longsword")) { - return 60; - } - if (name.equals("Dragon scimitar")) { - return 60; - } - if (name.equals("Dragon axe")) { - return 60; - } - if (name.equals("Dragon battleaxe")) { - return 60; - } - if (name.equals("Dragon mace")) { - return 60; - } - if (name.equals("Dragon halberd")) { - return 60; - } - if (name.equals("Abyssal whip")) { - return 70; - } - if (name.equals("Veracs flail")) { - return 70; - } - if (name.equals("Torags hammers")) { - return 70; - } - if (name.equals("Dharoks greataxe")) { - return 70; - } - if (name.equals("Guthans warspear")) { - return 70; - } - if (name.equals("Ahrims staff")) { - return 70; - } - if (name.equals("Granite maul")) { - return 50; - } - if (name.equals("Toktz-xil-ak")) { - return 60; - } - if (name.equals("Tzhaar-ket-em")) { - return 60; - } - if (name.equals("Toktz-xil-ek")) { - return 60; - } - if (name.equals("Granite legs")) { - return 99; - } - if (name.equals("Mud staff")) { - return 30; - } - if (name.equals("Armadyl godsword")) { - return 75; - } - if (name.equals("Bandos godsword")) { - return 75; - } - if (name.equals("Saradomin godsword")) { - return 75; - } - if (name.equals("Zamorak godsword")) { - return 75; - } - if (name.equals("Lava battlestaff")) { - return 30; - } - if (name.equals("Toktz-mej-tal")) { - return 60; - } - if (name.equals("Ancient staff")) { - return 50; - } + /** + * Gets the attack requirement. + * + * @param definition The item definition. + * @return The required level. + */ + private static int getAttackRequirement(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; + } + if (name.equals("Black sword")) { + return 10; + } + if (name.equals("Black dagger")) { + return 10; + } + if (name.equals("Black spear")) { + return 10; + } + if (name.equals("Black longsword")) { + return 10; + } + if (name.equals("Black scimitar")) { + return 10; + } + if (name.equals("Black axe")) { + return 10; + } + if (name.equals("Black battleaxe")) { + return 10; + } + if (name.equals("Black mace")) { + return 10; + } + if (name.equals("Black halberd")) { + return 10; + } + if (name.equals("Mithril sword")) { + return 20; + } + if (name.equals("Mithril dagger")) { + return 20; + } + if (name.equals("Mithril spear")) { + return 20; + } + if (name.equals("Mihril longsword")) { + return 20; + } + if (name.equals("Mithril scimitar")) { + return 20; + } + if (name.equals("Mithril axe")) { + return 20; + } + if (name.equals("Mithril battleaxe")) { + return 20; + } + if (name.equals("Mithril mace")) { + return 20; + } + if (name.equals("Mithril halberd")) { + return 20; + } + if (name.equals("Adamant sword")) { + return 30; + } + if (name.equals("Adamant dagger")) { + return 30; + } + if (name.equals("Adamant spear")) { + return 30; + } + if (name.equals("Adamant longsword")) { + return 30; + } + if (name.equals("Adamant scimitar")) { + return 30; + } + if (name.equals("Adamant axe")) { + return 30; + } + if (name.equals("Adamant battleaxe")) { + return 30; + } + if (name.equals("Adamant mace")) { + return 30; + } + if (name.equals("Adamant halberd")) { + return 30; + } + if (name.equals("Rune sword")) { + return 40; + } + if (name.equals("Rune dagger")) { + return 40; + } + if (name.equals("Rune spear")) { + return 40; + } + if (name.equals("Rune longsword")) { + return 40; + } + if (name.equals("Rune scimitar")) { + return 40; + } + if (name.equals("Rune axe")) { + return 40; + } + if (name.equals("Rune battleaxe")) { + return 40; + } + if (name.equals("Rune mace")) { + return 40; + } + if (name.equals("Rune halberd")) { + return 40; + } + if (name.equals("Dragon sword")) { + return 60; + } + if (name.equals("Dragon dagger(s)")) { + return 60; + } + if (name.equals("Dragon dagger")) { + return 60; + } + if (name.startsWith("Dragon spear")) { + return 60; + } + if (name.equals("Dragon longsword")) { + return 60; + } + if (name.equals("Dragon scimitar")) { + return 60; + } + if (name.equals("Dragon axe")) { + return 60; + } + if (name.equals("Dragon battleaxe")) { + return 60; + } + if (name.equals("Dragon mace")) { + return 60; + } + if (name.equals("Dragon halberd")) { + return 60; + } + if (name.equals("Abyssal whip")) { + return 70; + } + if (name.equals("Veracs flail")) { + return 70; + } + if (name.equals("Torags hammers")) { + return 70; + } + if (name.equals("Dharoks greataxe")) { + return 70; + } + if (name.equals("Guthans warspear")) { + return 70; + } + if (name.equals("Ahrims staff")) { + return 70; + } + if (name.equals("Granite maul")) { + return 50; + } + if (name.equals("Toktz-xil-ak")) { + return 60; + } + if (name.equals("Tzhaar-ket-em")) { + return 60; + } + if (name.equals("Toktz-xil-ek")) { + return 60; + } + if (name.equals("Granite legs")) { + return 99; + } + if (name.equals("Mud staff")) { + return 30; + } + if (name.equals("Armadyl godsword")) { + return 75; + } + if (name.equals("Bandos godsword")) { + return 75; + } + if (name.equals("Saradomin godsword")) { + return 75; + } + if (name.equals("Zamorak godsword")) { + return 75; + } + if (name.equals("Lava battlestaff")) { + return 30; + } + if (name.equals("Toktz-mej-tal")) { + return 60; + } + if (name.equals("Ancient staff")) { + return 50; + } + return 1; + } + + /** + * Gets the defence requirement. + * + * @param definition The item definition. + * @return The required level. + */ + private static int getDefenceRequirement(ItemDefinition definition) { + int id = definition.getId(); + String name = definition.getName(); + if (name == null) { + name = "null"; + } + if (name.equals("Rune boots")) { + return 40; + } + if (id == 2499) { + return 40; + } + if (id == 4123) { + return 5; + } + if (id == 4125) { + return 10; + } + if (id == 4127) { + return 20; + } + if (id == 4129) { + return 30; + } + if (id == 7990) { + return 60; + } + if (id == 2501) { + return 40; + } + if (id == 1131) { + return 10; + } + if (id == 2503) { + return 40; + } + if (id == 1135) { + return 40; + } + if (id == 7462) { + return 42; + } + if (id == 7461) { + return 42; + } + if (id == 7460) { + return 42; + } + if (id == 7459) { + return 20; + } + if (id == 7458) { + return 1; + } + if (id == 7457) { + return 1; + } + if (id == 7456) { + return 1; + } + if (name.equals("White med helm")) { + return 10; + } + if (name.equals("White chainbody")) { + return 10; + } + if (name.startsWith("White full helm")) { + return 10; + } + if (name.startsWith("White platebody")) { + return 10; + } + if (name.startsWith("White plateskirt")) { + return 10; + } + if (name.startsWith("White platelegs")) { + return 10; + } + if (name.startsWith("White kiteshield")) { + return 10; + } + if (name.startsWith("White sq shield")) { + return 10; + } + if (name.startsWith("Studded chaps")) { + return 1; + } + if (name.startsWith("Studded")) { + return 20; + } + if (name.startsWith("Black kiteshield(h)")) { + return 10; + } + if (name.startsWith("Rune kiteshield(h)")) { + return 40; + } + if (name.equals("Black med helm")) { + return 10; + } + if (name.equals("Black chainbody")) { + return 10; + } + if (name.startsWith("Black full helm")) { + return 10; + } + if (name.startsWith("Black platebody")) { + return 10; + } + if (name.startsWith("Black plateskirt")) { + return 10; + } + if (name.startsWith("Black platelegs")) { + return 10; + } + if (name.startsWith("Black kiteshield")) { + return 10; + } + if (name.startsWith("Black sq shield")) { + return 10; + } + if (name.equals("Mithril med helm")) { + return 20; + } + if (name.equals("Mithril chainbody")) { + return 20; + } + if (name.startsWith("Mithril full helm")) { + return 20; + } + if (name.startsWith("Mithril platebody")) { + return 20; + } + if (name.startsWith("Mithril plateskirt")) { + return 20; + } + if (name.startsWith("Mithril platelegs")) { + return 20; + } + if (name.startsWith("Mithril kiteshield")) { + return 20; + } + if (name.startsWith("Mithril sq shield")) { + return 20; + } + if (name.equals("Adamant med helm")) { + return 30; + } + if (name.equals("Adamant chainbody")) { + return 30; + } + if (name.startsWith("Adamant full helm")) { + return 30; + } + if (name.startsWith("Adamant platebody")) { + return 30; + } + if (name.startsWith("Adamant plateskirt")) { + return 30; + } + if (name.startsWith("Adamant platelegs")) { + return 30; + } + if (name.startsWith("Adamant kiteshield")) { + return 30; + } + if (name.startsWith("Adamant sq shield")) { + return 30; + } + if (name.startsWith("Adam full helm")) { + return 30; + } + if (name.startsWith("Adam platebody")) { + return 30; + } + if (name.startsWith("Adam plateskirt")) { + return 30; + } + if (name.startsWith("Adam platelegs")) { + return 30; + } + if (name.startsWith("Adam kiteshield")) { + return 30; + } + if (name.startsWith("Adam kiteshield(h)")) { + return 30; + } + if (name.startsWith("D-hide body(g)")) { + return 40; + } + if (name.startsWith("D-hide body(t)")) { + return 40; + } + if (name.equals("Dragon sq shield")) { + return 60; + } + if (name.equals("Dragon med helm")) { + return 60; + } + if (name.equals("Dragon chainbody")) { + return 60; + } + if (name.equals("Dragon plateskirt")) { + return 60; + } + if (name.equals("Dragon platelegs")) { + return 60; + } + if (name.equals("Dragon sq shield")) { + return 60; + } + if (name.equals("Rune med helm")) { + return 40; + } + if (name.equals("Rune chainbody")) { + return 40; + } + if (name.startsWith("Rune full helm")) { + return 40; + } + if (name.startsWith("Rune platebody")) { + return 40; + } + if (name.startsWith("Rune plateskirt")) { + return 40; + } + if (name.startsWith("Rune platelegs")) { + return 40; + } + if (name.startsWith("Rune kiteshield")) { + return 40; + } + if (name.startsWith("Zamorak full helm")) { + return 40; + } + if (name.startsWith("Zamorak platebody")) { + return 40; + } + if (name.startsWith("Zamorak plateskirt")) { + return 40; + } + if (name.startsWith("Zamorak platelegs")) { + return 40; + } + if (name.startsWith("Zamorak kiteshield")) { + return 40; + } + if (name.startsWith("Guthix full helm")) { + return 40; + } + if (name.startsWith("Guthix platebody")) { + return 40; + } + if (name.startsWith("Guthix plateskirt")) { + return 40; + } + if (name.startsWith("Guthix platelegs")) { + return 40; + } + if (name.startsWith("Guthix kiteshield")) { + return 40; + } + if (name.startsWith("Saradomin full")) { + return 40; + } + if (name.startsWith("Saradomrangedin plate")) { + return 40; + } + if (name.startsWith("Saradomin plateskirt")) { + return 40; + } + if (name.startsWith("Saradomin legs")) { + return 40; + } + if (name.startsWith("Zamorak kiteshield")) { + return 40; + } + if (name.startsWith("Rune sq shield")) { + return 40; + } + if (name.equals("Gilded full helm")) { + return 40; + } + if (name.equals("Gilded platebody")) { + return 40; + } + if (name.equals("Gilded plateskirt")) { + return 40; + } + if (name.equals("Gilded platelegs")) { + return 40; + } + if (name.equals("Gilded kiteshield")) { + return 40; + } + if (name.equals("Fighter torso")) { + return 40; + } + if (name.equals("Granite legs")) { + return 99; + } + if (name.equals("Toktz-ket-xil")) { + return 60; + } + if (name.equals("Dharoks helm")) { + return 70; + } + if (name.equals("Dharoks platebody")) { + return 70; + } + if (name.equals("Dharoks platelegs")) { + return 70; + } + if (name.equals("Guthans helm")) { + return 70; + } + if (name.equals("Guthans platebody")) { + return 70; + } + if (name.equals("Guthans chainskirt")) { + return 70; + } + if (name.equals("Torags helm")) { + return 70; + } + if (name.equals("Torags platebody")) { + return 70; + } + if (name.equals("Torags platelegs")) { + return 70; + } + if (name.equals("Veracs helm")) { + return 70; + } + if (name.equals("Veracs brassard")) { + return 70; + } + if (name.equals("Veracs plateskirt")) { + return 70; + } + if (name.equals("Ahrims hood")) { + return 70; + } + if (name.equals("Ahrims robetop")) { + return 70; + } + if (name.equals("Ahrims robeskirt")) { + return 70; + } + if (name.equals("Karils coif")) { + return 70; + } + if (name.equals("Karils leathertop")) { + return 70; + } + if (name.equals("Karils leatherskirt")) { + return 70; + } + if (name.equals("Granite shield")) { + return 50; + } + if (name.equals("New crystal shield")) { + return 70; + } + if (name.equals("Archer helm")) { + return 45; + } + if (name.equals("Berserker helm")) { + return 45; + } + if (name.equals("Warrior helm")) { + return 45; + } + if (name.equals("Farseer helm")) { + return 45; + } + if (name.equals("Initiate helm")) { + return 20; + } + if (name.equals("Initiate platemail")) { + return 20; + } + if (name.equals("Initiate platelegs")) { + return 20; + } + if (name.equals("Dragonhide body")) { + return 40; + } + if (name.equals("Mystic hat")) { + return 20; + } + if (name.equals("Mystic robe top")) { + return 20; + } + if (name.equals("Mystic robe bottom")) { + return 20; + } + if (name.equals("Mystic gloves")) { + return 20; + } + if (name.equals("Mystic boots")) { + return 20; + } + if (name.equals("Enchanted hat")) { + return 20; + } + if (name.equals("Enchanted top")) { + return 20; + } + if (name.equals("Enchanted robe")) { + return 20; + } + if (name.equals("Splitbark helm")) { + return 40; + } + if (name.equals("Splitbark body")) { + return 40; + } + if (name.equals("Splitbark gauntlets")) { + return 40; + } + if (name.equals("Splitbark legs")) { + return 40; + } + if (name.equals("Splitbark greaves")) { + return 40; + } + if (name.equals("Infinity gloves")) { + return 25; + } + if (name.equals("Infinity hat")) { + return 25; + } + if (name.equals("Infinity top")) { + return 25; + } + if (name.equals("Infinity bottoms")) { + return 25; + } + if (name.equals("Infinity boots")) { + return 25; + } + return 1; + } + + /** + * Gets the magic requirement. + * + * @param definition The item definition. + * @return The required level. + */ + private static int getMagicRequirement(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; + } + if (name.equals("Mystic hat")) { + return 40; + } + if (name.equals("Mystic robe top")) { + return 40; + } + if (name.equals("Mystic robe bottom")) { + return 40; + } + if (name.equals("Mystic gloves")) { + return 40; + } + if (name.equals("Mystic boots")) { + return 40; + } + if (name.equals("Slayer's staff")) { + return 50; + } + if (name.equals("Enchanted hat")) { + return 40; + } + if (name.equals("Enchanted top")) { + return 40; + } + if (name.equals("Enchanted robe")) { + return 40; + } + if (name.equals("Splitbark helm")) { + return 40; + } + if (name.equals("Splitbark body")) { + return 40; + } + if (name.equals("Splitbark gauntlets")) { + return 40; + } + if (name.equals("Splitbark legs")) { + return 40; + } + if (name.equals("Splitbark greaves")) { + return 40; + } + if (name.equals("Infinity gloves")) { + return 50; + } + if (name.equals("Infinity hat")) { + return 50; + } + if (name.equals("Infinity top")) { + return 50; + } + if (name.equals("Infinity bottoms")) { + return 50; + } + if (name.equals("Infinity boots")) { + return 50; + } + if (name.equals("Ahrims hood")) { + return 70; + } + if (name.equals("Ahrims robetop")) { + return 70; + } + if (name.equals("Ahrims robeskirt")) { + return 70; + } + if (name.equals("Ahrims staff")) { + return 70; + } + if (name.equals("Saradomin cape")) { + return 60; + } + if (name.equals("Saradomin staff")) { + return 60; + } + if (name.equals("Zamorak cape")) { + return 60; + } + if (name.equals("Zamorak staff")) { + return 60; + } + if (name.equals("Guthix cape")) { + return 60; + } + if (name.equals("Guthix staff")) { + return 60; + } + if (name.equals("mud staff")) { + return 30; + } + if (name.equals("Fire battlestaff")) { + return 30; + } + return 1; + } + + /** + * Gets the ranged requirement. + * + * @param definition The item. + * @return The required level. + */ + private static int getRangedRequirement(ItemDefinition definition) { + int id = definition.getId(); + String name = definition.getName(); + if (name == null) { + name = "null"; + } + if (id == 2499) { + return 50; + } + if (id == 1135) { + return 40; + } + if (id == 1099) { + return 40; + } + if (id == 1065) { + return 40; + } + if (id == 2501) { + return 60; + } + if (id == 2503) { + return 70; + } + if (id == 2487) { + return 50; + } + if (id == 2489) { + return 60; + } + if (id == 2495) { + return 60; + } + if (id == 2491) { + return 70; + } + if (id == 2493) { + return 50; + } + if (id == 2505) { + return 60; + } + if (id == 2507) { + return 70; + } + if (id == 859) { + return 40; + } + if (id == 861) { + return 40; + } + if (id == 7370) { + return 40; + } + if (id == 7372) { + return 40; + } + if (id == 7378) { + return 40; + } + if (id == 7380) { + return 40; + } + if (id == 7374) { + return 50; + } + if (id == 7376) { + return 50; + } + if (id == 7382) { + return 50; + } + if (id == 7384) { + return 50; + } + if (name.equals("Coif")) { + return 20; + } + if (name.startsWith("Studded chaps")) { + return 20; + } + if (name.startsWith("Studded")) { + return 20; + } + if (name.equals("Karils coif")) { + return 70; + } + if (name.equals("Karils leathertop")) { + return 70; + } + if (name.equals("Karils leatherskirt")) { + return 70; + } + if (name.equals("Robin hood hat")) { + return 40; + } + if (name.equals("Ranger boots")) { + return 40; + } + if (name.equals("Crystal bow full")) { + return 70; + } + if (name.equals("New crystal bow")) { + return 70; + } + if (name.equals("Karils crossbow")) { + return 70; + } + if (id == 2497) { + return 70; + } + if (name.equals("Rune thrownaxe")) { + return 40; + } + if (name.equals("Rune dart")) { + return 40; + } + if (name.equals("Rune javelin")) { + return 40; + } + if (name.equals("Rune knife")) { + return 40; + } + if (name.equals("Adamant thrownaxe")) { + return 30; + } + if (name.equals("Adamant dart")) { + return 30; + } + if (name.equals("Adamant javelin")) { + return 30; + } + if (name.equals("Adamant knife")) { + return 30; + } + if (name.equals("Toktz-xil-ul")) { + return 60; + } + if (name.equals("Seercull")) { + return 50; + } + if (name.equals("Bolt rack")) { + return 70; + } + if (name.equals("Rune arrow")) { + return 40; + } + if (name.equals("Adamant arrow")) { + return 30; + } + if (name.equals("Mithril arrow")) { + return 1; + } else { + return 1; + } + } + + /** + * Gets the strength requirement. + * + * @param def The item. + * @return The required level. + */ + private static int getStrengthRequirement(ItemDefinition def) { + String name = def.getName(); + if (name == null) { + name = "null"; + } + if (name.equals("Torags hammers")) { + return 70; + } + if (name.equals("Dharoks greataxe")) { + return 70; + } + if (name.equals("Granite maul")) { + return 50; + } + if (name.equals("Granite legs")) { + return 99; + } + if (name.equals("Tzhaar-ket-om")) { + return 60; + } + if (name.equals("Granite shield")) { + return 50; + } + return 1; + } + + /** + * Gets the weapon type. + * + * @param definition The item. + * @return The weapon type, or {@code -1} if it is not a weapon. + */ + private static int getWeaponType(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; + } + for (String element : EquipmentConstants.CAPES) { + if (name.contains(element)) { return 1; + } } - - /** - * Gets the defence requirement. - * - * @param definition The item definition. - * @return The required level. - */ - private static int getDefenceRequirement(ItemDefinition definition) { - int id = definition.getId(); - String name = definition.getName(); - if (name == null) { - name = "null"; - } - if (name.equals("Rune boots")) { - return 40; - } - if (id == 2499) { - return 40; - } - if (id == 4123) { - return 5; - } - if (id == 4125) { - return 10; - } - if (id == 4127) { - return 20; - } - if (id == 4129) { - return 30; - } - if (id == 7990) { - return 60; - } - if (id == 2501) { - return 40; - } - if (id == 1131) { - return 10; - } - if (id == 2503) { - return 40; - } - if (id == 1135) { - return 40; - } - if (id == 7462) { - return 42; - } - if (id == 7461) { - return 42; - } - if (id == 7460) { - return 42; - } - if (id == 7459) { - return 20; - } - if (id == 7458) { - return 1; - } - if (id == 7457) { - return 1; - } - if (id == 7456) { - return 1; - } - if (name.equals("White med helm")) { - return 10; - } - if (name.equals("White chainbody")) { - return 10; - } - if (name.startsWith("White full helm")) { - return 10; - } - if (name.startsWith("White platebody")) { - return 10; - } - if (name.startsWith("White plateskirt")) { - return 10; - } - if (name.startsWith("White platelegs")) { - return 10; - } - if (name.startsWith("White kiteshield")) { - return 10; - } - if (name.startsWith("White sq shield")) { - return 10; - } - if (name.startsWith("Studded chaps")) { - return 1; - } - if (name.startsWith("Studded")) { - return 20; - } - if (name.startsWith("Black kiteshield(h)")) { - return 10; - } - if (name.startsWith("Rune kiteshield(h)")) { - return 40; - } - if (name.equals("Black med helm")) { - return 10; - } - if (name.equals("Black chainbody")) { - return 10; - } - if (name.startsWith("Black full helm")) { - return 10; - } - if (name.startsWith("Black platebody")) { - return 10; - } - if (name.startsWith("Black plateskirt")) { - return 10; - } - if (name.startsWith("Black platelegs")) { - return 10; - } - if (name.startsWith("Black kiteshield")) { - return 10; - } - if (name.startsWith("Black sq shield")) { - return 10; - } - if (name.equals("Mithril med helm")) { - return 20; - } - if (name.equals("Mithril chainbody")) { - return 20; - } - if (name.startsWith("Mithril full helm")) { - return 20; - } - if (name.startsWith("Mithril platebody")) { - return 20; - } - if (name.startsWith("Mithril plateskirt")) { - return 20; - } - if (name.startsWith("Mithril platelegs")) { - return 20; - } - if (name.startsWith("Mithril kiteshield")) { - return 20; - } - if (name.startsWith("Mithril sq shield")) { - return 20; - } - if (name.equals("Adamant med helm")) { - return 30; - } - if (name.equals("Adamant chainbody")) { - return 30; - } - if (name.startsWith("Adamant full helm")) { - return 30; - } - if (name.startsWith("Adamant platebody")) { - return 30; - } - if (name.startsWith("Adamant plateskirt")) { - return 30; - } - if (name.startsWith("Adamant platelegs")) { - return 30; - } - if (name.startsWith("Adamant kiteshield")) { - return 30; - } - if (name.startsWith("Adamant sq shield")) { - return 30; - } - if (name.startsWith("Adam full helm")) { - return 30; - } - if (name.startsWith("Adam platebody")) { - return 30; - } - if (name.startsWith("Adam plateskirt")) { - return 30; - } - if (name.startsWith("Adam platelegs")) { - return 30; - } - if (name.startsWith("Adam kiteshield")) { - return 30; - } - if (name.startsWith("Adam kiteshield(h)")) { - return 30; - } - if (name.startsWith("D-hide body(g)")) { - return 40; - } - if (name.startsWith("D-hide body(t)")) { - return 40; - } - if (name.equals("Dragon sq shield")) { - return 60; - } - if (name.equals("Dragon med helm")) { - return 60; - } - if (name.equals("Dragon chainbody")) { - return 60; - } - if (name.equals("Dragon plateskirt")) { - return 60; - } - if (name.equals("Dragon platelegs")) { - return 60; - } - if (name.equals("Dragon sq shield")) { - return 60; - } - if (name.equals("Rune med helm")) { - return 40; - } - if (name.equals("Rune chainbody")) { - return 40; - } - if (name.startsWith("Rune full helm")) { - return 40; - } - if (name.startsWith("Rune platebody")) { - return 40; - } - if (name.startsWith("Rune plateskirt")) { - return 40; - } - if (name.startsWith("Rune platelegs")) { - return 40; - } - if (name.startsWith("Rune kiteshield")) { - return 40; - } - if (name.startsWith("Zamorak full helm")) { - return 40; - } - if (name.startsWith("Zamorak platebody")) { - return 40; - } - if (name.startsWith("Zamorak plateskirt")) { - return 40; - } - if (name.startsWith("Zamorak platelegs")) { - return 40; - } - if (name.startsWith("Zamorak kiteshield")) { - return 40; - } - if (name.startsWith("Guthix full helm")) { - return 40; - } - if (name.startsWith("Guthix platebody")) { - return 40; - } - if (name.startsWith("Guthix plateskirt")) { - return 40; - } - if (name.startsWith("Guthix platelegs")) { - return 40; - } - if (name.startsWith("Guthix kiteshield")) { - return 40; - } - if (name.startsWith("Saradomin full")) { - return 40; - } - if (name.startsWith("Saradomrangedin plate")) { - return 40; - } - if (name.startsWith("Saradomin plateskirt")) { - return 40; - } - if (name.startsWith("Saradomin legs")) { - return 40; - } - if (name.startsWith("Zamorak kiteshield")) { - return 40; - } - if (name.startsWith("Rune sq shield")) { - return 40; - } - if (name.equals("Gilded full helm")) { - return 40; - } - if (name.equals("Gilded platebody")) { - return 40; - } - if (name.equals("Gilded plateskirt")) { - return 40; - } - if (name.equals("Gilded platelegs")) { - return 40; - } - if (name.equals("Gilded kiteshield")) { - return 40; - } - if (name.equals("Fighter torso")) { - return 40; - } - if (name.equals("Granite legs")) { - return 99; - } - if (name.equals("Toktz-ket-xil")) { - return 60; - } - if (name.equals("Dharoks helm")) { - return 70; - } - if (name.equals("Dharoks platebody")) { - return 70; - } - if (name.equals("Dharoks platelegs")) { - return 70; - } - if (name.equals("Guthans helm")) { - return 70; - } - if (name.equals("Guthans platebody")) { - return 70; - } - if (name.equals("Guthans chainskirt")) { - return 70; - } - if (name.equals("Torags helm")) { - return 70; - } - if (name.equals("Torags platebody")) { - return 70; - } - if (name.equals("Torags platelegs")) { - return 70; - } - if (name.equals("Veracs helm")) { - return 70; - } - if (name.equals("Veracs brassard")) { - return 70; - } - if (name.equals("Veracs plateskirt")) { - return 70; - } - if (name.equals("Ahrims hood")) { - return 70; - } - if (name.equals("Ahrims robetop")) { - return 70; - } - if (name.equals("Ahrims robeskirt")) { - return 70; - } - if (name.equals("Karils coif")) { - return 70; - } - if (name.equals("Karils leathertop")) { - return 70; - } - if (name.equals("Karils leatherskirt")) { - return 70; - } - if (name.equals("Granite shield")) { - return 50; - } - if (name.equals("New crystal shield")) { - return 70; - } - if (name.equals("Archer helm")) { - return 45; - } - if (name.equals("Berserker helm")) { - return 45; - } - if (name.equals("Warrior helm")) { - return 45; - } - if (name.equals("Farseer helm")) { - return 45; - } - if (name.equals("Initiate helm")) { - return 20; - } - if (name.equals("Initiate platemail")) { - return 20; - } - if (name.equals("Initiate platelegs")) { - return 20; - } - if (name.equals("Dragonhide body")) { - return 40; - } - if (name.equals("Mystic hat")) { - return 20; - } - if (name.equals("Mystic robe top")) { - return 20; - } - if (name.equals("Mystic robe bottom")) { - return 20; - } - if (name.equals("Mystic gloves")) { - return 20; - } - if (name.equals("Mystic boots")) { - return 20; - } - if (name.equals("Enchanted hat")) { - return 20; - } - if (name.equals("Enchanted top")) { - return 20; - } - if (name.equals("Enchanted robe")) { - return 20; - } - if (name.equals("Splitbark helm")) { - return 40; - } - if (name.equals("Splitbark body")) { - return 40; - } - if (name.equals("Splitbark gauntlets")) { - return 40; - } - if (name.equals("Splitbark legs")) { - return 40; - } - if (name.equals("Splitbark greaves")) { - return 40; - } - if (name.equals("Infinity gloves")) { - return 25; - } - if (name.equals("Infinity hat")) { - return 25; - } - if (name.equals("Infinity top")) { - return 25; - } - if (name.equals("Infinity bottoms")) { - return 25; - } - if (name.equals("Infinity boots")) { - return 25; - } - return 1; + for (String element : EquipmentConstants.HATS) { + if (name.contains(element)) { + return 0; + } } - - /** - * Gets the magic requirement. - * - * @param definition The item definition. - * @return The required level. - */ - private static int getMagicRequirement(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - if (name.equals("Mystic hat")) { - return 40; - } - if (name.equals("Mystic robe top")) { - return 40; - } - if (name.equals("Mystic robe bottom")) { - return 40; - } - if (name.equals("Mystic gloves")) { - return 40; - } - if (name.equals("Mystic boots")) { - return 40; - } - if (name.equals("Slayer's staff")) { - return 50; - } - if (name.equals("Enchanted hat")) { - return 40; - } - if (name.equals("Enchanted top")) { - return 40; - } - if (name.equals("Enchanted robe")) { - return 40; - } - if (name.equals("Splitbark helm")) { - return 40; - } - if (name.equals("Splitbark body")) { - return 40; - } - if (name.equals("Splitbark gauntlets")) { - return 40; - } - if (name.equals("Splitbark legs")) { - return 40; - } - if (name.equals("Splitbark greaves")) { - return 40; - } - if (name.equals("Infinity gloves")) { - return 50; - } - if (name.equals("Infinity hat")) { - return 50; - } - if (name.equals("Infinity top")) { - return 50; - } - if (name.equals("Infinity bottoms")) { - return 50; - } - if (name.equals("Infinity boots")) { - return 50; - } - if (name.equals("Ahrims hood")) { - return 70; - } - if (name.equals("Ahrims robetop")) { - return 70; - } - if (name.equals("Ahrims robeskirt")) { - return 70; - } - if (name.equals("Ahrims staff")) { - return 70; - } - if (name.equals("Saradomin cape")) { - return 60; - } - if (name.equals("Saradomin staff")) { - return 60; - } - if (name.equals("Zamorak cape")) { - return 60; - } - if (name.equals("Zamorak staff")) { - return 60; - } - if (name.equals("Guthix cape")) { - return 60; - } - if (name.equals("Guthix staff")) { - return 60; - } - if (name.equals("mud staff")) { - return 30; - } - if (name.equals("Fire battlestaff")) { - return 30; - } - return 1; + for (String element : EquipmentConstants.BOOTS) { + if (name.endsWith(element) || name.startsWith(element)) { + return 10; + } } - - /** - * Gets the ranged requirement. - * - * @param definition The item. - * @return The required level. - */ - private static int getRangedRequirement(ItemDefinition definition) { - int id = definition.getId(); - String name = definition.getName(); - if (name == null) { - name = "null"; - } - if (id == 2499) { - return 50; - } - if (id == 1135) { - return 40; - } - if (id == 1099) { - return 40; - } - if (id == 1065) { - return 40; - } - if (id == 2501) { - return 60; - } - if (id == 2503) { - return 70; - } - if (id == 2487) { - return 50; - } - if (id == 2489) { - return 60; - } - if (id == 2495) { - return 60; - } - if (id == 2491) { - return 70; - } - if (id == 2493) { - return 50; - } - if (id == 2505) { - return 60; - } - if (id == 2507) { - return 70; - } - if (id == 859) { - return 40; - } - if (id == 861) { - return 40; - } - if (id == 7370) { - return 40; - } - if (id == 7372) { - return 40; - } - if (id == 7378) { - return 40; - } - if (id == 7380) { - return 40; - } - if (id == 7374) { - return 50; - } - if (id == 7376) { - return 50; - } - if (id == 7382) { - return 50; - } - if (id == 7384) { - return 50; - } - if (name.equals("Coif")) { - return 20; - } - if (name.startsWith("Studded chaps")) { - return 20; - } - if (name.startsWith("Studded")) { - return 20; - } - if (name.equals("Karils coif")) { - return 70; - } - if (name.equals("Karils leathertop")) { - return 70; - } - if (name.equals("Karils leatherskirt")) { - return 70; - } - if (name.equals("Robin hood hat")) { - return 40; - } - if (name.equals("Ranger boots")) { - return 40; - } - if (name.equals("Crystal bow full")) { - return 70; - } - if (name.equals("New crystal bow")) { - return 70; - } - if (name.equals("Karils crossbow")) { - return 70; - } - if (id == 2497) { - return 70; - } - if (name.equals("Rune thrownaxe")) { - return 40; - } - if (name.equals("Rune dart")) { - return 40; - } - if (name.equals("Rune javelin")) { - return 40; - } - if (name.equals("Rune knife")) { - return 40; - } - if (name.equals("Adamant thrownaxe")) { - return 30; - } - if (name.equals("Adamant dart")) { - return 30; - } - if (name.equals("Adamant javelin")) { - return 30; - } - if (name.equals("Adamant knife")) { - return 30; - } - if (name.equals("Toktz-xil-ul")) { - return 60; - } - if (name.equals("Seercull")) { - return 50; - } - if (name.equals("Bolt rack")) { - return 70; - } - if (name.equals("Rune arrow")) { - return 40; - } - if (name.equals("Adamant arrow")) { - return 30; - } - if (name.equals("Mithril arrow")) { - return 1; - } else { - return 1; - } + for (String element : EquipmentConstants.GLOVES) { + if (name.endsWith(element) || name.startsWith(element)) { + return 9; + } } - - /** - * Gets the strength requirement. - * - * @param def The item. - * @return The required level. - */ - private static int getStrengthRequirement(ItemDefinition def) { - String name = def.getName(); - if (name == null) { - name = "null"; - } - if (name.equals("Torags hammers")) { - return 70; - } - if (name.equals("Dharoks greataxe")) { - return 70; - } - if (name.equals("Granite maul")) { - return 50; - } - if (name.equals("Granite legs")) { - return 99; - } - if (name.equals("Tzhaar-ket-om")) { - return 60; - } - if (name.equals("Granite shield")) { - return 50; - } - return 1; + for (String element : EquipmentConstants.SHIELDS) { + if (name.contains(element)) { + return 5; + } } - - /** - * Gets the weapon type. - * - * @param definition The item. - * @return The weapon type, or {@code -1} if it is not a weapon. - */ - private static int getWeaponType(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - for (String element : EquipmentConstants.CAPES) { - if (name.contains(element)) { - return 1; - } - } - for (String element : EquipmentConstants.HATS) { - if (name.contains(element)) { - return 0; - } - } - for (String element : EquipmentConstants.BOOTS) { - if (name.endsWith(element) || name.startsWith(element)) { - return 10; - } - } - for (String element : EquipmentConstants.GLOVES) { - if (name.endsWith(element) || name.startsWith(element)) { - return 9; - } - } - for (String element : EquipmentConstants.SHIELDS) { - if (name.contains(element)) { - return 5; - } - } - for (String element : EquipmentConstants.AMULETS) { - if (name.endsWith(element) || name.startsWith(element)) { - return 2; - } - } - for (String element : EquipmentConstants.ARROWS) { - if (name.endsWith(element) || name.startsWith(element)) { - return 13; - } - } - for (String element : EquipmentConstants.RINGS) { - if (name.endsWith(element) || name.startsWith(element)) { - return 12; - } - } - for (String element : EquipmentConstants.BODY) { - if (name.contains(element)) { - return 4; - } - } - for (String element : EquipmentConstants.LEGS) { - if (name.contains(element)) { - return 7; - } - } - for (String element : EquipmentConstants.WEAPONS) { - if (name.endsWith(element) || name.startsWith(element)) { - return 3; - } - } - return -1; + for (String element : EquipmentConstants.AMULETS) { + if (name.endsWith(element) || name.startsWith(element)) { + return 2; + } } - - /** - * Checks if the item is a full body item. - * - * @param definition The item. - * @return {@code true} if so, {@code false} otherwise. - */ - private static boolean isFullBody(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - for (String element : EquipmentConstants.FULL_BODIES) { - if (name.contains(element)) { - return true; - } - } - return false; + for (String element : EquipmentConstants.ARROWS) { + if (name.endsWith(element) || name.startsWith(element)) { + return 13; + } } - - /** - * Checks if the item is a full hat item. - * - * @param definition The item. - * @return {@code true} if so, {@code false} otherwise. - */ - private static boolean isFullHat(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - for (String element : EquipmentConstants.FULL_HATS) { - if (name.endsWith(element)) { - return true; - } - } - return false; + for (String element : EquipmentConstants.RINGS) { + if (name.endsWith(element) || name.startsWith(element)) { + return 12; + } } - - /** - * Checks if the item is a full mask item. - * - * @param definition The item. - * @return {@code true} if so, {@code false} otherwise. - */ - private static boolean isFullMask(ItemDefinition definition) { - String name = definition.getName(); - if (name == null) { - name = "null"; - } - for (String element : EquipmentConstants.FULL_MASKS) { - if (name.endsWith(element)) { - return true; - } - } - return false; + for (String element : EquipmentConstants.BODY) { + if (name.contains(element)) { + return 4; + } } - - /** - * Checks if the item is two handed. - * - * @param definition The item. - * @return {@code true} if so, {@code false} otherwise. - */ - private static boolean isTwoHanded(ItemDefinition definition) { - int id = definition.getId(); - String name = definition.getName(); - if (name == null) { - name = "null"; - } - if (id == 4212) { - return true; - } else if (id == 4214) { - return true; - } else if (name.endsWith("2h sword")) { - return true; - } else if (name.endsWith("longbow")) { - return true; - } else if (name.equals("Seercull")) { - return true; - } else if (name.endsWith("shortbow")) { - return true; - } else if (name.endsWith("Longbow")) { - return true; - } else if (name.endsWith("Shortbow")) { - return true; - } else if (name.endsWith("bow full")) { - return true; - } else if (name.endsWith("halberd")) { - return true; - } else if (name.equals("Granite maul")) { - return true; - } else if (name.equals("Karils crossbow")) { - return true; - } else if (name.equals("Torags hammers")) { - return true; - } else if (name.equals("Veracs flail")) { - return true; - } else if (name.equals("Dharoks greataxe")) { - return true; - } else if (name.equals("Guthans warspear")) { - return true; - } else if (name.equals("Tzhaar-ket-om")) { - return true; - } else if (name.endsWith("godsword")) { - return true; - } else if (name.equals("Saradomin sword")) { - return true; - } - return false; + for (String element : EquipmentConstants.LEGS) { + if (name.contains(element)) { + return 7; + } } - - /** - * The entry point of the application. - * - * @param args The command line arguments. - * @throws Exception If an error occurs. - */ - public static void main(String[] args) throws Exception { - if (args.length != 1) { - throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.EquipmentUpdater [release]."); - } - String release = args[0]; - - try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/equipment-" - + release + ".dat"))); - IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + release), true)) { - ItemDefinitionDecoder decoder = new ItemDefinitionDecoder(fs); - ItemDefinition[] definitions = decoder.decode(); - ItemDefinition.init(definitions); - - os.writeShort(definitions.length); - for (int id = 0; id < definitions.length; id++) { - ItemDefinition def = ItemDefinition.lookup(id); - int type = getWeaponType(def); - os.writeByte(type); - if (type != -1) { - os.writeBoolean(isTwoHanded(def)); - os.writeBoolean(isFullBody(def)); - os.writeBoolean(isFullHat(def)); - os.writeBoolean(isFullMask(def)); - os.writeByte(getAttackRequirement(def)); - os.writeByte(getStrengthRequirement(def)); - os.writeByte(getDefenceRequirement(def)); - os.writeByte(getRangedRequirement(def)); - os.writeByte(getMagicRequirement(def)); - } - } - } + for (String element : EquipmentConstants.WEAPONS) { + if (name.endsWith(element) || name.startsWith(element)) { + return 3; + } } + return -1; + } - /** - * Default private constructor to prevent instantiation. - */ - private EquipmentUpdater() { + /** + * Checks if the item is a full body item. + * + * @param definition The item. + * @return {@code true} if so, {@code false} otherwise. + */ + private static boolean isFullBody(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; } + for (String element : EquipmentConstants.FULL_BODIES) { + if (name.contains(element)) { + return true; + } + } + return false; + } + + /** + * Checks if the item is a full hat item. + * + * @param definition The item. + * @return {@code true} if so, {@code false} otherwise. + */ + private static boolean isFullHat(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; + } + for (String element : EquipmentConstants.FULL_HATS) { + if (name.endsWith(element)) { + return true; + } + } + return false; + } + + /** + * Checks if the item is a full mask item. + * + * @param definition The item. + * @return {@code true} if so, {@code false} otherwise. + */ + private static boolean isFullMask(ItemDefinition definition) { + String name = definition.getName(); + if (name == null) { + name = "null"; + } + for (String element : EquipmentConstants.FULL_MASKS) { + if (name.endsWith(element)) { + return true; + } + } + return false; + } + + /** + * Checks if the item is two handed. + * + * @param definition The item. + * @return {@code true} if so, {@code false} otherwise. + */ + private static boolean isTwoHanded(ItemDefinition definition) { + int id = definition.getId(); + String name = definition.getName(); + if (name == null) { + name = "null"; + } + if (id == 4212) { + return true; + } else if (id == 4214) { + return true; + } else if (name.endsWith("2h sword")) { + return true; + } else if (name.endsWith("longbow")) { + return true; + } else if (name.equals("Seercull")) { + return true; + } else if (name.endsWith("shortbow")) { + return true; + } else if (name.endsWith("Longbow")) { + return true; + } else if (name.endsWith("Shortbow")) { + return true; + } else if (name.endsWith("bow full")) { + return true; + } else if (name.endsWith("halberd")) { + return true; + } else if (name.equals("Granite maul")) { + return true; + } else if (name.equals("Karils crossbow")) { + return true; + } else if (name.equals("Torags hammers")) { + return true; + } else if (name.equals("Veracs flail")) { + return true; + } else if (name.equals("Dharoks greataxe")) { + return true; + } else if (name.equals("Guthans warspear")) { + return true; + } else if (name.equals("Tzhaar-ket-om")) { + return true; + } else if (name.endsWith("godsword")) { + return true; + } else if (name.equals("Saradomin sword")) { + return true; + } + return false; + } + + /** + * The entry point of the application. + * + * @param args The command line arguments. + * @throws Exception If an error occurs. + */ + public static void main(String[] args) throws Exception { + if (args.length != 1) { + throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.EquipmentUpdater [release]."); + } + String release = args[0]; + + try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/equipment-" + + release + ".dat"))); + IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + release), true)) { + ItemDefinitionDecoder decoder = new ItemDefinitionDecoder(fs); + ItemDefinition[] definitions = decoder.decode(); + ItemDefinition.init(definitions); + + os.writeShort(definitions.length); + for (int id = 0; id < definitions.length; id++) { + ItemDefinition def = ItemDefinition.lookup(id); + int type = getWeaponType(def); + os.writeByte(type); + if (type != -1) { + os.writeBoolean(isTwoHanded(def)); + os.writeBoolean(isFullBody(def)); + os.writeBoolean(isFullHat(def)); + os.writeBoolean(isFullMask(def)); + os.writeByte(getAttackRequirement(def)); + os.writeByte(getStrengthRequirement(def)); + os.writeByte(getDefenceRequirement(def)); + os.writeByte(getRangedRequirement(def)); + os.writeByte(getMagicRequirement(def)); + } + } + } + } + + /** + * Default private constructor to prevent instantiation. + */ + private EquipmentUpdater() { + } } \ No newline at end of file diff --git a/src/org/apollo/tools/NoteUpdater.java b/src/org/apollo/tools/NoteUpdater.java index c47aa7db..e47122f1 100644 --- a/src/org/apollo/tools/NoteUpdater.java +++ b/src/org/apollo/tools/NoteUpdater.java @@ -18,44 +18,44 @@ import org.apollo.game.model.def.ItemDefinition; */ public final class NoteUpdater { - /** - * The entry point of the application. - * - * @param args The command line arguments. - * @throws Exception If an error occurs. - */ - public static void main(String[] args) throws Exception { - if (args.length != 1) { - throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.NoteUpdater [release]."); - } - String release = args[0]; - - try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/note-" - + release + ".dat"))); - IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + release), true)) { - ItemDefinitionDecoder decoder = new ItemDefinitionDecoder(fs); - ItemDefinition[] defs = decoder.decode(); - ItemDefinition.init(defs); - - os.writeShort(defs.length); - Map itemToNote = new HashMap(); - - for (int id = 0; id < defs.length; id++) { - ItemDefinition def = ItemDefinition.lookup(id); - if (def.isNote()) { - itemToNote.put(def.getNoteInfoId(), def.getId()); - } - } - - for (int id = 0; id < defs.length; id++) { - if (itemToNote.containsKey(id)) { - os.writeBoolean(true); // notable - os.writeShort(itemToNote.get(id)); - } else { - os.writeBoolean(false); // not notable - } - } - } + /** + * The entry point of the application. + * + * @param args The command line arguments. + * @throws Exception If an error occurs. + */ + public static void main(String[] args) throws Exception { + if (args.length != 1) { + throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.NoteUpdater [release]."); } + String release = args[0]; + + try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/note-" + + release + ".dat"))); + IndexedFileSystem fs = new IndexedFileSystem(new File("data/fs/" + release), true)) { + ItemDefinitionDecoder decoder = new ItemDefinitionDecoder(fs); + ItemDefinition[] defs = decoder.decode(); + ItemDefinition.init(defs); + + os.writeShort(defs.length); + Map itemToNote = new HashMap(); + + for (int id = 0; id < defs.length; id++) { + ItemDefinition def = ItemDefinition.lookup(id); + if (def.isNote()) { + itemToNote.put(def.getNoteInfoId(), def.getId()); + } + } + + for (int id = 0; id < defs.length; id++) { + if (itemToNote.containsKey(id)) { + os.writeBoolean(true); // notable + os.writeShort(itemToNote.get(id)); + } else { + os.writeBoolean(false); // not notable + } + } + } + } } \ No newline at end of file diff --git a/src/org/apollo/update/ChannelRequest.java b/src/org/apollo/update/ChannelRequest.java index 31f17faa..d8f89bf0 100644 --- a/src/org/apollo/update/ChannelRequest.java +++ b/src/org/apollo/update/ChannelRequest.java @@ -10,52 +10,52 @@ import io.netty.channel.Channel; */ public final class ChannelRequest implements Comparable> { - /** - * The channel. - */ - private final Channel channel; + /** + * The channel. + */ + private final Channel channel; - /** - * The request. - */ - private final T request; + /** + * The request. + */ + private final T request; - /** - * Creates a new channel request. - * - * @param channel The channel. - * @param request The request. - */ - public ChannelRequest(Channel channel, T request) { - this.channel = channel; - this.request = request; + /** + * Creates a new channel request. + * + * @param channel The channel. + * @param request The request. + */ + public ChannelRequest(Channel channel, T request) { + this.channel = channel; + this.request = request; + } + + @SuppressWarnings("unchecked") + @Override + public int compareTo(ChannelRequest o) { + if (request instanceof Comparable && o.request instanceof Comparable) { + return ((Comparable) request).compareTo(o.request); } + return 0; + } - @SuppressWarnings("unchecked") - @Override - public int compareTo(ChannelRequest o) { - if (request instanceof Comparable && o.request instanceof Comparable) { - return ((Comparable) request).compareTo(o.request); - } - return 0; - } + /** + * Gets the channel. + * + * @return The channel. + */ + public Channel getChannel() { + return channel; + } - /** - * Gets the channel. - * - * @return The channel. - */ - public Channel getChannel() { - return channel; - } - - /** - * Gets the request. - * - * @return The request. - */ - public T getRequest() { - return request; - } + /** + * Gets the request. + * + * @return The request. + */ + public T getRequest() { + return request; + } } \ No newline at end of file diff --git a/src/org/apollo/update/HttpRequestWorker.java b/src/org/apollo/update/HttpRequestWorker.java index 4ea9094c..5520f82f 100644 --- a/src/org/apollo/update/HttpRequestWorker.java +++ b/src/org/apollo/update/HttpRequestWorker.java @@ -28,121 +28,121 @@ import org.apollo.update.resource.VirtualResourceProvider; */ public final class HttpRequestWorker extends RequestWorker { - /** - * The default character set. - */ - private static final Charset CHARACTER_SET = Charset.forName("ISO-8859-1"); + /** + * The default character set. + */ + private static final Charset CHARACTER_SET = Charset.forName("ISO-8859-1"); - /** - * The value of the server header. - */ - private static final String SERVER_IDENTIFIER = "JAGeX/3.1"; + /** + * The value of the server header. + */ + private static final String SERVER_IDENTIFIER = "JAGeX/3.1"; - /** - * The directory with web files. - */ - private static final File WWW_DIRECTORY = new File("./data/www/"); + /** + * The directory with web files. + */ + private static final File WWW_DIRECTORY = new File("./data/www/"); - /** - * Creates the HTTP request worker. - * - * @param dispatcher The dispatcher. - * @param fs The file system. - */ - public HttpRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { - super(dispatcher, new CombinedResourceProvider(new VirtualResourceProvider(fs), new HypertextResourceProvider( - WWW_DIRECTORY))); + /** + * Creates the HTTP request worker. + * + * @param dispatcher The dispatcher. + * @param fs The file system. + */ + public HttpRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { + super(dispatcher, new CombinedResourceProvider(new VirtualResourceProvider(fs), new HypertextResourceProvider( + WWW_DIRECTORY))); + } + + /** + * Creates an error page. + * + * @param status The HTTP status. + * @param description The error description. + * @return The error page as a buffer. + */ + private ByteBuf createErrorPage(HttpResponseStatus status, String description) { + String title = status.code() + " " + status.reasonPhrase(); + + StringBuilder builder = new StringBuilder(); + + builder.append(""); + builder.append(title); + builder.append("

"); + builder.append(title); + builder.append("

"); + builder.append(description); + builder.append("


"); + builder.append(SERVER_IDENTIFIER); + builder.append(" Server
"); + + return Unpooled.copiedBuffer(builder.toString(), Charset.defaultCharset()); + } + + /** + * Gets the MIME type of a file by its name. + * + * @param name The file name. + * @return The MIME type. + */ + private String getMimeType(String name) { + if (name.endsWith("/")) { + name = name.concat("index.html"); + } + if (name.endsWith(".htm") || name.endsWith(".html")) { + return "text/html"; + } else if (name.endsWith(".css")) { + return "text/css"; + } else if (name.endsWith(".js")) { + return "text/javascript"; + } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { + return "image/jpeg"; + } else if (name.endsWith(".gif")) { + return "image/gif"; + } else if (name.endsWith(".png")) { + return "image/png"; + } else if (name.endsWith(".txt")) { + return "text/plain"; + } + return "application/octect-stream"; + } + + @Override + protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { + return dispatcher.nextHttpRequest(); + } + + @Override + protected void service(ResourceProvider provider, Channel channel, HttpRequest request) throws IOException { + String path = request.getUri(); + ByteBuffer buf = provider.get(path); + + ByteBuf wrapped; + HttpResponseStatus status = HttpResponseStatus.OK; + + String mime = getMimeType(request.getUri()); + + if (buf == null) { + status = HttpResponseStatus.NOT_FOUND; + wrapped = createErrorPage(status, "The page you requested could not be found."); + mime = "text/html"; + } else { + wrapped = Unpooled.wrappedBuffer(buf); } - /** - * Creates an error page. - * - * @param status The HTTP status. - * @param description The error description. - * @return The error page as a buffer. - */ - private ByteBuf createErrorPage(HttpResponseStatus status, String description) { - String title = status.code() + " " + status.reasonPhrase(); + HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), status); - StringBuilder builder = new StringBuilder(); + response.headers().set("Date", new Date()); + response.headers().set("Server", SERVER_IDENTIFIER); + response.headers().set("Content-type", mime + ", charset=" + CHARACTER_SET.name()); + response.headers().set("Cache-control", "no-cache"); + response.headers().set("Pragma", "no-cache"); + response.headers().set("Expires", new Date(0)); + response.headers().set("Connection", "close"); + response.headers().set("Content-length", wrapped.readableBytes()); - builder.append(""); - builder.append(title); - builder.append("

"); - builder.append(title); - builder.append("

"); - builder.append(description); - builder.append("


"); - builder.append(SERVER_IDENTIFIER); - builder.append(" Server
"); - - return Unpooled.copiedBuffer(builder.toString(), Charset.defaultCharset()); - } - - /** - * Gets the MIME type of a file by its name. - * - * @param name The file name. - * @return The MIME type. - */ - private String getMimeType(String name) { - if (name.endsWith("/")) { - name = name.concat("index.html"); - } - if (name.endsWith(".htm") || name.endsWith(".html")) { - return "text/html"; - } else if (name.endsWith(".css")) { - return "text/css"; - } else if (name.endsWith(".js")) { - return "text/javascript"; - } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { - return "image/jpeg"; - } else if (name.endsWith(".gif")) { - return "image/gif"; - } else if (name.endsWith(".png")) { - return "image/png"; - } else if (name.endsWith(".txt")) { - return "text/plain"; - } - return "application/octect-stream"; - } - - @Override - protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { - return dispatcher.nextHttpRequest(); - } - - @Override - protected void service(ResourceProvider provider, Channel channel, HttpRequest request) throws IOException { - String path = request.getUri(); - ByteBuffer buf = provider.get(path); - - ByteBuf wrapped; - HttpResponseStatus status = HttpResponseStatus.OK; - - String mime = getMimeType(request.getUri()); - - if (buf == null) { - status = HttpResponseStatus.NOT_FOUND; - wrapped = createErrorPage(status, "The page you requested could not be found."); - mime = "text/html"; - } else { - wrapped = Unpooled.wrappedBuffer(buf); - } - - HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), status); - - response.headers().set("Date", new Date()); - response.headers().set("Server", SERVER_IDENTIFIER); - response.headers().set("Content-type", mime + ", charset=" + CHARACTER_SET.name()); - response.headers().set("Cache-control", "no-cache"); - response.headers().set("Pragma", "no-cache"); - response.headers().set("Expires", new Date(0)); - response.headers().set("Connection", "close"); - response.headers().set("Content-length", wrapped.readableBytes()); - - channel.write(response); - channel.writeAndFlush(wrapped).addListener(ChannelFutureListener.CLOSE); - } + channel.write(response); + channel.writeAndFlush(wrapped).addListener(ChannelFutureListener.CLOSE); + } } \ No newline at end of file diff --git a/src/org/apollo/update/JagGrabRequestWorker.java b/src/org/apollo/update/JagGrabRequestWorker.java index f763f7f8..17d75464 100644 --- a/src/org/apollo/update/JagGrabRequestWorker.java +++ b/src/org/apollo/update/JagGrabRequestWorker.java @@ -21,30 +21,30 @@ import org.apollo.update.resource.VirtualResourceProvider; */ public final class JagGrabRequestWorker extends RequestWorker { - /** - * Creates the JAGGRAB request worker. - * - * @param dispatcher The dispatcher. - * @param fs The file system. - */ - public JagGrabRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { - super(dispatcher, new VirtualResourceProvider(fs)); - } + /** + * Creates the JAGGRAB request worker. + * + * @param dispatcher The dispatcher. + * @param fs The file system. + */ + public JagGrabRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { + super(dispatcher, new VirtualResourceProvider(fs)); + } - @Override - protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { - return dispatcher.nextJagGrabRequest(); - } + @Override + protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { + return dispatcher.nextJagGrabRequest(); + } - @Override - protected void service(ResourceProvider provider, Channel channel, JagGrabRequest request) throws IOException { - ByteBuffer buf = provider.get(request.getFilePath()); - if (buf == null) { - channel.close(); - } else { - ByteBuf wrapped = Unpooled.wrappedBuffer(buf); - channel.writeAndFlush(new JagGrabResponse(wrapped)).addListener(ChannelFutureListener.CLOSE); - } + @Override + protected void service(ResourceProvider provider, Channel channel, JagGrabRequest request) throws IOException { + ByteBuffer buf = provider.get(request.getFilePath()); + if (buf == null) { + channel.close(); + } else { + ByteBuf wrapped = Unpooled.wrappedBuffer(buf); + channel.writeAndFlush(new JagGrabResponse(wrapped)).addListener(ChannelFutureListener.CLOSE); } + } } \ No newline at end of file diff --git a/src/org/apollo/update/OnDemandRequestWorker.java b/src/org/apollo/update/OnDemandRequestWorker.java index 7a28a0a8..aacd936a 100644 --- a/src/org/apollo/update/OnDemandRequestWorker.java +++ b/src/org/apollo/update/OnDemandRequestWorker.java @@ -19,46 +19,46 @@ import org.apollo.net.codec.update.OnDemandResponse; */ public final class OnDemandRequestWorker extends RequestWorker { - /** - * The maximum length of a chunk, in bytes. - */ - private static final int CHUNK_LENGTH = 500; + /** + * The maximum length of a chunk, in bytes. + */ + private static final int CHUNK_LENGTH = 500; - /** - * Creates the 'on-demand' request worker. - * - * @param dispatcher The dispatcher. - * @param fs The file system. - */ - public OnDemandRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { - super(dispatcher, fs); - } - - @Override - protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { - return dispatcher.nextOnDemandRequest(); - } - - @Override - protected void service(IndexedFileSystem fs, Channel channel, OnDemandRequest request) throws IOException { - FileDescriptor desc = request.getFileDescriptor(); - - ByteBuffer buffer = fs.getFile(desc); - int length = buffer.remaining(); - - for (int chunk = 0; buffer.remaining() > 0; chunk++) { - int chunkSize = buffer.remaining(); - if (chunkSize > CHUNK_LENGTH) { - chunkSize = CHUNK_LENGTH; - } - - byte[] tmp = new byte[chunkSize]; - buffer.get(tmp, 0, tmp.length); - ByteBuf chunkData = Unpooled.wrappedBuffer(tmp, 0, chunkSize); - - OnDemandResponse response = new OnDemandResponse(desc, length, chunk, chunkData); - channel.writeAndFlush(response); - } + /** + * Creates the 'on-demand' request worker. + * + * @param dispatcher The dispatcher. + * @param fs The file system. + */ + public OnDemandRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { + super(dispatcher, fs); + } + + @Override + protected ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { + return dispatcher.nextOnDemandRequest(); + } + + @Override + protected void service(IndexedFileSystem fs, Channel channel, OnDemandRequest request) throws IOException { + FileDescriptor desc = request.getFileDescriptor(); + + ByteBuffer buffer = fs.getFile(desc); + int length = buffer.remaining(); + + for (int chunk = 0; buffer.remaining() > 0; chunk++) { + int chunkSize = buffer.remaining(); + if (chunkSize > CHUNK_LENGTH) { + chunkSize = CHUNK_LENGTH; + } + + byte[] tmp = new byte[chunkSize]; + buffer.get(tmp, 0, tmp.length); + ByteBuf chunkData = Unpooled.wrappedBuffer(tmp, 0, chunkSize); + + OnDemandResponse response = new OnDemandResponse(desc, length, chunk, chunkData); + channel.writeAndFlush(response); } + } } \ No newline at end of file diff --git a/src/org/apollo/update/RequestWorker.java b/src/org/apollo/update/RequestWorker.java index 2674a502..b40f767c 100644 --- a/src/org/apollo/update/RequestWorker.java +++ b/src/org/apollo/update/RequestWorker.java @@ -13,85 +13,85 @@ import java.io.IOException; */ public abstract class RequestWorker implements Runnable { - /** - * The update dispatcher. - */ - private final UpdateDispatcher dispatcher; + /** + * The update dispatcher. + */ + private final UpdateDispatcher dispatcher; - /** - * The resource provider. - */ - private final P provider; + /** + * The resource provider. + */ + private final P provider; - /** - * A flag indicating if the worker should be running. - */ - private boolean running = true; + /** + * A flag indicating if the worker should be running. + */ + private boolean running = true; - /** - * Creates the request worker with the specified file system. - * - * @param dispatcher The update dispatcher. - * @param provider The resource provider. - */ - public RequestWorker(UpdateDispatcher dispatcher, P provider) { - this.provider = provider; - this.dispatcher = dispatcher; - } + /** + * Creates the request worker with the specified file system. + * + * @param dispatcher The update dispatcher. + * @param provider The resource provider. + */ + public RequestWorker(UpdateDispatcher dispatcher, P provider) { + this.provider = provider; + this.dispatcher = dispatcher; + } - /** - * Gets the next request. - * - * @param dispatcher The dispatcher. - * @return The next request. - * @throws InterruptedException If the thread is interrupted. - */ - protected abstract ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException; + /** + * Gets the next request. + * + * @param dispatcher The dispatcher. + * @return The next request. + * @throws InterruptedException If the thread is interrupted. + */ + protected abstract ChannelRequest nextRequest(UpdateDispatcher dispatcher) throws InterruptedException; - @Override - public final void run() { - while (true) { - synchronized (this) { - if (!running) { - break; - } - } - - ChannelRequest request; - try { - request = nextRequest(dispatcher); - } catch (InterruptedException e) { - continue; - } - - Channel channel = request.getChannel(); - - try { - service(provider, channel, request.getRequest()); - } catch (IOException e) { - e.printStackTrace(); - channel.close(); - } + @Override + public final void run() { + while (true) { + synchronized (this) { + if (!running) { + break; } - } + } - /** - * Services a request. - * - * @param provider The resource provider. - * @param channel The channel. - * @param request The request to service. - * @throws IOException If an I/O error occurs. - */ - protected abstract void service(P provider, Channel channel, T request) throws IOException; + ChannelRequest request; + try { + request = nextRequest(dispatcher); + } catch (InterruptedException e) { + continue; + } - /** - * Stops this worker. The worker's thread may need to be interrupted. - */ - public final void stop() { - synchronized (this) { - running = false; - } + Channel channel = request.getChannel(); + + try { + service(provider, channel, request.getRequest()); + } catch (IOException e) { + e.printStackTrace(); + channel.close(); + } } + } + + /** + * Services a request. + * + * @param provider The resource provider. + * @param channel The channel. + * @param request The request to service. + * @throws IOException If an I/O error occurs. + */ + protected abstract void service(P provider, Channel channel, T request) throws IOException; + + /** + * Stops this worker. The worker's thread may need to be interrupted. + */ + public final void stop() { + synchronized (this) { + running = false; + } + } } \ No newline at end of file diff --git a/src/org/apollo/update/UpdateConstants.java b/src/org/apollo/update/UpdateConstants.java index b8b4c37f..11d88d96 100644 --- a/src/org/apollo/update/UpdateConstants.java +++ b/src/org/apollo/update/UpdateConstants.java @@ -7,11 +7,11 @@ package org.apollo.update; */ public final class UpdateConstants { - /** - * Default private constructor to prevent instantiation by other classes. - */ - private UpdateConstants() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private UpdateConstants() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/update/UpdateDispatcher.java b/src/org/apollo/update/UpdateDispatcher.java index 9a7be5d7..ae73ad39 100644 --- a/src/org/apollo/update/UpdateDispatcher.java +++ b/src/org/apollo/update/UpdateDispatcher.java @@ -17,93 +17,93 @@ import org.apollo.net.codec.update.OnDemandRequest; */ public final class UpdateDispatcher { - /** - * The maximum size of a queue before requests are rejected. - */ - private static final int MAXIMUM_QUEUE_SIZE = 1024; + /** + * The maximum size of a queue before requests are rejected. + */ + private static final int MAXIMUM_QUEUE_SIZE = 1024; - /** - * A queue for pending HTTP requests. - */ - private final BlockingQueue> httpQueue = new LinkedBlockingQueue>(); + /** + * A queue for pending HTTP requests. + */ + private final BlockingQueue> httpQueue = new LinkedBlockingQueue>(); - /** - * A queue for pending JAGGRAB requests. - */ - private final BlockingQueue> jagGrabQueue = new LinkedBlockingQueue>(); + /** + * A queue for pending JAGGRAB requests. + */ + private final BlockingQueue> jagGrabQueue = new LinkedBlockingQueue>(); - /** - * A queue for pending 'on-demand' requests. - */ - private final BlockingQueue> onDemandQueue = new PriorityBlockingQueue>(); + /** + * A queue for pending 'on-demand' requests. + */ + private final BlockingQueue> onDemandQueue = new PriorityBlockingQueue>(); - /** - * Dispatches a HTTP request. - * - * @param channel The channel. - * @param request The request. - */ - public void dispatch(Channel channel, HttpRequest request) { - if (httpQueue.size() >= MAXIMUM_QUEUE_SIZE) { - channel.close(); - } - httpQueue.add(new ChannelRequest(channel, request)); + /** + * Dispatches a HTTP request. + * + * @param channel The channel. + * @param request The request. + */ + public void dispatch(Channel channel, HttpRequest request) { + if (httpQueue.size() >= MAXIMUM_QUEUE_SIZE) { + channel.close(); } + httpQueue.add(new ChannelRequest<>(channel, request)); + } - /** - * Dispatches a JAGGRAB request. - * - * @param channel The channel. - * @param request The request. - */ - public void dispatch(Channel channel, JagGrabRequest request) { - if (jagGrabQueue.size() >= MAXIMUM_QUEUE_SIZE) { - channel.close(); - } - jagGrabQueue.add(new ChannelRequest(channel, request)); + /** + * Dispatches a JAGGRAB request. + * + * @param channel The channel. + * @param request The request. + */ + public void dispatch(Channel channel, JagGrabRequest request) { + if (jagGrabQueue.size() >= MAXIMUM_QUEUE_SIZE) { + channel.close(); } + jagGrabQueue.add(new ChannelRequest<>(channel, request)); + } - /** - * Dispatches an 'on-demand' request. - * - * @param channel The channel. - * @param request The request. - */ - public void dispatch(Channel channel, OnDemandRequest request) { - if (onDemandQueue.size() >= MAXIMUM_QUEUE_SIZE) { - channel.close(); - } - onDemandQueue.add(new ChannelRequest(channel, request)); + /** + * Dispatches an 'on-demand' request. + * + * @param channel The channel. + * @param request The request. + */ + public void dispatch(Channel channel, OnDemandRequest request) { + if (onDemandQueue.size() >= MAXIMUM_QUEUE_SIZE) { + channel.close(); } + onDemandQueue.add(new ChannelRequest<>(channel, request)); + } - /** - * Gets the next HTTP request from the queue, blocking if none are available. - * - * @return The HTTP request. - * @throws InterruptedException If the thread is interrupted. - */ - ChannelRequest nextHttpRequest() throws InterruptedException { - return httpQueue.take(); - } + /** + * Gets the next HTTP request from the queue, blocking if none are available. + * + * @return The HTTP request. + * @throws InterruptedException If the thread is interrupted. + */ + ChannelRequest nextHttpRequest() throws InterruptedException { + return httpQueue.take(); + } - /** - * Gets the next JAGGRAB request from the queue, blocking if none are available. - * - * @return The JAGGRAB request. - * @throws InterruptedException If the thread is interrupted. - */ - ChannelRequest nextJagGrabRequest() throws InterruptedException { - return jagGrabQueue.take(); - } + /** + * Gets the next JAGGRAB request from the queue, blocking if none are available. + * + * @return The JAGGRAB request. + * @throws InterruptedException If the thread is interrupted. + */ + ChannelRequest nextJagGrabRequest() throws InterruptedException { + return jagGrabQueue.take(); + } - /** - * Gets the next 'on-demand' request from the queue, blocking if none are available. - * - * @return The 'on-demand' request. - * @throws InterruptedException If the thread is interrupted. - */ - ChannelRequest nextOnDemandRequest() throws InterruptedException { - return onDemandQueue.take(); - } + /** + * Gets the next 'on-demand' request from the queue, blocking if none are available. + * + * @return The 'on-demand' request. + * @throws InterruptedException If the thread is interrupted. + */ + ChannelRequest nextOnDemandRequest() throws InterruptedException { + return onDemandQueue.take(); + } } \ No newline at end of file diff --git a/src/org/apollo/update/UpdateService.java b/src/org/apollo/update/UpdateService.java index 8fdb438a..2ae79ffe 100644 --- a/src/org/apollo/update/UpdateService.java +++ b/src/org/apollo/update/UpdateService.java @@ -16,79 +16,79 @@ import org.apollo.fs.IndexedFileSystem; */ public final class UpdateService extends Service { - /** - * The number of request types. - */ - private static final int REQUEST_TYPES = 3; + /** + * The number of request types. + */ + private static final int REQUEST_TYPES = 3; - /** - * The number of threads per request type. - */ - private static final int THREADS_PER_REQUEST_TYPE = Runtime.getRuntime().availableProcessors(); + /** + * The number of threads per request type. + */ + private static final int THREADS_PER_REQUEST_TYPE = Runtime.getRuntime().availableProcessors(); - /** - * The update dispatcher. - */ - private final UpdateDispatcher dispatcher = new UpdateDispatcher(); + /** + * The update dispatcher. + */ + private final UpdateDispatcher dispatcher = new UpdateDispatcher(); - /** - * The executor service. - */ - private final ExecutorService service; + /** + * The executor service. + */ + private final ExecutorService service; - /** - * A list of request workers. - */ - private final List> workers = new ArrayList>(); + /** + * A list of request workers. + */ + private final List> workers = new ArrayList>(); - /** - * Creates the update service. - */ - public UpdateService() { - int totalThreads = REQUEST_TYPES * THREADS_PER_REQUEST_TYPE; - service = Executors.newFixedThreadPool(totalThreads); + /** + * Creates the update service. + */ + public UpdateService() { + int totalThreads = REQUEST_TYPES * THREADS_PER_REQUEST_TYPE; + service = Executors.newFixedThreadPool(totalThreads); + } + + /** + * Gets the update dispatcher. + * + * @return The update dispatcher. + */ + public UpdateDispatcher getDispatcher() { + return dispatcher; + } + + /** + * Starts the threads in the pool. + */ + @Override + public void start() { + int release = getContext().getRelease().getReleaseNumber(); + try { + File base = new File("./data/fs/" + release + "/"); + for (int i = 0; i < THREADS_PER_REQUEST_TYPE; i++) { + workers.add(new JagGrabRequestWorker(dispatcher, new IndexedFileSystem(base, true))); + workers.add(new OnDemandRequestWorker(dispatcher, new IndexedFileSystem(base, true))); + workers.add(new HttpRequestWorker(dispatcher, new IndexedFileSystem(base, true))); + } + + for (RequestWorker worker : workers) { + service.submit(worker); + } + } catch (Exception ex) { + System.err.println("Error adding request workers - " + ex.getMessage()); + } + } + + /** + * Stops the threads in the pool. + */ + public void stop() { + for (RequestWorker worker : workers) { + worker.stop(); } - /** - * Gets the update dispatcher. - * - * @return The update dispatcher. - */ - public UpdateDispatcher getDispatcher() { - return dispatcher; - } - - /** - * Starts the threads in the pool. - */ - @Override - public void start() { - int release = getContext().getRelease().getReleaseNumber(); - try { - File base = new File("./data/fs/" + release + "/"); - for (int i = 0; i < THREADS_PER_REQUEST_TYPE; i++) { - workers.add(new JagGrabRequestWorker(dispatcher, new IndexedFileSystem(base, true))); - workers.add(new OnDemandRequestWorker(dispatcher, new IndexedFileSystem(base, true))); - workers.add(new HttpRequestWorker(dispatcher, new IndexedFileSystem(base, true))); - } - - for (RequestWorker worker : workers) { - service.submit(worker); - } - } catch (Exception ex) { - System.err.println("Error adding request workers - " + ex.getMessage()); - } - } - - /** - * Stops the threads in the pool. - */ - public void stop() { - for (RequestWorker worker : workers) { - worker.stop(); - } - - service.shutdownNow(); - } + service.shutdownNow(); + } } \ No newline at end of file diff --git a/src/org/apollo/update/resource/CombinedResourceProvider.java b/src/org/apollo/update/resource/CombinedResourceProvider.java index b2487565..ff874fa7 100644 --- a/src/org/apollo/update/resource/CombinedResourceProvider.java +++ b/src/org/apollo/update/resource/CombinedResourceProvider.java @@ -10,33 +10,33 @@ import java.nio.ByteBuffer; */ public final class CombinedResourceProvider extends ResourceProvider { - /** - * An array of resource providers. - */ - private final ResourceProvider[] providers; + /** + * An array of resource providers. + */ + private final ResourceProvider[] providers; - /** - * Creates the combined resource providers. - * - * @param providers The providers this provider delegates to. - */ - public CombinedResourceProvider(ResourceProvider... providers) { - this.providers = providers; - } + /** + * Creates the combined resource providers. + * + * @param providers The providers this provider delegates to. + */ + public CombinedResourceProvider(ResourceProvider... providers) { + this.providers = providers; + } - @Override - public boolean accept(String path) throws IOException { - return true; - } + @Override + public boolean accept(String path) throws IOException { + return true; + } - @Override - public ByteBuffer get(String path) throws IOException { - for (ResourceProvider provider : providers) { - if (provider.accept(path)) { - return provider.get(path); - } - } - return null; + @Override + public ByteBuffer get(String path) throws IOException { + for (ResourceProvider provider : providers) { + if (provider.accept(path)) { + return provider.get(path); + } } + return null; + } } \ No newline at end of file diff --git a/src/org/apollo/update/resource/HypertextResourceProvider.java b/src/org/apollo/update/resource/HypertextResourceProvider.java index 7b6fed1f..56ae68b3 100644 --- a/src/org/apollo/update/resource/HypertextResourceProvider.java +++ b/src/org/apollo/update/resource/HypertextResourceProvider.java @@ -14,49 +14,49 @@ import java.nio.channels.FileChannel.MapMode; */ public final class HypertextResourceProvider extends ResourceProvider { - /** - * The base directory from which documents are served. - */ - private final File base; + /** + * The base directory from which documents are served. + */ + private final File base; - /** - * Creates a new hypertext resource provider with the specified base directory. - * - * @param base The base directory. - */ - public HypertextResourceProvider(File base) { - this.base = base; + /** + * Creates a new hypertext resource provider with the specified base directory. + * + * @param base The base directory. + */ + public HypertextResourceProvider(File base) { + this.base = base; + } + + @Override + public boolean accept(String path) throws IOException { + File file = new File(base, path); + URI target = file.toURI().normalize(); + if (target.toASCIIString().startsWith(base.toURI().normalize().toASCIIString())) { + if (file.isDirectory()) { + file = new File(file, "index.html"); + } + return file.exists(); + } + return false; + } + + @Override + public ByteBuffer get(String path) throws IOException { + File file = new File(base, path); + if (file.isDirectory()) { + file = new File(file, "index.html"); + } + if (!file.exists()) { + return null; } - @Override - public boolean accept(String path) throws IOException { - File file = new File(base, path); - URI target = file.toURI().normalize(); - if (target.toASCIIString().startsWith(base.toURI().normalize().toASCIIString())) { - if (file.isDirectory()) { - file = new File(file, "index.html"); - } - return file.exists(); - } - return false; + ByteBuffer buffer; + try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { + buffer = raf.getChannel().map(MapMode.READ_ONLY, 0, raf.length()); } - @Override - public ByteBuffer get(String path) throws IOException { - File file = new File(base, path); - if (file.isDirectory()) { - file = new File(file, "index.html"); - } - if (!file.exists()) { - return null; - } - - ByteBuffer buffer; - try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { - buffer = raf.getChannel().map(MapMode.READ_ONLY, 0, raf.length()); - } - - return buffer; - } + return buffer; + } } \ No newline at end of file diff --git a/src/org/apollo/update/resource/ResourceProvider.java b/src/org/apollo/update/resource/ResourceProvider.java index f250b90f..87098ad3 100644 --- a/src/org/apollo/update/resource/ResourceProvider.java +++ b/src/org/apollo/update/resource/ResourceProvider.java @@ -10,22 +10,22 @@ import java.nio.ByteBuffer; */ public abstract class ResourceProvider { - /** - * Checks that this provider can fulfil a request to the specified resource. - * - * @param path The path to the resource, e.g. {@code /crc}. - * @return {@code true} if the provider can fulfil a request to the resource, {@code false} otherwise. - * @throws IOException If an I/O error occurs. - */ - public abstract boolean accept(String path) throws IOException; + /** + * Checks that this provider can fulfil a request to the specified resource. + * + * @param path The path to the resource, e.g. {@code /crc}. + * @return {@code true} if the provider can fulfil a request to the resource, {@code false} otherwise. + * @throws IOException If an I/O error occurs. + */ + public abstract boolean accept(String path) throws IOException; - /** - * Gets a resource by its path. - * - * @param path The path. - * @return The resource, or {@code null} if it doesn't exist. - * @throws IOException If an I/O error occurs. - */ - public abstract ByteBuffer get(String path) throws IOException; + /** + * Gets a resource by its path. + * + * @param path The path. + * @return The resource, or {@code null} if it doesn't exist. + * @throws IOException If an I/O error occurs. + */ + public abstract ByteBuffer get(String path) throws IOException; } \ No newline at end of file diff --git a/src/org/apollo/update/resource/VirtualResourceProvider.java b/src/org/apollo/update/resource/VirtualResourceProvider.java index e7babd27..15836df3 100644 --- a/src/org/apollo/update/resource/VirtualResourceProvider.java +++ b/src/org/apollo/update/resource/VirtualResourceProvider.java @@ -13,58 +13,58 @@ import org.apollo.fs.IndexedFileSystem; */ public final class VirtualResourceProvider extends ResourceProvider { - /** - * An array of valid prefixes. - */ - private static final String[] VALID_PREFIXES = { "crc", "title", "config", "interface", "media", "versionlist", - "textures", "wordenc", "sounds" }; + /** + * An array of valid prefixes. + */ + private static final String[] VALID_PREFIXES = { "crc", "title", "config", "interface", "media", "versionlist", + "textures", "wordenc", "sounds" }; - /** - * The file system. - */ - private final IndexedFileSystem fs; + /** + * The file system. + */ + private final IndexedFileSystem fs; - /** - * Creates a new virtual resource provider with the specified file system. - * - * @param fs The file system. - */ - public VirtualResourceProvider(IndexedFileSystem fs) { - this.fs = fs; + /** + * Creates a new virtual resource provider with the specified file system. + * + * @param fs The file system. + */ + public VirtualResourceProvider(IndexedFileSystem fs) { + this.fs = fs; + } + + @Override + public boolean accept(String path) throws IOException { + for (String prefix : VALID_PREFIXES) { + if (path.startsWith("/" + prefix)) { + return true; + } } + return false; + } - @Override - public boolean accept(String path) throws IOException { - for (String prefix : VALID_PREFIXES) { - if (path.startsWith("/" + prefix)) { - return true; - } - } - return false; - } - - @Override - public ByteBuffer get(String path) throws IOException { - if (path.startsWith("/crc")) { - return fs.getCrcTable(); - } else if (path.startsWith("/title")) { - return fs.getFile(0, 1); - } else if (path.startsWith("/config")) { - return fs.getFile(0, 2); - } else if (path.startsWith("/interface")) { - return fs.getFile(0, 3); - } else if (path.startsWith("/media")) { - return fs.getFile(0, 4); - } else if (path.startsWith("/versionlist")) { - return fs.getFile(0, 5); - } else if (path.startsWith("/textures")) { - return fs.getFile(0, 6); - } else if (path.startsWith("/wordenc")) { - return fs.getFile(0, 7); - } else if (path.startsWith("/sounds")) { - return fs.getFile(0, 8); - } - return null; + @Override + public ByteBuffer get(String path) throws IOException { + if (path.startsWith("/crc")) { + return fs.getCrcTable(); + } else if (path.startsWith("/title")) { + return fs.getFile(0, 1); + } else if (path.startsWith("/config")) { + return fs.getFile(0, 2); + } else if (path.startsWith("/interface")) { + return fs.getFile(0, 3); + } else if (path.startsWith("/media")) { + return fs.getFile(0, 4); + } else if (path.startsWith("/versionlist")) { + return fs.getFile(0, 5); + } else if (path.startsWith("/textures")) { + return fs.getFile(0, 6); + } else if (path.startsWith("/wordenc")) { + return fs.getFile(0, 7); + } else if (path.startsWith("/sounds")) { + return fs.getFile(0, 8); } + return null; + } } \ No newline at end of file diff --git a/src/org/apollo/util/BufferUtil.java b/src/org/apollo/util/BufferUtil.java index c5c10f65..564ebfe6 100644 --- a/src/org/apollo/util/BufferUtil.java +++ b/src/org/apollo/util/BufferUtil.java @@ -13,65 +13,65 @@ import org.apollo.net.NetworkConstants; */ public final class BufferUtil { - /** - * Reads a 'smart' (either a {@code byte} or {@code short} depending on the value) from the specified buffer. - * - * @param buffer The buffer. - * @return The 'smart'. - */ - public static int readSmart(ByteBuffer buffer) { - int peek = buffer.get(buffer.position()) & 0xFF; - if (peek < 128) { - return buffer.get() & 0xFF; - } - return (buffer.getShort() & 0xFFFF) - 32768; + /** + * Reads a 'smart' (either a {@code byte} or {@code short} depending on the value) from the specified buffer. + * + * @param buffer The buffer. + * @return The 'smart'. + */ + public static int readSmart(ByteBuffer buffer) { + int peek = buffer.get(buffer.position()) & 0xFF; + if (peek < 128) { + return buffer.get() & 0xFF; } + return (buffer.getShort() & 0xFFFF) - 32768; + } - /** - * Reads a string from the specified {@link ByteBuffer}. - * - * @param buffer The buffer. - * @return The string. - */ - public static String readString(ByteBuffer buffer) { - StringBuilder bldr = new StringBuilder(); - char character; - while ((character = (char) buffer.get()) != NetworkConstants.STRING_TERMINATOR) { - bldr.append(character); - } - return bldr.toString(); + /** + * Reads a string from the specified {@link ByteBuffer}. + * + * @param buffer The buffer. + * @return The string. + */ + public static String readString(ByteBuffer buffer) { + StringBuilder bldr = new StringBuilder(); + char character; + while ((character = (char) buffer.get()) != NetworkConstants.STRING_TERMINATOR) { + bldr.append(character); } + return bldr.toString(); + } - /** - * Reads a string from the specified {@link ByteBuf}. - * - * @param buffer The buffer. - * @return The string. - */ - public static String readString(ByteBuf buffer) { - StringBuilder builder = new StringBuilder(); - int character; - while (buffer.isReadable() && (character = buffer.readUnsignedByte()) != NetworkConstants.STRING_TERMINATOR) { - builder.append((char) character); - } - return builder.toString(); + /** + * Reads a string from the specified {@link ByteBuf}. + * + * @param buffer The buffer. + * @return The string. + */ + public static String readString(ByteBuf buffer) { + StringBuilder builder = new StringBuilder(); + int character; + while (buffer.isReadable() && (character = buffer.readUnsignedByte()) != NetworkConstants.STRING_TERMINATOR) { + builder.append((char) character); } + return builder.toString(); + } - /** - * Reads an unsigned tri-byte from the specified {@link ByteBuffer}. - * - * @param buffer The buffer. - * @return The tri-byte. - */ - public static int readUnsignedTriByte(ByteBuffer buffer) { - return (buffer.get() & 0xFF) << 16 | (buffer.get() & 0xFF) << 8 | buffer.get() & 0xFF; - } + /** + * Reads an unsigned tri-byte from the specified {@link ByteBuffer}. + * + * @param buffer The buffer. + * @return The tri-byte. + */ + public static int readUnsignedTriByte(ByteBuffer buffer) { + return (buffer.get() & 0xFF) << 16 | (buffer.get() & 0xFF) << 8 | buffer.get() & 0xFF; + } - /** - * Default private constructor to prevent instantiation. - */ - private BufferUtil() { + /** + * Default private constructor to prevent instantiation. + */ + private BufferUtil() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/util/CompressionUtil.java b/src/org/apollo/util/CompressionUtil.java index cc3ce697..8b1d20ae 100644 --- a/src/org/apollo/util/CompressionUtil.java +++ b/src/org/apollo/util/CompressionUtil.java @@ -20,108 +20,108 @@ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream */ public final class CompressionUtil { - /** - * Bzip2s the specified array. - * - * @param bytes The uncompressed array. - * @return The compressed array. - * @throws IOException If an I/O error occurs. - */ - public static byte[] bzip2(byte[] bytes) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - try (BZip2CompressorOutputStream os = new BZip2CompressorOutputStream(bout, 1)) { - os.write(bytes); - os.finish(); - byte[] compressed = bout.toByteArray(); - byte[] newCompressed = new byte[compressed.length - 4]; - System.arraycopy(compressed, 4, newCompressed, 0, newCompressed.length); - return newCompressed; + /** + * Bzip2s the specified array. + * + * @param bytes The uncompressed array. + * @return The compressed array. + * @throws IOException If an I/O error occurs. + */ + public static byte[] bzip2(byte[] bytes) throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try (BZip2CompressorOutputStream os = new BZip2CompressorOutputStream(bout, 1)) { + os.write(bytes); + os.finish(); + byte[] compressed = bout.toByteArray(); + byte[] newCompressed = new byte[compressed.length - 4]; + System.arraycopy(compressed, 4, newCompressed, 0, newCompressed.length); + return newCompressed; + } + } + + /** + * Gzips the specified array. + * + * @param bytes The uncompressed array. + * @return The compressed array. + * @throws IOException If an I/O error occurs. + */ + public static byte[] gzip(byte[] bytes) throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try (DeflaterOutputStream os = new GZIPOutputStream(bout)) { + os.write(bytes); + os.finish(); + return bout.toByteArray(); + } + } + + /** + * Unbzip2s the compressed array and places the result into the uncompressed array. + * + * @param compressed The compressed array. + * @param uncompressed The uncompressed array. + * @throws IOException If an I/O error occurs. + */ + public static void unbzip2(byte[] compressed, byte[] uncompressed) throws IOException { + byte[] newCompressed = new byte[compressed.length + 4]; + newCompressed[0] = 'B'; + newCompressed[1] = 'Z'; + newCompressed[2] = 'h'; + newCompressed[3] = '1'; + System.arraycopy(compressed, 0, newCompressed, 4, compressed.length); + + try (DataInputStream is = new DataInputStream(new BZip2CompressorInputStream(new ByteArrayInputStream( + newCompressed)))) { + is.readFully(uncompressed); + } + } + + /** + * Ungzips the compressed array and places the results into the uncompressed array. + * + * @param compressed The compressed array. + * @param uncompressed The uncompressed array. + * @throws IOException If an I/O error occurs. + */ + public static void ungzip(byte[] compressed, byte[] uncompressed) throws IOException { + try (DataInputStream is = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(compressed)))) { + is.readFully(uncompressed); + } + } + + /** + * Ungzips the compressed buffer and places the results into the returning array. + * + * @param compressed The compressed buffer. + * @return The uncompressed array. + * @throws IOException If an I/O error occurs. + */ + public static byte[] ungzip(ByteBuffer compressed) throws IOException { + byte[] data = new byte[compressed.remaining()]; + compressed.get(data); + InputStream is = new GZIPInputStream(new ByteArrayInputStream(data)); + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + while (true) { + byte[] buf = new byte[1024]; + int read = is.read(buf, 0, buf.length); + if (read == -1) { + break; } + os.write(buf, 0, read); + } + + return os.toByteArray(); + } finally { + is.close(); } + } - /** - * Gzips the specified array. - * - * @param bytes The uncompressed array. - * @return The compressed array. - * @throws IOException If an I/O error occurs. - */ - public static byte[] gzip(byte[] bytes) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - try (DeflaterOutputStream os = new GZIPOutputStream(bout)) { - os.write(bytes); - os.finish(); - return bout.toByteArray(); - } - } + /** + * Default private constructor to prevent instantiation. + */ + private CompressionUtil() { - /** - * Unbzip2s the compressed array and places the result into the uncompressed array. - * - * @param compressed The compressed array. - * @param uncompressed The uncompressed array. - * @throws IOException If an I/O error occurs. - */ - public static void unbzip2(byte[] compressed, byte[] uncompressed) throws IOException { - byte[] newCompressed = new byte[compressed.length + 4]; - newCompressed[0] = 'B'; - newCompressed[1] = 'Z'; - newCompressed[2] = 'h'; - newCompressed[3] = '1'; - System.arraycopy(compressed, 0, newCompressed, 4, compressed.length); - - try (DataInputStream is = new DataInputStream(new BZip2CompressorInputStream(new ByteArrayInputStream( - newCompressed)))) { - is.readFully(uncompressed); - } - } - - /** - * Ungzips the compressed array and places the results into the uncompressed array. - * - * @param compressed The compressed array. - * @param uncompressed The uncompressed array. - * @throws IOException If an I/O error occurs. - */ - public static void ungzip(byte[] compressed, byte[] uncompressed) throws IOException { - try (DataInputStream is = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(compressed)))) { - is.readFully(uncompressed); - } - } - - /** - * Ungzips the compressed buffer and places the results into the returning array. - * - * @param compressed The compressed buffer. - * @return The uncompressed array. - * @throws IOException If an I/O error occurs. - */ - public static byte[] ungzip(ByteBuffer compressed) throws IOException { - byte[] data = new byte[compressed.remaining()]; - compressed.get(data); - InputStream is = new GZIPInputStream(new ByteArrayInputStream(data)); - - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - while (true) { - byte[] buf = new byte[1024]; - int read = is.read(buf, 0, buf.length); - if (read == -1) { - break; - } - os.write(buf, 0, read); - } - - return os.toByteArray(); - } finally { - is.close(); - } - } - - /** - * Default private constructor to prevent instantiation. - */ - private CompressionUtil() { - - } + } } \ No newline at end of file diff --git a/src/org/apollo/util/EnumerationUtil.java b/src/org/apollo/util/EnumerationUtil.java index 9013e244..b309dd0a 100644 --- a/src/org/apollo/util/EnumerationUtil.java +++ b/src/org/apollo/util/EnumerationUtil.java @@ -11,39 +11,39 @@ import java.util.Iterator; */ public final class EnumerationUtil { - /** - * Returns an {@link Iterator} which wraps around the specified {@link Enumeration}. - * - * @param The type of object that is iterated over. - * @param enumeration The {@link Enumeration}. - * @return An {@link Iterator}. - */ - public static Iterator asIterator(final Enumeration enumeration) { - return new Iterator() { + /** + * Returns an {@link Iterator} which wraps around the specified {@link Enumeration}. + * + * @param The type of object that is iterated over. + * @param enumeration The {@link Enumeration}. + * @return An {@link Iterator}. + */ + public static Iterator asIterator(final Enumeration enumeration) { + return new Iterator() { - @Override - public boolean hasNext() { - return enumeration.hasMoreElements(); - } + @Override + public boolean hasNext() { + return enumeration.hasMoreElements(); + } - @Override - public E next() { - return enumeration.nextElement(); - } + @Override + public E next() { + return enumeration.nextElement(); + } - @Override - public void remove() { - throw new UnsupportedOperationException("Cannot remove an element using this wrapper."); - } + @Override + public void remove() { + throw new UnsupportedOperationException("Cannot remove an element using this wrapper."); + } - }; - } + }; + } - /** - * Default private constructor to prevent instantiation by other classes. - */ - private EnumerationUtil() { + /** + * Default private constructor to prevent instantiation by other classes. + */ + private EnumerationUtil() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/util/LanguageUtil.java b/src/org/apollo/util/LanguageUtil.java index 50a42372..ecee177c 100644 --- a/src/org/apollo/util/LanguageUtil.java +++ b/src/org/apollo/util/LanguageUtil.java @@ -7,23 +7,23 @@ package org.apollo.util; */ public final class LanguageUtil { - /** - * Gets the indefinite article of a 'thing'. - * - * @param thing The thing. - * @return The indefinite article. - */ - public static String getIndefiniteArticle(String thing) { - char first = thing.toLowerCase().charAt(0); - boolean vowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u'; - return vowel ? "an" : "a"; - } + /** + * Gets the indefinite article of a 'thing'. + * + * @param thing The thing. + * @return The indefinite article. + */ + public static String getIndefiniteArticle(String thing) { + char first = thing.toLowerCase().charAt(0); + boolean vowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u'; + return vowel ? "an" : "a"; + } - /** - * Default private constructor to prevent instantiation. - */ - private LanguageUtil() { + /** + * Default private constructor to prevent instantiation. + */ + private LanguageUtil() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/util/MobRepository.java b/src/org/apollo/util/MobRepository.java index 6d272a0a..e8bac096 100644 --- a/src/org/apollo/util/MobRepository.java +++ b/src/org/apollo/util/MobRepository.java @@ -13,193 +13,193 @@ import org.apollo.game.model.entity.Mob; */ public final class MobRepository implements Iterable { - /** - * The {@link Iterator} implementation for the {@link MobRepository} class. - * - * @author Graham - */ - private final class MobRepositoryIterator implements Iterator { - - /** - * The current index of this iterator. - */ - private int index = 0; - - /** - * The previous index of this iterator. - */ - private int previousIndex = -1; - - @Override - public boolean hasNext() { - for (int i = index; i < mobs.length; i++) { - if (mobs[i] != null) { - index = i; - return true; - } - } - return false; - } - - @SuppressWarnings("unchecked") - @Override - public T next() { - T mob = null; - for (int i = index; i < mobs.length; i++) { - if (mobs[i] != null) { - mob = (T) mobs[i]; - index = i; - break; - } - } - - if (mob == null) { - throw new NoSuchElementException("Mob does not exist."); - } - - previousIndex = index; - index++; - return mob; - } - - @SuppressWarnings("unchecked") - @Override - public void remove() { - if (previousIndex == -1) { - throw new IllegalStateException("Cannot remove as the repository is empty."); - } - MobRepository.this.remove((T) mobs[previousIndex]); - previousIndex = -1; - } - - } + /** + * The {@link Iterator} implementation for the {@link MobRepository} class. + * + * @author Graham + */ + private final class MobRepositoryIterator implements Iterator { /** - * The array of mobs in this repository. + * The current index of this iterator. */ - private final Mob[] mobs; + private int index = 0; /** - * The position of the next free index. + * The previous index of this iterator. */ - private int pointer = 0; - - /** - * The current size of this repository. - */ - private int size = 0; - - /** - * Creates a new mob repository with the specified capacity. - * - * @param capacity The maximum number of mobs that can be present in the repository. - */ - public MobRepository(int capacity) { - this.mobs = new Mob[capacity]; - } - - /** - * Adds a mob to the repository. - * - * @param mob The mob to add. - * @return {@code true} if the mob was added, {@code false} if the size has reached the capacity of this repository. - */ - public boolean add(T mob) { - if (size == mobs.length) { - return false; - } - - int index = -1; - for (int i = pointer; i < mobs.length; i++) { - if (mobs[i] == null) { - index = i; - break; - } - } - - if (index == -1) { - for (int i = 0; i < pointer; i++) { - if (mobs[i] == null) { - index = i; - break; - } - } - } - - if (index == -1) { - return false; // shouldn't happen, but just in case - } - - mobs[index] = mob; - mob.setIndex(index + 1); - - if (index == mobs.length - 1) { - pointer = 0; - } else { - pointer = index; - } - size++; - return true; - } - - /** - * Gets the capacity of this repository. - * - * @return The maximum size of this repository. - */ - public int capacity() { - return mobs.length; - } + private int previousIndex = -1; @Override - public Iterator iterator() { - return new MobRepositoryIterator(); + public boolean hasNext() { + for (int i = index; i < mobs.length; i++) { + if (mobs[i] != null) { + index = i; + return true; + } + } + return false; } - /** - * Removes a mob from the repository. - * - * @param mob The mob to remove. - * @return {@code true} if the mob was removed, {@code false} if it was not (e.g. if it was never added or has been - * removed already). - */ - public boolean remove(T mob) { - int index = mob.getIndex() - 1; - if (index < 0 || index >= mobs.length) { - return false; - } - - if (mobs[index] == mob) { - mobs[index] = null; - mob.setIndex(-1); - size--; - return true; - } - return false; - } - - /** - * Gets the mob at the given index - * - * @param index The index of the mob - * @return The mob instance - */ @SuppressWarnings("unchecked") - public T get(int index) { - if (index < 0 || index >= mobs.length) { - throw new IndexOutOfBoundsException("Mob index is out of bounds."); + @Override + public T next() { + T mob = null; + for (int i = index; i < mobs.length; i++) { + if (mobs[i] != null) { + mob = (T) mobs[i]; + index = i; + break; } + } - return (T) mobs[index]; + if (mob == null) { + throw new NoSuchElementException("Mob does not exist."); + } + + previousIndex = index; + index++; + return mob; } - /** - * Gets the size of this repository. - * - * @return The number of mobs in this repository. - */ - public int size() { - return size; + @SuppressWarnings("unchecked") + @Override + public void remove() { + if (previousIndex == -1) { + throw new IllegalStateException("Cannot remove as the repository is empty."); + } + MobRepository.this.remove((T) mobs[previousIndex]); + previousIndex = -1; } + } + + /** + * The array of mobs in this repository. + */ + private final Mob[] mobs; + + /** + * The position of the next free index. + */ + private int pointer = 0; + + /** + * The current size of this repository. + */ + private int size = 0; + + /** + * Creates a new mob repository with the specified capacity. + * + * @param capacity The maximum number of mobs that can be present in the repository. + */ + public MobRepository(int capacity) { + this.mobs = new Mob[capacity]; + } + + /** + * Adds a mob to the repository. + * + * @param mob The mob to add. + * @return {@code true} if the mob was added, {@code false} if the size has reached the capacity of this repository. + */ + public boolean add(T mob) { + if (size == mobs.length) { + return false; + } + + int index = -1; + for (int i = pointer; i < mobs.length; i++) { + if (mobs[i] == null) { + index = i; + break; + } + } + + if (index == -1) { + for (int i = 0; i < pointer; i++) { + if (mobs[i] == null) { + index = i; + break; + } + } + } + + if (index == -1) { + return false; // shouldn't happen, but just in case + } + + mobs[index] = mob; + mob.setIndex(index + 1); + + if (index == mobs.length - 1) { + pointer = 0; + } else { + pointer = index; + } + size++; + return true; + } + + /** + * Gets the capacity of this repository. + * + * @return The maximum size of this repository. + */ + public int capacity() { + return mobs.length; + } + + @Override + public Iterator iterator() { + return new MobRepositoryIterator(); + } + + /** + * Removes a mob from the repository. + * + * @param mob The mob to remove. + * @return {@code true} if the mob was removed, {@code false} if it was not (e.g. if it was never added or has been + * removed already). + */ + public boolean remove(T mob) { + int index = mob.getIndex() - 1; + if (index < 0 || index >= mobs.length) { + return false; + } + + if (mobs[index] == mob) { + mobs[index] = null; + mob.setIndex(-1); + size--; + return true; + } + return false; + } + + /** + * Gets the mob at the given index + * + * @param index The index of the mob + * @return The mob instance + */ + @SuppressWarnings("unchecked") + public T get(int index) { + if (index < 0 || index >= mobs.length) { + throw new IndexOutOfBoundsException("Mob index is out of bounds."); + } + + return (T) mobs[index]; + } + + /** + * Gets the size of this repository. + * + * @return The number of mobs in this repository. + */ + public int size() { + return size; + } + } \ No newline at end of file diff --git a/src/org/apollo/util/NameUtil.java b/src/org/apollo/util/NameUtil.java index 40d0e7c0..9a974693 100644 --- a/src/org/apollo/util/NameUtil.java +++ b/src/org/apollo/util/NameUtil.java @@ -7,64 +7,64 @@ package org.apollo.util; */ public final class NameUtil { - /** - * An array of valid characters in a player name encoded as a long. - */ - private static final char[] NAME_CHARS = { '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', ':', ';', '.', '>', '<', ',', - '"', '[', ']', '|', '?', '/', '`' }; + /** + * An array of valid characters in a player name encoded as a long. + */ + private static final char[] NAME_CHARS = { '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', ':', ';', '.', '>', '<', ',', + '"', '[', ']', '|', '?', '/', '`' }; - /** - * Converts a long to a player name. - * - * @param l The long. - * @return The player name. - */ - public static String decodeBase37(long l) { - int i = 0; - char[] chars = new char[12]; - while (l != 0L) { - long tmp = l; - l /= 37L; - chars[11 - i++] = NAME_CHARS[(int) (tmp - l * 37L)]; - } - return new String(chars, 12 - i, i); + /** + * Converts a long to a player name. + * + * @param l The long. + * @return The player name. + */ + public static String decodeBase37(long l) { + int i = 0; + char[] chars = new char[12]; + while (l != 0L) { + long tmp = l; + l /= 37L; + chars[11 - i++] = NAME_CHARS[(int) (tmp - l * 37L)]; } + return new String(chars, 12 - i, i); + } - /** - * Converts a player name to a long. - * - * @param name The player name. - * @return The long. - */ - public static long encodeBase37(String name) { - if (name.length() > 12) { - throw new IllegalArgumentException("Name too long."); - } - long l = 0L; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - l *= 37L; - if (c >= 'A' && c <= 'Z') { - l += 1 + c - 65; - } else if (c >= 'a' && c <= 'z') { - l += 1 + c - 97; - } else if (c >= '0' && c <= '9') { - l += 27 + c - 48; - } - } - for (; l % 37L == 0L && l != 0L; l /= 37L) { - ; - } - return l; + /** + * Converts a player name to a long. + * + * @param name The player name. + * @return The long. + */ + public static long encodeBase37(String name) { + if (name.length() > 12) { + throw new IllegalArgumentException("Name too long."); } - - /** - * Default private constructor to prevent instantiation. - */ - private NameUtil() { - + long l = 0L; + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + l *= 37L; + if (c >= 'A' && c <= 'Z') { + l += 1 + c - 65; + } else if (c >= 'a' && c <= 'z') { + l += 1 + c - 97; + } else if (c >= '0' && c <= '9') { + l += 27 + c - 48; + } } + for (; l % 37L == 0L && l != 0L; l /= 37L) { + ; + } + return l; + } + + /** + * Default private constructor to prevent instantiation. + */ + private NameUtil() { + + } } \ No newline at end of file diff --git a/src/org/apollo/util/NamedThreadFactory.java b/src/org/apollo/util/NamedThreadFactory.java index 78181380..2207a7ca 100644 --- a/src/org/apollo/util/NamedThreadFactory.java +++ b/src/org/apollo/util/NamedThreadFactory.java @@ -14,29 +14,29 @@ import java.util.concurrent.atomic.AtomicInteger; */ public final class NamedThreadFactory implements ThreadFactory { - /** - * The next id. - */ - private AtomicInteger id = new AtomicInteger(0); + /** + * The next id. + */ + private AtomicInteger id = new AtomicInteger(0); - /** - * The unique name. - */ - private final String name; + /** + * The unique name. + */ + private final String name; - /** - * Creates the named thread factory. - * - * @param name The unique name. - */ - public NamedThreadFactory(String name) { - this.name = name; - } + /** + * Creates the named thread factory. + * + * @param name The unique name. + */ + public NamedThreadFactory(String name) { + this.name = name; + } - @Override - public Thread newThread(Runnable runnable) { - int currentId = id.getAndIncrement(); - return new Thread(runnable, name + " [id=" + currentId + "]"); - } + @Override + public Thread newThread(Runnable runnable) { + int currentId = id.getAndIncrement(); + return new Thread(runnable, name + " [id=" + currentId + "]"); + } } \ No newline at end of file diff --git a/src/org/apollo/util/Point.java b/src/org/apollo/util/Point.java index 3938d054..d00dbdca 100644 --- a/src/org/apollo/util/Point.java +++ b/src/org/apollo/util/Point.java @@ -7,43 +7,43 @@ package org.apollo.util; */ public final class Point { - /** - * The x coordinate. - */ - private final int x; + /** + * The x coordinate. + */ + private final int x; - /** - * The y coordinate. - */ - private final int y; + /** + * The y coordinate. + */ + private final int y; - /** - * Creates a new point with the specified coordinates. - * - * @param x The x coordinate. - * @param y The y coordinate. - */ - public Point(int x, int y) { - this.x = x; - this.y = y; - } + /** + * Creates a new point with the specified coordinates. + * + * @param x The x coordinate. + * @param y The y coordinate. + */ + public Point(int x, int y) { + this.x = x; + this.y = y; + } - /** - * Gets the x coordinate of this point. - * - * @return The x coordinate. - */ - public int getX() { - return x; - } + /** + * Gets the x coordinate of this point. + * + * @return The x coordinate. + */ + public int getX() { + return x; + } - /** - * Gets the y coordinate of this point. - * - * @return The y coordinate. - */ - public int getY() { - return y; - } + /** + * Gets the y coordinate of this point. + * + * @return The y coordinate. + */ + public int getY() { + return y; + } } \ No newline at end of file diff --git a/src/org/apollo/util/StatefulFrameDecoder.java b/src/org/apollo/util/StatefulFrameDecoder.java index 3a4a60e8..a3487c70 100644 --- a/src/org/apollo/util/StatefulFrameDecoder.java +++ b/src/org/apollo/util/StatefulFrameDecoder.java @@ -26,76 +26,76 @@ import java.util.List; */ public abstract class StatefulFrameDecoder> extends ByteToMessageDecoder { - /** - * The current state. - */ - private T state; + /** + * The current state. + */ + private T state; - /** - * Creates the stateful frame decoder with the specified initial state. - * - * @param state The initial state. - * @throws NullPointerException If the state is {@code null}. - */ - public StatefulFrameDecoder(T state) { - this(state, false); - } - - /** - * Creates the stateful frame decoder with the specified initial state and unwrap flag. - * - * @param state The initial state. - * @param unwrap The unwrap flag. - * @throws NullPointerException If the state is {@code null}. - */ - public StatefulFrameDecoder(T state, boolean unwrap) { - setState(state); - } - - @Override - protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { - decode(ctx, in, out, state); - } - - /** - * Decodes the received packets into a frame. - * - * @param ctx The current context of this handler. - * @param channel The channel. - * @param buffer The cumulative buffer, which may contain zero or more bytes. - * @param state The current state. The state may be changed by calling {@link #setState(Enum)}. - */ - protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List out, T state) throws Exception; - - @Override - protected final void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out) { - decodeLast(ctx, in, out, state); - } - - /** - * Decodes remaining data before the channel is closed into a frame. You may override this method, but it is not - * required. If you do not, remaining data will be discarded! - * - * @param ctx The current context of this handler. - * @param channel The channel. - * @param buffer The cumulative buffer, which may contain zero or more bytes. - * @param state The current state. The state may be changed by calling {@link #setState(Enum)}. - */ - protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out, T state) { - - } - - /** - * Sets a new state. - * - * @param state The new state. - * @throws NullPointerException If the state is {@code null}. - */ - public final void setState(T state) { - if (state == null) { - throw new NullPointerException("state"); - } - this.state = state; + /** + * Creates the stateful frame decoder with the specified initial state. + * + * @param state The initial state. + * @throws NullPointerException If the state is {@code null}. + */ + public StatefulFrameDecoder(T state) { + this(state, false); + } + + /** + * Creates the stateful frame decoder with the specified initial state and unwrap flag. + * + * @param state The initial state. + * @param unwrap The unwrap flag. + * @throws NullPointerException If the state is {@code null}. + */ + public StatefulFrameDecoder(T state, boolean unwrap) { + setState(state); + } + + @Override + protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + decode(ctx, in, out, state); + } + + /** + * Decodes the received packets into a frame. + * + * @param ctx The current context of this handler. + * @param channel The channel. + * @param buffer The cumulative buffer, which may contain zero or more bytes. + * @param state The current state. The state may be changed by calling {@link #setState(Enum)}. + */ + protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List out, T state) throws Exception; + + @Override + protected final void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out) { + decodeLast(ctx, in, out, state); + } + + /** + * Decodes remaining data before the channel is closed into a frame. You may override this method, but it is not + * required. If you do not, remaining data will be discarded! + * + * @param ctx The current context of this handler. + * @param channel The channel. + * @param buffer The cumulative buffer, which may contain zero or more bytes. + * @param state The current state. The state may be changed by calling {@link #setState(Enum)}. + */ + protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out, T state) { + + } + + /** + * Sets a new state. + * + * @param state The new state. + * @throws NullPointerException If the state is {@code null}. + */ + public final void setState(T state) { + if (state == null) { + throw new NullPointerException("state"); } + this.state = state; + } } \ No newline at end of file diff --git a/src/org/apollo/util/StreamUtil.java b/src/org/apollo/util/StreamUtil.java index d32bff43..06377248 100644 --- a/src/org/apollo/util/StreamUtil.java +++ b/src/org/apollo/util/StreamUtil.java @@ -11,41 +11,41 @@ import java.io.OutputStream; */ public final class StreamUtil { - /** - * Reads a string from the specified input stream. - * - * @param is The input stream. - * @return The string. - * @throws IOException If an I/O error occurs. - */ - public static String readString(InputStream is) throws IOException { - StringBuilder builder = new StringBuilder(); - char character; - while ((character = (char) is.read()) != -1 && character != '\0') { - builder.append(character); - } - return builder.toString(); + /** + * Reads a string from the specified input stream. + * + * @param is The input stream. + * @return The string. + * @throws IOException If an I/O error occurs. + */ + public static String readString(InputStream is) throws IOException { + StringBuilder builder = new StringBuilder(); + char character; + while ((character = (char) is.read()) != -1 && character != '\0') { + builder.append(character); } + return builder.toString(); + } - /** - * Writes a string to the specified output stream. - * - * @param os The output stream. - * @param str The string. - * @throws IOException If an I/O error occurs. - */ - public static void writeString(OutputStream os, String str) throws IOException { - for (char c : str.toCharArray()) { - os.write(c); - } - os.write('\0'); + /** + * Writes a string to the specified output stream. + * + * @param os The output stream. + * @param str The string. + * @throws IOException If an I/O error occurs. + */ + public static void writeString(OutputStream os, String str) throws IOException { + for (char c : str.toCharArray()) { + os.write(c); } + os.write('\0'); + } - /** - * Default private constructor to prevent instantiation. - */ - private StreamUtil() { + /** + * Default private constructor to prevent instantiation. + */ + private StreamUtil() { - } + } } \ No newline at end of file diff --git a/src/org/apollo/util/TextUtil.java b/src/org/apollo/util/TextUtil.java index fa9a5ee8..121c0a5c 100644 --- a/src/org/apollo/util/TextUtil.java +++ b/src/org/apollo/util/TextUtil.java @@ -7,145 +7,145 @@ package org.apollo.util; */ public final class TextUtil { - /** - * An array of characters ordered by frequency - the elements with lower indices (generally) appear more often in - * chat messages. - */ - public static final char[] FREQUENCY_ORDERED_CHARS = { ' ', 'e', 't', 'a', 'o', 'i', 'h', 'n', 's', 'r', 'd', 'l', - 'u', 'm', 'w', 'c', 'y', 'f', 'g', 'p', 'b', 'v', 'k', 'x', 'j', 'q', 'z', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', ' ', '!', '?', '.', ',', ':', ';', '(', ')', '-', '&', '*', '\\', '\'', '@', '#', '+', - '=', '\243', '$', '%', '"', '[', ']' }; + /** + * An array of characters ordered by frequency - the elements with lower indices (generally) appear more often in + * chat messages. + */ + public static final char[] FREQUENCY_ORDERED_CHARS = { ' ', 'e', 't', 'a', 'o', 'i', 'h', 'n', 's', 'r', 'd', 'l', + 'u', 'm', 'w', 'c', 'y', 'f', 'g', 'p', 'b', 'v', 'k', 'x', 'j', 'q', 'z', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', ' ', '!', '?', '.', ',', ':', ';', '(', ')', '-', '&', '*', '\\', '\'', '@', '#', '+', + '=', '\243', '$', '%', '"', '[', ']' }; - /** - * Capitalizes the string correctly. - * - * @param str The input string. - * @return The string with correct capitalization. - */ - public static String capitalize(String str) { - char[] chars = str.toCharArray(); - boolean sentenceStart = true; - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; - if (sentenceStart) { - if (c >= 'a' && c <= 'z') { - chars[i] -= 0x20; - sentenceStart = false; - } else if (c >= 'A' && c <= 'Z') { - sentenceStart = false; - } - } else { - if (c >= 'A' && c <= 'Z') { - chars[i] += 0x20; - } - } - if (c == '.' || c == '!' || c == '?') { - sentenceStart = true; - } + /** + * Capitalizes the string correctly. + * + * @param str The input string. + * @return The string with correct capitalization. + */ + public static String capitalize(String str) { + char[] chars = str.toCharArray(); + boolean sentenceStart = true; + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + if (sentenceStart) { + if (c >= 'a' && c <= 'z') { + chars[i] -= 0x20; + sentenceStart = false; + } else if (c >= 'A' && c <= 'Z') { + sentenceStart = false; } - return new String(chars, 0, chars.length); + } else { + if (c >= 'A' && c <= 'Z') { + chars[i] += 0x20; + } + } + if (c == '.' || c == '!' || c == '?') { + sentenceStart = true; + } } + return new String(chars, 0, chars.length); + } - /** - * Compresses the input text ({@code in}) and places the result in the {@code out} array. - * - * @param in The input text. - * @param out The output array. - * @return The number of bytes written to the output array. - */ - public static int compress(String in, byte[] out) { - if (in.length() > 80) { - in = in.substring(0, 80); - } - in = in.toLowerCase(); - - int carry = -1; - int outPos = 0; - for (int inPos = 0; inPos < in.length(); inPos++) { - char c = in.charAt(inPos); - int tblPos = 0; - for (int i = 0; i < FREQUENCY_ORDERED_CHARS.length; i++) { - if (c == FREQUENCY_ORDERED_CHARS[i]) { - tblPos = i; - break; - } - } - if (tblPos > 12) { - tblPos += 195; - } - if (carry == -1) { - if (tblPos < 13) { - carry = tblPos; - } else { - out[outPos++] = (byte) tblPos; - } - } else if (tblPos < 13) { - out[outPos++] = (byte) ((carry << 4) + tblPos); - carry = -1; - } else { - out[outPos++] = (byte) ((carry << 4) + (tblPos >> 4)); - carry = tblPos & 0xF; - } - } - if (carry != -1) { - out[outPos++] = (byte) (carry << 4); - } - return outPos; + /** + * Compresses the input text ({@code in}) and places the result in the {@code out} array. + * + * @param in The input text. + * @param out The output array. + * @return The number of bytes written to the output array. + */ + public static int compress(String in, byte[] out) { + if (in.length() > 80) { + in = in.substring(0, 80); } + in = in.toLowerCase(); - /** - * Filters invalid characters from the specified string. - * - * @param str The input string. - * @return The filtered string. - */ - public static String filterInvalidCharacters(String str) { - StringBuilder bldr = new StringBuilder(); - for (char c : str.toLowerCase().toCharArray()) { - for (char validChar : FREQUENCY_ORDERED_CHARS) { - if (c == validChar) { - bldr.append((char) c); - break; - } - } + int carry = -1; + int outPos = 0; + for (int inPos = 0; inPos < in.length(); inPos++) { + char c = in.charAt(inPos); + int tblPos = 0; + for (int i = 0; i < FREQUENCY_ORDERED_CHARS.length; i++) { + if (c == FREQUENCY_ORDERED_CHARS[i]) { + tblPos = i; + break; } - return bldr.toString(); - } - - /** - * Uncompresses the compressed data ({@code in}) with the length ({@code len}) and returns the uncompressed - * {@link String}. - * - * @param in The compressed input data. - * @param len The length. - * @return The uncompressed {@link String}. - */ - public static String uncompress(byte[] in, int len) { - byte[] out = new byte[4096]; - int outPos = 0; - int carry = -1; - - for (int i = 0; i < len * 2; i++) { - int tblPos = in[i / 2] >> 4 - 4 * (i % 2) & 0xF; - if (carry == -1) { - if (tblPos < 13) { - out[outPos++] = (byte) FREQUENCY_ORDERED_CHARS[tblPos]; - } else { - carry = tblPos; - } - } else { - out[outPos++] = (byte) FREQUENCY_ORDERED_CHARS[(carry << 4) + tblPos - 195]; - carry = -1; - } + } + if (tblPos > 12) { + tblPos += 195; + } + if (carry == -1) { + if (tblPos < 13) { + carry = tblPos; + } else { + out[outPos++] = (byte) tblPos; } - return new String(out, 0, outPos); + } else if (tblPos < 13) { + out[outPos++] = (byte) ((carry << 4) + tblPos); + carry = -1; + } else { + out[outPos++] = (byte) ((carry << 4) + (tblPos >> 4)); + carry = tblPos & 0xF; + } } - - /** - * Default private constructor to prevent instantiation. - */ - private TextUtil() { - + if (carry != -1) { + out[outPos++] = (byte) (carry << 4); } + return outPos; + } + + /** + * Filters invalid characters from the specified string. + * + * @param str The input string. + * @return The filtered string. + */ + public static String filterInvalidCharacters(String str) { + StringBuilder bldr = new StringBuilder(); + for (char c : str.toLowerCase().toCharArray()) { + for (char validChar : FREQUENCY_ORDERED_CHARS) { + if (c == validChar) { + bldr.append((char) c); + break; + } + } + } + return bldr.toString(); + } + + /** + * Uncompresses the compressed data ({@code in}) with the length ({@code len}) and returns the uncompressed + * {@link String}. + * + * @param in The compressed input data. + * @param len The length. + * @return The uncompressed {@link String}. + */ + public static String uncompress(byte[] in, int len) { + byte[] out = new byte[4096]; + int outPos = 0; + int carry = -1; + + for (int i = 0; i < len * 2; i++) { + int tblPos = in[i / 2] >> 4 - 4 * (i % 2) & 0xF; + if (carry == -1) { + if (tblPos < 13) { + out[outPos++] = (byte) FREQUENCY_ORDERED_CHARS[tblPos]; + } else { + carry = tblPos; + } + } else { + out[outPos++] = (byte) FREQUENCY_ORDERED_CHARS[(carry << 4) + tblPos - 195]; + carry = -1; + } + } + return new String(out, 0, outPos); + } + + /** + * Default private constructor to prevent instantiation. + */ + private TextUtil() { + + } } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/DependencyException.java b/src/org/apollo/util/plugin/DependencyException.java index bb40ea2c..e516a2eb 100644 --- a/src/org/apollo/util/plugin/DependencyException.java +++ b/src/org/apollo/util/plugin/DependencyException.java @@ -7,18 +7,18 @@ package org.apollo.util.plugin; */ public final class DependencyException extends Exception { - /** - * A generated serial version id. - */ - private static final long serialVersionUID = -3335727281501054641L; + /** + * A generated serial version id. + */ + private static final long serialVersionUID = -3335727281501054641L; - /** - * Creates the dependency exception. - * - * @param message The message describing what happened. - */ - public DependencyException(String message) { - super(message); - } + /** + * Creates the dependency exception. + * + * @param message The message describing what happened. + */ + public DependencyException(String message) { + super(message); + } } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/PluginContext.java b/src/org/apollo/util/plugin/PluginContext.java index 1fd43f98..1bcf62a6 100644 --- a/src/org/apollo/util/plugin/PluginContext.java +++ b/src/org/apollo/util/plugin/PluginContext.java @@ -22,94 +22,94 @@ import org.apollo.net.release.Release; */ public final class PluginContext { - /** - * The server context. - */ - private final ServerContext context; + /** + * The server context. + */ + private final ServerContext context; - /** - * Creates the plugin context. - * - * @param context The server context. - */ - public PluginContext(ServerContext context) { - this.context = context; - } + /** + * Creates the plugin context. + * + * @param context The server context. + */ + public PluginContext(ServerContext context) { + this.context = context; + } - /** - * Adds a {@link CommandListener}. - * - * @param name The name of the listener. - * @param listener The listener. - */ - public void addCommandListener(String name, CommandListener listener) { - World.getWorld().getCommandDispatcher().register(name, listener); - } + /** + * Adds a {@link CommandListener}. + * + * @param name The name of the listener. + * @param listener The listener. + */ + public void addCommandListener(String name, CommandListener listener) { + World.getWorld().getCommandDispatcher().register(name, listener); + } - /** - * Adds an {@link EventDecoder}. - * - * @param The type of decoder. - * @param releaseNo The release number. - * @param opcode The opcode. - * @param decoder The event decoder. - */ - public void addEventDecoder(int releaseNo, int opcode, EventDecoder decoder) { - Release release = context.getRelease(); - if (release.getReleaseNumber() == releaseNo) { - release.register(opcode, decoder); - } + /** + * Adds an {@link EventDecoder}. + * + * @param The type of decoder. + * @param releaseNo The release number. + * @param opcode The opcode. + * @param decoder The event decoder. + */ + public void addEventDecoder(int releaseNo, int opcode, EventDecoder decoder) { + Release release = context.getRelease(); + if (release.getReleaseNumber() == releaseNo) { + release.register(opcode, decoder); } + } - /** - * Adds an {@link EventEncoder}. - * - * @param The type of encoder. - * @param releaseNo The release number. - * @param event The event. - * @param encoder The event encoder. - */ - public void addEventEncoder(int releaseNo, Class event, EventEncoder encoder) { - Release release = context.getRelease(); - if (release.getReleaseNumber() == releaseNo) { - release.register(event, encoder); - } + /** + * Adds an {@link EventEncoder}. + * + * @param The type of encoder. + * @param releaseNo The release number. + * @param event The event. + * @param encoder The event encoder. + */ + public void addEventEncoder(int releaseNo, Class event, EventEncoder encoder) { + Release release = context.getRelease(); + if (release.getReleaseNumber() == releaseNo) { + release.register(event, encoder); } + } - /** - * Adds an {@link EventHandler} to the end of the chain. - * - * @param The type of event. - * @param event The event. - * @param handler The handler. - */ - public void addLastEventHandler(Class event, EventHandler handler) { - EventHandlerChainGroup chains = context.getService(GameService.class).getEventHandlerChains(); - EventHandlerChain chain = chains.getChain(event); - if (chain == null) { - chain = new EventHandlerChain(handler); - chains.register(event, chain); - } else { - chain.addLast(handler); - } + /** + * Adds an {@link EventHandler} to the end of the chain. + * + * @param The type of event. + * @param event The event. + * @param handler The handler. + */ + public void addLastEventHandler(Class event, EventHandler handler) { + EventHandlerChainGroup chains = context.getService(GameService.class).getEventHandlerChains(); + EventHandlerChain chain = chains.getChain(event); + if (chain == null) { + chain = new EventHandlerChain<>(handler); + chains.register(event, chain); + } else { + chain.addLast(handler); } + } - /** - * Adds a {@link LoginListener}. - * - * @param listener The listener. - */ - public void addLoginListener(LoginListener listener) { - World.getWorld().getLoginDispatcher().register(listener); - } + /** + * Adds a {@link LoginListener}. + * + * @param listener The listener. + */ + public void addLoginListener(LoginListener listener) { + World.getWorld().getLoginDispatcher().register(listener); + } - /** - * Adds a {@link LogoutListener}. - * - * @param listener The listener. - */ - public void addLogoutListener(LogoutListener listener) { - World.getWorld().getLogoutDispatcher().register(listener); - } + /** + * Adds a {@link LogoutListener}. + * + * @param listener The listener. + */ + public void addLogoutListener(LogoutListener listener) { + World.getWorld().getLogoutDispatcher().register(listener); + } } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/PluginEnvironment.java b/src/org/apollo/util/plugin/PluginEnvironment.java index 695ca733..7d73d091 100644 --- a/src/org/apollo/util/plugin/PluginEnvironment.java +++ b/src/org/apollo/util/plugin/PluginEnvironment.java @@ -9,19 +9,19 @@ import java.io.InputStream; */ public interface PluginEnvironment { - /** - * Parses the input stream. - * - * @param is The input stream. - * @param name The name of the file. - */ - public void parse(InputStream is, String name); + /** + * Parses the input stream. + * + * @param is The input stream. + * @param name The name of the file. + */ + public void parse(InputStream is, String name); - /** - * Sets the context for this environment. - * - * @param context The context. - */ - public void setContext(PluginContext context); + /** + * Sets the context for this environment. + * + * @param context The context. + */ + public void setContext(PluginContext context); } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/PluginManager.java b/src/org/apollo/util/plugin/PluginManager.java index 90d864dc..656d3248 100644 --- a/src/org/apollo/util/plugin/PluginManager.java +++ b/src/org/apollo/util/plugin/PluginManager.java @@ -24,163 +24,163 @@ import org.xml.sax.SAXException; */ public final class PluginManager { - /** - * A set of all author names. - */ - private SortedSet authors = new TreeSet(); + /** + * A set of all author names. + */ + private SortedSet authors = new TreeSet<>(); - /** - * The plugin context. - */ - private final PluginContext context; + /** + * The plugin context. + */ + private final PluginContext context; - /** - * Creates the plugin manager. - * - * @param context The plugin context. - */ - public PluginManager(PluginContext context) { - this.context = context; - initAuthors(); + /** + * Creates the plugin manager. + * + * @param context The plugin context. + */ + public PluginManager(PluginContext context) { + this.context = context; + initAuthors(); + } + + /** + * Creates a plugin map from a collection. + * + * @param plugins The plugin collection. + * @return The plugin map. + */ + private Map createMap(Collection plugins) { + Map map = new HashMap(); + for (PluginMetaData plugin : plugins) { + map.put(plugin.getId(), plugin); } + return Collections.unmodifiableMap(map); + } - /** - * Creates a plugin map from a collection. - * - * @param plugins The plugin collection. - * @return The plugin map. - */ - private Map createMap(Collection plugins) { - Map map = new HashMap(); - for (PluginMetaData plugin : plugins) { - map.put(plugin.getId(), plugin); - } - return Collections.unmodifiableMap(map); - } + /** + * Finds plugins and loads their meta data. + * + * @return A collection of plugin meta data objects. + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + */ + private Collection findPlugins() throws IOException, SAXException { + return findPlugins(new File("./data/plugins")); + } - /** - * Finds plugins and loads their meta data. - * - * @return A collection of plugin meta data objects. - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - */ - private Collection findPlugins() throws IOException, SAXException { - return findPlugins(new File("./data/plugins")); - } - - /** - * Finds plugins and loads their meta data. - * - * @param dir The directory to search - * - * @return A collection of plugin meta data objects. - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - */ - private Collection findPlugins(File dir) throws IOException, SAXException { - Collection plugins = new ArrayList(); - for (File plugin : dir.listFiles()) { - if (plugin.isDirectory() && !plugin.getName().startsWith(".")) { - File xml = new File(plugin, "plugin.xml"); - if (xml.exists()) { - try (InputStream is = new FileInputStream(xml)) { - PluginMetaDataParser parser = new PluginMetaDataParser(is); - PluginMetaData meta = parser.parse(plugin); - for (String author : meta.getAuthors()) { - authors.add(author); - } - plugins.add(meta); - } - } else { - plugins.addAll(findPlugins(plugin)); - } + /** + * Finds plugins and loads their meta data. + * + * @param dir The directory to search + * + * @return A collection of plugin meta data objects. + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + */ + private Collection findPlugins(File dir) throws IOException, SAXException { + Collection plugins = new ArrayList<>(); + for (File plugin : dir.listFiles()) { + if (plugin.isDirectory() && !plugin.getName().startsWith(".")) { + File xml = new File(plugin, "plugin.xml"); + if (xml.exists()) { + try (InputStream is = new FileInputStream(xml)) { + PluginMetaDataParser parser = new PluginMetaDataParser(is); + PluginMetaData meta = parser.parse(plugin); + for (String author : meta.getAuthors()) { + authors.add(author); } + plugins.add(meta); + } + } else { + plugins.addAll(findPlugins(plugin)); } - return Collections.unmodifiableCollection(plugins); + } + } + return Collections.unmodifiableCollection(plugins); + } + + /** + * Creates an unmodifiable {@link Set} containing the authors. + * + * @return The set. + */ + public Set getAuthors() { + return Collections.unmodifiableSortedSet(authors); + } + + /** + * Populates the list with the authors of the Apollo core. + */ + private void initAuthors() { + // Please don't remove or add names here, unless that person worked on + // the Apollo core! See the notice in CreditsCommandListener for more + // information about why we think you shouldn't (tl;dr we put loads of + // effort into it for free, keeping the credits intact is the least you + // can do in return). + // + // If you want to add your own name, make a plugin and add your name + // to the plugin.xml file. + // + // Thank you! + authors.add("Graham"); + authors.add("Major"); + authors.add("Chris Fletcher"); + authors.add("Blake"); + } + + /** + * Starts the plugin system by finding and loading all the plugins. + * + * @throws SAXException If a SAX error occurs. + * @throws IOException If an I/O error occurs. + * @throws DependencyException If a dependency could not be resolved. + */ + public void start() throws IOException, SAXException, DependencyException { + Map plugins = createMap(findPlugins()); + Set started = new HashSet<>(); + + PluginEnvironment env = new RubyPluginEnvironment(); // TODO isolate plugins if possible in the future! + env.setContext(context); + + for (PluginMetaData plugin : plugins.values()) { + start(env, plugin, plugins, started); + } + } + + /** + * Starts a specific plugin. + * + * @param env The environment. + * @param plugin The plugin. + * @param plugins The plugin map. + * @param started A set of started plugins. + * @throws DependencyException If a dependency error occurs. + * @throws IOException If an I/O error occurs. + */ + private void start(PluginEnvironment env, PluginMetaData plugin, Map plugins, + Set started) throws DependencyException, IOException { + // TODO check for cyclic dependencies! this way just won't cut it, we need an exception + if (started.contains(plugin)) { + return; + } + started.add(plugin); + + for (String dependencyId : plugin.getDependencies()) { + PluginMetaData dependency = plugins.get(dependencyId); + if (dependency == null) { + throw new DependencyException("Unresolved dependency: " + dependencyId + "."); + } + start(env, dependency, plugins, started); } - /** - * Creates an unmodifiable {@link Set} containing the authors. - * - * @return The set. - */ - public Set getAuthors() { - return Collections.unmodifiableSortedSet(authors); - } - - /** - * Populates the list with the authors of the Apollo core. - */ - private void initAuthors() { - // Please don't remove or add names here, unless that person worked on - // the Apollo core! See the notice in CreditsCommandListener for more - // information about why we think you shouldn't (tl;dr we put loads of - // effort into it for free, keeping the credits intact is the least you - // can do in return). - // - // If you want to add your own name, make a plugin and add your name - // to the plugin.xml file. - // - // Thank you! - authors.add("Graham"); - authors.add("Major"); - authors.add("Chris Fletcher"); - authors.add("Blake"); - } - - /** - * Starts the plugin system by finding and loading all the plugins. - * - * @throws SAXException If a SAX error occurs. - * @throws IOException If an I/O error occurs. - * @throws DependencyException If a dependency could not be resolved. - */ - public void start() throws IOException, SAXException, DependencyException { - Map plugins = createMap(findPlugins()); - Set started = new HashSet(); - - PluginEnvironment env = new RubyPluginEnvironment(); // TODO isolate plugins if possible in the future! - env.setContext(context); - - for (PluginMetaData plugin : plugins.values()) { - start(env, plugin, plugins, started); - } - } - - /** - * Starts a specific plugin. - * - * @param env The environment. - * @param plugin The plugin. - * @param plugins The plugin map. - * @param started A set of started plugins. - * @throws DependencyException If a dependency error occurs. - * @throws IOException If an I/O error occurs. - */ - private void start(PluginEnvironment env, PluginMetaData plugin, Map plugins, - Set started) throws DependencyException, IOException { - // TODO check for cyclic dependencies! this way just won't cut it, we need an exception - if (started.contains(plugin)) { - return; - } - started.add(plugin); - - for (String dependencyId : plugin.getDependencies()) { - PluginMetaData dependency = plugins.get(dependencyId); - if (dependency == null) { - throw new DependencyException("Unresolved dependency: " + dependencyId + "."); - } - start(env, dependency, plugins, started); - } - - String[] scripts = plugin.getScripts(); - - for (String script : scripts) { - File scriptFile = new File(plugin.getBase(), script); - InputStream is = new FileInputStream(scriptFile); - env.parse(is, scriptFile.getAbsolutePath()); - } + String[] scripts = plugin.getScripts(); + + for (String script : scripts) { + File scriptFile = new File(plugin.getBase(), script); + InputStream is = new FileInputStream(scriptFile); + env.parse(is, scriptFile.getAbsolutePath()); } + } } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/PluginMetaData.java b/src/org/apollo/util/plugin/PluginMetaData.java index 4ee4be0e..94d7c543 100644 --- a/src/org/apollo/util/plugin/PluginMetaData.java +++ b/src/org/apollo/util/plugin/PluginMetaData.java @@ -9,138 +9,138 @@ import java.io.File; */ public final class PluginMetaData { - /** - * The plugin's authors. - */ - private final String[] authors; + /** + * The plugin's authors. + */ + private final String[] authors; - /** - * The plugin's dependencies. - */ - private final String[] dependencies; + /** + * The plugin's dependencies. + */ + private final String[] dependencies; - /** - * The plugin's description. - */ - private final String description; + /** + * The plugin's description. + */ + private final String description; - /** - * The plugin's id. - */ - private final String id; + /** + * The plugin's id. + */ + private final String id; - /** - * The plugin's name. - */ - private final String name; + /** + * The plugin's name. + */ + private final String name; - /** - * The plugin's scripts. - */ - private final String[] scripts; + /** + * The plugin's scripts. + */ + private final String[] scripts; - /** - * The plugin's version. - */ - private final double version; + /** + * The plugin's version. + */ + private final double version; - /** - * The plugin's base folder - */ - private final File base; + /** + * The plugin's base folder + */ + private final File base; - /** - * Creates the plugin meta data. - * - * @param id The plugin's id. - * @param name The plugin's name. - * @param description The plugin's description. - * @param authors The plugin's authors. - * @param scripts The plugin's scripts. - * @param dependencies The plugin's dependencies. - * @param version The plugin's version. - */ - public PluginMetaData(String id, File base, String name, String description, String[] authors, String[] scripts, - String[] dependencies, double version) { - this.id = id; - this.base = base; - this.name = name; - this.description = description; - this.authors = authors; - this.scripts = scripts; - this.dependencies = dependencies; - this.version = version; - } + /** + * Creates the plugin meta data. + * + * @param id The plugin's id. + * @param name The plugin's name. + * @param description The plugin's description. + * @param authors The plugin's authors. + * @param scripts The plugin's scripts. + * @param dependencies The plugin's dependencies. + * @param version The plugin's version. + */ + public PluginMetaData(String id, File base, String name, String description, String[] authors, String[] scripts, + String[] dependencies, double version) { + this.id = id; + this.base = base; + this.name = name; + this.description = description; + this.authors = authors; + this.scripts = scripts; + this.dependencies = dependencies; + this.version = version; + } - /** - * Gets the plugin's authors. - * - * @return The plugin's authors. - */ - public String[] getAuthors() { - return authors; - } + /** + * Gets the plugin's authors. + * + * @return The plugin's authors. + */ + public String[] getAuthors() { + return authors; + } - /** - * Gets the plugin's dependencies. - * - * @return The plugin's dependencies. - */ - public String[] getDependencies() { - return dependencies; - } + /** + * Gets the plugin's dependencies. + * + * @return The plugin's dependencies. + */ + public String[] getDependencies() { + return dependencies; + } - /** - * Gets the plugin's description. - * - * @return The plugin's description. - */ - public String getDescription() { - return description; - } + /** + * Gets the plugin's description. + * + * @return The plugin's description. + */ + public String getDescription() { + return description; + } - /** - * Gets the plugin's id. - * - * @return The plugin's id. - */ - public String getId() { - return id; - } + /** + * Gets the plugin's id. + * + * @return The plugin's id. + */ + public String getId() { + return id; + } - /** - * Gets the plugin's name. - * - * @return The plugin's name. - */ - public String getName() { - return name; - } + /** + * Gets the plugin's name. + * + * @return The plugin's name. + */ + public String getName() { + return name; + } - /** - * Gets the plugin's scripts. - * - * @return The plugin's scripts. - */ - public String[] getScripts() { - return scripts; - } + /** + * Gets the plugin's scripts. + * + * @return The plugin's scripts. + */ + public String[] getScripts() { + return scripts; + } - /** - * Gets the plugin's version. - * - * @return The plugin's version. - */ - public double getVersion() { - return version; - } + /** + * Gets the plugin's version. + * + * @return The plugin's version. + */ + public double getVersion() { + return version; + } - /** - * Gets the plugin's base folder. - * - * @return The plugin's base folder (where plugin.xml is) - */ - public File getBase() { - return base; - } + /** + * Gets the plugin's base folder. + * + * @return The plugin's base folder (where plugin.xml is) + */ + public File getBase() { + return base; + } } \ No newline at end of file diff --git a/src/org/apollo/util/plugin/RubyPluginEnvironment.java b/src/org/apollo/util/plugin/RubyPluginEnvironment.java index 23745705..2ddc59c8 100644 --- a/src/org/apollo/util/plugin/RubyPluginEnvironment.java +++ b/src/org/apollo/util/plugin/RubyPluginEnvironment.java @@ -14,45 +14,45 @@ import org.jruby.embed.ScriptingContainer; */ public final class RubyPluginEnvironment implements PluginEnvironment { - /** - * The scripting container. - */ - private final ScriptingContainer container = new ScriptingContainer(); + /** + * The scripting container. + */ + private final ScriptingContainer container = new ScriptingContainer(); - /** - * Creates and bootstraps the Ruby plugin environment. - * - * @throws IOException If an I/O error occurs during bootstrapping. - */ - public RubyPluginEnvironment() throws IOException { - parseBootstrapper(); - } + /** + * Creates and bootstraps the Ruby plugin environment. + * + * @throws IOException If an I/O error occurs during bootstrapping. + */ + public RubyPluginEnvironment() throws IOException { + parseBootstrapper(); + } - @Override - public void parse(InputStream is, String name) { - try { - container.runScriptlet(is, name); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Error parsing scriptlet " + name + "."); - } + @Override + public void parse(InputStream is, String name) { + try { + container.runScriptlet(is, name); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Error parsing scriptlet " + name + "."); } + } - /** - * Parses the bootstrapper. - * - * @throws IOException If an I/O error occurs. - */ - private void parseBootstrapper() throws IOException { - File bootstrap = new File("./data/plugins/bootstrap.rb"); - try (InputStream is = new FileInputStream(bootstrap)) { - parse(is, bootstrap.getAbsolutePath()); - } + /** + * Parses the bootstrapper. + * + * @throws IOException If an I/O error occurs. + */ + private void parseBootstrapper() throws IOException { + File bootstrap = new File("./data/plugins/bootstrap.rb"); + try (InputStream is = new FileInputStream(bootstrap)) { + parse(is, bootstrap.getAbsolutePath()); } + } - @Override - public void setContext(PluginContext context) { - container.put("$ctx", context); - } + @Override + public void setContext(PluginContext context) { + container.put("$ctx", context); + } } \ No newline at end of file diff --git a/src/org/apollo/util/xml/XmlNode.java b/src/org/apollo/util/xml/XmlNode.java index fdf2b2fd..4121f3a1 100644 --- a/src/org/apollo/util/xml/XmlNode.java +++ b/src/org/apollo/util/xml/XmlNode.java @@ -17,221 +17,221 @@ import java.util.Set; */ public final class XmlNode implements Iterable { - /** - * The attribute map. - */ - private final Map attributes = new HashMap(); + /** + * The attribute map. + */ + private final Map attributes = new HashMap(); - /** - * The list of child nodes. - */ - private final List children = new ArrayList(); + /** + * The list of child nodes. + */ + private final List children = new ArrayList<>(); - /** - * The name of this node. - */ - private String name; + /** + * The name of this node. + */ + private String name; - /** - * The value of this node, or {@code null} if it has no value. - */ - private String value; + /** + * The value of this node, or {@code null} if it has no value. + */ + private String value; - /** - * Creates a new {@link XmlNode} with the specified name. - * - * @param name The name of this node. - */ - public XmlNode(String name) { - this.name = name; + /** + * Creates a new {@link XmlNode} with the specified name. + * + * @param name The name of this node. + */ + public XmlNode(String name) { + this.name = name; + } + + /** + * Adds a child {@link XmlNode}. + * + * @param child The child to add. + */ + public void addChild(XmlNode child) { + children.add(child); + } + + /** + * Checks if an attribute with the specified name exists. + * + * @param name The attribute's name. + * @return {@code true} if an attribute with that name exists, {@code false} otherwise. + */ + public boolean containsAttribute(String name) { + return attributes.containsKey(name); + } + + /** + * Gets an attribute by it's name. + * + * @param name The name of the attribute. + * @return The attribute's value, or {@code null} if it doesn't exist. + */ + public String getAttribute(String name) { + return attributes.get(name); + } + + /** + * Gets the attribute count. + * + * @return The number of attributes. + */ + public int getAttributeCount() { + return attributes.size(); + } + + /** + * Gets a {@link Set} of attribute names. + * + * @return The set of names. + */ + public Set getAttributeNames() { + return attributes.keySet(); + } + + /** + * Gets a {@link Set} of attribute map entries. + * + * @return The set of entries. + */ + public Set> getAttributes() { + return attributes.entrySet(); + } + + /** + * Gets the first child with the specified name. + * + * @param name The name of the child. + * @return The {@link XmlNode} if a child was found with a matching name, {@code null} otherwise. + */ + public XmlNode getChild(String name) { + for (XmlNode child : children) { + if (child.getName().equals(name)) { + return child; + } } + return null; + } - /** - * Adds a child {@link XmlNode}. - * - * @param child The child to add. - */ - public void addChild(XmlNode child) { - children.add(child); - } + /** + * Gets the child count. + * + * @return The number of child {@link XmlNode}s. + */ + public int getChildCount() { + return children.size(); + } - /** - * Checks if an attribute with the specified name exists. - * - * @param name The attribute's name. - * @return {@code true} if an attribute with that name exists, {@code false} otherwise. - */ - public boolean containsAttribute(String name) { - return attributes.containsKey(name); - } + /** + * Gets a {@link Collection} of child {@link XmlNode}s. + * + * @return The collection. + */ + public Collection getChildren() { + return Collections.unmodifiableCollection(children); + } - /** - * Gets an attribute by it's name. - * - * @param name The name of the attribute. - * @return The attribute's value, or {@code null} if it doesn't exist. - */ - public String getAttribute(String name) { - return attributes.get(name); - } + /** + * Gets the name of this node. + * + * @return The name of this node. + */ + public String getName() { + return name; + } - /** - * Gets the attribute count. - * - * @return The number of attributes. - */ - public int getAttributeCount() { - return attributes.size(); - } + /** + * Gets the value of this node. + * + * @return The value of this node, or {@code null} if it has no value. + */ + public String getValue() { + return value; + } - /** - * Gets a {@link Set} of attribute names. - * - * @return The set of names. - */ - public Set getAttributeNames() { - return attributes.keySet(); - } + /** + * Checks if this node has a value. + * + * @return {@code true} if so, {@code false} if not. + */ + public boolean hasValue() { + return value != null; + } - /** - * Gets a {@link Set} of attribute map entries. - * - * @return The set of entries. - */ - public Set> getAttributes() { - return attributes.entrySet(); - } + @Override + public Iterator iterator() { + return children.iterator(); + } - /** - * Gets the first child with the specified name. - * - * @param name The name of the child. - * @return The {@link XmlNode} if a child was found with a matching name, {@code null} otherwise. - */ - public XmlNode getChild(String name) { - for (XmlNode child : children) { - if (child.getName().equals(name)) { - return child; - } - } - return null; - } + /** + * Removes all attributes. + */ + public void removeAllAttributes() { + attributes.clear(); + } - /** - * Gets the child count. - * - * @return The number of child {@link XmlNode}s. - */ - public int getChildCount() { - return children.size(); - } + /** + * Removes all children. + */ + public void removeAllChildren() { + children.clear(); + } - /** - * Gets a {@link Collection} of child {@link XmlNode}s. - * - * @return The collection. - */ - public Collection getChildren() { - return Collections.unmodifiableCollection(children); - } + /** + * Removes an attribute. + * + * @param name The name of the attribute. + */ + public void removeAttribute(String name) { + attributes.remove(name); + } - /** - * Gets the name of this node. - * - * @return The name of this node. - */ - public String getName() { - return name; - } + /** + * Removes a child {@link XmlNode}. + * + * @param child The child to remove. + */ + public void removeChild(XmlNode child) { + children.remove(child); + } - /** - * Gets the value of this node. - * - * @return The value of this node, or {@code null} if it has no value. - */ - public String getValue() { - return value; - } + /** + * Removes the value of this node. + */ + public void removeValue() { + value = null; + } - /** - * Checks if this node has a value. - * - * @return {@code true} if so, {@code false} if not. - */ - public boolean hasValue() { - return value != null; - } + /** + * Adds an attribute. It will overwrite an existing attribute if it exists. + * + * @param name The name of the attribute. + * @param value The value of the attribute. + */ + public void setAttribute(String name, String value) { + attributes.put(name, value); + } - @Override - public Iterator iterator() { - return children.iterator(); - } + /** + * Sets the name of this node. + * + * @param name The name of this node. + */ + public void setName(String name) { + this.name = name; + } - /** - * Removes all attributes. - */ - public void removeAllAttributes() { - attributes.clear(); - } - - /** - * Removes all children. - */ - public void removeAllChildren() { - children.clear(); - } - - /** - * Removes an attribute. - * - * @param name The name of the attribute. - */ - public void removeAttribute(String name) { - attributes.remove(name); - } - - /** - * Removes a child {@link XmlNode}. - * - * @param child The child to remove. - */ - public void removeChild(XmlNode child) { - children.remove(child); - } - - /** - * Removes the value of this node. - */ - public void removeValue() { - value = null; - } - - /** - * Adds an attribute. It will overwrite an existing attribute if it exists. - * - * @param name The name of the attribute. - * @param value The value of the attribute. - */ - public void setAttribute(String name, String value) { - attributes.put(name, value); - } - - /** - * Sets the name of this node. - * - * @param name The name of this node. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Sets the value of this node. - * - * @param value The value of this node. - */ - public void setValue(String value) { - this.value = value; - } + /** + * Sets the value of this node. + * + * @param value The value of this node. + */ + public void setValue(String value) { + this.value = value; + } } \ No newline at end of file diff --git a/src/org/apollo/util/xml/XmlParser.java b/src/org/apollo/util/xml/XmlParser.java index f8793e97..b0d22a33 100644 --- a/src/org/apollo/util/xml/XmlParser.java +++ b/src/org/apollo/util/xml/XmlParser.java @@ -19,137 +19,137 @@ import org.xml.sax.helpers.XMLReaderFactory; */ public final class XmlParser { - /** - * A class which handles SAX events. - * - * @author Graham - */ - private final class XmlHandler extends DefaultHandler { - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { - currentNode.setValue(new String(ch, start, length)); - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - if (!nodeStack.isEmpty()) { - currentNode = nodeStack.pop(); - } - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - XmlNode next = new XmlNode(localName); - - if (rootNode == null) { - rootNode = currentNode = next; - } else { - currentNode.addChild(next); - nodeStack.add(currentNode); - currentNode = next; - } - - if (attributes != null) { - int attributeCount = attributes.getLength(); - for (int i = 0; i < attributeCount; i++) { - String attribLocalName = attributes.getLocalName(i); - currentNode.setAttribute(attribLocalName, attributes.getValue(i)); - } - } - } + /** + * A class which handles SAX events. + * + * @author Graham + */ + private final class XmlHandler extends DefaultHandler { + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + currentNode.setValue(new String(ch, start, length)); } - /** - * The current node. - */ - private XmlNode currentNode; - - /** - * The SAX event handler. - */ - private final XmlHandler eventHandler; - - /** - * The stack of nodes, which is used when traversing the document and going through child nodes. - */ - private Stack nodeStack = new Stack(); - - /** - * The current root node. - */ - private XmlNode rootNode; - - /** - * The {@link XMLReader} backing this {@link XmlParser}. - */ - private final XMLReader xmlReader; - - /** - * Creates a new xml parser. - * - * @throws SAXException If a SAX error occurs. - */ - public XmlParser() throws SAXException { - xmlReader = XMLReaderFactory.createXMLReader(); - eventHandler = this.new XmlHandler(); - init(); + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + if (!nodeStack.isEmpty()) { + currentNode = nodeStack.pop(); + } } - /** - * Initialises this parser. - */ - private void init() { - xmlReader.setContentHandler(eventHandler); - xmlReader.setDTDHandler(eventHandler); - xmlReader.setEntityResolver(eventHandler); - xmlReader.setErrorHandler(eventHandler); - } + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + XmlNode next = new XmlNode(localName); - /** - * Parses XML data from the {@link InputSource}. - * - * @param source The {@link InputSource}. - * @return The root {@link XmlNode}. - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - */ - private XmlNode parse(InputSource source) throws IOException, SAXException { - rootNode = null; - xmlReader.parse(source); - if (rootNode == null) { - throw new SAXException("No root element."); + if (rootNode == null) { + rootNode = currentNode = next; + } else { + currentNode.addChild(next); + nodeStack.add(currentNode); + currentNode = next; + } + + if (attributes != null) { + int attributeCount = attributes.getLength(); + for (int i = 0; i < attributeCount; i++) { + String attribLocalName = attributes.getLocalName(i); + currentNode.setAttribute(attribLocalName, attributes.getValue(i)); } - return rootNode; + } } - /** - * Parses XML data from the given {@link InputStream}. - * - * @param is The {@link InputStream}. - * @return The root {@link XmlNode}. - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - */ - public XmlNode parse(InputStream is) throws IOException, SAXException { - synchronized (this) { - return parse(new InputSource(is)); - } - } + } - /** - * Parses XML data from the given {@link Reader}. - * - * @param reader The {@link Reader}. - * @return The root {@link XmlNode}. - * @throws IOException If an I/O error occurs. - * @throws SAXException If a SAX error occurs. - */ - public XmlNode parse(Reader reader) throws IOException, SAXException { - synchronized (this) { - return parse(new InputSource(reader)); - } + /** + * The current node. + */ + private XmlNode currentNode; + + /** + * The SAX event handler. + */ + private final XmlHandler eventHandler; + + /** + * The stack of nodes, which is used when traversing the document and going through child nodes. + */ + private Stack nodeStack = new Stack<>(); + + /** + * The current root node. + */ + private XmlNode rootNode; + + /** + * The {@link XMLReader} backing this {@link XmlParser}. + */ + private final XMLReader xmlReader; + + /** + * Creates a new xml parser. + * + * @throws SAXException If a SAX error occurs. + */ + public XmlParser() throws SAXException { + xmlReader = XMLReaderFactory.createXMLReader(); + eventHandler = this.new XmlHandler(); + init(); + } + + /** + * Initialises this parser. + */ + private void init() { + xmlReader.setContentHandler(eventHandler); + xmlReader.setDTDHandler(eventHandler); + xmlReader.setEntityResolver(eventHandler); + xmlReader.setErrorHandler(eventHandler); + } + + /** + * Parses XML data from the {@link InputSource}. + * + * @param source The {@link InputSource}. + * @return The root {@link XmlNode}. + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + */ + private XmlNode parse(InputSource source) throws IOException, SAXException { + rootNode = null; + xmlReader.parse(source); + if (rootNode == null) { + throw new SAXException("No root element."); } + return rootNode; + } + + /** + * Parses XML data from the given {@link InputStream}. + * + * @param is The {@link InputStream}. + * @return The root {@link XmlNode}. + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + */ + public XmlNode parse(InputStream is) throws IOException, SAXException { + synchronized (this) { + return parse(new InputSource(is)); + } + } + + /** + * Parses XML data from the given {@link Reader}. + * + * @param reader The {@link Reader}. + * @return The root {@link XmlNode}. + * @throws IOException If an I/O error occurs. + * @throws SAXException If a SAX error occurs. + */ + public XmlNode parse(Reader reader) throws IOException, SAXException { + synchronized (this) { + return parse(new InputSource(reader)); + } + } } \ No newline at end of file