Compare commits

...
500 Commits
Author SHA1 Message Date
bigguy345 ff33ebfe8d cool PanelTextBox QoL 2025-03-18 06:20:20 +02:00
bigguy345 5f04b6fa69 Fixed grid mouse wheel code running outside of grid 2025-03-18 06:19:03 +02:00
bigguy345 a4bca99126 New cursor handler 2025-03-18 06:18:35 +02:00
bigguy345 a7d1b9cd1f Improved PanelTextBox implementations 2025-03-18 03:03:08 +02:00
bigguy345 56c4d3e7f1 More GuiNpcTextField tweaks 2025-03-18 03:02:42 +02:00
bigguy345 1f44ea5987 PanelActiveFrame WIP 2025-03-17 23:40:10 +02:00
bigguy345 cb8a78e82b Playhead now displays interpolated Y value between 2 frames
PanelTextBox
2025-03-17 23:39:52 +02:00
bigguy345 04d37623eb colors 2025-03-17 23:37:59 +02:00
bigguy345 1a4f513fb3 Calculated grid width/height properly 2025-03-17 23:37:38 +02:00
bigguy345 e187b62348 GuiNpcTextField fix 2025-03-17 23:35:49 +02:00
bigguy345 a9e19294f8 PanelFrameType type value boxes functionality 2025-03-15 03:32:17 +02:00
bigguy345 54a45fbeb8 PanelFrameType is almost done + another refactor 2025-03-15 02:21:09 +02:00
bigguy345 435ff3f5de Fixes and tweaks 2025-03-14 06:24:04 +02:00
bigguy345 8b92c04c45 temp 2025-03-14 03:32:51 +02:00
Kam 32e828f2c8 Add Textures 2025-03-13 17:42:47 -04:00
Kam 689db91622 Add Easing stuff 2025-03-13 17:41:27 -04:00
Kam 06a8317860 Fix Magic Crashes 2025-03-13 17:20:23 -04:00
Kam 180d257024 Proper Reformating 2025-03-13 17:14:45 -04:00
Kam ce75880aba Fix up to Dev 2025-03-13 16:52:08 -04:00
Kam 250edf099c Soulstone Crash Fix 2025-03-12 20:03:08 -04:00
Kam 207d9f6124 Item Config + Machine Gun Fixes 2025-03-12 05:00:21 -04:00
Kam 3939e6cf2b Fix Magic Interaction Textfields 2025-03-12 02:27:51 -04:00
Kam b1e4a6f0fe Fix Diagram Crash 2025-03-12 00:59:43 -04:00
Kam 4d1231a09e Fix Clone List 2025-03-11 23:59:58 -04:00
Kam 53daf359cd Better DBC Loaded Handling 2025-03-11 22:18:39 -04:00
Kam 7e2ed41169 Fix Mob Spawn, Mount and Cloner Packets 2025-03-11 21:48:07 -04:00
Kam a1a0ebdc3f Apply new API 2025-03-11 20:25:00 -04:00
Kam 495fd98bfd Implement Profile Events to Player Scripts 2025-03-11 17:16:54 -04:00
Kam 9ac8ce3389 Update CommandProfileAdmin.java 2025-03-10 19:47:24 -04:00
Kam 7f77894cfc Recalc on Load 2025-03-10 18:32:24 -04:00
Kam 79c8765c51 Better Profile Rollback 2025-03-10 18:07:22 -04:00
Kam bbd70a06f0 Item Attribute Tooltip Fixes 2025-03-10 18:00:32 -04:00
Kam 17ab0ccc22 Hud Editor Button properly positioned 2025-03-10 17:37:43 -04:00
Kam a8f5fd3b87 Distribute Button Info 2025-03-10 17:34:09 -04:00
Kam e85c4c9259 Banner Modifies Banner Trims 2025-03-10 17:28:24 -04:00
Kam eda6b72058 Chair + Hammer Pushing Functionality 2025-03-09 20:02:24 -04:00
Kam ffcc8f603f Remove Item Tool Errors 2025-03-09 19:06:53 -04:00
Kam 08a18a123e Campfire Item 2D Texture 2025-03-09 19:06:47 -04:00
Kam b45d06458f Max Profile 2025-03-09 18:58:42 -04:00
Kam 900a8889aa Update BlockCarpentryBenchRenderer.java 2025-03-09 18:48:50 -04:00
Kam d37368efc8 Profile Packets are Permission Based and not Op Based 2025-03-09 18:15:51 -04:00
Kam 710cb04f8d Apple Attributes for Items if DBC is not available, Resistances Always 2025-03-09 16:08:26 -04:00
Kam 6c1330552b Use Float 2025-03-09 13:52:19 -04:00
Kam 5ab2203a8a Only Attributes + Resistances with DBC Addon 2025-03-09 03:17:21 -04:00
Kam f30cbf78f3 Better Mark Rendering for Compass 2025-03-08 20:30:10 -05:00
Kam 06754a05d0 Fix Help Item Renderer 2025-03-08 19:59:51 -05:00
Kam c1fa75d4cb Fix Region Add Command 2025-03-08 19:22:31 -05:00
Kam 64a94a4830 Clear Quest Tracker on Server/World Switch 2025-03-08 19:19:41 -05:00
Kam 83c560e7c1 Allow Hud Component Cycling 2025-03-08 19:17:25 -05:00
Kam cef643777f Fix Magic Controller Crash 2025-03-08 18:54:22 -05:00
Kam fcdd552874 Mark Rendering Order 2025-03-08 18:48:09 -05:00
Kam 95da5e78c8 Better Defaults 2025-03-08 18:29:02 -05:00
Kam 1ae5d1bc12 Update todo.txt 2025-03-08 17:55:41 -05:00
Kam b43d8d9065 Fix Scripted Item Crash 2025-03-08 17:52:39 -05:00
Kam 299d3f3bcc Add Permissions for PlayerData Modifcation 2025-03-08 16:47:28 -05:00
Kam 71d309eed1 Magic Modification Per NPC 2025-03-08 16:45:06 -05:00
Kam 382fb0cf9c Modifiable Magic Data in PlayerData tab 2025-03-07 16:00:06 -05:00
Kam 20e3cdd1f0 Attribute Configs 2025-03-06 17:53:07 -05:00
Kam 78c4aed595 Simplify Attack Functions 2025-03-06 17:40:26 -05:00
Kam 73594e46c0 Passivity to Factions 2025-03-06 17:33:44 -05:00
Kam 4ba1358af2 Apply Neutral Damage from Player Attacks 2025-03-06 13:29:00 -05:00
Kam 049d0baf5f NPCs to Players Magic Damage 2025-03-06 13:26:49 -05:00
Kam 8bcdaf5f11 Gear! 2025-03-06 12:20:14 -05:00
Kam e3fad91547 Attribute and Magic Damage Calculations for Players to MOBS, Players, NPCs 2025-03-06 04:07:16 -05:00
Kam f1a606e183 Better Effect Command result messages now show effect name 2025-03-06 02:48:14 -05:00
Kam c5093b3227 Fix Open Scripts Null for Linked and Effect Scripts 2025-03-06 02:44:07 -05:00
Kam 8ae4ae26dc Fix Color Rendering for Linked Items in GUI 2025-03-06 02:37:29 -05:00
Kam fdf6205b64 Fix YesNo for Linked Item losing Access 2025-03-06 02:35:15 -05:00
Kam 6571e09911 Fix to Dialog Event 2025-03-06 02:22:21 -05:00
Kam 763174525d Merge pull request #143 from TheLivan/dev
Correct odd places and fix potential errors
2025-03-06 02:19:33 -05:00
Kam 43c940f7ed Merge branch 'dev' into dev 2025-03-06 02:19:17 -05:00
Kam 9712813749 Merge pull request #135 from kaixiten/patch-1
Update zh_CN.lang
2025-03-06 02:17:08 -05:00
Kam 66e06849cb Update api 2025-03-06 01:53:53 -05:00
Kam 67a1650fb6 Profile Events 2025-03-06 01:24:51 -05:00
Luis C.M. b64481dec1 Fixed music continuing to play for server bards even after logging out 2025-03-05 22:57:24 -06:00
Kam 6e1b2f957f Merge branch 'dev' of https://github.com/KAMKEEL/CustomNPC-Plus into dev 2025-03-05 23:13:41 -05:00
Kam f334980f22 Better Effect List, Give and Remove Commands with Tab Completion 2025-03-05 23:13:39 -05:00
Luis C.M. f662944181 Fixed custom/linked items rotating with fast graphics 2025-03-05 20:56:21 -06:00
Kam 7a16cdf520 Magic for PlayerData and NPCs 2025-03-05 19:40:55 -05:00
Kam d4eddf4551 Update todo.txt 2025-03-05 19:18:33 -05:00
Kam 1d2e00a0fb NBT Tag Helpers 2025-03-05 19:04:56 -05:00
Kam 311e45b010 Update DataAdvanced.java 2025-03-05 19:04:47 -05:00
Kam 34047e288e Add Todo List 2025-03-05 19:03:39 -05:00
Kam d4940f1208 Fix Compass Hud Crash 2025-03-05 16:09:14 -05:00
Kam 7a9e8e22f3 BETA 5 2025-03-05 14:34:55 -05:00
Kam 70a8fa2849 Add Default Cycle and Magic 2025-03-05 14:27:32 -05:00
Kam 4d8832a005 White Space 2025-03-04 21:09:13 -05:00
Kam 7e9dfbdb2e Fix Custom GUI Components being Request Packets 2025-03-04 21:05:24 -05:00
Kam f0547cf876 Magic Diagram Viewer 2025-03-04 21:03:36 -05:00
Kam 080fa62771 Sync Magic 2025-03-04 18:19:53 -05:00
Kam b060daab44 Move Guis 2025-03-04 17:42:03 -05:00
Kam 1f17c6638e Gui Magic Cycle 2025-03-04 17:41:17 -05:00
Kam a1e886afe5 Fix Linked Item Scripting Labels 2025-03-04 16:34:26 -05:00
Kam ffaf21d3d8 Magic Editor Sub GUI 2025-03-04 16:34:18 -05:00
Kam 0aef78fd43 Add Buttons and Updating 2025-03-04 11:32:14 -05:00
Kam ab194fba22 Manage Magic Global Menu 2025-03-04 03:28:11 -05:00
Kam 2e9f0c1dd0 Fix Toggle Button 2025-03-04 03:27:58 -05:00
Kam 82bad818f9 Magic Get Packet 2025-03-04 02:49:19 -05:00
Kam debbd25f18 Update GuiNpcManageMagic.java 2025-03-04 01:52:29 -05:00
Kam ba661de91f Send Magic Info Packets 2025-03-03 23:08:18 -05:00
Kam 4e6d6b7082 Magic Packet Fixes 2025-03-03 23:03:12 -05:00
Kam c2fa74c541 Scheduled Actions 2025-03-03 20:05:19 -05:00
Kam 150b8bfe2d Merge pull request #147 from bigguy345/dev
Added Scheduled Tasks system for NPC scripting.
2025-03-03 19:54:41 -05:00
Kam 9d288e9d09 Remove ScrollGroup Packet 2025-03-03 18:44:05 -05:00
Kam f5ee7451f5 Fix Cached Item and Scripted Item Errors 2025-03-03 18:25:29 -05:00
bigguy345 0033413235 Added Scheduled Tasks system for NPC scripting.
Allows for scripting the scheduling of runnable methods in sequence within the NPC's AI

An example sequence of tasks:
1. Dashes towards player (might take 3-5 seconds, doesn't matter, task durations are dynamic so it can take as long as it needs).
2. Punches player away
3. Waits 10 ticks - Fires a ki blast
4. Teleports behind player
5. Knocks player out
2025-03-03 23:59:49 +02:00
bigguy345 a8e8566e7d Formatted EntityNPCInterface 2025-03-03 23:58:58 +02:00
Kam 79f2b9b52c Fix Crash 2025-03-03 16:12:30 -05:00
Kam 58ff772e3c Magic GUI WIP Push 2025-03-03 05:13:07 -05:00
Kam 758485b4d0 Mailbox Remodel 2025-03-02 22:28:28 -05:00
Kam cdc5cc0983 TODO 2025-02-28 19:15:05 -05:00
Kam be9d664017 on profile change recalc attributes 2025-02-28 18:38:11 -05:00
Kam 05df0509e1 Active Quest Requirement 2025-02-28 18:31:59 -05:00
Kam c5c2590bc2 Reorg 2025-02-28 18:21:14 -05:00
Kam 2d89b8d450 Requirement System for Items 2025-02-28 18:17:39 -05:00
Kam 413236b0b5 Tooltip Sorting 2025-02-28 17:32:17 -05:00
Kam 98355a5fc1 Fix Legacy Steel Issue 2025-02-28 17:15:12 -05:00
Kam 05041464c1 Better Attribute Handling System + Requirement Registry System 2025-02-28 17:14:26 -05:00
Kam d0bd5ff210 All application with definition 2025-02-28 16:22:26 -05:00
Kam 033d45878d Fix Stack Overflow 2025-02-28 13:40:18 -05:00
Kam cd487e1122 Add another Register 2025-02-28 13:05:43 -05:00
Kam 93bb6243db Add Recalc Event for Listeners in Other Mods 2025-02-28 13:02:11 -05:00
Kam e27aade87d Add Stat Type to Attributes 2025-02-28 12:22:26 -05:00
Kam da0489296e Better Reorganization 2025-02-27 15:54:42 -05:00
Kam a328a635d7 Attribute Command Fix and Conditional Enabling 2025-02-27 15:25:05 -05:00
Kam baf06e7162 Custom Attributes can now modify health 2025-02-27 14:29:04 -05:00
Kam 4e0359902d Attribute THINGS 2025-02-27 13:47:09 -05:00
Kam c132db8299 Whoops 2025-02-27 11:54:56 -05:00
Kam f8b3dcee75 Rename to AttributeAttackHelper 2025-02-27 11:49:45 -05:00
Kam d482213c85 Change from Double to Float 2025-02-27 11:48:03 -05:00
Kam c4fdf1a7b6 Magic Key 2025-02-27 09:27:34 -05:00
Kam 53adb4c9a5 Better Formatting for Tooltips 2025-02-27 00:48:10 -05:00
Kam 90c3fab6c7 Magic Cycles 2025-02-27 00:36:59 -05:00
Kam 58cd2bc535 Tooltip Helper for RPG Items 2025-02-27 00:30:39 -05:00
Kam 50977543c0 More Item Attribute Things 2025-02-26 22:49:26 -05:00
Kam 9b7af03de3 Fix Color Codes for Objectives 2025-02-26 16:22:54 -05:00
Kam 6e59cc760f More Attribute Pushing 2025-02-26 16:13:43 -05:00
Kam c3573d5d2c Register Item Attribute Controller 2025-02-26 12:51:22 -05:00
luisc d41311147c Fixed first person rendering animation issue 2025-02-25 17:31:02 -06:00
Kam dbf81895a9 Fix Magic Map Diagram 2025-02-25 17:26:16 -05:00
Kam a16a930237 Party Disband and Create for Controller & Scripting 2025-02-25 17:24:43 -05:00
Kam 0b9e727e0c Merge branch 'dev' of https://github.com/KAMKEEL/CustomNPC-Plus into dev 2025-02-25 17:15:03 -05:00
Kam 6903726300 Attribute Command and Player Equipment Tracking 2025-02-25 17:14:55 -05:00
luisc e585f11bb2 Merge remote-tracking branch 'origin/dev' into dev 2025-02-25 16:13:22 -06:00
luisc c4c1be3e2b Fixed some issues with full model animation rendering. 2025-02-25 16:13:12 -06:00
Kam f1b77fe94f Tick Attribute Tracker 2025-02-25 16:46:05 -05:00
Kam 0c1ce7ed7a Equipment Tracker for Players 2025-02-25 16:25:08 -05:00
Kam f2286a382f Fix to RPGCore for Future Porting 2025-02-25 16:05:40 -05:00
Kam 865978a971 Another Attribute Refactor 2025-02-24 20:07:32 -05:00
Kam 3d90ddab46 Renaming 2025-02-24 19:43:40 -05:00
Kam 5818060656 Large Unused Attribute Push 2025-02-24 16:08:22 -05:00
Kam 4faa851078 Update MagicController.java 2025-02-24 15:37:39 -05:00
Kam b099e78093 magic 2025-02-24 02:57:43 -05:00
Kam ef05817991 Sort Profile Info 2025-02-23 22:43:55 -05:00
Kam 56ab018320 Fix Profile Locked Bug 2025-02-23 22:26:08 -05:00
Kam ab9209e4f8 1.10 Beta 2025-02-23 19:58:54 -05:00
Kam 8b1fdc5132 Better Brush Controls 2025-02-23 16:15:00 -05:00
Kam 3bd3a125b6 Dont Print Magics or Register them yet 2025-02-23 15:51:35 -05:00
Kam 2640a6c7e0 Hud Component Modifications 2025-02-23 15:50:45 -05:00
Kam 3e23893e78 Fix Effective Scaling 2025-02-23 15:38:42 -05:00
Kam 84b07f4f6f Compass in Progress 2025-02-23 06:29:53 -05:00
Kam 7135f1ad27 Compass 2025-02-23 05:58:56 -05:00
Kam fe9bb02aea Better Hud System CNPC+ 2025-02-23 04:58:41 -05:00
Kam c023071ff0 Quest Tracking Changes 2025-02-22 23:58:56 -05:00
Kam 294abe4d25 Apply Configs to Packets 2025-02-22 22:29:27 -05:00
Kam aeee864bf7 Scripted & Linked Items now Rendering Images in Banners + Wall Banners 2025-02-22 05:09:22 -05:00
Kam 5dfe061bad Fix Tool Renderer 2025-02-22 01:21:35 -05:00
Kam faf335c831 Working Tool Renderer 2025-02-21 21:43:47 -05:00
Kam b98f024fbd Shrink Chair + Add Lang for Items 2025-02-21 20:00:55 -05:00
Kam 1c190fe5c4 Fix Some Rendering 2025-02-21 19:37:57 -05:00
Kam a37b32c1a5 Effects Rendering Borders 2025-02-21 18:13:08 -05:00
Kam d7d968bf86 Scripting for Effects and Profiles 2025-02-21 17:30:57 -05:00
Kam ce1f652d53 Fix Slot Creation Quest Syncing 2025-02-21 17:23:51 -05:00
Kam 9f71370c1f Add Langs 2025-02-21 16:44:40 -05:00
Kam 9905aaaf0c Update Quest.java 2025-02-21 16:42:09 -05:00
Kam 05487a06a2 Better Shared Quest Completion 2025-02-21 16:40:44 -05:00
Kam 98605b7276 moreee 2025-02-21 07:05:56 -05:00
Kam 40154f9c53 Quest Profile Options 2025-02-21 06:19:24 -05:00
Kam 2141c5c4ca Custom Quest Cooldowns / Shared Profile Cooldowns + Profile Packet Fixes 2025-02-20 22:19:21 -05:00
Kam 83c16ae419 Fine Tuning Profile Controller Instance 2025-02-20 21:44:15 -05:00
Kam c3538836be Optimize Imports 2025-02-20 21:40:39 -05:00
Kam 7820e37180 Incomplete Push for Refactoring 2025-02-20 21:39:02 -05:00
Kam cd3514aa73 Don't save current PlayerData if we're modifying it within a Profile 2025-02-20 13:48:40 -05:00
Kam 19a1b629c8 More Fixerinos 2025-02-20 13:36:07 -05:00
Kam 3ee39e8b95 Add Pagging to Grabbable Middle Section 2025-02-20 13:15:49 -05:00
Kam 36183cd181 Completely Renovated PlayerData Menu + Toggle Button 2025-02-20 03:53:47 -05:00
Kam 478e16d279 fixxx 2025-02-20 01:02:27 -05:00
Kam ea1f142571 Fix Packet + Compact Code 2025-02-20 00:49:31 -05:00
Kam e15e72d478 Full Refactor and Now it looks better 💯 2025-02-20 00:41:45 -05:00
Kam 98e886703c Push a TERRIBLY INCOMPLETE CODE!!! :DDDDD 2025-02-20 00:31:52 -05:00
Kam cf6e6dd655 Implement Profile Regions 2025-02-19 18:15:05 -05:00
Kam db330d0038 Remap Keybind to N by Default, L is used by DBC 2025-02-19 17:14:11 -05:00
Kam 3ce7203978 Fixes 2025-02-19 16:31:36 -05:00
Kam d62b02410e Profile Operations + Packets for GUI Handling 2025-02-19 16:27:27 -05:00
Kam cd12397927 Profile GUI and Effect Bar 2025-02-19 05:43:28 -05:00
Kam 5a38f9057f Profile + Effect Loading 2025-02-19 00:21:40 -05:00
Kam e8f657f7e6 More Profile Handling + Login Packet 2025-02-18 22:22:40 -05:00
Kam 36181d5165 Better 2025-02-18 20:08:26 -05:00
Kam f5a2ce27ff Profile Operations in Order 2025-02-18 20:05:55 -05:00
Kam ccc16aa1ac Fix Profile Tab Bugging out 2025-02-18 18:56:15 -05:00
Kam 64bb024e61 Change Inventory Tab Handling 2025-02-18 18:48:56 -05:00
Kam 753a2a1927 Update ChatAlertPacket.java 2025-02-18 16:23:03 -05:00
Kam a728ff13c1 Better Label + Error Message 2025-02-18 16:16:06 -05:00
Kam eb899061bf Better Chat Color Utility Handling for Commands 2025-02-18 16:11:58 -05:00
Kam 3cac4e764f Profile Rename Command + List Command 2025-02-18 06:31:21 -05:00
Kam 2ebe4ed9c5 Profile Implementations 2025-02-18 06:25:09 -05:00
Kam 8ed86f5ec7 Clear Cache 2025-02-18 04:57:22 -05:00
Kam efcdeecbf2 Caching Some Paths for Efficiency 2025-02-18 04:57:17 -05:00
Kam 79955f549e Complete Some Todos and Remove Some 2025-02-18 04:45:47 -05:00
Kam 598491fe8c Hook Up Effects Packet Permissions 2025-02-18 04:36:53 -05:00
Kam 78380c3e09 Small Fix 2025-02-18 04:34:53 -05:00
Kam 030b44035e Complete Manage Linked Items / NPCs 2025-02-18 04:29:38 -05:00
Kam fdd47691ae Fix Linked Item Duplication Bug 2025-02-18 02:15:06 -05:00
Luis C.M. a5f661b679 Implemented anvil repair and item destroyed events for custom items and linked items 2025-02-17 21:49:30 -06:00
Luis C.M. 972e930b31 Implemented anvil repair and item destroyed events for custom items and linked items 2025-02-17 21:39:18 -06:00
Luis C.M. 90bd8aeb02 Implemented version change and build events for linked items 2025-02-17 18:01:11 -06:00
Luis C.M. f62ff8a474 Added a function to create an item stack from a linked item in the LinkedItem class, referenced in the controller and creation packet as well. 2025-02-17 17:26:40 -06:00
Kam 5c04b1aae6 Update NpcAPI.java 2025-02-17 16:45:57 -05:00
Kam 690f2ca10d Hook Up Linked Item to existing Events 2025-02-17 16:02:56 -05:00
Kam f84dd5477d Linked Item Scripts + Effect Script Fix 2025-02-17 15:21:59 -05:00
Kam 5cbab2581c Linked Item Saving & Writing 2025-02-17 14:38:42 -05:00
Kam 85165070e0 Linked Item Building 2025-02-17 14:06:26 -05:00
Kam 639e44f98f Try and work? 2025-02-17 13:44:01 -05:00
Kam e316946915 push something?? 2025-02-16 06:24:57 -05:00
Kam f51c636b79 LinkedItem Things 2025-02-16 05:50:03 -05:00
Kam eb8b5387ea Linked Item GUI + Packets 2025-02-16 04:54:21 -05:00
Kam a2d4c4fd5a Custom Item NBT Renderers for TileColorable for Block Picking its NBT Colors 2025-02-15 23:54:03 -05:00
Kam 768f494631 Fix Weird Chat Bubbles causing Weird GL11 Issues 2025-02-15 23:09:00 -05:00
Kam de2e3ce4fb More Linked Manage Controls 2025-02-15 22:59:51 -05:00
Kam 4dc8d8a971 Update api 2025-02-15 19:38:21 -05:00
Kam 7fc259e158 Update api 2025-02-15 19:38:04 -05:00
Kam dac4ef66f3 Update api 2025-02-15 19:37:43 -05:00
Kam 025e1ada3c Linked Item Things 2025-02-15 19:37:25 -05:00
Kam 1ca70be090 Short Lmap Bounds 2025-02-15 17:26:59 -05:00
Kam 114d9d0941 Fix Short Lamp 2025-02-15 17:19:22 -05:00
Kam c94f928f5e Brush Color Tag 2025-02-15 17:14:40 -05:00
Kam 4703faa515 Allow Translating in Frame 2025-02-15 02:14:57 -05:00
luisc 7ee1b57763 Merged packet API branch 2025-02-14 17:04:02 -06:00
Kam def6f60553 Fix Signs 2025-02-14 17:00:22 -05:00
Kam fb39c6bd49 Fix Sign Bug 2025-02-14 16:52:35 -05:00
Kam 9b0272ef29 Merge branch 'packet' into animation-events-2 2025-02-14 16:38:59 -05:00
luisc 74b71a290d Fixed exception caused by import in API 2025-02-14 14:49:35 -06:00
Kam 25d917c338 Merge branch 'packet' into animation-events-2 2025-02-14 15:22:59 -05:00
luisc 30aa37ba6f Made ScriptLinkedItem implement IItemLinked api interface 2025-02-14 12:30:07 -06:00
luisc 8909124fff Made ScriptLinkedItem implement IItemLinked api interface 2025-02-14 12:29:53 -06:00
luisc 4a1a092757 More linked item changes 2025-02-14 12:28:17 -06:00
luisc d394174108 Made item events use IItemCustomizable interface. 2025-02-13 19:00:21 -06:00
luisc 6d80acb5f0 Created IItemCustomizable interface 2025-02-13 18:44:11 -06:00
luisc cb5b8898bb Moved common stuff into ItemCustomizable 2025-02-13 18:20:01 -06:00
luisc d9e6372acb Added ItemCustomizable abstract class which both scripted and linked items extend from. Common behavior between the classes should move there. 2025-02-13 18:16:53 -06:00
luisc 44e5c8b4c5 progress on linked items 2025-02-13 18:11:58 -06:00
Kam 6193f77bf5 Brush Setting and Getting Packets 2025-02-13 17:40:16 -05:00
luisc fb87e2a72c removed unused ItemLinked class 2025-02-13 14:55:25 -06:00
luisc 42de9a0568 NBT changes to accommodate nullable fields 2025-02-13 14:48:36 -06:00
luisc fb75f52806 NBT changes to accommodate nullable fields 2025-02-13 14:48:21 -06:00
Kam 4b8e0cd8c3 Brush Color Setting and Changing Interaction 2025-02-13 15:35:45 -05:00
luisc 82dfbc8635 Made display fields nullable 2025-02-13 14:12:27 -06:00
luisc b7d57671b1 Merge remote-tracking branch 'origin/packet' into packet 2025-02-13 13:49:11 -06:00
luisc d510fe8a00 Created abstract ScriptCustomizableItem class for scripted items 2025-02-13 13:48:59 -06:00
Kam bd2eb0fe16 Fix Some Types and isColorTile simpler 2025-02-13 14:06:00 -05:00
Kam 16d838d6eb Fix Tall Lamps 2025-02-13 03:38:22 -05:00
Kam 8547c21474 Fix Lamps 2025-02-13 03:30:04 -05:00
Kam 3a00d08304 Hex Color Update 2025-02-13 03:12:46 -05:00
Kam 3c610e7105 Rename to Banner Trim 2025-02-13 02:14:07 -05:00
Kam cb2c7910cf Brush Editor 2025-02-13 02:09:50 -05:00
Kam 16f2901fbc Merge branch 'packet' into animation-events-2 2025-02-12 22:37:52 -05:00
Kam eb57a15417 Add Anvil Recipe 2025-02-12 22:37:34 -05:00
Kam afa5bd81bd Updated Pedestal Model 2025-02-12 22:29:16 -05:00
Kam f74984a014 NPC Tool 2025-02-12 21:58:44 -05:00
Kam 0dfcae05f4 Updated Tall Lamp + New Short Lamp 2025-02-12 21:44:14 -05:00
Kam 6d61c64cb6 Fix Anvil Lighting 2025-02-12 21:06:01 -05:00
Kam 936a56ddcb Completed Anvil Model 2025-02-12 20:35:46 -05:00
Kam 50acac65cd Update BlockChairRenderer.java 2025-02-12 18:39:24 -05:00
Kam f00948ebdc Fix Table Lighting 2025-02-12 18:19:45 -05:00
Kam 5dd260bb42 Anvil Model + Push Attributes 2025-02-12 17:39:33 -05:00
Kam 4905b9400a Complete Candle Texture + Lantern 2D Texture 2025-02-12 16:46:42 -05:00
Kam 0a04560243 Complete Couch Model 2025-02-12 15:41:47 -05:00
luisc 0418aa11e4 Fixed some issues with animations not continuing when they should 2025-02-12 13:16:39 -06:00
luisc 3b9c38124e Removed millisecond ticks and tick duration from animations. 2025-02-12 12:15:33 -06:00
Kam c6bb5b1b74 Couches WIP 2025-02-12 05:23:27 -05:00
Kam 0f6d912743 Table Revamp 2025-02-12 04:33:46 -05:00
Kam d6c70167bf Some More Fixes to Rendering, etc 2025-02-12 04:06:25 -05:00
Kam cb206348c5 Fix Custom Effect Desync 2025-02-12 03:15:28 -05:00
Kam 411b4dac51 Barrel Completion 2025-02-12 02:48:06 -05:00
Kam 5d4088b9d1 Lantern Model + Texture 2025-02-12 02:34:05 -05:00
Kam 79fc173e3b Slight Changes 2025-02-12 01:46:42 -05:00
Kam 8e70e958f3 Fix Decrement 2025-02-11 22:35:47 -05:00
Kam c2c101641f Effect Command 2025-02-11 22:05:34 -05:00
luisc e5673a85e7 completely annihilated animation caching (not worth it) 2025-02-11 18:03:41 -06:00
luisc 4d963b0205 Removed animation caching (FILTHY FILTHY YUCK GUACALA) 2025-02-11 18:00:29 -06:00
luisc 2c4038dec8 Merge remote-tracking branch 'origin/animation-events-2' into animation-events-2 2025-02-11 17:59:44 -06:00
luisc 272b1c5e5a Fixed animations starting over instead of jumping to the current frame. 2025-02-11 17:59:35 -06:00
Kam de18cee44c Link API 2025-02-11 18:12:43 -05:00
Kam 901f2e8bc7 Link 2025-02-11 18:11:10 -05:00
luisc 00af353e65 Merge remote-tracking branch 'refs/remotes/origin/packet' into animation-events-2
# Conflicts:
#	src/api
#	src/main/java/noppes/npcs/CommonProxy.java
#	src/main/java/noppes/npcs/ServerEventsHandler.java
#	src/main/java/noppes/npcs/client/PacketHandlerClient.java
#	src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java
#	src/main/java/noppes/npcs/controllers/data/AnimationData.java
2025-02-11 16:53:36 -06:00
somehussar 3f91be9498 Remove comment 2025-02-11 22:49:48 +01:00
somehussar 155cacf3c1 Merge remote-tracking branch 'upstream/packet' into packet 2025-02-11 22:39:17 +01:00
somehussar 9188499e7e Move purely display data into ScriptItemCustom.Display 2025-02-11 22:39:08 +01:00
Kam 4a064add75 Fix Spawn Particle 2025-02-11 16:05:49 -05:00
Kam adef51cd53 HUSSAR PLEASE!!! 2025-02-11 15:37:36 -05:00
Kam eef2e349de Linked Item WIP 2025-02-11 14:12:00 -05:00
Kam 8d2ffdc5e3 Rename to Effect Script 2025-02-11 13:56:28 -05:00
Kam b434600cbe Legacy Couch 2025-02-11 01:01:58 -05:00
Kam 88790cd207 Null Checks 2025-02-10 22:00:50 -05:00
Kam 097f1f9d1d Sync Effects Packet 2025-02-10 21:41:54 -05:00
Kam 7d37670494 Rename to NPC AI to NPC AIs 2025-02-10 21:32:55 -05:00
Kam a35db3f9e5 Fix Rotation Get / Set for NPCs 2025-02-10 21:01:53 -05:00
Kam 44684277ba More Fixes to Custom Effects 2025-02-10 18:56:54 -05:00
Kam def3102354 Beta 2.5 2025-02-10 18:51:21 -05:00
Kam 58cf52fd1f Effect Map Register + Effect Command WIP 2025-02-10 18:33:05 -05:00
Kam 3240970252 Hook up some more things 2025-02-10 18:12:58 -05:00
Kam f2041e855b Rename to CustomEffectHandler 2025-02-10 17:24:26 -05:00
Kam de0e425b87 Effect Keys 2025-02-10 17:19:58 -05:00
Kam 0072369fca Fix Effect Packet Bug 2025-02-10 16:56:17 -05:00
Kam ea8e52e8e6 Register Packets 2025-02-10 16:42:03 -05:00
Kam d2c7e634ec Fix Packets for Effects + Syncing 2025-02-10 16:38:50 -05:00
Kam 070e032907 Push Working Compile 2025-02-10 15:04:44 -05:00
Kam 20a46e6007 Custom Effect [WIP] 2025-02-10 14:58:45 -05:00
Kam 65ac349c08 API Link 2025-02-10 14:26:32 -05:00
Kam 29e182e82d Linked Item [WIP] 2025-02-10 14:20:40 -05:00
Kam d45e550321 Availability Options for Recipe & Anvil Recipes 2025-02-10 13:59:59 -05:00
Kam 48dd7bedea New Anvil Recipe System 2025-02-10 02:44:28 -05:00
Kam 9cda5503ed Anvil Recipes Beginning 2025-02-09 20:49:45 -05:00
Kam e9004aafa3 Rename to Linked GUI 2025-02-09 04:47:36 -05:00
Kam eeb6b2ea8b Scripted Items Display Errors & Fix Console Scroll Wheel and Scroll Bar 2025-02-09 04:02:16 -05:00
Kam 4202cb7271 Fix Scripted Items re-evaluating Scripts 2025-02-09 01:09:23 -05:00
Kam 8a270b1548 Fix Button 2025-02-06 18:42:46 -05:00
Kam 5de68934eb Square Buttons for Menu 2025-02-06 18:08:38 -05:00
Kam 328a3d4186 Best Image Scaling 2025-02-06 15:55:21 -05:00
Mark Zharkov f168eb34d5 fix strange field 2025-02-06 22:50:02 +03:00
Mark Zharkov 5180e3cc4b maybe it should be like this? part 2 2025-02-06 22:49:17 +03:00
Mark Zharkov 7244d8fcd7 fix a potential NPE 2025-02-06 22:44:28 +03:00
Mark Zharkov f2e85c1347 maybe it should be like this? 2025-02-06 22:42:50 +03:00
Mark Zharkov e963ead882 fix the comparison with yourself 2025-02-06 22:39:43 +03:00
Mark Zharkov 37ad1755fd fix loss of the block 2025-02-06 22:38:44 +03:00
Mark Zharkov 21a1dd0ba9 fix missprint 2025-02-06 22:37:49 +03:00
Mark Zharkov 002a64cb88 fix the strange places 2025-02-06 22:37:16 +03:00
Mark Zharkov 30714e92a5 fix missprint (minutes/minute) 2025-02-06 22:35:51 +03:00
Kam 3e6a5410ab Make Public for DBC Addon to use 2025-02-06 12:26:09 -05:00
Kam 48e3ae5271 Icons for Global Menu 2025-02-06 12:11:37 -05:00
Kam dfb4c511cc Revamped Model Table 2025-02-04 15:39:25 -05:00
Kam a973eca54c Huge Chart Implementation 2025-02-04 14:38:13 -05:00
Kam ee727146a9 Huge PUSH to Types of Diagram Generation 2025-02-04 03:48:25 -05:00
Kam 4f52e2674b Fix Campfire Bug 2025-02-04 02:19:51 -05:00
Kam 1be707ce47 Better Magic Graph Generation + Defaults 2025-02-04 00:29:18 -05:00
Kam fc7b7f627d Diagram Completed 2025-02-03 21:18:45 -05:00
Kam a0ace95d35 Only input scroll wheel if we're within it 2025-02-03 20:32:02 -05:00
Kam d84092eeaf Add a Highlighting, Not Highlighted and Default State + Fix Panning and Hovering Positioning 2025-02-03 20:22:16 -05:00
Kam 64b033da65 Button Icons 2025-02-03 19:53:30 -05:00
Kam 334eca1b40 Circular Magic Map 2025-02-03 18:15:43 -05:00
Kam 7a0c742833 GuiNPCDiagram + Magic System PRE-PUSH 2025-02-03 17:28:03 -05:00
Kam 50c6ab644b Semi Functioning Magic Map System 2025-02-03 16:59:06 -05:00
Kam d28935ab58 Resizing for Gui Quests Management 2025-02-03 13:43:51 -05:00
Kam e37519f4e3 Fix Tag Packets 2025-02-03 13:43:38 -05:00
Kam 268bd0f456 Remove Blank Override 2025-02-03 13:06:53 -05:00
Kam 29c456ab4e Add Search to Remote Editor 2025-02-03 12:36:28 -05:00
Kam c0dc526d41 Resizing for Dialog Page 2025-02-03 01:47:47 -05:00
Kam de9b373973 Duplicate Entry 2025-02-03 01:47:41 -05:00
Kam e3cfdd5ee1 Fix Some Bugs 2025-02-02 23:47:41 -05:00
Kam 4ae8978399 Expand Large Packet Size to 30MB 2025-02-02 23:23:09 -05:00
Kam fe7c24186d Remove Redundant Old Packet Handlers 2025-02-02 23:18:18 -05:00
Kam 0f948a9d62 Script Packets 2025-02-02 23:15:53 -05:00
Kam 04fc429a53 Merge branch 'packet' of https://github.com/KAMKEEL/CustomNPC-Plus into packet 2025-02-02 22:47:44 -05:00
Kam d11f72eb0d More THings 2025-02-02 22:47:40 -05:00
somehussar c55ef6d0fc Register packets 2025-02-03 04:45:03 +01:00
somehussar 3d2a6954f9 Book & Sign packets 2025-02-03 04:43:41 +01:00
somehussar 4143298da3 Merge remote-tracking branch 'upstream/packet' into packet 2025-02-03 04:33:10 +01:00
somehussar 10f12ad036 Get NPC Role packet 2025-02-03 04:32:59 +01:00
Kam a41a320676 Merge branch 'packet' of https://github.com/KAMKEEL/CustomNPC-Plus into packet 2025-02-02 22:31:43 -05:00
Kam 9841d158ff Cloner Packets 2025-02-02 22:31:39 -05:00
somehussar a5c3c6768b CompanionActionPacket 2025-02-03 04:29:07 +01:00
somehussar 54a07ffb48 Dialog packet needs NPC 2025-02-03 04:19:20 +01:00
somehussar ea1f5b259d Dialog packet 2025-02-03 04:16:24 +01:00
somehussar c5329a1c63 General get packet 2025-02-03 03:57:40 +01:00
somehussar 021989aa79 ScreenSize packet 2025-02-03 03:41:01 +01:00
somehussar e6e860b895 SideOnly on MailActionPacket 2025-02-03 03:31:52 +01:00
somehussar 94fc6e035c Register mail packets 2025-02-03 03:31:04 +01:00
somehussar a2a3d94de6 Merge remote-tracking branch 'upstream/packet' into packet 2025-02-03 03:23:54 +01:00
somehussar a93c0fc3c6 Start work on Mail packets 2025-02-03 03:23:50 +01:00
Kam 0326947b23 Mounter Packets Completed + Cloner Packets 2025-02-02 19:49:36 -05:00
somehussar 20e44c919f Rename BankPacket to BankActionPacket 2025-02-03 01:47:47 +01:00
somehussar fb32ca6e29 InputDevicePacket 2025-02-03 01:32:49 +01:00
Kam 42fe078efd Pather and Mounter Packets 2025-02-02 19:23:14 -05:00
Kam b0e4d555ce Complete Block & Wand Packets 2025-02-02 19:08:18 -05:00
Kam f314d9d826 Quest Get Packet 2025-02-02 18:14:52 -05:00
Kam f950ba0a22 Bunch more Get Packets 2025-02-02 18:10:57 -05:00
Kam 57e41412dd Small Fixes 2025-02-02 17:49:57 -05:00
Kam b5d294dd20 Merge branch 'packet' of https://github.com/KAMKEEL/CustomNPC-Plus into packet 2025-02-02 17:38:46 -05:00
Kam 4a1732c5f0 Finish a ton more packets 2025-02-02 17:38:42 -05:00
somehussar abfb06aa7a TransportPacket 2025-02-02 23:20:03 +01:00
somehussar 87eeebc1af Remove unused imports 2025-02-02 23:08:23 +01:00
somehussar 5117c39a2f Update packet name 2025-02-02 23:07:53 +01:00
somehussar 2677809c0e Remove null check 2025-02-02 23:04:57 +01:00
somehussar 5ce4beab34 Merge remote-tracking branch 'upstream/packet' into packet 2025-02-02 23:03:49 +01:00
Kam 902fad4e6f Tile Entity Get and Save 2025-02-02 17:03:45 -05:00
somehussar 28acfbc8f8 register packets & needNPC 2025-02-02 23:03:34 +01:00
Kam 55d271abad Lots more packet schtuff 2025-02-02 17:00:32 -05:00
somehussar 21557ff857 @SideOnly added 2025-02-02 22:57:57 +01:00
somehussar 864e1cb8c7 Bank packet 2025-02-02 22:57:46 +01:00
somehussar 30e58dc049 Merge branch 'packet' of https://github.com/KAMKEEL/CustomNPC-Plus into packet 2025-02-02 22:26:23 +01:00
somehussar 7c2ad0749b Follower packet 2025-02-02 22:21:29 +01:00
Kam 601123811a Informed IsGuiOpen 2025-02-02 16:09:46 -05:00
Kam 47e30ac8b4 Huge Commit and Refactoring 2025-02-02 16:07:16 -05:00
Kam 0124154380 Job Packets 2025-02-02 03:28:13 -05:00
Kam 7366b11077 Cache Animation Packet 2025-02-02 03:08:52 -05:00
Kam bd783a2e98 Dimension Get Packet 2025-02-02 03:04:03 -05:00
Kam 364bf2414f Custom GUI Packets 2025-02-02 03:01:12 -05:00
Kam b22105341f BUNCH OF NEW PACKETS 2025-02-02 02:25:21 -05:00
Kam f2c34699b1 Large Packet Commit 2025-02-01 23:43:06 -05:00
Kam b15d64bd09 Linked Packets 2025-02-01 21:44:22 -05:00
Kam 35da0f92f6 MAKE A trillion + 1 packets now 🐶 2025-02-01 21:23:49 -05:00
Kam 1e5cc66f2f packet progress 2025-01-31 01:58:54 -05:00
Kam 3979d1895b Fixes 2025-01-30 22:50:10 -05:00
Kam 9ea1385ac2 Fix Packets not working for testing 2025-01-30 18:44:50 -05:00
Kam e77a1032d3 commit 2025-01-30 18:13:04 -05:00
Kam c2bc9c6c11 Request Packet 2025-01-30 14:16:39 -05:00
Kam 702df25036 Reorganization again 2025-01-30 13:58:09 -05:00
Kam 68404d353f more Data packet 2025-01-30 13:54:55 -05:00
Kam db2144116f Reorg -- Data Packets designed to send to Client 2025-01-30 13:54:49 -05:00
Kam da9ed1d60f Remove PacketHandlerClient Reference 2025-01-30 12:51:43 -05:00
Kam db7473fd57 Delete more 2025-01-30 12:45:10 -05:00
Kam e042b2cfac EnumPacketClient Deleted 2025-01-30 12:45:06 -05:00
Kam c3179b36f2 Remove PacketHandlerClient 2025-01-30 12:44:39 -05:00
Kam 43b0e7c23b More Reworking 2025-01-30 12:16:16 -05:00
Kam a1f10db0de Continue to replace Client Packet Handler with PacketHandler 2025-01-30 12:16:11 -05:00
Kam e8c3fc4d0a MORE SWAPPING 2025-01-30 11:03:57 -05:00
Kam 4f5f870e2b More Packet Swapping 2025-01-30 11:03:52 -05:00
Kam a70300c54b Register More Packets + Remove Useless Sync Packets 2025-01-30 10:32:01 -05:00
Kam 87cad579ae Large GUI Data Packet 2025-01-30 09:30:31 -05:00
Kam fb496ce1e2 SyncController 2025-01-30 09:26:10 -05:00
Kam ee8527f261 SyncController Fixes 2025-01-30 09:26:04 -05:00
Kam 5d308b1f56 Sync Recipes 2025-01-30 09:22:43 -05:00
Kam 90605ee808 ok 2025-01-30 01:44:45 -05:00
Kam 31c7ceacab Sound Packet Commit 2025-01-30 01:35:48 -05:00
Kam e8e868993b SideOnly Client for Client Packets 2025-01-29 23:47:50 -05:00
Kam 1c97d84518 uh oh 2025-01-29 23:40:05 -05:00
Kam 29f9774d1f WE KEEPPPP ON GOING 2025-01-29 23:33:35 -05:00
Kam 4eae773f86 Still going 2025-01-29 22:56:28 -05:00
Kam d91d4668d6 WHEN WILL THIS END! 2025-01-29 21:50:55 -05:00
Kam 06275fffa6 All 10MB of NBT Size to function 2025-01-29 19:43:45 -05:00
Kam de56032118 Syncing and Large Packet Completion 2025-01-29 18:25:34 -05:00
Kam dcf3a0d8b0 Fix Packet Logging 2025-01-29 15:08:24 -05:00
Kam f573259fd1 Complete Large Packet Sending 2025-01-29 15:04:19 -05:00
Kam 36c8b70eb4 Generate Packet Chunks for Large Packets 2025-01-29 13:28:14 -05:00
Kam 5d41f5b939 Rename Namespace to kamkeel.npcs 2025-01-29 13:20:04 -05:00
Kam 19c31b985d Large Abstract Packet By UUID 2025-01-28 18:25:30 -05:00
Kam 476efb0317 Register Large Packets 2025-01-28 18:19:58 -05:00
Kam 5790926e51 More Super Commits for Packet System 2025-01-28 18:14:18 -05:00
Kam 882bce2d4b Reorgs 2025-01-28 15:51:50 -05:00
Kam d2da5c6000 Rename Packet 2025-01-28 15:50:00 -05:00
Kam 8a2a3e1ac3 Add all Client Packets 2025-01-28 15:49:17 -05:00
Kam ec133ce74c Remove Packet Names 2025-01-28 15:00:49 -05:00
Kam be6c318619 New Packet Things - WIP 2025-01-28 14:37:07 -05:00
Kam 17eac9a690 Merge branch 'dev' of https://github.com/KAMKEEL/CustomNPC-Plus into dev 2025-01-28 13:39:48 -05:00
Kam 36b2610d3d Packet PRE 2025-01-28 13:39:46 -05:00
Kam c95341b60b Stool and Chair Models Completed 2025-01-28 01:12:41 -05:00
Kam 26f4158c17 Legacy Carpentry Bench Support 2025-01-27 23:21:30 -05:00
Kam 4d2ced4528 Updated Banners 2025-01-27 17:21:11 -05:00
Kam 2f5d5f84c2 Modern Stool 2025-01-26 17:55:25 -05:00
Kam 8f4a5cdd16 Legacy Chair Config 2025-01-26 17:39:04 -05:00
Kam 81b4f7a0ef Campfire Model Completed + Particles 2025-01-26 16:48:53 -05:00
Kam 4aa0a96f1f Banner Upgrade WIP 2025-01-26 15:47:04 -05:00
Kam db9ac7f7c4 Upgraded Barrel & Campfire Models 2025-01-25 19:41:54 -05:00
Kam 435c31ddda Link Profiles 2025-01-24 12:35:34 -05:00
Kam 62482c307c Profile Tab + Config Sync 2025-01-24 00:29:11 -05:00
Kam c7c981f4a7 Profile Work 2025-01-23 17:56:53 -05:00
Kam 52aa1a75c1 Profile Change Command Completed 2025-01-23 17:45:13 -05:00
Kam 10edf72ed9 Profile Change Command 2025-01-23 17:45:05 -05:00
Kam f6e3f867e0 Remove Redundancy 2025-01-23 17:06:12 -05:00
Kam bf604774c0 [WIP] Multiple Profile Handlers 2025-01-23 16:10:01 -05:00
Luis C.M. 34d002191e Animation fixes, temporarily removed caching. 2025-01-23 00:35:25 -06:00
Luis C.M. 572077b7e5 Loads of changes from the animation branch 2025-01-22 18:54:00 -06:00
Luis C.M. 990419a411 New event hooks and animation event class 2025-01-22 15:49:27 -06:00
Luis C.M. 0bb5dee58f Change to animation frame API 2025-01-22 15:47:10 -06:00
Kam b2b9248c55 Updated Model Chair 2025-01-22 12:42:35 -05:00
Kam a01297d437 Update Carpentry Bench Model 2025-01-22 12:35:20 -05:00
Kam 437d365de3 Update api 2025-01-22 12:32:21 -05:00
Kam 64fdc9baa8 Save when Pressing Escape on Console Command 2025-01-22 12:14:04 -05:00
Kam 7a28d9107c Fix Casting Error for PickUp Event 2025-01-22 11:53:22 -05:00
Luis C.M. 179c7b6fb4 Moved world stored/temp data into the API, functionally the data is the same since different worlds don't have different data. 2024-12-22 17:26:09 -06:00
Kam c36ac283e4 Beta 1 Branding 1.9.4 2024-12-21 15:52:04 -05:00
Kam 0a7a638040 Fix Player vs. Player Interaction Quest Kill Crash 2024-12-21 15:51:37 -05:00
Kam 6a59dc91a0 Allow Tag Modifying through Cloner without Closing + Fix Removing All Tags Bug 2024-12-21 14:23:22 -05:00
Kam 810d2ca12c Don't rotate when sliding a slider 2024-12-20 01:56:18 -05:00
Kam f98b31c8d9 Fix for Angelica Display List Compiling Optimizations 2024-12-19 19:31:28 -05:00
ten 9f6f864a36 Update zh_CN.lang
Update the Chinese language file and correct any previous mistranslations.
2024-11-08 20:53:11 +08:00
Luis C.M. 8c10235ee2 Merge remote-tracking branch 'origin/dev' into dev 2024-10-26 10:46:09 -05:00
Luis C.M. ca7debb51b Fixed null pointer exception when setting animation in animation controller. 2024-10-26 10:45:59 -05:00
luisc 600f225d7a Fixed exception when opening scripter on servers. ConfigScript.canScript() should only ever be called on the server side. 2024-10-25 13:45:12 -05:00
luisc d57571ea0d Made API return a DBC player object if a player is a DBC player. Deprecated old getDBCPlayer() function. 2024-10-24 17:12:00 -05:00
Kam ad222657c4 Fix Cancel calculations for Attacked / Attack or Damaged / Damage 2024-10-23 21:16:59 -04:00
Kam 213c02660b Artifact V4 Upload 2024-10-17 11:16:25 -04:00
Kam b81c038584 Update Gradle / Build Script 2024-10-17 11:12:58 -04:00
Kam 0a4abfca9e Hopefully null checks 2024-10-12 14:01:49 -04:00
luisc d0bff7cb6f music controller fix (o_O ??) 2024-10-09 14:18:08 -05:00
Kam a459a27872 Is Script Dev logic change 2024-10-06 20:23:58 -04:00
Kam f0ab36e4a1 Fix Script Ops Only Logic 2024-10-06 17:29:17 -04:00
Kam e7f48ae70d Send 20 Quests / Dialogs at once instead of 40 2024-10-06 15:49:36 -04:00
Kam a6bb327c08 Fix Dialog Categories kicking on New Categories 2024-10-06 14:34:31 -04:00
Kam 5eb2e98305 Log Oversized Packets 2024-10-06 14:28:51 -04:00
1287 changed files with 62205 additions and 20651 deletions

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
run: ./gradlew SetupCIWorkspace build run: ./gradlew SetupCIWorkspace build
- name: Build with Gradle (nomixin) - name: Build with Gradle (nomixin)
run: ./gradlew build -Pnomixin run: ./gradlew build -Pnomixin
- uses: actions/upload-artifact@v2 - uses: actions/upload-artifact@v4
with: with:
name: Package name: Package
path: build/libs path: build/libs
+2 -2
View File
@@ -5,7 +5,7 @@ plugins {
id 'idea' id 'idea'
} }
version = "1.9.3" version = "1.10-testingbeta1"
group= "kamkeel.customnpc-plus" group= "kamkeel.customnpc-plus"
archivesBaseName = "CustomNPC-Plus" archivesBaseName = "CustomNPC-Plus"
@@ -37,4 +37,4 @@ sourceSets {
} }
// Modify the existing 'build' task to depend on 'updateAPI' // Modify the existing 'build' task to depend on 'updateAPI'
tasks.apiClasses.dependsOn 'updateAPI' //tasks.apiClasses.dependsOn 'updateAPI'
+65 -5
View File
@@ -1,3 +1,13 @@
# ExampleMod tag to use as Blowdryer (Spotless, etc.) settings version, leave empty to disable.
# LOCAL to test local config updates.
gtnh.settings.blowdryerTag = 0.2.2
# Whether to automatically set the version based on the VERSION environment variable or the current git status.
gtnh.modules.gitVersion = false
# Sets up code style plugins like Spotless and Checkstyle.
gtnh.modules.codeStyle = true
# Human-readable mod name, available for mcmod.info population. # Human-readable mod name, available for mcmod.info population.
modName = CustomNPC+ modName = CustomNPC+
@@ -8,10 +18,6 @@ modId = customnpcs
# Root package of the mod, used to find various classes in other properties, # Root package of the mod, used to find various classes in other properties,
# mcmod.info substitution, enabling assertions in run tasks, etc. # mcmod.info substitution, enabling assertions in run tasks, etc.
modGroup = noppes.npcs modGroup = noppes.npcs
modVersion = 1.9.3
gtnh.modules.codeStyle=true
gtnh.modules.gitVersion=false
# Whether to use modGroup as the maven publishing group. # Whether to use modGroup as the maven publishing group.
# Due to a history of using JitPack, the default is com.github.GTNewHorizons for all mods. # Due to a history of using JitPack, the default is com.github.GTNewHorizons for all mods.
@@ -22,10 +28,14 @@ autoUpdateBuildScript = false
# Version of Minecraft to target # Version of Minecraft to target
minecraftVersion = 1.7.10 minecraftVersion = 1.7.10
# Version of Minecraft Forge to target
forgeVersion = 10.13.4.1614 forgeVersion = 10.13.4.1614
# Specify an MCP channel for dependency deobfuscation and the deobfParams task. # Specify an MCP channel for dependency deobfuscation and the deobfParams task.
channel = stable channel = stable
# Specify an MCP mappings version for dependency deobfuscation and the deobfParams task.
mappingsVersion = 12 mappingsVersion = 12
# Defines other MCP mappings for dependency deobfuscation. # Defines other MCP mappings for dependency deobfuscation.
@@ -71,25 +81,53 @@ accessTransformersFile = customnpcs_at.cfg
# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! # Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled!
usesMixins = true usesMixins = true
# Set to a non-empty string to configure mixins in a separate source set under src/VALUE, instead of src/main.
# This can speed up compile times thanks to not running the mixin annotation processor on all input sources.
# Mixin classes will have access to "main" classes, but not the other way around.
separateMixinSourceSet =
# Adds some debug arguments like verbose output and class export. # Adds some debug arguments like verbose output and class export.
usesMixinDebug = true usesMixinDebug = true
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin = mixin.CustomNPCsMixinPlugin mixinPlugin = mixin.CustomNPCsMixinPlugin
# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
mixinsPackage = mixin mixinsPackage = mixin
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
# This parameter is for legacy compatibility only
# Example value: (coreModClass = asm.FMLPlugin) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.asm.FMLPlugin
coreModClass =
# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class
# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false!
containsMixinsAndOrCoreModOnly = false containsMixinsAndOrCoreModOnly = false
# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins.
forceEnableMixins = false forceEnableMixins = false
# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated into your jar. It is your # If enabled, you may use 'shadowCompile' for dependencies. They will be integrated into your jar. It is your
# responsibility to check the license and request permission for distribution if required. # responsibility to check the license and request permission for distribution if required.
usesShadowedDependencies = true usesShadowedDependencies = true
# If disabled, won't remove unused classes from shadowed dependencies. Some libraries use reflection to access # If disabled, won't remove unused classes from shadowed dependencies. Some libraries use reflection to access
# their own classes, making the minimization unreliable. # their own classes, making the minimization unreliable.
minimizeShadowedDependencies = false minimizeShadowedDependencies = false
# If disabled, won't rename the shadowed classes. # If disabled, won't rename the shadowed classes.
relocateShadowedDependencies = false relocateShadowedDependencies = false
# Adds the GTNH maven, CurseMaven, IC2/Player maven, and some more well-known 1.7.10 repositories. # Adds CurseMaven, Modrinth, and some more well-known 1.7.10 repositories.
includeWellKnownRepositories = true includeWellKnownRepositories = true
# A list of repositories to exclude from the includeWellKnownRepositories setting. Should be a space separated
# list of strings, with the acceptable keys being(case does not matter):
# cursemaven
# modrinth
excludeWellKnownRepositories =
# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven. # Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven.
# Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables. # Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables.
# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle. # If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle.
@@ -103,8 +141,28 @@ usesMavenPublishing = false
# The project's ID on Modrinth. Can be either the slug or the ID. # The project's ID on Modrinth. Can be either the slug or the ID.
# Leave this empty if you don't want to publish to Modrinth. # Leave this empty if you don't want to publish to Modrinth.
modrinthProjectId = modrinthProjectId =
# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth.
# Syntax: scope1-type1:name1;scope2-type2:name2;...
# Where scope can be one of [required, optional, incompatible, embedded],
# type can be one of [project, version],
# and the name is the Modrinth project or version slug/id of the other mod.
# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech
# Note: GTNH Mixins is automatically set as a required dependency if usesMixins = true
modrinthRelations = modrinthRelations =
# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens.
#
# The project's numeric ID on CurseForge. You can find this in the About Project box.
# Leave this empty if you don't want to publish on CurseForge.
curseForgeProjectId = curseForgeProjectId =
# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge.
# Syntax: type1:name1;type2:name2;...
# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible],
# and the name is the CurseForge project slug of the other mod.
# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
curseForgeRelations = curseForgeRelations =
# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older # Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older
@@ -140,3 +198,5 @@ disableCheckstyle = true
# This is meant to be set in $HOME/.gradle/gradle.properties. # This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true # ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
modVersion = 1.10
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
Vendored Regular → Executable
View File
File mode changed.
+1 -1
View File
@@ -17,5 +17,5 @@ pluginManagement {
} }
plugins { plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.14' id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.27'
} }
+1 -1
Submodule src/api updated: 9fdd2c667e...c7a74a3e0e.
+8 -14
View File
@@ -40,8 +40,7 @@ public class CmdClone extends ChMcLogger {
int tab = 0; int tab = 0;
try { try {
tab = Integer.parseInt(args[1]); tab = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
} }
List<EntityNPCInterface> list = Utils.getNearbeEntityFromPlayer(EntityNPCInterface.class, player, 80); List<EntityNPCInterface> list = Utils.getNearbeEntityFromPlayer(EntityNPCInterface.class, player, 80);
@@ -67,8 +66,7 @@ public class CmdClone extends ChMcLogger {
int tab = 0; int tab = 0;
try { try {
tab = Integer.parseInt(args[0]); tab = Integer.parseInt(args[0]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
} }
for (String name : ServerCloneController.Instance.getClones(tab)) { for (String name : ServerCloneController.Instance.getClones(tab)) {
@@ -84,8 +82,7 @@ public class CmdClone extends ChMcLogger {
int tab = 0; int tab = 0;
try { try {
tab = Integer.parseInt(args[1]); tab = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
} }
boolean deleted = false; boolean deleted = false;
@@ -113,8 +110,7 @@ public class CmdClone extends ChMcLogger {
int tab = 0; int tab = 0;
try { try {
tab = Integer.parseInt(args[1]); tab = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
} }
String newname = null; String newname = null;
@@ -172,7 +168,7 @@ public class CmdClone extends ChMcLogger {
entity.setPosition(posX + 0.5, posY + 1, posZ + 0.5); entity.setPosition(posX + 0.5, posY + 1, posZ + 0.5);
if (entity instanceof EntityNPCInterface) { if (entity instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) entity; EntityNPCInterface npc = (EntityNPCInterface) entity;
npc.ai.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)}; npc.ais.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)};
if (newname != null && !newname.isEmpty()) if (newname != null && !newname.isEmpty())
npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way
} }
@@ -189,8 +185,7 @@ public class CmdClone extends ChMcLogger {
int tab = 0; int tab = 0;
try { try {
tab = Integer.parseInt(args[1]); tab = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
} }
@@ -198,8 +193,7 @@ public class CmdClone extends ChMcLogger {
try { try {
width = Integer.parseInt(args[2]); width = Integer.parseInt(args[2]);
height = Integer.parseInt(args[3]); height = Integer.parseInt(args[3]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendmessage("lenght or width wasnt a number"); sendmessage("lenght or width wasnt a number");
return false; return false;
} }
@@ -274,7 +268,7 @@ public class CmdClone extends ChMcLogger {
entity.setPosition(posX + 0.5 + x, yy + 1, posZ + 0.5 + z); entity.setPosition(posX + 0.5 + x, yy + 1, posZ + 0.5 + z);
if (entity instanceof EntityNPCInterface) { if (entity instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) entity; EntityNPCInterface npc = (EntityNPCInterface) entity;
npc.ai.startPos = new int[]{xx, yy, zz}; npc.ais.startPos = new int[]{xx, yy, zz};
if (newname != null && !newname.isEmpty()) if (newname != null && !newname.isEmpty())
npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way
} }
+17 -23
View File
@@ -5,15 +5,17 @@ import foxz.commandhelper.annotations.Command;
import foxz.commandhelper.annotations.SubCommand; import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly; import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.PlayerOnly; import foxz.commandhelper.permissions.PlayerOnly;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumConfigOperation;
import kamkeel.npcs.network.packets.data.ConfigCommandPacket;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockIce; import net.minecraft.block.BlockIce;
import net.minecraft.block.BlockLeavesBase; import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.BlockVine; import net.minecraft.block.BlockVine;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.CustomNpcs; import noppes.npcs.CustomNpcs;
import noppes.npcs.Server; import noppes.npcs.config.ConfigItem;
import noppes.npcs.config.ConfigMain; import noppes.npcs.config.ConfigMain;
import noppes.npcs.constants.EnumPacketClient;
import noppes.npcs.controllers.ChunkController; import noppes.npcs.controllers.ChunkController;
import java.util.Arrays; import java.util.Arrays;
@@ -39,8 +41,7 @@ public class CmdConfig extends ChMcLogger {
public boolean leavesdecay(String[] args) { public boolean leavesdecay(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("LeavesDecay: " + ConfigMain.LeavesDecayEnabled); sendmessage("LeavesDecay: " + ConfigMain.LeavesDecayEnabled);
} } else {
else{
ConfigMain.LeavesDecayEnabled = Boolean.parseBoolean(args[0]); ConfigMain.LeavesDecayEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.LeavesDecayEnabledProperty.set(ConfigMain.LeavesDecayEnabled); ConfigMain.LeavesDecayEnabledProperty.set(ConfigMain.LeavesDecayEnabled);
if (ConfigMain.config.hasChanged()) { if (ConfigMain.config.hasChanged()) {
@@ -67,8 +68,7 @@ public class CmdConfig extends ChMcLogger {
public boolean vinegrowth(String[] args) { public boolean vinegrowth(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("VineGrowth: " + ConfigMain.VineGrowthEnabled); sendmessage("VineGrowth: " + ConfigMain.VineGrowthEnabled);
} } else {
else{
ConfigMain.VineGrowthEnabled = Boolean.parseBoolean(args[0]); ConfigMain.VineGrowthEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.VineGrowthEnabledProperty.set(ConfigMain.VineGrowthEnabled); ConfigMain.VineGrowthEnabledProperty.set(ConfigMain.VineGrowthEnabled);
if (ConfigMain.config.hasChanged()) { if (ConfigMain.config.hasChanged()) {
@@ -95,8 +95,7 @@ public class CmdConfig extends ChMcLogger {
public boolean icemelts(String[] args) { public boolean icemelts(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("IceMelts: " + ConfigMain.IceMeltsEnabled); sendmessage("IceMelts: " + ConfigMain.IceMeltsEnabled);
} } else {
else{
ConfigMain.IceMeltsEnabled = Boolean.parseBoolean(args[0]); ConfigMain.IceMeltsEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.IceMeltsEnabledProperty.set(ConfigMain.IceMeltsEnabled); ConfigMain.IceMeltsEnabledProperty.set(ConfigMain.IceMeltsEnabled);
if (ConfigMain.config.hasChanged()) { if (ConfigMain.config.hasChanged()) {
@@ -122,15 +121,14 @@ public class CmdConfig extends ChMcLogger {
) )
public boolean guns(String[] args) { public boolean guns(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("GunsEnabled: " + ConfigMain.GunsEnabled); sendmessage("GunsEnabled: " + ConfigItem.GunsEnabled);
} } else {
else{ ConfigItem.GunsEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.GunsEnabled = Boolean.parseBoolean(args[0]); ConfigItem.GunsEnabledProperty.set(ConfigItem.GunsEnabled);
ConfigMain.GunsEnabledProperty.set(ConfigMain.GunsEnabled);
if (ConfigMain.config.hasChanged()) { if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save(); ConfigMain.config.save();
} }
sendmessage("GunsEnabled is now " + ConfigMain.GunsEnabled); sendmessage("GunsEnabled is now " + ConfigItem.GunsEnabled);
} }
return true; return true;
} }
@@ -144,8 +142,7 @@ public class CmdConfig extends ChMcLogger {
public boolean freezenpcs(String[] args) { public boolean freezenpcs(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("Frozen NPCs: " + CustomNpcs.FreezeNPCs); sendmessage("Frozen NPCs: " + CustomNpcs.FreezeNPCs);
} } else {
else{
CustomNpcs.FreezeNPCs = Boolean.parseBoolean(args[0]); CustomNpcs.FreezeNPCs = Boolean.parseBoolean(args[0]);
sendmessage("FrozenNPCs is now " + CustomNpcs.FreezeNPCs); sendmessage("FrozenNPCs is now " + CustomNpcs.FreezeNPCs);
} }
@@ -161,12 +158,10 @@ public class CmdConfig extends ChMcLogger {
public boolean chunkloaders(String[] args) { public boolean chunkloaders(String[] args) {
if (args.length == 0) { if (args.length == 0) {
sendmessage("ChunkLoaders: " + ChunkController.Instance.size() + "/" + ConfigMain.ChunkLoaders); sendmessage("ChunkLoaders: " + ChunkController.Instance.size() + "/" + ConfigMain.ChunkLoaders);
} } else {
else{
try { try {
ConfigMain.ChunkLoaders = Integer.parseInt(args[0]); ConfigMain.ChunkLoaders = Integer.parseInt(args[0]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendmessage("Didnt get a number"); sendmessage("Didnt get a number");
return false; return false;
} }
@@ -198,8 +193,7 @@ public class CmdConfig extends ChMcLogger {
try { try {
size = Integer.parseInt(args[args.length - 1]); size = Integer.parseInt(args[args.length - 1]);
args = Arrays.copyOfRange(args, 0, args.length - 1); args = Arrays.copyOfRange(args, 0, args.length - 1);
} } catch (Exception e) {
catch(Exception e){
} }
} }
@@ -207,6 +201,6 @@ public class CmdConfig extends ChMcLogger {
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
font += " " + args[i]; font += " " + args[i];
} }
Server.sendData((EntityPlayerMP)this.pcParam, EnumPacketClient.CONFIG, 0, font.trim(), size); PacketHandler.Instance.sendToPlayer(new ConfigCommandPacket(EnumConfigOperation.FONT, font.trim(), size), (EntityPlayerMP) this.pcParam);
} }
} }
+2 -1
View File
@@ -5,12 +5,12 @@ import foxz.commandhelper.annotations.Command;
import foxz.commandhelper.annotations.SubCommand; import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly; import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck; import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.NoppesUtilServer; import noppes.npcs.NoppesUtilServer;
import noppes.npcs.client.EntityUtil; import noppes.npcs.client.EntityUtil;
import noppes.npcs.controllers.DialogController; import noppes.npcs.controllers.DialogController;
import noppes.npcs.controllers.SyncController;
import noppes.npcs.controllers.data.Dialog; import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogOption; import noppes.npcs.controllers.data.DialogOption;
import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.PlayerData;
@@ -83,6 +83,7 @@ public class CmdDialog extends ChMcLogger {
} }
return true; return true;
} }
@SubCommand( @SubCommand(
desc = "reload dialogs from disk", desc = "reload dialogs from disk",
permissions = {OpOnly.class} permissions = {OpOnly.class}
+3 -4
View File
@@ -50,7 +50,7 @@ public class CmdNpc extends ChMcLogger {
posZ = CommandBase.func_110666_a(pcParam, selectedNpc.posZ, args[2]); posZ = CommandBase.func_110666_a(pcParam, selectedNpc.posZ, args[2]);
} }
selectedNpc.ai.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)}; selectedNpc.ais.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)};
} }
@SubCommand( @SubCommand(
@@ -101,8 +101,7 @@ public class CmdNpc extends ChMcLogger {
sendmessage("No owner"); sendmessage("No owner");
else else
sendmessage("Owner is: " + player.getCommandSenderName()); sendmessage("Owner is: " + player.getCommandSenderName());
} } else {
else{
EntityPlayerMP player = CommandBase.getPlayer(pcParam, args[0]); EntityPlayerMP player = CommandBase.getPlayer(pcParam, args[0]);
if (selectedNpc.roleInterface instanceof RoleFollower) if (selectedNpc.roleInterface instanceof RoleFollower)
((RoleFollower) selectedNpc.roleInterface).setOwner(player); ((RoleFollower) selectedNpc.roleInterface).setOwner(player);
@@ -144,7 +143,7 @@ public class CmdNpc extends ChMcLogger {
if (args.length > 0) if (args.length > 0)
npc.display.name = args[0]; npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch); npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.ai.startPos = new int[]{MathHelper.floor_double(player.posX),MathHelper.floor_double(player.posY),MathHelper.floor_double(player.posZ)}; npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc); pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth()); npc.setHealth(npc.getMaxHealth());
NoppesUtilServer.sendOpenGui(player, EnumGuiType.MainMenuDisplay, npc); NoppesUtilServer.sendOpenGui(player, EnumGuiType.MainMenuDisplay, npc);
+7 -7
View File
@@ -5,11 +5,11 @@ import foxz.commandhelper.annotations.Command;
import foxz.commandhelper.annotations.SubCommand; import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly; import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck; import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.Server;
import noppes.npcs.constants.EnumPacketClient;
import noppes.npcs.controllers.QuestController; import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.SyncController;
import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.Quest; import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestData; import noppes.npcs.controllers.data.QuestData;
@@ -58,8 +58,8 @@ public class CmdQuest extends ChMcLogger{
playerdata.questData.activeQuests.put(questid, questdata); playerdata.questData.activeQuests.put(questid, questdata);
playerdata.save(); playerdata.save();
if (playerdata.player != null) { if (playerdata.player != null) {
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.MESSAGE, "quest.newquest", quest.title); AchievementPacket.sendAchievement((EntityPlayerMP) playerdata.player, false, "quest.newquest", quest.title);
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.CHAT, "quest.newquest", ": ", quest.title); ChatAlertPacket.sendChatAlert((EntityPlayerMP) playerdata.player, "quest.newquest", ": ", quest.title);
} }
playerdata.updateClient = true; playerdata.updateClient = true;
} }
@@ -76,8 +76,7 @@ public class CmdQuest extends ChMcLogger{
int questid; int questid;
try { try {
questid = Integer.parseInt(args[1]); questid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendmessage("QuestID must be an integer"); sendmessage("QuestID must be an integer");
return false; return false;
} }
@@ -164,6 +163,7 @@ public class CmdQuest extends ChMcLogger{
} }
return true; return true;
} }
@SubCommand( @SubCommand(
desc = "reload quests from disk", desc = "reload quests from disk",
permissions = {OpOnly.class} permissions = {OpOnly.class}
@@ -51,12 +51,13 @@ public class ScriptedCommand extends CommandBase implements ICommand {
public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) { public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) {
} }
public int getRequiredPermissionLevel() public int getRequiredPermissionLevel() {
{
return this.permissionLevel; return this.permissionLevel;
} }
public int getPermissionLevel() { return this.getRequiredPermissionLevel(); } public int getPermissionLevel() {
return this.getRequiredPermissionLevel();
}
public List<?> getCommandAliases() { public List<?> getCommandAliases() {
return this.aliases; return this.aliases;
@@ -99,6 +99,7 @@ public abstract class AbstractCommandHelper extends CommandHelper {
} }
} }
} }
@Override @Override
public List addTabCompletion(ICommandSender par1, String[] args) { public List addTabCompletion(ICommandSender par1, String[] args) {
String[] np = currentHelper.usage.split(" "); String[] np = currentHelper.usage.split(" ");
@@ -157,8 +158,7 @@ public abstract class AbstractCommandHelper extends CommandHelper {
f.parentCmdHelper = this; f.parentCmdHelper = this;
f.rootCmdHelper = this.rootCmdHelper; f.rootCmdHelper = this.rootCmdHelper;
return f.processCommand(param, args); return f.processCommand(param, args);
} } else if (ch instanceof MethodSubCmd) {
else if (ch instanceof MethodSubCmd) {
MethodSubCmd m = (MethodSubCmd) ch; MethodSubCmd m = (MethodSubCmd) ch;
m.method.setAccessible(true); m.method.setAccessible(true);
currentHelper = ch.commandHelper; currentHelper = ch.commandHelper;
@@ -174,8 +174,7 @@ public abstract class AbstractCommandHelper extends CommandHelper {
Logger.getLogger(AbstractCommandHelper.class.getName()).log(Level.SEVERE, m.commandHelper.name, ex); Logger.getLogger(AbstractCommandHelper.class.getName()).log(Level.SEVERE, m.commandHelper.name, ex);
} }
return true; return true;
} } else
else
cmdError(cmd); cmdError(cmd);
return false; return false;
} }
@@ -192,13 +191,11 @@ public abstract class AbstractCommandHelper extends CommandHelper {
if (ch instanceof AbstractCommandHelper) { if (ch instanceof AbstractCommandHelper) {
((AbstractCommandHelper) ch).pcParam = param; ((AbstractCommandHelper) ch).pcParam = param;
((AbstractCommandHelper) ch).allHelp(); ((AbstractCommandHelper) ch).allHelp();
} } else if (ch instanceof MethodSubCmd && ((MethodSubCmd) ch).commandHelper.usage.isEmpty())
else if(ch instanceof MethodSubCmd && ((MethodSubCmd)ch).commandHelper.usage.isEmpty())
return false; return false;
else else
help(ch.commandHelper.name, ch.commandHelper.desc, ch.commandHelper.usage); help(ch.commandHelper.name, ch.commandHelper.desc, ch.commandHelper.usage);
} } else
else
allHelp(); allHelp();
return true; return true;
} }
@@ -227,8 +224,7 @@ public abstract class AbstractCommandHelper extends CommandHelper {
PlayerData data = PlayerDataController.Instance.getDataFromUsername(username); PlayerData data = PlayerDataController.Instance.getDataFromUsername(username);
if (data != null) if (data != null)
list.add(data); list.add(data);
} } else {
else{
for (EntityPlayer player : players) { for (EntityPlayer player : players) {
list.add(PlayerDataController.Instance.getPlayerData(player)); list.add(PlayerDataController.Instance.getPlayerData(player));
} }
@@ -13,7 +13,9 @@ public abstract class CommandHelper {
public String desc; public String desc;
public boolean hasEmptyCall; public boolean hasEmptyCall;
} }
public Helper commandHelper = new Helper(); public Helper commandHelper = new Helper();
public List addTabCompletion(ICommandSender par1, String[] args) { public List addTabCompletion(ICommandSender par1, String[] args) {
return null; return null;
} }
@@ -9,7 +9,6 @@ import foxz.commandhelper.AbstractCommandHelper;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
/** /**
*
* @author foxz * @author foxz
*/ */
public class PlayerOnly extends AbstractPermission { public class PlayerOnly extends AbstractPermission {
+4 -8
View File
@@ -95,8 +95,7 @@ public class Market {
if (ConfigMain.MarketDatFormat) { if (ConfigMain.MarketDatFormat) {
NBTTagCompound compound = NBTJsonUtil.loadNBTData(file); NBTTagCompound compound = NBTJsonUtil.loadNBTData(file);
role.readNBT(compound); role.readNBT(compound);
} } else {
else {
role.readNBT(NBTJsonUtil.LoadFile(file)); role.readNBT(NBTJsonUtil.LoadFile(file));
} }
} catch (Exception e) { } catch (Exception e) {
@@ -109,8 +108,7 @@ public class Market {
if (!file.exists()) if (!file.exists())
file.mkdir(); file.mkdir();
return file; return file;
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@@ -124,8 +122,7 @@ public class Market {
} }
file.mkdir(); file.mkdir();
return file; return file;
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@@ -158,8 +155,7 @@ public class Market {
String fileType; String fileType;
if (type) { if (type) {
fileType = ".dat"; fileType = ".dat";
} } else {
else {
fileType = ".json"; fileType = ".json";
} }
@@ -1,153 +0,0 @@
package kamkeel.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.scripted.CustomNPCsException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandKamkeel extends CommandBase{
public Map<String, CommandKamkeelBase> map = new HashMap<String, CommandKamkeelBase>();
public HelpCommand help = new HelpCommand(this);
public String[] alias = {"kam"};
public CommandKamkeel(){
registerCommand(help);
registerCommand(new ScriptCommand());
registerCommand(new SlayCommand());
registerCommand(new QuestCommand());
registerCommand(new QuestCategoryCommand());
registerCommand(new DialogCommand());
registerCommand(new DialogCategoryCommand());
registerCommand(new FactionCommand());
registerCommand(new NpcCommand());
registerCommand(new CloneCommand());
registerCommand(new ConfigCommand());
registerCommand(new AnimationCommand());
registerCommand(new OverlayCommand());
registerCommand(new CommandCommand());
}
public void registerCommand(CommandKamkeelBase command){
String name = command.getCommandName().toLowerCase();
if(map.containsKey(name))
throw new CustomNPCsException("Already a subcommand with the name: " + name);
map.put(name, command);
}
@Override
public String getCommandName() {
return "kamkeel";
}
@Override
public List getCommandAliases()
{
return Arrays.asList(alias);
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "Use as /kamkeel subcommand";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if(args.length == 0){
help.processCommand(sender, args);
return;
}
CommandKamkeelBase command = getCommand(args);
if(command == null)
throw new CommandException("Unknown command " + args[0]);
args = Arrays.copyOfRange(args, 1, args.length);
if(command.subcommands.isEmpty() || !command.runSubCommands()){
if(!canSendCommand(sender, command))
throw new CommandException("You are not allowed to use this command: " + command);
command.canRun(sender, command.getUsage(), args);
command.processCommand(sender, args);
return;
}
if(args.length == 0){
help.processCommand(sender, new String[]{command.getCommandName()});
return;
}
command.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args){
if(args.length == 1)
return CommandBase.getListOfStringsMatchingLastWord(args, map.keySet().toArray(new String[map.size()]));
CommandKamkeelBase command = getCommand(args);
if(command == null)
return null;
if(args.length == 2 && command.runSubCommands())
return CommandBase.getListOfStringsMatchingLastWord(args, command.subcommands.keySet().toArray(new String[command.subcommands.keySet().size()]));
String[] useArgs = command.getUsage().split(" ");
if(command.runSubCommands()) {
Method m = command.subcommands.get(args[1].toLowerCase());
if(m != null) {
useArgs = m.getAnnotation(CommandKamkeelBase.SubCommand.class).usage().split(" ");
}
}
if(args.length <= useArgs.length + 2) {
if(args.length - 3 >= 0){
String usage = useArgs[args.length - 3];
if(usage.equals("<player>") || usage.equals("[player]")) {
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
}
}
}
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
public CommandKamkeelBase getCommand(String[] args){
if(args.length == 0)
return null;
return map.get(args[0].toLowerCase());
}
@Override
public int getRequiredPermissionLevel(){
return 2;
}
public static String getCommandPermission(String command){
return "cnpc.kamkeel." + command.toLowerCase();
}
public static String getUniversalPermission(){
return "cnpc.kamkeel.*";
}
public static boolean canSendCommand(ICommandSender sender, CommandKamkeelBase command){
if(sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getUniversalPermission())){
return true;
}
if(sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getCommandPermission(command.getCommandName()))){
return true;
}
if(sender instanceof EntityPlayer){
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getCommandPermission(command.getCommandName()));
}
return false;
}
}
@@ -1,148 +0,0 @@
package kamkeel.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
import noppes.npcs.CustomNpcsPermissions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class CommandKamkeelBase extends CommandBase{
public Map<String, Method> subcommands = new HashMap<String, Method>();
public CommandKamkeelBase(){
for (Method m : this.getClass().getDeclaredMethods()) {
SubCommand sc = m.getAnnotation(SubCommand.class);
if (sc != null) {
String name = sc.name();
if (name.equals(""))
name = m.getName();
subcommands.put(name.toLowerCase(), m);
}
}
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
}
@Override
public String getCommandUsage(ICommandSender sender) {
return getDescription();
}
public abstract String getDescription();
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
public String getUsage(){
return "";
}
public boolean runSubCommands(){
return !subcommands.isEmpty();
}
protected static void sendMessage(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation(message, obs));
}
protected static void sendResult(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation("\u00A76[\u00A7eCNPC+\u00A76]\u00A77 " + message, obs));
}
protected static void sendError(ICommandSender sender, String message, Object... obs) {
sender.addChatMessage(new ChatComponentTranslation("\u00A76[\u00A7eCNPC+\u00A76]\u00A74 Error:\u00A7c " + message, obs));
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SubCommand {
String name() default "";
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
String usage() default "";
String desc();
int permission() default 2;
}
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
Method m = subcommands.get(command.toLowerCase());
if(m == null)
throw new CommandException("Unknown subcommand " + command);
SubCommand sc = m.getAnnotation(SubCommand.class);
if(!canSendCommand(sender, sc, command))
throw new CommandException("You are not allowed to use this command: " + command);
canRun(sender, sc.usage(), args);
try {
m.invoke(this, sender, args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void canRun(ICommandSender sender, String usage, String[] args) throws CommandException{
String[] np = usage.split(" ");
List<String> required = new ArrayList<String>();
for(int i = 0; i < np.length; i++){
String command = np[i];
if(command.startsWith("<")){
required.add(command);
}
if(command.equals("<player>") && args.length > i){
CommandBase.getPlayer(sender, args[i]); //throws PlayerNotFoundException if no player is found
}
}
if (args.length < required.size()) {
throw new CommandException("Missing parameter: " + required.get(args.length));
}
}
public int getRequiredPermissionLevel(){
return 2;
}
public String getSubCommandPermission(String subCommand){
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "." + subCommand.toLowerCase();
}
public String getSubUniversalPermission(){
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "*";
}
public boolean canSendCommand(ICommandSender sender, SubCommand command, String subCommand){
if(sender.canCommandSenderUseCommand(command.permission(), getSubUniversalPermission())){
return true;
}
if(sender.canCommandSenderUseCommand(command.permission(), getSubCommandPermission(subCommand))){
return true;
}
if(sender instanceof EntityPlayer){
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
}
return false;
}
}
@@ -1,298 +0,0 @@
package kamkeel.command;
import foxz.utils.Market;
import net.minecraft.block.Block;
import net.minecraft.block.BlockIce;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.BlockVine;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.CustomNpcs;
import noppes.npcs.Server;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.constants.EnumPacketClient;
import noppes.npcs.controllers.ChunkController;
import noppes.npcs.controllers.PlayerDataController;
import java.util.Arrays;
import java.util.Set;
public class ConfigCommand extends CommandKamkeelBase {
@Override
public String getCommandName() {
return "config";
}
@Override
public String getDescription() {
return "Some config things you can set";
}
@SubCommand(
desc = "Disable/Enable the natural leaves decay",
usage = "[true/false]",
permission = 4
)
public void leavesdecay(ICommandSender sender, String[] args){
if(args.length == 0){
sendResult(sender, "LeavesDecay: \u00A7c" + ConfigMain.LeavesDecayEnabled);
}
else{
ConfigMain.LeavesDecayEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.LeavesDecayEnabledProperty.set(ConfigMain.LeavesDecayEnabled);
if(ConfigMain.config.hasChanged()){
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for(ResourceLocation name : names){
Block block = (Block) Block.blockRegistry.getObject(name);
if(block instanceof BlockLeavesBase){
block.setTickRandomly(ConfigMain.LeavesDecayEnabled);
}
}
sendResult(sender, "LeavesDecay is now \u00A7c" + ConfigMain.LeavesDecayEnabled);
}
}
@SubCommand(
desc = "Disable/Enable the vines growing",
usage = "[true/false]",
permission = 4
)
public void vinegrowth(ICommandSender sender, String[] args){
if(args.length == 0){
sendResult(sender, "VineGrowth: \u00A7c" + ConfigMain.VineGrowthEnabled);
}
else{
ConfigMain.VineGrowthEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.VineGrowthEnabledProperty.set(ConfigMain.VineGrowthEnabled);
if(ConfigMain.config.hasChanged()){
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for(ResourceLocation name : names){
Block block = (Block) Block.blockRegistry.getObject(name);
if(block instanceof BlockVine){
block.setTickRandomly(ConfigMain.VineGrowthEnabled);
}
}
sendResult(sender, "VineGrowth is now \u00A7c" + ConfigMain.VineGrowthEnabled);
}
}
@SubCommand(
desc = "Disable/Enable the ice melting",
usage = "[true/false]",
permission = 4
)
public void icemelts(ICommandSender sender, String[] args){
if(args.length == 0){
sendResult(sender, "IceMelts: \u00A7c" + ConfigMain.IceMeltsEnabled);
}
else{
ConfigMain.IceMeltsEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.IceMeltsEnabledProperty.set(ConfigMain.IceMeltsEnabled);
if(ConfigMain.config.hasChanged()){
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for(ResourceLocation name : names){
Block block = (Block) Block.blockRegistry.getObject(name);
if(block instanceof BlockIce){
block.setTickRandomly(ConfigMain.IceMeltsEnabled);
}
}
sendResult(sender, "IceMelts is now \u00A7c" + ConfigMain.IceMeltsEnabled);
}
}
@SubCommand(
desc = "Disable/Enable guns shooting",
usage = "[true/false]",
permission = 4
)
public void guns(ICommandSender sender, String[] args){
if(args.length == 0){
sendResult(sender, "GunsEnabled: \u00A7c" + ConfigMain.GunsEnabled);
}
else{
ConfigMain.GunsEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.GunsEnabledProperty.set(ConfigMain.GunsEnabled);
if(ConfigMain.config.hasChanged()){
ConfigMain.config.save();
}
sendResult(sender, "GunsEnabled is now \u00A7c" + ConfigMain.GunsEnabled);
}
}
@SubCommand(
desc = "Freezes/Unfreezes npcs",
usage = "[true/false]",
permission = 4
)
public void freezenpcs(ICommandSender sender, String[] args){
if(args.length == 0){
sendResult(sender, "Frozen NPCs: \u00A7c" + CustomNpcs.FreezeNPCs);
}
else{
CustomNpcs.FreezeNPCs = Boolean.parseBoolean(args[0]);
sendResult(sender, "FrozenNPCs is now \u00A7c" + CustomNpcs.FreezeNPCs);
}
}
@SubCommand(
desc = "Set number of active chunkloaders",
usage = "<number>",
permission = 4
)
public void chunkloaders(ICommandSender sender, String[] args) throws CommandException{
if(args.length == 0){
sendResult(sender, "ChunkLoaders: \u00A7c" + ChunkController.Instance.size() + "\u00A77/\u00A7c" + ConfigMain.ChunkLoaders);
}
else{
try{
ConfigMain.ChunkLoaders = Integer.parseInt(args[0]);
}
catch(NumberFormatException ex){
sendError(sender, "Did not get a number: " + args[0]);
return;
}
ConfigMain.ChunkLoadersProperty.set(ConfigMain.ChunkLoaders);
if(ConfigMain.config.hasChanged()){
ConfigMain.config.save();
}
int size = ChunkController.Instance.size();
if(size > ConfigMain.ChunkLoaders){
ChunkController.Instance.unload(size - ConfigMain.ChunkLoaders);
sendResult(sender, size - ConfigMain.ChunkLoaders + " chunksloaders unloaded");
}
sendResult(sender, "ChunkLoaders: \u00A7c" + ChunkController.Instance.size() + "\u00A77/\u00A7c" + ConfigMain.ChunkLoaders);
}
}
@SubCommand(
desc = "Generate PlayerData to JSON/DAT",
usage = "[fileType] [convert]",
permission = 4
)
public void playerdata(ICommandSender sender, String[] args) throws CommandException{
String fileType;
if(ConfigMain.DatFormat){
fileType = "DAT";
}
else {
fileType = "JSON";
}
if(args.length == 0){
sendResult(sender, "PlayerData Filetype: \u00A7c" + fileType);
}
else if(args.length == 1){
sendResult(sender, "Please write the word 'convert' at the end to confirm. \u00A7c<dat/json> convert");
}
else{
if(args.length != 2){
sendError(sender, "Two many arguments");
return;
}
String formatType = args[0].toLowerCase();
if(!formatType.equals("dat") && !formatType.equals("json")){
sendError(sender, "Invalid Format Type - Please use dat or json");
return;
}
String convert = args[1].toLowerCase();
if(!convert.equals("convert")){
sendError(sender, "Please enter the word 'convert' at the end");
return;
}
boolean convertToDat = formatType.equals("dat");
EntityPlayerMP send = null;
if(sender instanceof EntityPlayerMP){
send = (EntityPlayerMP) sender;
}
sendResult(sender, "Started Conversion Process for PlayerData");
PlayerDataController.Instance.convertPlayerFiles(send, convertToDat);
}
}
@SubCommand(
desc = "Generate Market to JSON/DAT",
usage = "[fileType] [convert]",
permission = 4
)
public void market(ICommandSender sender, String[] args) throws CommandException{
String fileType;
if(ConfigMain.MarketDatFormat){
fileType = "DAT";
}
else {
fileType = "JSON";
}
if(args.length == 0){
sendResult(sender, "Market Filetype: \u00A7c" + fileType);
}
else if(args.length == 1){
sendResult(sender, "Please write the word 'convert' at the end to confirm. \u00A7c<dat/json> convert");
}
else{
if(args.length != 2){
sendError(sender, "Two many arguments");
return;
}
String formatType = args[0].toLowerCase();
if(!formatType.equals("dat") && !formatType.equals("json")){
sendError(sender, "Invalid Format Type - Please use dat or json");
return;
}
String convert = args[1].toLowerCase();
if(!convert.equals("convert")){
sendError(sender, "Please enter the word 'convert' at the end");
return;
}
boolean convertToDat = formatType.equals("dat");
EntityPlayerMP send = null;
if(sender instanceof EntityPlayerMP){
send = (EntityPlayerMP) sender;
}
sendResult(sender, "Started Conversion Process for Market");
Market.convertMarketFiles(send, convertToDat);
}
}
@SubCommand(
desc = "Get/Set font",
usage = "[type] [size]",
permission = 4
)
public void font(ICommandSender sender, String[] args){
if(!(sender instanceof EntityPlayerMP))
return;
int size = 18;
if(args.length > 1){
try{
size = Integer.parseInt(args[args.length - 1]);
args = Arrays.copyOfRange(args, 0, args.length - 1);
}
catch(Exception e){
}
}
String font = "";
for(int i = 0; i < args.length; i++){
font += " " + args[i];
}
Server.sendData((EntityPlayerMP)sender, EnumPacketClient.CONFIG, 0, font.trim(), size);
}
}
@@ -1,70 +0,0 @@
package kamkeel.command;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentTranslation;
import java.lang.reflect.Method;
import java.util.Map.Entry;
public class HelpCommand extends CommandKamkeelBase{
private CommandKamkeel parent;
public HelpCommand(CommandKamkeel parent){
this.parent = parent;
}
@Override
public String getCommandName() {
return "help";
}
@Override
public String getDescription() {
return "help [command]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if(args.length == 0){
sendMessage(sender, "\u00A78------ \u00A7cKamkeel Commands \u00A78------");
for(Entry<String, CommandKamkeelBase> entry : parent.map.entrySet()){
sendMessage(sender, "\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getCommandUsage(sender));
}
return;
}
CommandKamkeelBase command = parent.getCommand(args);
if(command == null){
sendError(sender, "Unknown command " + args[0]);
return;
}
if(command.subcommands.isEmpty()){
sender.addChatMessage(new ChatComponentTranslation(command.getCommandUsage(sender)));
return;
}
Method m = null;
if(args.length > 1){
m = command.subcommands.get(args[1].toLowerCase());
}
if(m == null){
sendMessage(sender, "\u00A78------ \u00A7a" + command.getCommandName().toUpperCase() + " SubCommands \u00A78------");
sendMessage(sender, "\u00A77Usage: \u00A76" + command.getUsage());
for(Entry<String, Method> entry : command.subcommands.entrySet()){
sender.addChatMessage(new ChatComponentTranslation("\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getAnnotation(SubCommand.class).desc()));
}
sender.addChatMessage(new ChatComponentTranslation("\u00A78Permission:\u00A77 " + CommandKamkeel.getCommandPermission(command.getCommandName())));
}
else{
sendMessage(sender, "\u00A78------ \u00A7b" + command.getCommandName().toUpperCase() + "." + args[1].toUpperCase() + " Command \u00A78------");
SubCommand sc = m.getAnnotation(SubCommand.class);
sender.addChatMessage(new ChatComponentTranslation("\u00A77" + sc.desc()));
if(!sc.usage().isEmpty())
sender.addChatMessage(new ChatComponentTranslation("\u00A77Usage: \u00A76" + sc.usage()));
sender.addChatMessage(new ChatComponentTranslation("\u00A78Permission:\u00A77 " + getSubCommandPermission(args[1])));
}
}
}
@@ -1,230 +0,0 @@
package kamkeel.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.PlayerNotFoundException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.constants.EnumGuiType;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.roles.RoleCompanion;
import noppes.npcs.roles.RoleFollower;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.List;
public class NpcCommand extends CommandKamkeelBase {
public EntityNPCInterface selectedNpc;
@Override
public String getCommandName() {
return "npc";
}
@Override
public String getDescription() {
return "NPC operation";
}
@Override
public String getUsage() {
return "<name> <command>";
}
@Override
public boolean runSubCommands(){
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
String npcname = args[0].replace("%", " ");
String command = args[1];
args = Arrays.copyOfRange(args, 2, args.length);
if(command.equalsIgnoreCase("create")){
args = ArrayUtils.add(args, 0, npcname);
processSubCommand(sender, command, args);
return;
}
int x = sender.getPlayerCoordinates().posX;
int y = sender.getPlayerCoordinates().posY;
int z = sender.getPlayerCoordinates().posZ;
List<EntityNPCInterface> list = getEntities(EntityNPCInterface.class, sender.getEntityWorld(), x, y, z, 80);
for (EntityNPCInterface npc : list) {
String name = npc.display.getName().replace(" ", "_");
if (name.equalsIgnoreCase(npcname)){
if(selectedNpc == null || selectedNpc.getDistanceSq(x, y, z) > npc.getDistanceSq(x, y, z))
selectedNpc = npc;
}
}
if(selectedNpc == null){
sendError(sender, "Npc " + npcname + " was not found");
return;
}
processSubCommand(sender, command, args);
selectedNpc = null;
}
@SubCommand(
desc = "Set Home (respawn place)",
usage = "[x] [y] [z]"
)
public void home(ICommandSender sender, String[] args) {
double posX = sender.getPlayerCoordinates().posX;
double posY = sender.getPlayerCoordinates().posY;
double posZ = sender.getPlayerCoordinates().posZ;
if(args.length == 3){
posX = CommandBase.func_110666_a(sender, selectedNpc.posX, args[0]);
posY = CommandBase.func_110665_a(sender, selectedNpc.posY, args[1].trim(), 0, 0);
posZ = CommandBase.func_110666_a(sender, selectedNpc.posZ, args[2]);
}
selectedNpc.ai.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)};
sendResult(sender, String.format("Set NPC \u00A7e%s\u00A77 Home to \u00A7b[%.1f] [%.1f] [%.1f]\u00A77", selectedNpc.display.name, posX, posY, posZ));
}
@SubCommand(
desc = "Set NPC visibility",
usage = "[true/false/semi]"
)
public void visible(ICommandSender sender, String[] args){
if(args.length < 1)
return;
boolean bo = args[0].equalsIgnoreCase("true");
boolean semi = args[0].equalsIgnoreCase("semi");
int current = selectedNpc.display.visible;
if(semi)
selectedNpc.display.visible = 2;
else if(bo)
selectedNpc.display.visible = 0;
else
selectedNpc.display.visible = 1;
String[] list = new String[]{"True", "False", "Semi"};
if(current != selectedNpc.display.visible)
selectedNpc.updateClient = true;
sendResult(sender, String.format("Set NPC \u00A7e%s\u00A77 Visibility to \u00A7b%s\u00A77", selectedNpc.display.name, list[selectedNpc.display.visible]));
}
@SubCommand(desc = "Delete an NPC")
public void delete(ICommandSender sender, String[] args){
selectedNpc.delete();
}
@SubCommand(
desc = "Sets the owner of an follower/companion",
usage = "[player]"
)
public void owner(ICommandSender sender, String[] args){
if(args.length < 1){
EntityPlayer player = null;
if(selectedNpc.roleInterface instanceof RoleFollower)
player = ((RoleFollower)selectedNpc.roleInterface).owner;
if(selectedNpc.roleInterface instanceof RoleCompanion)
player = ((RoleCompanion)selectedNpc.roleInterface).owner;
if(player == null)
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, "NULL"));
else
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, player.getDisplayName()));
}
else{
EntityPlayerMP player = null;
try {
player = CommandBase.getPlayer(sender, args[0]);
} catch (PlayerNotFoundException e) {
}
if(selectedNpc.roleInterface instanceof RoleFollower)
((RoleFollower)selectedNpc.roleInterface).setOwner(player);
if(selectedNpc.roleInterface instanceof RoleCompanion)
((RoleCompanion)selectedNpc.roleInterface).setOwner(player);
if(player == null)
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, "NULL"));
else
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, player.getDisplayName()));
}
}
@SubCommand(
desc = "Set NPC name",
usage = "[name]"
)
public void name(ICommandSender sender, String[] args){
if(args.length < 1)
return;
String name = args[0];
for(int i = 1; i < args.length; i++){
name += " " + args[i];
}
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Name set to \u00A7b%s\u00A77", selectedNpc.display.name, name));
if(!selectedNpc.display.getName().equals(name)){
selectedNpc.display.setName(name);
selectedNpc.updateClient = true;
}
}
@SubCommand(
desc = "Creates an NPC",
usage = "[name]"
)
public void create(ICommandSender sender, String[] args) {
EntityPlayerMP player = (EntityPlayerMP) sender;
World pw = player.getEntityWorld();
EntityCustomNpc npc = new EntityCustomNpc(pw);
if(args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.ai.startPos = new int[]{MathHelper.floor_double(player.posX),MathHelper.floor_double(player.posY),MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
NoppesUtilServer.sendOpenGui(player, EnumGuiType.MainMenuDisplay, npc);
}
@Override
public List addTabCompletionOptions(ICommandSender par1, String[] args) {
if(args.length == 2){
return CommandBase.getListOfStringsMatchingLastWord(args, new String[]{"create", "home", "visible", "delete", "owner", "name"});
}
if(args.length == 3 && args[1].equalsIgnoreCase("owner")){
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
}
return null;
}
@Override
public int getRequiredPermissionLevel(){
return 4;
}
public <T extends Entity> List<T> getEntities(Class<? extends T> cls, World world, int x, int y, int z, int range) {
AxisAlignedBB bb = AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 1, z + 1).expand(range, range, range);
List<T> list = world.getEntitiesWithinAABB(cls, bb);
return list;
}
}
@@ -1,40 +0,0 @@
package kamkeel.command;
import net.minecraft.command.ICommandSender;
import noppes.npcs.controllers.ScriptController;
public class ScriptCommand extends CommandKamkeelBase {
@SubCommand(desc = "Reload scripts data and folders.")
public Boolean reload(ICommandSender sender, String args[]) {
ScriptController.Instance.loadCategories();
if(ScriptController.Instance.loadPlayerScripts())
sendResult(sender, "Reload player scripts successfully");
else
sendError(sender, "Failed reloading player scripts");
if(ScriptController.Instance.loadForgeScripts())
sendResult(sender, "Reload forge scripts successfully");
else
sendError(sender, "Failed reloading forge scripts");
if(ScriptController.Instance.loadStoredData())
sendResult(sender, "Reload stored data successfully");
else
sendError(sender, "Failed reloading stored data");
return true;
}
@Override
public String getCommandName() {
return "script";
}
@Override
public String getDescription() {
return "Commands for scripts";
}
}
@@ -1,139 +0,0 @@
package kamkeel.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.AxisAlignedBB;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.*;
public class SlayCommand extends CommandKamkeelBase {
public Map<String, Class<?>> SlayMap = new LinkedHashMap<String, Class<?>>();
public SlayCommand(){
SlayMap.clear();
SlayMap.put("all",EntityLivingBase.class);
SlayMap.put("mobs",EntityMob.class);
SlayMap.put("animals", EntityAnimal.class);
SlayMap.put("items", EntityItem.class);
SlayMap.put("xporbs", EntityXPOrb.class);
SlayMap.put("npcs", EntityNPCInterface.class);
HashMap<String,Class<?>> list = new HashMap<String,Class<?>>(EntityList.stringToClassMapping);
for(String name : list.keySet()){
Class<?> cls = list.get(name);
if(EntityNPCInterface.class.isAssignableFrom(cls))
continue;
if(!EntityLivingBase.class.isAssignableFrom(cls))
continue;
SlayMap.put(name.toLowerCase(), list.get(name));
}
SlayMap.remove("monster");
SlayMap.remove("mob");
}
@Override
public String getCommandName() {
return "slay";
}
@Override
public String getDescription() {
return "Kills given entity within range. Tab to see options.";
}
@Override
public String getUsage(){
return "<type>.. [range]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
EntityPlayerMP player = (EntityPlayerMP) sender;
ArrayList<Class<?>> toDelete = new ArrayList<Class<?>>();
boolean deleteNPCs = false;
for(String delete : args){
delete = delete.toLowerCase();
Class<?> cls = SlayMap.get(delete);
if(cls != null)
toDelete.add(cls);
if(delete.equals("mobs")){
toDelete.add(EntityGhast.class);
toDelete.add(EntityDragon.class);
}
if(delete.equals("npcs"))
deleteNPCs = true;
}
int count = 0;
int range = 120;
try{
range = Integer.parseInt(args[args.length - 1]);
}
catch(NumberFormatException ex){
}
AxisAlignedBB box = player.boundingBox.expand(range, range, range);
List<? extends Entity> list = sender.getEntityWorld().getEntitiesWithinAABB(EntityLivingBase.class, box);
for(Entity entity : list){
if(entity instanceof EntityPlayer)
continue;
if(entity instanceof EntityTameable && ((EntityTameable)entity).isTamed())
continue;
if(entity instanceof EntityNPCInterface && !deleteNPCs)
continue;
if(delete(entity,toDelete))
count++;
}
if(toDelete.contains(EntityXPOrb.class)){
list = sender.getEntityWorld().getEntitiesWithinAABB(EntityXPOrb.class, box);
for(Entity entity : list){
entity.isDead = true;
count++;
}
}
if(toDelete.contains(EntityItem.class)){
list = sender.getEntityWorld().getEntitiesWithinAABB(EntityItem.class, box);
for(Entity entity : list){
entity.isDead = true;
count++;
}
}
sendResult(sender, count + " entities deleted");
}
private boolean delete(Entity entity, ArrayList<Class<?>> toDelete) {
for(Class<?> delete : toDelete){
if(delete == EntityAnimal.class && (entity instanceof EntityHorse)){
continue;
}
if(delete.isAssignableFrom(entity.getClass())){
entity.isDead = true;
return true;
}
}
return false;
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args){
return CommandBase.getListOfStringsMatchingLastWord(args, SlayMap.keySet().toArray(new String[SlayMap.size()]));
}
}
@@ -0,0 +1,72 @@
package kamkeel.npcs;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.AttributeValueType;
import kamkeel.npcs.controllers.data.attribute.requirement.RequirementCheckerRegistry;
import kamkeel.npcs.controllers.data.attribute.requirement.types.QuestActiveRequirement;
import kamkeel.npcs.controllers.data.attribute.requirement.types.QuestCompletedRequirement;
/**
* ModAttributes registers the core attributes (both non–magic and magic–based).
*/
public class CustomAttributes {
public static final String HEALTH_KEY = "health";
public static final String MAIN_ATTACK_KEY = "main_attack";
public static final String MAIN_ATTACK_BOOST_KEY = "main_attack_boost";
public static final String NEUTRAL_KEY = "neutral";
public static final String NEUTRAL_BOOST_KEY = "neutral_boost";
public static final String CRITICAL_DAMAGE_KEY = "critical_damage";
public static final String CRITICAL_CHANCE_KEY = "critical_chance";
public static final String MAGIC_DAMAGE_KEY = "magic_damage";
public static final String MAGIC_BOOST_KEY = "magic_boost";
public static final String MAGIC_DEFENSE_KEY = "magic_defense";
public static final String MAGIC_RESISTANCE_KEY = "magic_resistance";
public static AttributeDefinition MAIN_ATTACK;
public static AttributeDefinition MAIN_BOOST;
public static AttributeDefinition NEUTRAL_ATTACK;
public static AttributeDefinition NEUTRAL_BOOST;
public static AttributeDefinition HEALTH;
public static AttributeDefinition CRITICAL_CHANCE;
public static AttributeDefinition CRITICAL_DAMAGE;
public static AttributeDefinition MAGIC_DAMAGE;
public static AttributeDefinition MAGIC_BOOST;
public static AttributeDefinition MAGIC_DEFENSE;
public static AttributeDefinition MAGIC_RESISTANCE;
public CustomAttributes() {
HEALTH = AttributeController.registerAttribute(HEALTH_KEY, "Health", 'c', AttributeValueType.FLAT, AttributeDefinition.AttributeSection.BASE);
MAIN_ATTACK = AttributeController.registerAttribute(MAIN_ATTACK_KEY, "Main Attack Damage", '4', AttributeValueType.FLAT, AttributeDefinition.AttributeSection.BASE);
MAIN_BOOST = AttributeController.registerAttribute(MAIN_ATTACK_BOOST_KEY, "Main Attack Damage", '4', AttributeValueType.PERCENT, AttributeDefinition.AttributeSection.MODIFIER);
NEUTRAL_ATTACK = AttributeController.registerAttribute(NEUTRAL_KEY, "Neutral Damage", '6', AttributeValueType.FLAT, AttributeDefinition.AttributeSection.BASE);
NEUTRAL_BOOST = AttributeController.registerAttribute(NEUTRAL_BOOST_KEY, "Neutral Damage", '6', AttributeValueType.PERCENT, AttributeDefinition.AttributeSection.MODIFIER);
CRITICAL_CHANCE = AttributeController.registerAttribute(CRITICAL_CHANCE_KEY, "Critical Chance", '6', AttributeValueType.PERCENT, AttributeDefinition.AttributeSection.INFO);
CRITICAL_DAMAGE = AttributeController.registerAttribute(CRITICAL_DAMAGE_KEY, "Critical Damage", '6', AttributeValueType.FLAT, AttributeDefinition.AttributeSection.INFO);
MAGIC_DAMAGE = AttributeController.registerAttribute(MAGIC_DAMAGE_KEY, "Magic Damage", '3', AttributeValueType.MAGIC, AttributeDefinition.AttributeSection.BASE);
MAGIC_BOOST = AttributeController.registerAttribute(MAGIC_BOOST_KEY, "Magic Damage", '3', AttributeValueType.MAGIC, AttributeDefinition.AttributeSection.MODIFIER);
MAGIC_DEFENSE = AttributeController.registerAttribute(MAGIC_DEFENSE_KEY, "Magic Defense", 'b', AttributeValueType.MAGIC, AttributeDefinition.AttributeSection.BASE);
MAGIC_RESISTANCE = AttributeController.registerAttribute(MAGIC_RESISTANCE_KEY, "Magic Resistance", 'b', AttributeValueType.MAGIC, AttributeDefinition.AttributeSection.MODIFIER);
// TODO: Attributes
// Durability Attribute
// Unique Name Attribute
// Requirement
RequirementCheckerRegistry.registerChecker(new QuestCompletedRequirement());
RequirementCheckerRegistry.registerChecker(new QuestActiveRequirement());
// TODO: Requirements
// Player Requirement : Soulbound UUID
// Profile Requirement : Slot Number
}
}
@@ -1,7 +1,7 @@
package kamkeel.addon; package kamkeel.npcs.addon;
import kamkeel.addon.client.DBCClient; import kamkeel.npcs.addon.client.DBCClient;
import kamkeel.addon.client.GeckoAddonClient; import kamkeel.npcs.addon.client.GeckoAddonClient;
public class AddonManager { public class AddonManager {
public static AddonManager Instance; public static AddonManager Instance;
@@ -1,6 +1,6 @@
package kamkeel.addon; package kamkeel.npcs.addon;
import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.Loader;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
@@ -22,21 +22,33 @@ public class DBCAddon {
instance = this; instance = this;
} }
public void dbcCopyData(EntityLivingBase copied, EntityLivingBase entity){} public static boolean IsAvailable() {
return Loader.isModLoaded("npcdbc");
}
public void dbcCopyData(EntityLivingBase copied, EntityLivingBase entity) {
}
// AI / STATS // AI / STATS
public boolean canDBCAttack(EntityNPCInterface npc, float attackStrength, Entity receiver) { public boolean canDBCAttack(EntityNPCInterface npc, float attackStrength, Entity receiver) {
return false; return false;
} }
public void doDBCDamage(EntityNPCInterface npc, float attackStrength, Entity receiver){}
public void doDBCDamage(EntityNPCInterface npc, float attackStrength, Entity receiver) {
}
public boolean isKO(EntityNPCInterface npc, EntityPlayer player) { public boolean isKO(EntityNPCInterface npc, EntityPlayer player) {
return false; return false;
} }
// PlayerData NBT // PlayerData NBT
public void writeToNBT(PlayerData playerData, NBTTagCompound nbtTagCompound){} public void writeToNBT(PlayerData playerData, NBTTagCompound nbtTagCompound) {
public void readFromNBT(PlayerData playerData, NBTTagCompound nbtTagCompound){} }
public void readFromNBT(PlayerData playerData, NBTTagCompound nbtTagCompound) {
}
// Client Sync // Client Sync
public void syncPlayer(EntityPlayerMP playerMP){} public void syncPlayer(EntityPlayerMP playerMP) {
}
} }
@@ -1,4 +1,4 @@
package kamkeel.addon; package kamkeel.npcs.addon;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
@@ -15,6 +15,7 @@ public class GeckoAddon {
instance = this; instance = this;
} }
public void geckoCopyData(EntityLivingBase copied, EntityLivingBase entity){} public void geckoCopyData(EntityLivingBase copied, EntityLivingBase entity) {
}
} }
@@ -1,15 +1,9 @@
package kamkeel.addon.client; package kamkeel.npcs.addon.client;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.model.ModelBase;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.client.gui.mainmenu.GuiNpcStats; import noppes.npcs.client.gui.mainmenu.GuiNpcStats;
import noppes.npcs.client.gui.model.GuiCreationScreen;
import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory;
import noppes.npcs.client.gui.util.GuiNPCInterface2; import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.model.ModelMPM;
import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.entity.EntityNPCInterface;
public class DBCClient { public class DBCClient {
@@ -28,18 +22,24 @@ public class DBCClient {
} }
// Stat Buttons // Stat Buttons
public void showDBCStatButtons(GuiNpcStats stats, EntityLivingBase entity){} public void showDBCStatButtons(GuiNpcStats stats, EntityLivingBase entity) {
public void showDBCStatActionPerformed(GuiNpcStats stats, GuiNpcButton btn){} }
public void showDBCStatActionPerformed(GuiNpcStats stats, GuiNpcButton btn) {
}
// Render Auras // Render Auras
public void renderDBCAuras(EntityNPCInterface npcInterface){} public void renderDBCAuras(EntityNPCInterface npcInterface) {
}
// Manage Custom Forms
public GuiNPCInterface2 manageCustomForms(EntityNPCInterface npcInterface){ return null; } // Manage Custom Forms
// Manage Custom Forms public GuiNPCInterface2 manageCustomForms(EntityNPCInterface npcInterface) {
public GuiNPCInterface2 manageCustomAuras(EntityNPCInterface npcInterface){ return null; } return null;
}
// Inventory GUI
public GuiCNPCInventory inventoryGUI(){ return null; } // Manage Custom Forms
public GuiNPCInterface2 manageCustomAuras(EntityNPCInterface npcInterface) {
return null;
}
} }
@@ -1,4 +1,4 @@
package kamkeel.addon.client; package kamkeel.npcs.addon.client;
import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelBase;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
@@ -24,14 +24,24 @@ public class GeckoAddonClient {
} }
// Creation Screen Mixins // Creation Screen Mixins
public void showGeckoButtons(GuiCreationScreen creationScreen, EntityLivingBase entity){} public void showGeckoButtons(GuiCreationScreen creationScreen, EntityLivingBase entity) {
public void geckoGuiCreationScreenActionPerformed(GuiCreationScreen creationScreen, GuiNpcButton btn){} }
public void geckoGuiCreationScreenActionPerformed(GuiCreationScreen creationScreen, GuiNpcButton btn) {
}
// Npc Display Mixins // Npc Display Mixins
public void geckoNpcDisplayInitGui(GuiNPCInterface2 guiNPCInterface){} public void geckoNpcDisplayInitGui(GuiNPCInterface2 guiNPCInterface) {
public void geckoNpcDisplayActionPerformed(GuiNPCInterface2 guiNPCInterface, GuiNpcButton btn){} }
public void geckoNpcDisplayActionPerformed(GuiNPCInterface2 guiNPCInterface, GuiNpcButton btn) {
}
// Render Npc Mixins // Render Npc Mixins
public boolean isGeckoModel(ModelBase mainModel){ return false;} public boolean isGeckoModel(ModelBase mainModel) {
public void geckoRenderModel(ModelMPM mainModel, EntityNPCInterface npc, float rotationYaw, float renderPartialTicks) {} return false;
}
public void geckoRenderModel(ModelMPM mainModel, EntityNPCInterface npc, float rotationYaw, float renderPartialTicks) {
}
} }
@@ -1,4 +1,4 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
@@ -9,6 +9,9 @@ import noppes.npcs.controllers.data.PlayerData;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class AnimationCommand extends CommandKamkeelBase { public class AnimationCommand extends CommandKamkeelBase {
@Override @Override
@@ -0,0 +1,245 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.AttributeValueType;
import kamkeel.npcs.util.AttributeItemUtil;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import noppes.npcs.controllers.MagicController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class AttributeCommand extends CommandKamkeelBase {
@Override
public String getCommandName() {
return "attribute";
}
@Override
public String getDescription() {
return "Manage attributes on your held item";
}
@SubCommand(
name = "list",
usage = "[page]",
desc = "Lists all available attributes"
)
public void list(ICommandSender sender, String[] args) throws CommandException {
// Get all registered attributes.
List<AttributeDefinition> defs = new ArrayList<AttributeDefinition>(AttributeController.getAllAttributes());
if (defs.isEmpty()) {
sendError(sender, "No attributes found.");
return;
}
// Sort attributes by display name.
Collections.sort(defs, new Comparator<AttributeDefinition>() {
@Override
public int compare(AttributeDefinition a, AttributeDefinition b) {
return a.getKey().compareToIgnoreCase(b.getKey());
}
});
// Determine which page to show.
int page = 1;
if (args.length > 0) {
try {
page = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
// If parsing fails, default to page 1.
}
}
int perPage = 10;
int total = defs.size();
int totalPages = (int) Math.ceil(total / (double) perPage);
if (page < 1) page = 1;
if (page > totalPages) page = totalPages;
int startIndex = (page - 1) * perPage;
int endIndex = Math.min(startIndex + perPage, total);
sendResult(sender, "--------------------");
sendResult(sender, "Attributes (Page " + page + "/" + totalPages + "):");
for (int i = startIndex; i < endIndex; i++) {
AttributeDefinition def = defs.get(i);
// First line: numbered display name.
sendResult(sender, (i + 1) + ". " + def.getDisplayName());
// Second line: key and value type.
sendResult(sender, " - " + def.getKey() + ", " + def.getValueType());
}
sendResult(sender, "--------------------");
}
@SubCommand(
name = "apply",
usage = "<attribute> <value> [magicID]",
desc = "Applies an attribute to your held item. For magic attributes, provide a magicID."
)
public void apply(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "Only players can use this command.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
ItemStack held = player.getHeldItem();
if (held == null) {
sendError(sender, "You are not holding an item.");
return;
}
String attrKey = args[0];
AttributeDefinition def = AttributeController.getAttribute(attrKey);
if (def == null) {
sendError(sender, "Unknown attribute: " + attrKey);
return;
}
// Check if this is a magic attribute.
if (def.getValueType() == AttributeValueType.MAGIC) {
if (args.length < 3) {
sendError(sender, "Usage for magic attribute: apply <attribute> <value> <magicID>");
return;
}
int magicId;
float value;
try {
value = Float.parseFloat(args[1]);
magicId = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid number format for magicID or value.");
return;
}
if (MagicController.getInstance().getMagic(magicId) == null) {
sendError(sender, "No Magic Found for Magic ID %d", magicId);
return;
}
AttributeItemUtil.writeMagicAttribute(held, attrKey, magicId, value);
sendResult(sender, "Applied magic attribute " + attrKey + " with magicID " + magicId + " and value " + value + " to held item.");
} else {
if (args.length < 2) {
sendError(sender, "Usage: <attribute> <value>");
return;
}
float value;
try {
value = Float.parseFloat(args[1]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid number format for value.");
return;
}
AttributeItemUtil.applyAttribute(held, attrKey, value);
sendResult(sender, "Applied attribute " + attrKey + " with value " + value + " to held item.");
}
}
@SubCommand(
name = "remove",
usage = "<attribute> [magicID)",
desc = "Removes an attribute from your held item. For magic attributes, provide a magicID."
)
public void remove(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "Only players can use this command.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
ItemStack held = player.getHeldItem();
if (held == null) {
sendError(sender, "You are not holding an item.");
return;
}
String attrKey = args[0];
AttributeDefinition def = AttributeController.getAttribute(attrKey);
if (def == null) {
sendError(sender, "Unknown attribute: " + attrKey);
return;
}
if (def.getValueType() == AttributeValueType.MAGIC) {
if (args.length < 2) {
sendError(sender, "Usage for magic attribute: remove <attribute> <magicID>");
return;
}
int magicId;
try {
magicId = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid magicID format.");
return;
}
if (MagicController.getInstance().getMagic(magicId) == null) {
sendError(sender, "No Magic Found for Magic ID %d", magicId);
return;
}
AttributeItemUtil.removeMagicAttribute(held, attrKey, magicId);
sendResult(sender, "Removed magic attribute " + attrKey + " (magicID " + magicId + ") from held item.");
} else {
AttributeItemUtil.removeAttribute(held, attrKey);
sendResult(sender, "Removed attribute " + attrKey + " from held item.");
}
}
@SubCommand(
name = "requirement",
usage = "<apply|remove> <requirement> [value]",
desc = "Apply or remove a requirement from your held item."
)
public void requirement(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "Only players can use this command.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
ItemStack held = player.getHeldItem();
if (held == null) {
sendError(sender, "You are not holding an item.");
return;
}
if (args.length < 2) {
sendError(sender, "Usage: requirement <apply|remove> <requirementKey> [value]");
return;
}
String action = args[0];
String reqKey = args[1];
if (action.equalsIgnoreCase("apply")) {
if (args.length < 3) {
sendError(sender, "Usage: requirement apply <requirementKey> <value>");
return;
}
String valueStr = args[2];
Object value;
try {
value = Integer.parseInt(valueStr);
} catch (NumberFormatException e1) {
try {
value = Float.parseFloat(valueStr);
} catch (NumberFormatException e2) {
value = valueStr;
}
}
AttributeItemUtil.applyRequirement(held, reqKey, value);
sendResult(sender, "Applied requirement " + reqKey + " with value " + value + " to held item.");
} else if (action.equalsIgnoreCase("remove")) {
AttributeItemUtil.removeRequirement(held, reqKey);
sendResult(sender, "Removed requirement " + reqKey + " from held item.");
} else {
sendError(sender, "Invalid action. Use apply or remove.");
}
}
}
@@ -1,8 +1,7 @@
package kamkeel.command; package kamkeel.npcs.command;
import foxz.utils.Utils; import foxz.utils.Utils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
@@ -18,6 +17,8 @@ import noppes.npcs.entity.EntityNPCInterface;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.*;
public class CloneCommand extends CommandKamkeelBase { public class CloneCommand extends CommandKamkeelBase {
@Override @Override
@@ -43,8 +44,7 @@ public class CloneCommand extends CommandKamkeelBase {
sendError(sender, "Tab must be within 1-15"); sendError(sender, "Tab must be within 1-15");
return; return;
} }
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, String.format("Tab is not a number: %s", args[1])); sendError(sender, String.format("Tab is not a number: %s", args[1]));
return; return;
} }
@@ -82,8 +82,7 @@ public class CloneCommand extends CommandKamkeelBase {
sendError(sender, "Tab must be within 1-15"); sendError(sender, "Tab must be within 1-15");
return; return;
} }
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, String.format("Tab is not a number: %s", args[1])); sendError(sender, String.format("Tab is not a number: %s", args[1]));
return; return;
} }
@@ -108,8 +107,7 @@ public class CloneCommand extends CommandKamkeelBase {
sendError(sender, String.format("Tab must be within 1-15")); sendError(sender, String.format("Tab must be within 1-15"));
return; return;
} }
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, String.format("Tab is not a number: %s", args[1])); sendError(sender, String.format("Tab is not a number: %s", args[1]));
return; return;
} }
@@ -143,8 +141,7 @@ public class CloneCommand extends CommandKamkeelBase {
sendError(sender, String.format("Tab must be within 1-15")); sendError(sender, String.format("Tab must be within 1-15"));
return; return;
} }
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, String.format("Tab is not a number: %s", args[1])); sendError(sender, String.format("Tab is not a number: %s", args[1]));
return; return;
} }
@@ -180,9 +177,9 @@ public class CloneCommand extends CommandKamkeelBase {
return; return;
} }
try { try {
posX = CommandBase.func_110666_a(sender, posX, par[0]); posX = func_110666_a(sender, posX, par[0]);
posY = CommandBase.func_110665_a(sender, posY, par[1].trim(), 0, 0); posY = func_110665_a(sender, posY, par[1].trim(), 0, 0);
posZ = CommandBase.func_110666_a(sender, posZ, par[2]); posZ = func_110666_a(sender, posZ, par[2]);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
sendError(sender, "Location should be in numbers"); sendError(sender, "Location should be in numbers");
return; return;
@@ -204,7 +201,7 @@ public class CloneCommand extends CommandKamkeelBase {
entity.setPosition(posX + 0.5, posY + 1, posZ + 0.5); entity.setPosition(posX + 0.5, posY + 1, posZ + 0.5);
if (entity instanceof EntityNPCInterface) { if (entity instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) entity; EntityNPCInterface npc = (EntityNPCInterface) entity;
npc.ai.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)}; npc.ais.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)};
if (newname != null && !newname.isEmpty()) if (newname != null && !newname.isEmpty())
npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way
} }
@@ -225,8 +222,7 @@ public class CloneCommand extends CommandKamkeelBase {
sendError(sender, String.format("Tab must be within 1-15")); sendError(sender, String.format("Tab must be within 1-15"));
return; return;
} }
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, String.format("Tab is not a number: %s", args[1])); sendError(sender, String.format("Tab is not a number: %s", args[1]));
return; return;
} }
@@ -235,8 +231,7 @@ public class CloneCommand extends CommandKamkeelBase {
try { try {
width = Integer.parseInt(args[2]); width = Integer.parseInt(args[2]);
height = Integer.parseInt(args[3]); height = Integer.parseInt(args[3]);
} } catch (NumberFormatException ex) {
catch(NumberFormatException ex){
sendError(sender, "length or width was not a number"); sendError(sender, "length or width was not a number");
return; return;
} }
@@ -272,9 +267,9 @@ public class CloneCommand extends CommandKamkeelBase {
return; return;
} }
try { try {
posX = CommandBase.func_110666_a(sender, posX, par[0]); posX = func_110666_a(sender, posX, par[0]);
posY = CommandBase.func_110665_a(sender, posY, par[1].trim(), 0, 0); posY = func_110665_a(sender, posY, par[1].trim(), 0, 0);
posZ = CommandBase.func_110666_a(sender, posZ, par[2]); posZ = func_110666_a(sender, posZ, par[2]);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
sendError(sender, "Location should be in numbers"); sendError(sender, "Location should be in numbers");
return; return;
@@ -310,7 +305,7 @@ public class CloneCommand extends CommandKamkeelBase {
entity.setPosition(posX + 0.5 + x, yy + 1, posZ + 0.5 + z); entity.setPosition(posX + 0.5 + x, yy + 1, posZ + 0.5 + z);
if (entity instanceof EntityNPCInterface) { if (entity instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) entity; EntityNPCInterface npc = (EntityNPCInterface) entity;
npc.ai.startPos = new int[]{xx, yy, zz}; npc.ais.startPos = new int[]{xx, yy, zz};
if (newname != null && !newname.isEmpty()) if (newname != null && !newname.isEmpty())
npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way npc.display.name = newname.replaceAll("%", " "); // like name, newname must use % in place of space to keep a logical way
} }
@@ -1,4 +1,4 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
@@ -10,6 +10,9 @@ import noppes.npcs.api.IWorld;
import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.CustomNPCsEvent; import noppes.npcs.scripted.event.CustomNPCsEvent;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendMessage;
public class CommandCommand extends CommandKamkeelBase { public class CommandCommand extends CommandKamkeelBase {
@Override @Override
@@ -0,0 +1,171 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.requirement.RequirementCheckerRegistry;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.scripted.CustomNPCsException;
import java.lang.reflect.Method;
import java.util.*;
import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames;
public class CommandKamkeel extends CommandBase {
public Map<String, CommandKamkeelBase> map = new HashMap<String, CommandKamkeelBase>();
public HelpCommand help = new HelpCommand(this);
public String[] alias = {"kam"};
public CommandKamkeel() {
registerCommand(help);
registerCommand(new ScriptCommand());
registerCommand(new SlayCommand());
registerCommand(new QuestCommand());
registerCommand(new QuestCategoryCommand());
registerCommand(new DialogCommand());
registerCommand(new DialogCategoryCommand());
registerCommand(new FactionCommand());
registerCommand(new NpcCommand());
registerCommand(new CloneCommand());
registerCommand(new ConfigCommand());
registerCommand(new AnimationCommand());
registerCommand(new OverlayCommand());
registerCommand(new CommandCommand());
registerCommand(new EffectCommand());
if (ConfigMain.AttributesEnabled)
registerCommand(new AttributeCommand());
}
public void registerCommand(CommandKamkeelBase command) {
String name = command.getCommandName().toLowerCase();
if (map.containsKey(name))
throw new CustomNPCsException("Already a subcommand with the name: " + name);
map.put(name, command);
}
@Override
public String getCommandName() {
return "kamkeel";
}
@Override
public List getCommandAliases() {
return Arrays.asList(alias);
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "Use as /kamkeel subcommand";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
help.processCommand(sender, args);
return;
}
CommandKamkeelBase command = getCommand(args);
if (command == null)
throw new CommandException("Unknown command " + args[0]);
args = Arrays.copyOfRange(args, 1, args.length);
if (command.subcommands.isEmpty() || !command.runSubCommands()) {
if (!canSendCommand(sender, command))
throw new CommandException("You are not allowed to use this command: " + command);
command.canRun(sender, command.getUsage(), args);
command.processCommand(sender, args);
return;
}
if (args.length == 0) {
help.processCommand(sender, new String[]{command.getCommandName()});
return;
}
command.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
if (args.length == 1)
return CommandBase.getListOfStringsMatchingLastWord(args, map.keySet().toArray(new String[map.size()]));
CommandKamkeelBase command = getCommand(args);
if (command == null)
return null;
if (args.length == 2 && command.runSubCommands())
return CommandBase.getListOfStringsMatchingLastWord(args, command.subcommands.keySet().toArray(new String[command.subcommands.keySet().size()]));
String[] useArgs = command.getUsage().split(" ");
if (command.runSubCommands()) {
Method m = command.subcommands.get(args[1].toLowerCase());
if (m != null) {
useArgs = m.getAnnotation(CommandKamkeelBase.SubCommand.class).usage().split(" ");
}
}
if (args.length <= useArgs.length + 2) {
if (args.length - 3 >= 0) {
String usage = useArgs[args.length - 3];
if (usage.equals("<player>") || usage.equals("[player]")) {
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
} else if (usage.equals("<attribute>")) {
List<String> keys = new ArrayList<>();
for (AttributeDefinition def : AttributeController.getAllAttributes()) {
keys.add(def.getKey());
}
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<requirement>")) {
List<String> keys = new ArrayList<>(RequirementCheckerRegistry.getAllKeys());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<effectName>")) {
List<String> keys = getSortedEffectNames();
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
}
}
}
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
public CommandKamkeelBase getCommand(String[] args) {
if (args.length == 0)
return null;
return map.get(args[0].toLowerCase());
}
@Override
public int getRequiredPermissionLevel() {
return 2;
}
public static String getCommandPermission(String command) {
return "cnpc.kamkeel." + command.toLowerCase();
}
public static String getUniversalPermission() {
return "cnpc.kamkeel.*";
}
public static boolean canSendCommand(ICommandSender sender, CommandKamkeelBase command) {
if (sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getUniversalPermission())) {
return true;
}
if (sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getCommandPermission(command.getCommandName()))) {
return true;
}
if (sender instanceof EntityPlayer) {
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getCommandPermission(command.getCommandName()));
}
return false;
}
}
@@ -0,0 +1,135 @@
package kamkeel.npcs.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.CustomNpcsPermissions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class CommandKamkeelBase extends CommandBase {
public Map<String, Method> subcommands = new HashMap<String, Method>();
public CommandKamkeelBase() {
for (Method m : this.getClass().getDeclaredMethods()) {
SubCommand sc = m.getAnnotation(SubCommand.class);
if (sc != null) {
String name = sc.name();
if (name.equals(""))
name = m.getName();
subcommands.put(name.toLowerCase(), m);
}
}
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
}
@Override
public String getCommandUsage(ICommandSender sender) {
return getDescription();
}
public abstract String getDescription();
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
public String getUsage() {
return "";
}
public boolean runSubCommands() {
return !subcommands.isEmpty();
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SubCommand {
String name() default "";
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
String usage() default "";
String desc();
int permission() default 2;
}
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
Method m = subcommands.get(command.toLowerCase());
if (m == null)
throw new CommandException("Unknown subcommand " + command);
SubCommand sc = m.getAnnotation(SubCommand.class);
if (!canSendCommand(sender, sc, command))
throw new CommandException("You are not allowed to use this command: " + command);
canRun(sender, sc.usage(), args);
try {
m.invoke(this, sender, args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void canRun(ICommandSender sender, String usage, String[] args) throws CommandException {
String[] np = usage.split(" ");
List<String> required = new ArrayList<String>();
for (int i = 0; i < np.length; i++) {
String command = np[i];
if (command.startsWith("<")) {
required.add(command);
}
if (command.equals("<player>") && args.length > i) {
CommandBase.getPlayer(sender, args[i]); //throws PlayerNotFoundException if no player is found
}
}
if (args.length < required.size()) {
throw new CommandException("Missing parameter: " + required.get(args.length));
}
}
public int getRequiredPermissionLevel() {
return 2;
}
public String getSubCommandPermission(String subCommand) {
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "." + subCommand.toLowerCase();
}
public String getSubUniversalPermission() {
return "cnpc.kamkeel." + getCommandName().toLowerCase() + "*";
}
public boolean canSendCommand(ICommandSender sender, SubCommand command, String subCommand) {
if (sender.canCommandSenderUseCommand(command.permission(), getSubUniversalPermission())) {
return true;
}
if (sender.canCommandSenderUseCommand(command.permission(), getSubCommandPermission(subCommand))) {
return true;
}
if (sender instanceof EntityPlayer) {
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
}
return false;
}
}
@@ -0,0 +1,288 @@
package kamkeel.npcs.command;
import foxz.utils.Market;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumConfigOperation;
import kamkeel.npcs.network.packets.data.ConfigCommandPacket;
import net.minecraft.block.Block;
import net.minecraft.block.BlockIce;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.BlockVine;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.CustomNpcs;
import noppes.npcs.config.ConfigItem;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.controllers.ChunkController;
import noppes.npcs.controllers.PlayerDataController;
import java.util.Arrays;
import java.util.Set;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class ConfigCommand extends CommandKamkeelBase {
@Override
public String getCommandName() {
return "config";
}
@Override
public String getDescription() {
return "Some config things you can set";
}
@SubCommand(
desc = "Disable/Enable the natural leaves decay",
usage = "[true/false]",
permission = 4
)
public void leavesdecay(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendResult(sender, "LeavesDecay: \u00A7c" + ConfigMain.LeavesDecayEnabled);
} else {
ConfigMain.LeavesDecayEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.LeavesDecayEnabledProperty.set(ConfigMain.LeavesDecayEnabled);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for (ResourceLocation name : names) {
Block block = (Block) Block.blockRegistry.getObject(name);
if (block instanceof BlockLeavesBase) {
block.setTickRandomly(ConfigMain.LeavesDecayEnabled);
}
}
sendResult(sender, "LeavesDecay is now \u00A7c" + ConfigMain.LeavesDecayEnabled);
}
}
@SubCommand(
desc = "Disable/Enable the vines growing",
usage = "[true/false]",
permission = 4
)
public void vinegrowth(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendResult(sender, "VineGrowth: \u00A7c" + ConfigMain.VineGrowthEnabled);
} else {
ConfigMain.VineGrowthEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.VineGrowthEnabledProperty.set(ConfigMain.VineGrowthEnabled);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for (ResourceLocation name : names) {
Block block = (Block) Block.blockRegistry.getObject(name);
if (block instanceof BlockVine) {
block.setTickRandomly(ConfigMain.VineGrowthEnabled);
}
}
sendResult(sender, "VineGrowth is now \u00A7c" + ConfigMain.VineGrowthEnabled);
}
}
@SubCommand(
desc = "Disable/Enable the ice melting",
usage = "[true/false]",
permission = 4
)
public void icemelts(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendResult(sender, "IceMelts: \u00A7c" + ConfigMain.IceMeltsEnabled);
} else {
ConfigMain.IceMeltsEnabled = Boolean.parseBoolean(args[0]);
ConfigMain.IceMeltsEnabledProperty.set(ConfigMain.IceMeltsEnabled);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
Set<ResourceLocation> names = Block.blockRegistry.getKeys();
for (ResourceLocation name : names) {
Block block = (Block) Block.blockRegistry.getObject(name);
if (block instanceof BlockIce) {
block.setTickRandomly(ConfigMain.IceMeltsEnabled);
}
}
sendResult(sender, "IceMelts is now \u00A7c" + ConfigMain.IceMeltsEnabled);
}
}
@SubCommand(
desc = "Disable/Enable guns shooting",
usage = "[true/false]",
permission = 4
)
public void guns(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendResult(sender, "GunsEnabled: \u00A7c" + ConfigItem.GunsEnabled);
} else {
ConfigItem.GunsEnabled = Boolean.parseBoolean(args[0]);
ConfigItem.GunsEnabledProperty.set(ConfigItem.GunsEnabled);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
sendResult(sender, "GunsEnabled is now \u00A7c" + ConfigItem.GunsEnabled);
}
}
@SubCommand(
desc = "Freezes/Unfreezes npcs",
usage = "[true/false]",
permission = 4
)
public void freezenpcs(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendResult(sender, "Frozen NPCs: \u00A7c" + CustomNpcs.FreezeNPCs);
} else {
CustomNpcs.FreezeNPCs = Boolean.parseBoolean(args[0]);
sendResult(sender, "FrozenNPCs is now \u00A7c" + CustomNpcs.FreezeNPCs);
}
}
@SubCommand(
desc = "Set number of active chunkloaders",
usage = "<number>",
permission = 4
)
public void chunkloaders(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
sendResult(sender, "ChunkLoaders: \u00A7c" + ChunkController.Instance.size() + "\u00A77/\u00A7c" + ConfigMain.ChunkLoaders);
} else {
try {
ConfigMain.ChunkLoaders = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
sendError(sender, "Did not get a number: " + args[0]);
return;
}
ConfigMain.ChunkLoadersProperty.set(ConfigMain.ChunkLoaders);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
int size = ChunkController.Instance.size();
if (size > ConfigMain.ChunkLoaders) {
ChunkController.Instance.unload(size - ConfigMain.ChunkLoaders);
sendResult(sender, size - ConfigMain.ChunkLoaders + " chunksloaders unloaded");
}
sendResult(sender, "ChunkLoaders: \u00A7c" + ChunkController.Instance.size() + "\u00A77/\u00A7c" + ConfigMain.ChunkLoaders);
}
}
@SubCommand(
desc = "Generate PlayerData to JSON/DAT",
usage = "[fileType] [convert]",
permission = 4
)
public void playerdata(ICommandSender sender, String[] args) throws CommandException {
String fileType;
if (ConfigMain.DatFormat) {
fileType = "DAT";
} else {
fileType = "JSON";
}
if (args.length == 0) {
sendResult(sender, "PlayerData Filetype: \u00A7c" + fileType);
} else if (args.length == 1) {
sendResult(sender, "Please write the word 'convert' at the end to confirm. \u00A7c<dat/json> convert");
} else {
if (args.length != 2) {
sendError(sender, "Two many arguments");
return;
}
String formatType = args[0].toLowerCase();
if (!formatType.equals("dat") && !formatType.equals("json")) {
sendError(sender, "Invalid Format Type - Please use dat or json");
return;
}
String convert = args[1].toLowerCase();
if (!convert.equals("convert")) {
sendError(sender, "Please enter the word 'convert' at the end");
return;
}
boolean convertToDat = formatType.equals("dat");
EntityPlayerMP send = null;
if (sender instanceof EntityPlayerMP) {
send = (EntityPlayerMP) sender;
}
sendResult(sender, "Started Conversion Process for PlayerData");
PlayerDataController.Instance.convertPlayerFiles(send, convertToDat);
}
}
@SubCommand(
desc = "Generate Market to JSON/DAT",
usage = "[fileType] [convert]",
permission = 4
)
public void market(ICommandSender sender, String[] args) throws CommandException {
String fileType;
if (ConfigMain.MarketDatFormat) {
fileType = "DAT";
} else {
fileType = "JSON";
}
if (args.length == 0) {
sendResult(sender, "Market Filetype: \u00A7c" + fileType);
} else if (args.length == 1) {
sendResult(sender, "Please write the word 'convert' at the end to confirm. \u00A7c<dat/json> convert");
} else {
if (args.length != 2) {
sendError(sender, "Two many arguments");
return;
}
String formatType = args[0].toLowerCase();
if (!formatType.equals("dat") && !formatType.equals("json")) {
sendError(sender, "Invalid Format Type - Please use dat or json");
return;
}
String convert = args[1].toLowerCase();
if (!convert.equals("convert")) {
sendError(sender, "Please enter the word 'convert' at the end");
return;
}
boolean convertToDat = formatType.equals("dat");
EntityPlayerMP send = null;
if (sender instanceof EntityPlayerMP) {
send = (EntityPlayerMP) sender;
}
sendResult(sender, "Started Conversion Process for Market");
Market.convertMarketFiles(send, convertToDat);
}
}
@SubCommand(
desc = "Get/Set font",
usage = "[type] [size]",
permission = 4
)
public void font(ICommandSender sender, String[] args) {
if (!(sender instanceof EntityPlayerMP))
return;
int size = 18;
if (args.length > 1) {
try {
size = Integer.parseInt(args[args.length - 1]);
args = Arrays.copyOfRange(args, 0, args.length - 1);
} catch (Exception e) {
}
}
String font = "";
for (int i = 0; i < args.length; i++) {
font += " " + args[i];
}
PacketHandler.Instance.sendToPlayer(new ConfigCommandPacket(EnumConfigOperation.FONT, font.trim(), size), (EntityPlayerMP) sender);
}
}
@@ -1,4 +1,4 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
@@ -11,6 +11,9 @@ import noppes.npcs.controllers.data.PlayerData;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class DialogCategoryCommand extends CommandKamkeelBase { public class DialogCategoryCommand extends CommandKamkeelBase {
@Override @Override
@@ -57,8 +60,7 @@ public class DialogCategoryCommand extends CommandKamkeelBase {
int dialogCatId; int dialogCatId;
try { try {
dialogCatId = Integer.parseInt(args[1]); dialogCatId = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "DialogCatID must be an integer: " + args[1]); sendError(sender, "DialogCatID must be an integer: " + args[1]);
return; return;
} }
@@ -99,8 +101,7 @@ public class DialogCategoryCommand extends CommandKamkeelBase {
int dialogCatId; int dialogCatId;
try { try {
dialogCatId = Integer.parseInt(args[1]); dialogCatId = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "DialogCatID must be an integer: " + args[1]); sendError(sender, "DialogCatID must be an integer: " + args[1]);
return; return;
} }
@@ -1,5 +1,6 @@
package kamkeel.command; package kamkeel.npcs.command;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
@@ -10,7 +11,6 @@ import noppes.npcs.constants.EnumAvailabilityDialog;
import noppes.npcs.constants.EnumAvailabilityQuest; import noppes.npcs.constants.EnumAvailabilityQuest;
import noppes.npcs.controllers.DialogController; import noppes.npcs.controllers.DialogController;
import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.SyncController;
import noppes.npcs.controllers.data.Availability; import noppes.npcs.controllers.data.Availability;
import noppes.npcs.controllers.data.Dialog; import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogOption; import noppes.npcs.controllers.data.DialogOption;
@@ -20,6 +20,9 @@ import noppes.npcs.entity.EntityDialogNpc;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class DialogCommand extends CommandKamkeelBase { public class DialogCommand extends CommandKamkeelBase {
@Override @Override
@@ -83,6 +86,7 @@ public class DialogCommand extends CommandKamkeelBase {
sendResult(sender, String.format("Forced Unread for Dialog \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", diagid, playerdata.playername)); sendResult(sender, String.format("Forced Unread for Dialog \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", diagid, playerdata.playername));
} }
} }
@SubCommand( @SubCommand(
desc = "reload dialogs from disk", desc = "reload dialogs from disk",
permission = 4 permission = 4
@@ -0,0 +1,350 @@
package kamkeel.npcs.command;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.scripted.event.PlayerEvent.EffectEvent.ExpirationType;
import java.util.*;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class EffectCommand extends CommandKamkeelBase {
@Override
public String getDescription() {
return "Custom Effect operations";
}
@Override
public String getCommandName() {
return "effect";
}
// List command with pagination
@SubCommand(desc = "Lists all Effects", usage = "[page]")
public void list(ICommandSender sender, String[] args) throws CommandException {
CustomEffectController controller = CustomEffectController.getInstance();
if (controller.indexMapper.isEmpty()) {
sendError(sender, "No effects found.");
return;
}
// Flatten effects into a list
List<EffectEntry> effectsList = new ArrayList<>();
for (Map.Entry<Integer, HashMap<Integer, CustomEffect>> entry : controller.indexMapper.entrySet()) {
int idx = entry.getKey();
Map<Integer, CustomEffect> effects = entry.getValue();
if (effects == null || effects.isEmpty())
continue;
for (Map.Entry<Integer, CustomEffect> effectEntry : effects.entrySet()) {
int id = effectEntry.getKey();
CustomEffect effect = effectEntry.getValue();
effectsList.add(new EffectEntry(idx, id, effect));
}
}
// Sort by index then by effect ID
Collections.sort(effectsList, Comparator.comparingInt((EffectEntry e) -> e.index)
.thenComparingInt(e -> e.id));
// Determine page number
int page = 1;
if (args.length > 0) {
try {
page = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
// default to page 1
}
}
int perPage = 10;
int total = effectsList.size();
int totalPages = (int) Math.ceil(total / (double) perPage);
if (page < 1) page = 1;
if (page > totalPages) page = totalPages;
int startIndex = (page - 1) * perPage;
int endIndex = Math.min(startIndex + perPage, total);
sendResult(sender, "--------------------");
sendResult(sender, "Effects (Page " + page + "/" + totalPages + "):");
for (int i = startIndex; i < endIndex; i++) {
EffectEntry entry = effectsList.get(i);
sendResult(sender, String.format("\u00a7b%s \u00a77(ID: %d, INDEX: %d)",
entry.effect.getName(),
entry.id,
entry.index));
}
sendResult(sender, "--------------------");
}
// Give effect by name.
// Usage: <player> <time> <effectName>
@SubCommand(desc = "Gives an effect to a player", usage = "<player> <time> <effectName>")
public void give(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 3) {
sendError(sender, "Usage: <player> <time> <effectName>");
return;
}
String playername = args[0];
int time;
try {
time = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid time: " + args[1]);
return;
}
// Join all remaining arguments as the effect name.
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]).append(i < args.length - 1 ? " " : "");
}
String effectName = sb.toString();
List<EffectEntry> matches = findEffectsByName(effectName);
if (matches.isEmpty()) {
sendError(sender, "Unknown effect: " + effectName);
return;
}
if (matches.size() > 1) {
StringBuilder ambig = new StringBuilder();
ambig.append("Ambiguous effect name '").append(effectName).append("'. Multiple matches: ");
for (EffectEntry match : matches) {
ambig.append(match.effect.getName())
.append(" (ID: ").append(match.id)
.append(", INDEX: ").append(match.index)
.append("), ");
}
sendError(sender, ambig.substring(0, ambig.length() - 2));
return;
}
EffectEntry match = matches.get(0);
List<PlayerData> players = PlayerDataController.Instance.getPlayersData(sender, playername);
if (players.isEmpty()) {
sendError(sender, "Unknown player: " + playername);
return;
}
for (PlayerData pdata : players) {
if (pdata.player != null) {
CustomEffectController.getInstance().applyEffect(pdata.player, match.id, time, (byte) 1, match.index);
sendResult(sender, String.format("%s §agiven to §7'§b%s§7'", match.effect.getName(), pdata.playername));
}
}
}
// Remove effect by name.
// Usage: <player> <effectName>
@SubCommand(desc = "Removes an effect from a player", usage = "<player> <effectName>")
public void remove(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 2) {
sendError(sender, "Usage: <player> <effectName>");
return;
}
String playername = args[0];
// Join all remaining arguments as the effect name.
StringBuilder sb = new StringBuilder();
for (int i = 1; i < args.length; i++) {
sb.append(args[i]).append(i < args.length - 1 ? " " : "");
}
String effectName = sb.toString();
List<EffectEntry> matches = findEffectsByName(effectName);
if (matches.isEmpty()) {
sendError(sender, "Unknown effect: " + effectName);
return;
}
if (matches.size() > 1) {
StringBuilder ambig = new StringBuilder();
ambig.append("Ambiguous effect name '").append(effectName).append("'. Multiple matches: ");
for (EffectEntry match : matches) {
ambig.append(match.effect.getName())
.append(" (ID: ").append(match.id)
.append(", INDEX: ").append(match.index)
.append("), ");
}
sendError(sender, ambig.substring(0, ambig.length() - 2));
return;
}
EffectEntry match = matches.get(0);
List<PlayerData> players = PlayerDataController.Instance.getPlayersData(sender, playername);
if (players.isEmpty()) {
sendError(sender, "Unknown player: " + playername);
return;
}
for (PlayerData pdata : players) {
if (pdata.player != null) {
CustomEffectController.getInstance().removeEffect(pdata.player, match.id, match.index, ExpirationType.REMOVED);
sendResult(sender, String.format("Effect %s removed from %s", match.effect.getName(), pdata.playername));
}
}
}
// Give effect by ID.
// Usage: <player> <time> <effectId> [index]
@SubCommand(desc = "Gives an effect to a player by ID", usage = "<player> <time> <effectId> [index]")
public void giveId(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 3) {
sendError(sender, "Usage: <player> <time> <effectId> [index]");
return;
}
String playername = args[0];
int time;
try {
time = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid time: " + args[1]);
return;
}
int effectId;
int index = 0;
try {
effectId = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid effect ID: " + args[2]);
return;
}
if (args.length > 3) {
try {
index = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
index = 0;
}
}
List<PlayerData> players = PlayerDataController.Instance.getPlayersData(sender, playername);
if (players.isEmpty()) {
sendError(sender, "Unknown player: " + playername);
return;
}
CustomEffect effect = CustomEffectController.getInstance().get(effectId, index);
if (effect == null) {
sendError(sender, "Unknown effect with ID: " + effectId + " and index " + index);
return;
}
for (PlayerData pdata : players) {
if (pdata.player != null) {
CustomEffectController.getInstance().applyEffect(pdata.player, effect.id, time, (byte) 1, effect.index);
sendResult(sender, String.format("%s §agiven to §7'§b%s§7'", effect.getName(), pdata.playername));
}
}
}
// Remove effect by ID.
// Usage: <player> <effectId> [index]
@SubCommand(desc = "Removes an effect from a player by ID", usage = "<player> <effectId> [index]")
public void removeId(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 2) {
sendError(sender, "Usage: <player> <effectId> [index]");
return;
}
String playername = args[0];
int effectId;
int index = 0;
try {
effectId = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sendError(sender, "Invalid effect ID: " + args[1]);
return;
}
if (args.length > 2) {
try {
index = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
index = 0;
}
}
List<PlayerData> players = PlayerDataController.Instance.getPlayersData(sender, playername);
if (players.isEmpty()) {
sendError(sender, "Unknown player: " + playername);
return;
}
CustomEffect effect = CustomEffectController.getInstance().get(effectId, index);
if (effect == null) {
sendError(sender, "Unknown effect with ID: " + effectId + " and index " + index);
return;
}
for (PlayerData pdata : players) {
if (pdata.player != null) {
CustomEffectController.getInstance().removeEffect(pdata.player, effect.id, effect.index, ExpirationType.REMOVED);
sendResult(sender, String.format("Effect %s removed from %s", effect.getName(), pdata.playername));
}
}
}
private static class EffectEntry {
int index;
int id;
CustomEffect effect;
public EffectEntry(int index, int id, CustomEffect effect) {
this.index = index;
this.id = id;
this.effect = effect;
}
}
// Helper method to find effects by name.
private List<EffectEntry> findEffectsByName(String name) {
List<EffectEntry> matches = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
for (Map.Entry<Integer, HashMap<Integer, CustomEffect>> entry : controller.indexMapper.entrySet()) {
int idx = entry.getKey();
Map<Integer, CustomEffect> effects = entry.getValue();
if (effects == null) continue;
for (Map.Entry<Integer, CustomEffect> effectEntry : effects.entrySet()) {
int id = effectEntry.getKey();
CustomEffect effect = effectEntry.getValue();
if (effect.getName().equalsIgnoreCase(name)) {
List<EffectEntry> exact = new ArrayList<>();
exact.add(new EffectEntry(idx, id, effect));
return exact;
} else if (effect.getName().toLowerCase().contains(name.toLowerCase())) {
matches.add(new EffectEntry(idx, id, effect));
}
}
}
return matches;
}
public static List<String> getSortedEffectNames() {
List<EffectEntry> entries = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
for (Map.Entry<Integer, HashMap<Integer, CustomEffect>> indexEntry : controller.indexMapper.entrySet()) {
int index = indexEntry.getKey();
Map<Integer, CustomEffect> effects = indexEntry.getValue();
if (effects != null) {
for (Map.Entry<Integer, CustomEffect> effectEntry : effects.entrySet()) {
int id = effectEntry.getKey();
CustomEffect effect = effectEntry.getValue();
entries.add(new EffectEntry(index, id, effect));
}
}
}
// Sort entries by index then by effect ID.
entries.sort(Comparator.comparingInt((EffectEntry e) -> e.index)
.thenComparingInt(e -> e.id));
List<String> effectNames = new ArrayList<>();
for (EffectEntry entry : entries) {
effectNames.add(entry.effect.getName());
}
return effectNames;
}
}
@@ -1,6 +1,5 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import noppes.npcs.controllers.FactionController; import noppes.npcs.controllers.FactionController;
@@ -12,6 +11,9 @@ import noppes.npcs.controllers.data.PlayerFactionData;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class FactionCommand extends CommandKamkeelBase { public class FactionCommand extends CommandKamkeelBase {
public Faction selectedFaction; public Faction selectedFaction;
@@ -51,8 +53,7 @@ public class FactionCommand extends CommandKamkeelBase {
try { try {
selectedFaction = FactionController.getInstance().getFaction(Integer.parseInt(factionname)); selectedFaction = FactionController.getInstance().getFaction(Integer.parseInt(factionname));
} } catch (NumberFormatException e) {
catch(NumberFormatException e){
selectedFaction = FactionController.getInstance().getFactionFromName(factionname); selectedFaction = FactionController.getInstance().getFactionFromName(factionname);
} }
@@ -153,7 +154,7 @@ public class FactionCommand extends CommandKamkeelBase {
@Override @Override
public List addTabCompletionOptions(ICommandSender par1, String[] args) { public List addTabCompletionOptions(ICommandSender par1, String[] args) {
if (args.length == 3) { if (args.length == 3) {
return CommandBase.getListOfStringsMatchingLastWord(args, new String[]{"add", "subtract", "set", "reset", "drop", "create"}); return getListOfStringsMatchingLastWord(args, new String[]{"add", "subtract", "set", "reset", "drop", "create"});
} }
return null; return null;
} }
@@ -0,0 +1,71 @@
package kamkeel.npcs.command;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import java.lang.reflect.Method;
import java.util.Map.Entry;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendMessage;
public class HelpCommand extends CommandKamkeelBase {
private CommandKamkeel parent;
public HelpCommand(CommandKamkeel parent) {
this.parent = parent;
}
@Override
public String getCommandName() {
return "help";
}
@Override
public String getDescription() {
return "help [command]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
sendMessage(sender, "\u00A78------ \u00A7cKamkeel Commands \u00A78------");
for (Entry<String, CommandKamkeelBase> entry : parent.map.entrySet()) {
sendMessage(sender, "\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getCommandUsage(sender));
}
return;
}
CommandKamkeelBase command = parent.getCommand(args);
if (command == null) {
sendError(sender, "Unknown command " + args[0]);
return;
}
if (command.subcommands.isEmpty()) {
sendMessage(sender, (command.getCommandUsage(sender)));
return;
}
Method m = null;
if (args.length > 1) {
m = command.subcommands.get(args[1].toLowerCase());
}
if (m == null) {
sendMessage(sender, "\u00A78------ \u00A7a" + command.getCommandName().toUpperCase() + " SubCommands \u00A78------");
sendMessage(sender, "\u00A77Usage: \u00A76" + command.getUsage());
for (Entry<String, Method> entry : command.subcommands.entrySet()) {
sendMessage(sender, ("\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77" + entry.getValue().getAnnotation(SubCommand.class).desc()));
}
sendMessage(sender, ("\u00A78Permission:\u00A77 " + CommandKamkeel.getCommandPermission(command.getCommandName())));
} else {
sendMessage(sender, "\u00A78------ \u00A7b" + command.getCommandName().toUpperCase() + "." + args[1].toUpperCase() + " Command \u00A78------");
SubCommand sc = m.getAnnotation(SubCommand.class);
sendMessage(sender, ("\u00A77" + sc.desc()));
if (!sc.usage().isEmpty())
sendMessage(sender, ("\u00A77Usage: \u00A76" + sc.usage()));
sendMessage(sender, ("\u00A78Permission:\u00A77 " + getSubCommandPermission(args[1])));
}
}
}
@@ -0,0 +1,232 @@
package kamkeel.npcs.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.PlayerNotFoundException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.constants.EnumGuiType;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.roles.RoleCompanion;
import noppes.npcs.roles.RoleFollower;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class NpcCommand extends CommandKamkeelBase {
public EntityNPCInterface selectedNpc;
@Override
public String getCommandName() {
return "npc";
}
@Override
public String getDescription() {
return "NPC operation";
}
@Override
public String getUsage() {
return "<name> <command>";
}
@Override
public boolean runSubCommands() {
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
String npcname = args[0].replace("%", " ");
String command = args[1];
args = Arrays.copyOfRange(args, 2, args.length);
if (command.equalsIgnoreCase("create")) {
args = ArrayUtils.add(args, 0, npcname);
processSubCommand(sender, command, args);
return;
}
int x = sender.getPlayerCoordinates().posX;
int y = sender.getPlayerCoordinates().posY;
int z = sender.getPlayerCoordinates().posZ;
List<EntityNPCInterface> list = getEntities(EntityNPCInterface.class, sender.getEntityWorld(), x, y, z, 80);
for (EntityNPCInterface npc : list) {
String name = npc.display.getName().replace(" ", "_");
if (name.equalsIgnoreCase(npcname)) {
if (selectedNpc == null || selectedNpc.getDistanceSq(x, y, z) > npc.getDistanceSq(x, y, z))
selectedNpc = npc;
}
}
if (selectedNpc == null) {
sendError(sender, "Npc " + npcname + " was not found");
return;
}
processSubCommand(sender, command, args);
selectedNpc = null;
}
@SubCommand(
desc = "Set Home (respawn place)",
usage = "[x] [y] [z]"
)
public void home(ICommandSender sender, String[] args) {
double posX = sender.getPlayerCoordinates().posX;
double posY = sender.getPlayerCoordinates().posY;
double posZ = sender.getPlayerCoordinates().posZ;
if (args.length == 3) {
posX = CommandBase.func_110666_a(sender, selectedNpc.posX, args[0]);
posY = CommandBase.func_110665_a(sender, selectedNpc.posY, args[1].trim(), 0, 0);
posZ = CommandBase.func_110666_a(sender, selectedNpc.posZ, args[2]);
}
selectedNpc.ais.startPos = new int[]{MathHelper.floor_double(posX), MathHelper.floor_double(posY), MathHelper.floor_double(posZ)};
sendResult(sender, String.format("Set NPC \u00A7e%s\u00A77 Home to \u00A7b[%.1f] [%.1f] [%.1f]\u00A77", selectedNpc.display.name, posX, posY, posZ));
}
@SubCommand(
desc = "Set NPC visibility",
usage = "[true/false/semi]"
)
public void visible(ICommandSender sender, String[] args) {
if (args.length < 1)
return;
boolean bo = args[0].equalsIgnoreCase("true");
boolean semi = args[0].equalsIgnoreCase("semi");
int current = selectedNpc.display.visible;
if (semi)
selectedNpc.display.visible = 2;
else if (bo)
selectedNpc.display.visible = 0;
else
selectedNpc.display.visible = 1;
String[] list = new String[]{"True", "False", "Semi"};
if (current != selectedNpc.display.visible)
selectedNpc.updateClient = true;
sendResult(sender, String.format("Set NPC \u00A7e%s\u00A77 Visibility to \u00A7b%s\u00A77", selectedNpc.display.name, list[selectedNpc.display.visible]));
}
@SubCommand(desc = "Delete an NPC")
public void delete(ICommandSender sender, String[] args) {
selectedNpc.delete();
}
@SubCommand(
desc = "Sets the owner of an follower/companion",
usage = "[player]"
)
public void owner(ICommandSender sender, String[] args) {
if (args.length < 1) {
EntityPlayer player = null;
if (selectedNpc.roleInterface instanceof RoleFollower)
player = ((RoleFollower) selectedNpc.roleInterface).owner;
if (selectedNpc.roleInterface instanceof RoleCompanion)
player = ((RoleCompanion) selectedNpc.roleInterface).owner;
if (player == null)
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, "NULL"));
else
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, player.getDisplayName()));
} else {
EntityPlayerMP player = null;
try {
player = CommandBase.getPlayer(sender, args[0]);
} catch (PlayerNotFoundException e) {
}
if (selectedNpc.roleInterface instanceof RoleFollower)
((RoleFollower) selectedNpc.roleInterface).setOwner(player);
if (selectedNpc.roleInterface instanceof RoleCompanion)
((RoleCompanion) selectedNpc.roleInterface).setOwner(player);
if (player == null)
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, "NULL"));
else
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Owner: \u00A7b%s\u00A77", selectedNpc.display.name, player.getDisplayName()));
}
}
@SubCommand(
desc = "Set NPC name",
usage = "[name]"
)
public void name(ICommandSender sender, String[] args) {
if (args.length < 1)
return;
String name = args[0];
for (int i = 1; i < args.length; i++) {
name += " " + args[i];
}
sendResult(sender, String.format("NPC \u00A7e%s\u00A77 Name set to \u00A7b%s\u00A77", selectedNpc.display.name, name));
if (!selectedNpc.display.getName().equals(name)) {
selectedNpc.display.setName(name);
selectedNpc.updateClient = true;
}
}
@SubCommand(
desc = "Creates an NPC",
usage = "[name]"
)
public void create(ICommandSender sender, String[] args) {
EntityPlayerMP player = (EntityPlayerMP) sender;
World pw = player.getEntityWorld();
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
NoppesUtilServer.sendOpenGui(player, EnumGuiType.MainMenuDisplay, npc);
}
@Override
public List addTabCompletionOptions(ICommandSender par1, String[] args) {
if (args.length == 2) {
return CommandBase.getListOfStringsMatchingLastWord(args, new String[]{"create", "home", "visible", "delete", "owner", "name"});
}
if (args.length == 3 && args[1].equalsIgnoreCase("owner")) {
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
}
return null;
}
@Override
public int getRequiredPermissionLevel() {
return 4;
}
public <T extends Entity> List<T> getEntities(Class<? extends T> cls, World world, int x, int y, int z, int range) {
AxisAlignedBB bb = AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 1, z + 1).expand(range, range, range);
List<T> list = world.getEntitiesWithinAABB(cls, bb);
return list;
}
}
@@ -1,4 +1,4 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
@@ -9,6 +9,9 @@ import noppes.npcs.controllers.data.SkinOverlay;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class OverlayCommand extends CommandKamkeelBase { public class OverlayCommand extends CommandKamkeelBase {
@Override @Override
@@ -71,8 +74,7 @@ public class OverlayCommand extends CommandKamkeelBase {
playerdata.skinOverlays.remove(overlayID); playerdata.skinOverlays.remove(overlayID);
playerdata.save(); playerdata.save();
sendResult(sender, String.format("Overlay removed to Player '\u00A7b%s\u00A77' on ID \u00A7d%d", playerdata.playername, overlayID)); sendResult(sender, String.format("Overlay removed to Player '\u00A7b%s\u00A77' on ID \u00A7d%d", playerdata.playername, overlayID));
} } else {
else {
sendError(sender, String.format("No overlay found for Player '\u00A7b%s\u00A74' on ID \u00A7d%d", playerdata.playername, overlayID)); sendError(sender, String.format("No overlay found for Player '\u00A7b%s\u00A74' on ID \u00A7d%d", playerdata.playername, overlayID));
} }
return; return;
@@ -125,8 +127,7 @@ public class OverlayCommand extends CommandKamkeelBase {
if (isBlend) { if (isBlend) {
skinOverlay.setBlend(isTrue); skinOverlay.setBlend(isTrue);
} } else {
else{
skinOverlay.setGlow(isTrue); skinOverlay.setGlow(isTrue);
} }
playerdata.skinOverlays.add(overlayID, skinOverlay); playerdata.skinOverlays.add(overlayID, skinOverlay);
@@ -171,8 +172,7 @@ public class OverlayCommand extends CommandKamkeelBase {
sendResult(sender, "--------------------"); sendResult(sender, "--------------------");
if (playerdata.skinOverlays.size() == 0) { if (playerdata.skinOverlays.size() == 0) {
sendResult(sender, String.format("No Overlays found for Player '\u00A7b%s\u00A77'", playerdata.playername)); sendResult(sender, String.format("No Overlays found for Player '\u00A7b%s\u00A77'", playerdata.playername));
} } else {
else {
for (ISkinOverlay overlay : playerdata.skinOverlays.overlayList.values()) { for (ISkinOverlay overlay : playerdata.skinOverlays.overlayList.values()) {
if (overlay != null) { if (overlay != null) {
sendResult(sender, String.format("%s", overlay.getTexture())); sendResult(sender, String.format("%s", overlay.getTexture()));
@@ -1,10 +1,13 @@
package kamkeel.command; package kamkeel.npcs.command;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.Server; import noppes.npcs.config.ConfigMain;
import noppes.npcs.constants.EnumPacketClient; import noppes.npcs.constants.EnumProfileSync;
import noppes.npcs.constants.EnumQuestRepeat; import noppes.npcs.constants.EnumQuestRepeat;
import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.QuestController; import noppes.npcs.controllers.QuestController;
@@ -16,6 +19,9 @@ import noppes.npcs.controllers.data.QuestData;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class QuestCategoryCommand extends CommandKamkeelBase { public class QuestCategoryCommand extends CommandKamkeelBase {
@Override @Override
@@ -62,8 +68,7 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
int questcatid; int questcatid;
try { try {
questcatid = Integer.parseInt(args[1]); questcatid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "QuestCatID must be an integer: " + args[1]); sendError(sender, "QuestCatID must be an integer: " + args[1]);
return; return;
} }
@@ -82,19 +87,25 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
int count = 0; int count = 0;
for (PlayerData playerdata : data) { for (PlayerData playerdata : data) {
count = 0;
for (Quest quest : questCategory.quests.values()) { for (Quest quest : questCategory.quests.values()) {
if(playerdata.questData.activeQuests.containsKey(quest.id)){
playerdata.questData.activeQuests.remove(quest.id); playerdata.questData.activeQuests.remove(quest.id);
long completeTime;
if (quest.repeat == EnumQuestRepeat.RLDAILY || quest.repeat == EnumQuestRepeat.RLWEEKLY || quest.repeat == EnumQuestRepeat.RLCUSTOM) {
completeTime = System.currentTimeMillis();
playerdata.questData.finishedQuests.put(quest.id, completeTime);
} else {
completeTime = sender.getEntityWorld().getTotalWorldTime();
playerdata.questData.finishedQuests.put(quest.id, completeTime);
} }
if(quest.repeat == EnumQuestRepeat.RLDAILY || quest.repeat == EnumQuestRepeat.RLWEEKLY) if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
playerdata.questData.finishedQuests.put(quest.id, System.currentTimeMillis()); ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
else ;
playerdata.questData.finishedQuests.put(quest.id, sender.getEntityWorld().getTotalWorldTime());
if (playerdata.player != null) { if (playerdata.player != null) {
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.MESSAGE, "quest.completed", quest.title); AchievementPacket.sendAchievement((EntityPlayerMP) playerdata.player, false, "quest.completed", quest.title);
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.CHAT, "quest.completed", ": ", quest.title); ChatAlertPacket.sendChatAlert((EntityPlayerMP) playerdata.player, "quest.completed", ": ", quest.title);
} }
count++; count++;
} }
@@ -115,8 +126,7 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
int questcatid; int questcatid;
try { try {
questcatid = Integer.parseInt(args[1]); questcatid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "QuestCatID must be an integer: " + args[1]); sendError(sender, "QuestCatID must be an integer: " + args[1]);
return; return;
} }
@@ -158,8 +168,7 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
int questcatid; int questcatid;
try { try {
questcatid = Integer.parseInt(args[1]); questcatid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "QuestCatID must be an integer: " + args[1]); sendError(sender, "QuestCatID must be an integer: " + args[1]);
return; return;
} }
@@ -185,8 +194,8 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
count++; count++;
if (playerdata.player != null && questData.sendAlerts) { if (playerdata.player != null && questData.sendAlerts) {
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.MESSAGE, "quest.newquest", quest.title); AchievementPacket.sendAchievement((EntityPlayerMP) playerdata.player, false, "quest.newquest", quest.title);
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.CHAT, "quest.newquest", ": ", quest.title); ChatAlertPacket.sendChatAlert((EntityPlayerMP) playerdata.player, "quest.newquest", ": ", quest.title);
} }
} }
} }
@@ -208,8 +217,7 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
int questcatid; int questcatid;
try { try {
questcatid = Integer.parseInt(args[1]); questcatid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "QuestCatID must be an integer: " + args[1]); sendError(sender, "QuestCatID must be an integer: " + args[1]);
return; return;
} }
@@ -1,19 +1,20 @@
package kamkeel.command; package kamkeel.npcs.command;
import net.minecraft.command.CommandBase; import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.Server;
import noppes.npcs.api.handler.data.IQuestObjective; import noppes.npcs.api.handler.data.IQuestObjective;
import noppes.npcs.constants.EnumPacketClient; import noppes.npcs.config.ConfigMain;
import noppes.npcs.constants.EnumProfileSync;
import noppes.npcs.constants.EnumQuestCompletion; import noppes.npcs.constants.EnumQuestCompletion;
import noppes.npcs.constants.EnumQuestRepeat; import noppes.npcs.constants.EnumQuestRepeat;
import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.QuestController; import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.SyncController;
import noppes.npcs.controllers.data.Party; import noppes.npcs.controllers.data.Party;
import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.Quest; import noppes.npcs.controllers.data.Quest;
@@ -23,6 +24,9 @@ import noppes.npcs.util.ValueUtil;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class QuestCommand extends CommandKamkeelBase { public class QuestCommand extends CommandKamkeelBase {
@Override @Override
@@ -67,8 +71,8 @@ public class QuestCommand extends CommandKamkeelBase {
playerdata.questData.activeQuests.put(questid, questdata); playerdata.questData.activeQuests.put(questid, questdata);
playerdata.save(); playerdata.save();
if (playerdata.player != null && questdata.sendAlerts) { if (playerdata.player != null && questdata.sendAlerts) {
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.MESSAGE, "quest.newquest", quest.title); AchievementPacket.sendAchievement((EntityPlayerMP) playerdata.player, false, "quest.newquest", quest.title);
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.CHAT, "quest.newquest", ": ", quest.title); ChatAlertPacket.sendChatAlert((EntityPlayerMP) playerdata.player, "quest.newquest", ": ", quest.title);
} }
playerdata.updateClient = true; playerdata.updateClient = true;
sendResult(sender, String.format("Started Quest \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", questid, playerdata.playername)); sendResult(sender, String.format("Started Quest \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", questid, playerdata.playername));
@@ -84,8 +88,7 @@ public class QuestCommand extends CommandKamkeelBase {
int questid; int questid;
try { try {
questid = Integer.parseInt(args[1]); questid = Integer.parseInt(args[1]);
} } catch (NumberFormatException ex) {
catch (NumberFormatException ex) {
sendError(sender, "QuestID must be an integer: " + args[1]); sendError(sender, "QuestID must be an integer: " + args[1]);
return; return;
} }
@@ -102,19 +105,23 @@ public class QuestCommand extends CommandKamkeelBase {
return; return;
} }
for (PlayerData playerdata : data) { for (PlayerData playerdata : data) {
if(playerdata.questData.activeQuests.containsKey(questid)){
playerdata.questData.activeQuests.remove(questid); playerdata.questData.activeQuests.remove(questid);
long completeTime;
if (quest.repeat == EnumQuestRepeat.RLDAILY || quest.repeat == EnumQuestRepeat.RLWEEKLY || quest.repeat == EnumQuestRepeat.RLCUSTOM) {
completeTime = System.currentTimeMillis();
playerdata.questData.finishedQuests.put(quest.id, completeTime);
} else {
completeTime = sender.getEntityWorld().getTotalWorldTime();
playerdata.questData.finishedQuests.put(quest.id, completeTime);
} }
if(quest.repeat == EnumQuestRepeat.RLDAILY || quest.repeat == EnumQuestRepeat.RLWEEKLY) if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
playerdata.questData.finishedQuests.put(quest.id, System.currentTimeMillis()); ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
else
playerdata.questData.finishedQuests.put(quest.id, sender.getEntityWorld().getTotalWorldTime());
playerdata.save(); playerdata.save();
if (playerdata.player != null) { if (playerdata.player != null) {
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.MESSAGE, "quest.completed", quest.title); AchievementPacket.sendAchievement((EntityPlayerMP) playerdata.player, false, "quest.completed", quest.title);
Server.sendData((EntityPlayerMP)playerdata.player, EnumPacketClient.CHAT, "quest.completed", ": ", quest.title); ChatAlertPacket.sendChatAlert((EntityPlayerMP) playerdata.player, "quest.completed", ": ", quest.title);
} }
playerdata.updateClient = true; playerdata.updateClient = true;
sendResult(sender, String.format("Finished Quest \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", questid, playerdata.playername)); sendResult(sender, String.format("Finished Quest \u00A7e%d\u00A77 for Player '\u00A7b%s\u00A77'", questid, playerdata.playername));
@@ -192,7 +199,7 @@ public class QuestCommand extends CommandKamkeelBase {
usage = "<player> <quest> [objective] [value]" usage = "<player> <quest> [objective] [value]"
) )
public void objective(ICommandSender sender, String[] args) throws CommandException { public void objective(ICommandSender sender, String[] args) throws CommandException {
EntityPlayer player = CommandBase.getPlayer(sender, args[0]); EntityPlayer player = getPlayer(sender, args[0]);
int questid; int questid;
try { try {
questid = Integer.parseInt(args[1]); questid = Integer.parseInt(args[1]);
@@ -0,0 +1,43 @@
package kamkeel.npcs.command;
import net.minecraft.command.ICommandSender;
import noppes.npcs.controllers.ScriptController;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class ScriptCommand extends CommandKamkeelBase {
@SubCommand(desc = "Reload scripts data and folders.")
public Boolean reload(ICommandSender sender, String args[]) {
ScriptController.Instance.loadCategories();
if (ScriptController.Instance.loadPlayerScripts())
sendResult(sender, "Reload player scripts successfully");
else
sendError(sender, "Failed reloading player scripts");
if (ScriptController.Instance.loadForgeScripts())
sendResult(sender, "Reload forge scripts successfully");
else
sendError(sender, "Failed reloading forge scripts");
if (ScriptController.Instance.loadStoredData())
sendResult(sender, "Reload stored data successfully");
else
sendError(sender, "Failed reloading stored data");
return true;
}
@Override
public String getCommandName() {
return "script";
}
@Override
public String getDescription() {
return "Commands for scripts";
}
}
@@ -0,0 +1,139 @@
package kamkeel.npcs.command;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.AxisAlignedBB;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.*;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class SlayCommand extends CommandKamkeelBase {
public Map<String, Class<?>> SlayMap = new LinkedHashMap<String, Class<?>>();
public SlayCommand() {
SlayMap.clear();
SlayMap.put("all", EntityLivingBase.class);
SlayMap.put("mobs", EntityMob.class);
SlayMap.put("animals", EntityAnimal.class);
SlayMap.put("items", EntityItem.class);
SlayMap.put("xporbs", EntityXPOrb.class);
SlayMap.put("npcs", EntityNPCInterface.class);
HashMap<String, Class<?>> list = new HashMap<String, Class<?>>(EntityList.stringToClassMapping);
for (String name : list.keySet()) {
Class<?> cls = list.get(name);
if (EntityNPCInterface.class.isAssignableFrom(cls))
continue;
if (!EntityLivingBase.class.isAssignableFrom(cls))
continue;
SlayMap.put(name.toLowerCase(), list.get(name));
}
SlayMap.remove("monster");
SlayMap.remove("mob");
}
@Override
public String getCommandName() {
return "slay";
}
@Override
public String getDescription() {
return "Kills given entity within range. Tab to see options.";
}
@Override
public String getUsage() {
return "<type>.. [range]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
EntityPlayerMP player = (EntityPlayerMP) sender;
ArrayList<Class<?>> toDelete = new ArrayList<Class<?>>();
boolean deleteNPCs = false;
for (String delete : args) {
delete = delete.toLowerCase();
Class<?> cls = SlayMap.get(delete);
if (cls != null)
toDelete.add(cls);
if (delete.equals("mobs")) {
toDelete.add(EntityGhast.class);
toDelete.add(EntityDragon.class);
}
if (delete.equals("npcs"))
deleteNPCs = true;
}
int count = 0;
int range = 120;
try {
range = Integer.parseInt(args[args.length - 1]);
} catch (NumberFormatException ex) {
}
AxisAlignedBB box = player.boundingBox.expand(range, range, range);
List<? extends Entity> list = sender.getEntityWorld().getEntitiesWithinAABB(EntityLivingBase.class, box);
for (Entity entity : list) {
if (entity instanceof EntityPlayer)
continue;
if (entity instanceof EntityTameable && ((EntityTameable) entity).isTamed())
continue;
if (entity instanceof EntityNPCInterface && !deleteNPCs)
continue;
if (delete(entity, toDelete))
count++;
}
if (toDelete.contains(EntityXPOrb.class)) {
list = sender.getEntityWorld().getEntitiesWithinAABB(EntityXPOrb.class, box);
for (Entity entity : list) {
entity.isDead = true;
count++;
}
}
if (toDelete.contains(EntityItem.class)) {
list = sender.getEntityWorld().getEntitiesWithinAABB(EntityItem.class, box);
for (Entity entity : list) {
entity.isDead = true;
count++;
}
}
sendResult(sender, count + " entities deleted");
}
private boolean delete(Entity entity, ArrayList<Class<?>> toDelete) {
for (Class<?> delete : toDelete) {
if (delete == EntityAnimal.class && (entity instanceof EntityHorse)) {
continue;
}
if (delete.isAssignableFrom(entity.getClass())) {
entity.isDead = true;
return true;
}
}
return false;
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
return getListOfStringsMatchingLastWord(args, SlayMap.keySet().toArray(new String[SlayMap.size()]));
}
}
@@ -0,0 +1,91 @@
package kamkeel.npcs.command.profile;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.CustomNpcsPermissions;
import java.lang.reflect.Method;
import java.util.Map.Entry;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendMessage;
public class CommandHelpProfile extends CommandProfileBase {
private CommandProfile parent;
public CommandHelpProfile(CommandProfile parent) {
this.parent = parent;
}
@Override
public String getCommandName() {
return "help";
}
@Override
public String getDescription() {
return "help [command]";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
sendMessage(sender, "\u00A78------ \u00A7aProfile Commands \u00A78------");
for (Entry<String, CommandProfileBase> entry : parent.map.entrySet()) {
sendMessage(sender, "\u00A77> " + "\u00A7e" + entry.getKey() + "\u00A78: \u00A77"
+ entry.getValue().getCommandUsage(sender));
}
return;
}
CommandProfileBase command = parent.getCommand(args);
if (command == null) {
sendError(sender, "Unknown command " + args[0]);
return;
}
if (command.subcommands.isEmpty()) {
sendMessage(sender, (command.getCommandUsage(sender)));
return;
}
Method m = null;
if (args.length > 1) {
m = command.subcommands.get(args[1].toLowerCase());
}
if (m == null) {
sendMessage(sender, "\u00A78------ \u00A7a" + command.getCommandName().toUpperCase()
+ " SubCommands \u00A78------");
sendMessage(sender, "\u00A77Usage: \u00A76" + command.getUsage());
for (Entry<String, Method> entry : command.subcommands.entrySet()) {
SubCommand sc = entry.getValue().getAnnotation(SubCommand.class);
// For players, only list subcommands if they have permission; for console, show all.
if (!(sender instanceof EntityPlayer) || command.canSendCommand(sender, sc, entry.getKey())) {
sendMessage(sender, ("\u00A77> "
+ "\u00A7e" + entry.getKey()
+ "\u00A78: \u00A77" + sc.desc()));
}
}
// Show permission node only if sender is console or has permission.
if (!(sender instanceof EntityPlayer) ||
CustomNpcsPermissions.hasPermission((EntityPlayer) sender, CustomNpcsPermissions.PROFILE_ADMIN)) {
sendMessage(sender, ("\u00A78Permission:\u00A77 "
+ CommandProfile.getCommandPermission(command.getCommandName())));
}
} else {
sendMessage(sender, "\u00A78------ \u00A7b" + command.getCommandName().toUpperCase()
+ "." + args[1].toUpperCase() + " Command \u00A78------");
SubCommand sc = m.getAnnotation(SubCommand.class);
sendMessage(sender, ("\u00A77" + sc.desc()));
if (!sc.usage().isEmpty()) {
sendMessage(sender, ("\u00A77Usage: \u00A76" + sc.usage()));
}
if (!(sender instanceof EntityPlayer) ||
CustomNpcsPermissions.hasPermission((EntityPlayer) sender, CustomNpcsPermissions.PROFILE_ADMIN)) {
sendMessage(sender, ("\u00A78Permission:\u00A77 "
+ getSubCommandPermission(args[1])));
}
}
}
}
@@ -0,0 +1,147 @@
package kamkeel.npcs.command.profile;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.scripted.CustomNPCsException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandProfile extends CommandBase {
public Map<String, CommandProfileBase> map = new HashMap<String, CommandProfileBase>();
public CommandHelpProfile help = new CommandHelpProfile(this);
public String[] alias = {"profile"};
public CommandProfile() {
registerCommand(help);
registerCommand(new CommandProfileChange());
registerCommand(new CommandProfileCreate());
registerCommand(new CommandProfileRemove());
registerCommand(new CommandProfileAdmin());
registerCommand(new CommandProfileRegion());
registerCommand(new CommandProfileList());
registerCommand(new CommandProfileRename());
}
public void registerCommand(CommandProfileBase command) {
String name = command.getCommandName().toLowerCase();
if (map.containsKey(name))
throw new CustomNPCsException("Already a subcommand with the name: " + name);
map.put(name, command);
}
@Override
public String getCommandName() {
return "profile";
}
@Override
public List getCommandAliases() {
return Arrays.asList(alias);
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "Use as /profile subcommand";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length == 0) {
help.processCommand(sender, args);
return;
}
CommandProfileBase command = getCommand(args);
if (command == null)
throw new CommandException("Unknown command " + args[0]);
args = Arrays.copyOfRange(args, 1, args.length);
if (command.subcommands.isEmpty() || !command.runSubCommands()) {
if (!canSendCommand(sender, command))
throw new CommandException("You are not allowed to use this command: " + command);
command.canRun(sender, command.getUsage(), args);
command.processCommand(sender, args);
return;
}
if (args.length == 0) {
help.processCommand(sender, new String[]{command.getCommandName()});
return;
}
command.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
if (args.length == 1)
return CommandBase.getListOfStringsMatchingLastWord(args, map.keySet().toArray(new String[map.size()]));
CommandProfileBase command = getCommand(args);
if (command == null)
return null;
if (args.length == 2 && command.runSubCommands())
return getListOfStringsMatchingLastWord(args, command.subcommands.keySet().toArray(new String[command.subcommands.keySet().size()]));
String[] useArgs = command.getUsage().split(" ");
if (command.runSubCommands()) {
Method m = command.subcommands.get(args[1].toLowerCase());
if (m != null) {
useArgs = m.getAnnotation(CommandProfileBase.SubCommand.class).usage().split(" ");
}
}
if (args.length <= useArgs.length + 2) {
if (args.length - 3 >= 0) {
String usage = useArgs[args.length - 3];
if (usage.equals("<player>") || usage.equals("[player]") || usage.equals("<targetPlayer>")
|| usage.equals("<sourcePlayer>") || usage.equals("<destinationPlayer>")) {
return CommandBase.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames());
}
}
}
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
public CommandProfileBase getCommand(String[] args) {
if (args.length == 0)
return null;
return map.get(args[0].toLowerCase());
}
@Override
public int getRequiredPermissionLevel() {
return 4;
}
public static String getCommandPermission(String command) {
return "profile.kamkeel." + command.toLowerCase();
}
public static String getUniversalPermission() {
return "profile.kamkeel.*";
}
public static boolean canSendCommand(ICommandSender sender, CommandProfileBase command) {
if (sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getUniversalPermission())) {
return true;
}
if (sender.canCommandSenderUseCommand(command.getRequiredPermissionLevel(), getCommandPermission(command.getCommandName()))) {
return true;
}
if (sender instanceof EntityPlayer) {
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getCommandPermission(command.getCommandName()));
}
return false;
}
}
@@ -0,0 +1,259 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.EnumProfileOperation;
import kamkeel.npcs.controllers.data.profile.Profile;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import noppes.npcs.api.handler.data.ISlot;
import java.io.File;
import java.util.Map;
import java.util.UUID;
import static kamkeel.npcs.util.ColorUtil.*;
public class CommandProfileAdmin extends CommandProfileBase {
@Override
public String getCommandName() {
return "admin";
}
@Override
public String getDescription() {
return "Admin profile management: clone, remove, change, list, rename, and rollback profiles.";
}
@Override
public String getUsage() {
return "<subcommand>";
}
@SubCommand(
desc = "Clone a slot from one player's profile to another player.",
usage = "<sourcePlayer> <destinationPlayer> <sourceSlot> <destinationSlot> [temp]"
)
public void clone(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 4) {
sendError(sender, "Usage: /profile admin clone <sourcePlayer> <destinationPlayer> <sourceSlot> <destinationSlot> [temp]");
return;
}
String sourcePlayer = args[0];
String destinationPlayer = args[1];
int sourceSlot, destinationSlot;
try {
sourceSlot = Integer.parseInt(args[2]);
destinationSlot = Integer.parseInt(args[3]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot IDs must be numbers.");
return;
}
boolean temporary = (args.length >= 5 && args[4].equalsIgnoreCase("temp"));
ProfileOperation result = ProfileController.Instance.cloneSlot(sourcePlayer, sourceSlot, destinationSlot, temporary);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "Successfully cloned slot %d from %s to slot %d for %s.", sourceSlot, sourcePlayer, destinationSlot, destinationPlayer);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
// Detail message for admins – note: using result.getMessage() for further details.
sendError(sender, "Clone failed for %s: Profile is locked. Details: %s", sourcePlayer, result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error cloning slot for %s: %s", sourcePlayer, result.getMessage());
} else {
sendError(sender, "Unexpected error cloning slot: %s", result.getMessage());
}
}
@SubCommand(
desc = "Remove a specified slot from a player's profile.",
usage = "<targetPlayer> <slotId>"
)
public void remove(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 2) {
sendError(sender, "Usage: /profile admin remove <targetPlayer> <slotId>");
return;
}
String targetPlayer = args[0];
int slotId;
try {
slotId = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number.");
return;
}
ProfileOperation result = ProfileController.Instance.removeSlot(targetPlayer, slotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "Successfully removed slot %d from %s.", slotId, targetPlayer);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Remove failed for %s: Profile is locked. Details: %s", targetPlayer, result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error removing slot %d from %s: %s", slotId, targetPlayer, result.getMessage());
} else {
sendError(sender, "Unexpected error during removal: %s", result.getMessage());
}
}
@SubCommand(
desc = "Change a specified player's active slot.",
usage = "<targetPlayer> <newSlotId>"
)
public void change(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 2) {
sendError(sender, "Usage: /profile admin change <targetPlayer> <newSlotId>");
return;
}
String targetPlayer = args[0];
int newSlotId;
try {
newSlotId = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number.");
return;
}
ProfileOperation result = ProfileController.Instance.changeSlot(targetPlayer, newSlotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "Successfully changed %s's active slot to %d.", targetPlayer, newSlotId);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Change failed for %s: Profile is locked. Details: %s", targetPlayer, result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error changing active slot for %s: %s", targetPlayer, result.getMessage());
} else {
sendError(sender, "Unexpected error during change: %s", result.getMessage());
}
}
@SubCommand(
desc = "Create a new slot for a specified player's profile.",
usage = "<targetPlayer>"
)
public void create(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 1) {
sendError(sender, "Usage: /profile admin create <targetPlayer>");
return;
}
String targetPlayer = args[0];
Profile profile = ProfileController.Instance.getProfile(targetPlayer);
if (profile == null) {
sendError(sender, "Profile not found for player: %s", targetPlayer);
return;
}
ProfileOperation result = ProfileController.Instance.createSlotInternal(profile);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "New slot created successfully for %s.", targetPlayer);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Create failed for %s: Profile is locked. Details: %s", targetPlayer, result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error creating new slot for %s: %s", targetPlayer, result.getMessage());
} else {
sendError(sender, "Unexpected error during slot creation: %s", result.getMessage());
}
}
@SubCommand(
desc = "List all slots (IDs and names) for a specified player's profile.",
usage = "<targetPlayer>"
)
public void list(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 1) {
sendError(sender, "Usage: /profile admin list <targetPlayer>");
return;
}
String targetPlayer = args[0];
Profile profile = ProfileController.Instance.getProfile(targetPlayer);
if (profile == null) {
sendError(sender, "Profile not found for player: %s", targetPlayer);
return;
}
sendMessage(sender, "Profile Slots for %s:", targetPlayer);
for (Map.Entry<Integer, ISlot> entry : profile.getSlots().entrySet()) {
int id = entry.getKey();
String name = entry.getValue().getName();
String prefix = (id == profile.currentSlotId) ? "* " : "- ";
sendMessage(sender, prefix + "Slot " + id + ": " + name);
}
}
@SubCommand(
desc = "Rename a specified player's slot.",
usage = "<targetPlayer> <slotId> <newName>"
)
public void rename(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 3) {
sendError(sender, "Usage: /profile admin rename <targetPlayer> <slotId> <newName>");
return;
}
String targetPlayer = args[0];
int slotId;
try {
slotId = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number.");
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
if (i > 2) sb.append(" ");
sb.append(args[i]);
}
String newName = sb.toString().trim();
if (newName.length() > 20) {
newName = newName.substring(0, 20);
}
if (!newName.matches("[A-Za-z ]+")) {
sendError(sender, "Invalid name. Only alphabetic characters and spaces are allowed.");
return;
}
Profile profile = ProfileController.Instance.getProfile(targetPlayer);
if (profile == null) {
sendError(sender, "Profile not found for player: %s", targetPlayer);
return;
}
if (profile.isLocked()) {
sendError(sender, "Profile for %s is locked. Please try again later.", targetPlayer);
return;
}
if (!profile.getSlots().containsKey(slotId)) {
sendError(sender, "Slot %d not found in %s's profile.", slotId, targetPlayer);
return;
}
profile.getSlots().get(slotId).setName(newName);
if (profile.getPlayer() != null) {
ProfileController.Instance.save(profile.player, profile);
} else {
UUID uuid = ProfileController.Instance.getUUIDFromUsername(targetPlayer);
if (uuid != null)
ProfileController.Instance.saveOffline(profile, uuid);
}
sendResult(sender, "Successfully renamed slot %d for %s to '%s'.", slotId, targetPlayer, newName);
}
@SubCommand(
desc = "Rollback a player's profile to one of their backups.",
usage = "<targetPlayer> <backupFileName>"
)
public void rollback(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 2) {
sendError(sender, "Usage: /profile admin rollback <targetPlayer> <backupFileName>");
return;
}
String targetPlayer = args[0];
String backupFileName = args[1] + ".dat";
Profile profile = ProfileController.Instance.getProfile(targetPlayer);
if (profile == null || profile.player == null)
return;
File backupDir = new File(ProfileController.getBackupDir(), profile.getPlayer().getUniqueID().toString());
File backupFile = new File(backupDir, backupFileName);
if (!backupFile.exists()) {
sendError(sender, "Backup file %s not found for player %s.", backupFileName, targetPlayer);
return;
}
boolean success = ProfileController.Instance.rollbackProfile(targetPlayer, backupFile);
if (success) {
sendResult(sender, "Successfully rolled back %s's profile to backup %s.", targetPlayer, backupFileName);
} else {
sendError(sender, "Failed to rollback %s's profile.", targetPlayer);
}
}
}
@@ -0,0 +1,135 @@
package kamkeel.npcs.command.profile;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.CustomNpcsPermissions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class CommandProfileBase extends CommandBase {
public Map<String, Method> subcommands = new HashMap<String, Method>();
public CommandProfileBase() {
for (Method m : this.getClass().getDeclaredMethods()) {
SubCommand sc = m.getAnnotation(SubCommand.class);
if (sc != null) {
String name = sc.name();
if (name.equals(""))
name = m.getName();
subcommands.put(name.toLowerCase(), m);
}
}
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
}
@Override
public String getCommandUsage(ICommandSender sender) {
return getDescription();
}
public abstract String getDescription();
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
public String getUsage() {
return "";
}
public boolean runSubCommands() {
return !subcommands.isEmpty();
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SubCommand {
String name() default "";
/**
* @return Should return a string in the format of <arg> <arg2> <arg3> [arg4] where <> is a required parameter and [] optional
*/
String usage() default "";
String desc();
int permission() default 2;
}
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
Method m = subcommands.get(command.toLowerCase());
if (m == null)
throw new CommandException("Unknown subcommand " + command);
SubCommand sc = m.getAnnotation(SubCommand.class);
if (!canSendCommand(sender, sc, command))
throw new CommandException("You are not allowed to use this command: " + command);
canRun(sender, sc.usage(), args);
try {
m.invoke(this, sender, args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void canRun(ICommandSender sender, String usage, String[] args) throws CommandException {
String[] np = usage.split(" ");
List<String> required = new ArrayList<String>();
for (int i = 0; i < np.length; i++) {
String command = np[i];
if (command.startsWith("<")) {
required.add(command);
}
if (command.equals("<player>") && args.length > i) {
CommandBase.getPlayer(sender, args[i]); //throws PlayerNotFoundException if no player is found
}
}
if (args.length < required.size()) {
throw new CommandException("Missing parameter: " + required.get(args.length));
}
}
public int getRequiredPermissionLevel() {
return 2;
}
public String getSubCommandPermission(String subCommand) {
return "profile.kamkeel." + getCommandName().toLowerCase() + "." + subCommand.toLowerCase();
}
public String getSubUniversalPermission() {
return "profile.kamkeel." + getCommandName().toLowerCase() + "*";
}
public boolean canSendCommand(ICommandSender sender, SubCommand command, String subCommand) {
if (sender.canCommandSenderUseCommand(command.permission(), getSubUniversalPermission())) {
return true;
}
if (sender.canCommandSenderUseCommand(command.permission(), getSubCommandPermission(subCommand))) {
return true;
}
if (sender instanceof EntityPlayer) {
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
}
return false;
}
}
@@ -0,0 +1,64 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.EnumProfileOperation;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class CommandProfileChange extends CommandProfileBase {
@Override
public String getCommandName() {
return "change";
}
@Override
public String getDescription() {
return "Change your active profile slot.";
}
@Override
public String getUsage() {
return "<slotId>";
}
@Override
public boolean runSubCommands() {
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "This command can only be used by a player.");
return;
}
if (args.length < 1) {
sendError(sender, "Usage: " + getUsage());
return;
}
int slotId;
try {
slotId = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number: " + args[0]);
return;
}
EntityPlayer player = (EntityPlayer) sender;
ProfileOperation result = ProfileController.Instance.changeSlot(player, slotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "Successfully changed profile slot to %d.", slotId);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Profile is locked. Details: %s", result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error changing your profile slot: %s", result.getMessage());
} else {
sendError(sender, "Unexpected error: %s", result.getMessage());
}
}
}
@@ -0,0 +1,57 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.EnumProfileOperation;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class CommandProfileCreate extends CommandProfileBase {
@Override
public String getCommandName() {
return "create";
}
@Override
public String getDescription() {
return "Create a new profile slot.";
}
@Override
public String getUsage() {
return "";
}
@Override
public boolean runSubCommands() {
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "This command can only be used by a player.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
if (ProfileController.Instance.getProfile(player) == null) {
sendError(sender, "Profile not found.");
return;
}
ProfileOperation result = ProfileController.Instance.createSlotInternal(ProfileController.Instance.getProfile(player));
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "New profile slot created successfully.");
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Profile is locked. Details: %s", result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error creating new profile slot: %s", result.getMessage());
} else {
sendError(sender, "Unexpected error: %s", result.getMessage());
}
}
}
@@ -0,0 +1,55 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.Profile;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.api.handler.data.ISlot;
import java.util.Map;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendMessage;
public class CommandProfileList extends CommandProfileBase {
@Override
public String getCommandName() {
return "list";
}
@Override
public String getDescription() {
return "List all your current profile slots (IDs and names).";
}
@Override
public String getUsage() {
return ""; // No extra parameters.
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "This command can only be used by a player.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
Profile profile = ProfileController.Instance.getProfile(player);
if (profile == null) {
sendError(sender, "Profile not found.");
return;
}
if (profile.getSlots().isEmpty()) {
sendMessage(sender, "No slots found. Using default slot 0.");
}
sendMessage(sender, "Your Profile Slots:");
for (Map.Entry<Integer, ISlot> entry : profile.getSlots().entrySet()) {
int id = entry.getKey();
String name = entry.getValue().getName();
String prefix = (id == profile.currentSlotId) ? "* " : "- ";
sendMessage(sender, prefix + "Slot " + id + ": " + name);
}
}
}
@@ -0,0 +1,152 @@
package kamkeel.npcs.command.profile;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import noppes.npcs.config.ConfigMain;
import java.util.ArrayList;
import java.util.List;
import static kamkeel.npcs.util.ColorUtil.*;
public class CommandProfileRegion extends CommandProfileBase {
@Override
public String getCommandName() {
return "region";
}
@Override
public String getDescription() {
return "Manage profile region switching and restricted regions";
}
@Override
public String getUsage() {
return "<subcommand>";
}
@SubCommand(
desc = "Enable region-based profile switching",
usage = ""
)
public void enable(ICommandSender sender, String[] args) throws CommandException {
ConfigMain.RegionProfileSwitching = true;
ConfigMain.RegionProfileSwitchingProperty.set(true);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
sendResult(sender, "Profile region switching enabled.");
}
@SubCommand(
desc = "Disable region-based profile switching",
usage = ""
)
public void disable(ICommandSender sender, String[] args) throws CommandException {
ConfigMain.RegionProfileSwitching = false;
ConfigMain.RegionProfileSwitchingProperty.set(false);
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
sendResult(sender, "Profile region switching disabled.");
}
@SubCommand(
desc = "Add a new region. Format: DIM X1 Y1 Z1 X2 Y2 Z2",
usage = "<dim> <x1> <y1> <z1> <x2> <y2> <z2>"
)
public void add(ICommandSender sender, String[] args) throws CommandException {
if (args.length != 7) {
sendError(sender, "Usage: /profile region add <dim> <x1> <y1> <z1> <x2> <y2> <z2>");
return;
}
List<Integer> regionList = new ArrayList<>();
try {
for (String arg : args) {
regionList.add(Integer.parseInt(arg));
}
} catch (NumberFormatException e) {
sendError(sender, "Invalid number format in region data.");
return;
}
ConfigMain.RestrictedProfileRegions.add(regionList);
// Update config property value
List<String> regionStrings = new ArrayList<>();
for (List<Integer> region : ConfigMain.RestrictedProfileRegions) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < region.size(); i++) {
if (i > 0) sb.append(" ");
sb.append(region.get(i));
}
regionStrings.add(sb.toString());
}
ConfigMain.RestrictedProfileRegionsProperty.set(regionStrings.toArray(new String[0]));
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
sendResult(sender, "Region added successfully.");
}
@SubCommand(
desc = "Remove a region by its index (1-based).",
usage = "<index>"
)
public void remove(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 1) {
sendError(sender, "Usage: /profile region remove <index>");
return;
}
int index;
try {
index = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
sendError(sender, "Index must be a number.");
return;
}
index = index - 1; // Convert to 0-based index
if (index < 0 || index >= ConfigMain.RestrictedProfileRegions.size()) {
sendError(sender, "Invalid index. Must be between 1 and " + ConfigMain.RestrictedProfileRegions.size());
return;
}
ConfigMain.RestrictedProfileRegions.remove(index);
// Update config property value
List<String> regionStrings = new ArrayList<>();
for (List<Integer> region : ConfigMain.RestrictedProfileRegions) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < region.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(region.get(i));
}
regionStrings.add(sb.toString());
}
ConfigMain.RestrictedProfileRegionsProperty.set(regionStrings.toArray(new String[0]));
if (ConfigMain.config.hasChanged()) {
ConfigMain.config.save();
}
sendResult(sender, "Region removed successfully.");
}
@SubCommand(
desc = "List all restricted profile regions.",
usage = ""
)
public void list(ICommandSender sender, String[] args) throws CommandException {
if (ConfigMain.RestrictedProfileRegions.isEmpty()) {
sendMessage(sender, "No restricted profile regions configured.");
return;
}
sendMessage(sender, "Restricted Profile Regions:");
int i = 1;
for (List<Integer> region : ConfigMain.RestrictedProfileRegions) {
StringBuilder sb = new StringBuilder();
sb.append(i).append(": ");
for (int j = 0; j < region.size(); j++) {
if (j > 0) sb.append(", ");
sb.append(region.get(j));
}
sendMessage(sender, sb.toString());
i++;
}
}
}
@@ -0,0 +1,64 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.data.profile.EnumProfileOperation;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class CommandProfileRemove extends CommandProfileBase {
@Override
public String getCommandName() {
return "remove";
}
@Override
public String getDescription() {
return "Remove a slot from your profile. You cannot remove your active slot.";
}
@Override
public String getUsage() {
return "<slotId>";
}
@Override
public boolean runSubCommands() {
return false;
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "This command can only be used by a player.");
return;
}
if (args.length < 1) {
sendError(sender, "Usage: " + getUsage());
return;
}
int slotId;
try {
slotId = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number: " + args[0]);
return;
}
EntityPlayer player = (EntityPlayer) sender;
ProfileOperation result = ProfileController.Instance.removeSlot(player, slotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
sendResult(sender, "Successfully removed slot %d from your profile.", slotId);
} else if (result.getResult() == EnumProfileOperation.LOCKED) {
sendError(sender, "Profile is locked. Details: %s", result.getMessage());
} else if (result.getResult() == EnumProfileOperation.ERROR) {
sendError(sender, "Error removing slot: %s", result.getMessage());
} else {
sendError(sender, "Unexpected error: %s", result.getMessage());
}
}
}
@@ -0,0 +1,71 @@
package kamkeel.npcs.command.profile;
import kamkeel.npcs.controllers.ProfileController;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import static kamkeel.npcs.util.ColorUtil.sendError;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class CommandProfileRename extends CommandProfileBase {
@Override
public String getCommandName() {
return "rename";
}
@Override
public String getDescription() {
return "Rename one of your profile slots. Only letters and spaces are allowed (max 20 characters).";
}
@Override
public String getUsage() {
return "<slotId> <newName>";
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (!(sender instanceof EntityPlayer)) {
sendError(sender, "This command can only be used by a player.");
return;
}
if (args.length < 2) {
sendError(sender, "Usage: " + getUsage());
return;
}
int slotId;
try {
slotId = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
sendError(sender, "Slot ID must be a number.");
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i < args.length; i++) {
if (i > 1) sb.append(" ");
sb.append(args[i]);
}
String newName = sb.toString().trim();
if (newName.length() > 20) {
newName = newName.substring(0, 20);
}
if (!newName.matches("[A-Za-z ]+")) {
sendError(sender, "Invalid name. Only alphabetic characters and spaces are allowed.");
return;
}
EntityPlayer player = (EntityPlayer) sender;
if (ProfileController.Instance.getProfile(player) == null) {
sendError(sender, "Profile not found.");
return;
}
if (!ProfileController.Instance.getProfile(player).getSlots().containsKey(slotId)) {
sendError(sender, "Slot %d not found in your profile.", slotId);
return;
}
ProfileController.Instance.getProfile(player).getSlots().get(slotId).setName(newName);
ProfileController.Instance.save(player, ProfileController.Instance.getProfile(player));
sendResult(sender, "Successfully renamed slot %d to '%s'.", slotId, newName);
}
}
@@ -0,0 +1,78 @@
package kamkeel.npcs.controllers;
import kamkeel.npcs.CustomAttributes;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.AttributeValueType;
import kamkeel.npcs.controllers.data.attribute.tracker.PlayerAttributeTracker;
import net.minecraft.entity.player.EntityPlayer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* AttributeController is the central registry for attribute definitions.
* It ensures that keys are unique.
*/
public class AttributeController {
public AttributeController Instance;
public CustomAttributes attributes;
// Tracking Player Attributes
private static final Map<UUID, PlayerAttributeTracker> trackers = new HashMap<>();
private static final Map<String, AttributeDefinition> definitions = new HashMap<>();
public AttributeController() {
this.Instance = this;
definitions.clear();
trackers.clear();
attributes = new CustomAttributes();
}
public static AttributeDefinition registerAttribute(String key, String displayName, char colorCode, AttributeValueType valueType, AttributeDefinition.AttributeSection section) {
if (definitions.containsKey(key)) {
throw new IllegalArgumentException("Attribute already registered with key: " + key);
}
AttributeDefinition def = new AttributeDefinition(key, displayName, colorCode, valueType, section);
definitions.put(key, def);
return def;
}
public static AttributeDefinition registerAttribute(AttributeDefinition definition) {
if (definitions.containsKey(definition.getKey())) {
throw new IllegalArgumentException("Attribute already registered with key: " + definition.getKey());
} else {
definitions.put(definition.getKey(), definition);
return definition;
}
}
public static AttributeDefinition getAttribute(String key) {
return definitions.get(key);
}
public static Collection<AttributeDefinition> getAllAttributes() {
return definitions.values();
}
public static PlayerAttributeTracker getTracker(EntityPlayer player) {
return trackers.computeIfAbsent(player.getUniqueID(), id -> new PlayerAttributeTracker(id));
}
public static void removeTracker(UUID playerId) {
trackers.remove(playerId);
}
/**
* Update all trackers (e.g. called every 10 ticks for all online players).
*/
public static void updateAllTrackers(Iterable<EntityPlayer> players) {
for (EntityPlayer player : players) {
PlayerAttributeTracker tracker = getTracker(player);
tracker.updateIfChanged(player);
}
}
}
@@ -0,0 +1,830 @@
package kamkeel.npcs.controllers;
import kamkeel.npcs.controllers.data.profile.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.*;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.api.handler.IPlayerData;
import noppes.npcs.api.handler.IProfileHandler;
import noppes.npcs.api.handler.data.IProfile;
import noppes.npcs.api.handler.data.ISlot;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.PlayerDataScript;
import noppes.npcs.controllers.data.PlayerQuestData;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.util.CustomNPCsThreader;
import noppes.npcs.util.NBTJsonUtil;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import static noppes.npcs.CustomNpcsPermissions.*;
public class ProfileController implements IProfileHandler {
// Message constants
private static final String MSG_PLAYER_NOT_FOUND = "Player not found.";
private static final String MSG_PROFILE_LOCKED_CLONE = "Profile is locked; cannot clone slot.";
private static final String MSG_SOURCE_SLOT_NOT_EXIST = "Source slot does not exist.";
private static final String MSG_CANNOT_CLONE_CURRENT = "Cannot clone to the current active slot.";
private static final String MSG_INVALID_DEST_SLOT = "Invalid destination slot id.";
private static final String MSG_CLONE_SUCCESS = "Slot cloned successfully.";
private static final String MSG_PROFILE_LOCKED_REMOVE = "Profile is locked; cannot remove slot.";
private static final String MSG_CANNOT_REMOVE_ACTIVE = "Cannot remove the currently active slot.";
private static final String MSG_SLOT_NOT_EXIST = "Slot does not exist.";
private static final String MSG_REMOVE_SUCCESS = "Slot removed successfully.";
private static final String MSG_PROFILE_LOCKED_CREATE = "Profile is locked; cannot create slot.";
private static final String MSG_MAX_SLOTS_REACHED = "Maximum allowed slots reached.";
private static final String MSG_NEW_SLOT_CREATED = "New slot created successfully.";
private static final String MSG_PROFILE_LOCKED_CHANGE = "Profile is locked; cannot change slot.";
private static final String MSG_SLOT_ALREADY_ACTIVE = "Slot is already active.";
private static final String MSG_REGION_NOT_ALLOWED = "Profile switching not allowed from your current location.";
private static final String MSG_CHANGE_SUCCESS = "Slot changed successfully.";
private static final String MSG_CANCELLED = "Operation cancelled.";
public static Map<String, IProfileData> profileTypes = new HashMap<>();
public static Map<UUID, Profile> activeProfiles = new HashMap<>();
public static String profile_directory = "profiles";
public static ProfileController Instance;
public ProfileController() {
Instance = this;
profileTypes = new HashMap<>();
activeProfiles = new HashMap<>();
}
public static boolean registerProfileType(IProfileData type) {
if (profileTypes.containsKey(type.getTagName()))
return false;
profileTypes.put(type.getTagName(), type);
return true;
}
public static File getProfileDir() {
try {
File file = new File(CustomNpcs.getWorldSaveDirectory(), profile_directory);
if (!file.exists())
file.mkdir();
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static File getBackupDir() {
File base = getProfileDir();
File backup = new File(base, "backup");
if (!backup.exists()) {
backup.mkdir();
}
return backup;
}
public synchronized void login(EntityPlayer player) {
if (!ConfigMain.ProfilesEnabled)
return;
if (player == null)
return;
Profile profile;
if (activeProfiles.containsKey(player.getUniqueID())) {
profile = activeProfiles.get(player.getUniqueID());
profile.player = player;
} else {
NBTTagCompound compound = load(player);
profile = new Profile(player, compound);
if (profile.getSlots().isEmpty()) {
Slot defaultSlot = new Slot(0, "Default Slot");
defaultSlot.setLastLoaded(System.currentTimeMillis());
profile.getSlots().put(0, defaultSlot);
profile.currentSlotId = 0;
saveSlotData(player);
}
profile.player = player;
activeProfiles.put(player.getUniqueID(), profile);
verifySlotQuests(profile.player);
save(player, profile);
}
}
public synchronized NBTTagCompound load(EntityPlayer player) {
File saveDir = getProfileDir();
String filename = player.getUniqueID().toString() + ".dat";
try {
File file = new File(saveDir, filename);
if (file.exists()) {
return NBTJsonUtil.loadNBTData(file);
}
} catch (Exception e) {
LogWriter.error("Error loading profile file: " + filename, e);
}
return new NBTTagCompound();
}
public synchronized NBTTagCompound load(UUID uuid) {
File saveDir = getProfileDir();
String filename = uuid.toString() + ".dat";
try {
File file = new File(saveDir, filename);
if (file.exists()) {
return NBTJsonUtil.loadNBTData(file);
}
} catch (Exception e) {
LogWriter.error("Error loading profile file: " + filename, e);
}
return new NBTTagCompound();
}
public synchronized void saveOffline(Profile profile, UUID uuid) {
profile.setLocked(true);
CustomNPCsThreader.customNPCThread.execute(() -> {
final NBTTagCompound compound = profile.writeToNBT();
final String filename = uuid.toString() + ".dat";
try {
File saveDir = getProfileDir();
File fileNew = new File(saveDir, filename + "_new");
File fileOld = new File(saveDir, filename);
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(fileNew));
if (fileOld.exists()) {
fileOld.delete();
}
fileNew.renameTo(fileOld);
backupProfile(uuid, compound);
} catch (Exception e) {
LogWriter.except(e);
} finally {
profile.setLocked(false);
}
});
}
public synchronized void save(EntityPlayer player, Profile profile) {
profile.setLocked(true);
CustomNPCsThreader.customNPCThread.execute(() -> {
final NBTTagCompound compound = profile.writeToNBT();
final String filename = player.getUniqueID() + ".dat";
try {
File saveDir = getProfileDir();
File fileNew = new File(saveDir, filename + "_new");
File fileOld = new File(saveDir, filename);
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(fileNew));
if (fileOld.exists()) {
fileOld.delete();
}
fileNew.renameTo(fileOld);
if (ConfigMain.AllowProfileBackups) {
backupProfile(player.getUniqueID(), compound);
}
} catch (Exception e) {
LogWriter.except(e);
} finally {
profile.setLocked(false);
}
});
}
private void backupProfile(UUID uuid, NBTTagCompound compound) {
try {
File backupDir = new File(getBackupDir(), uuid.toString());
if (!backupDir.exists()) {
backupDir.mkdirs();
}
String dateStr = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File backupFile = new File(backupDir, dateStr + ".dat");
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(backupFile));
File[] backups = backupDir.listFiles((dir, name) -> name.endsWith(".dat"));
if (backups != null && backups.length > ConfigMain.ProfileBackupAmount) {
Arrays.sort(backups, Comparator.comparingLong(File::lastModified));
for (int i = 0; i < backups.length - ConfigMain.ProfileBackupAmount; i++) {
backups[i].delete();
}
}
} catch (Exception e) {
LogWriter.except(e);
}
}
public boolean rollbackProfile(String username, File backupFile) {
UUID uuid = getUUIDFromUsername(username);
if (uuid == null)
return false;
try (FileInputStream fis = new FileInputStream(backupFile)) {
NBTTagCompound compound = CompressedStreamTools.readCompressed(fis);
File saveDir = getProfileDir();
File mainFile = new File(saveDir, uuid.toString() + ".dat");
File fileNew = new File(saveDir, uuid.toString() + "_new");
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(fileNew));
if (mainFile.exists()) {
mainFile.delete();
}
fileNew.renameTo(mainFile);
EntityPlayer player = NoppesUtilServer.getPlayerByName(username);
Profile newProfile;
if (player != null) {
newProfile = new Profile(player, compound);
activeProfiles.put(uuid, newProfile);
loadSlotData(player);
return true;
}
} catch (Exception e) {
LogWriter.except(e);
}
return false;
}
public synchronized void logout(EntityPlayer player) {
if (player != null) {
activeProfiles.remove(player.getUniqueID());
}
}
public Profile getProfile(EntityPlayer player) {
if (player == null)
return null;
if (!activeProfiles.containsKey(player.getUniqueID()))
login(player);
return activeProfiles.get(player.getUniqueID());
}
public Profile getProfile(UUID uuid) {
if (activeProfiles.containsKey(uuid))
return activeProfiles.get(uuid);
NBTTagCompound compound = load(uuid);
return new Profile(null, compound);
}
public Profile getProfile(String username) {
EntityPlayer player = NoppesUtilServer.getPlayerByName(username);
if (player != null) {
return getProfile(player);
} else {
UUID uuid = getUUIDFromUsername(username);
if (uuid == null)
return null;
return getProfile(uuid);
}
}
public UUID getUUIDFromUsername(String username) {
try {
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + username);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder temp = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
temp.append(line);
}
in.close();
con.disconnect();
String response = temp.toString();
if (response.contains("\"id\"")) {
int idIndex = response.indexOf("\"id\"");
int colonIndex = response.indexOf(":", idIndex);
int quoteStart = response.indexOf("\"", colonIndex);
int quoteEnd = response.indexOf("\"", quoteStart + 1);
String idString = response.substring(quoteStart + 1, quoteEnd);
idString = idString.replaceFirst(
"(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)",
"$1-$2-$3-$4-$5"
);
return UUID.fromString(idString);
}
} catch (IOException e) {
LogWriter.error("Error retrieving UUID for " + username, e);
}
return null;
}
private int getNextAvailableTempSlot(Profile profile) {
int id = -1;
while (profile.getSlots().containsKey(id)) {
id--;
}
return id;
}
private ProfileOperation cloneSlotInternal(Profile profile, int sourceSlotId, int destinationSlotId, boolean temporary) {
if (profile.isLocked()) {
return ProfileOperation.locked(MSG_PROFILE_LOCKED_CLONE);
}
if (profile.player != null) {
List<IProfileData> dataList = new ArrayList<>(profileTypes.values());
dataList.sort(Comparator.comparingInt(IProfileData::getSwitchPriority));
for (IProfileData pd : dataList) {
if (pd.verifySwitch(profile.player).getResult() != EnumProfileOperation.SUCCESS) {
return pd.verifySwitch(profile.player);
}
}
}
if (!profile.getSlots().containsKey(sourceSlotId)) {
return ProfileOperation.error(MSG_SOURCE_SLOT_NOT_EXIST);
}
if (destinationSlotId == profile.getCurrentSlotId()) {
return ProfileOperation.error(MSG_CANNOT_CLONE_CURRENT);
}
if (temporary) {
destinationSlotId = getNextAvailableTempSlot(profile);
} else {
if (destinationSlotId <= 0) {
return ProfileOperation.error(MSG_INVALID_DEST_SLOT);
}
}
ISlot sourceSlot = profile.getSlots().get(sourceSlotId);
Map<String, NBTTagCompound> newComponents = new HashMap<>();
for (String key : sourceSlot.getComponents().keySet()) {
newComponents.put(key, (NBTTagCompound) sourceSlot.getComponentData(key).copy());
}
Slot clonedSlot = new Slot(destinationSlotId, "Cloned Slot " + destinationSlotId, System.currentTimeMillis(), temporary, newComponents);
profile.getSlots().put(destinationSlotId, clonedSlot);
return ProfileOperation.success(MSG_CLONE_SUCCESS);
}
private ProfileOperation removeSlotInternal(Profile profile, int slotId) {
if (profile.isLocked()) {
return ProfileOperation.locked(MSG_PROFILE_LOCKED_REMOVE);
}
if (slotId == profile.getCurrentSlotId()) {
return ProfileOperation.error(MSG_CANNOT_REMOVE_ACTIVE);
}
if (!profile.getSlots().containsKey(slotId)) {
return ProfileOperation.error(MSG_SLOT_NOT_EXIST);
}
PlayerDataScript handler = ScriptController.Instance.playerScripts;
if (profile.player != null) {
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
if (EventHooks.onProfileRemove(handler, scriptPlayer, profile, slotId, false))
return ProfileOperation.error(MSG_CANCELLED);
}
profile.getSlots().remove(slotId);
if (profile.player != null) {
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
EventHooks.onProfileRemove(handler, scriptPlayer, profile, slotId, true);
}
return ProfileOperation.success(MSG_REMOVE_SUCCESS);
}
public ProfileOperation createSlotInternal(Profile profile) {
if (profile.isLocked()) {
return ProfileOperation.locked(MSG_PROFILE_LOCKED_CREATE);
}
int newSlotId = 0;
while (profile.getSlots().containsKey(newSlotId)) {
newSlotId++;
}
if (!allowSlotPermission(profile.player)) {
return ProfileOperation.error(MSG_MAX_SLOTS_REACHED);
}
if (profile.player != null) {
List<IProfileData> dataList = new ArrayList<>(profileTypes.values());
dataList.sort(Comparator.comparingInt(IProfileData::getSwitchPriority));
for (IProfileData pd : dataList) {
if (pd.verifySwitch(profile.player).getResult() != EnumProfileOperation.SUCCESS) {
return pd.verifySwitch(profile.player);
}
}
}
PlayerDataScript handler = ScriptController.Instance.playerScripts;
if (profile.player != null) {
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
if (EventHooks.onProfileCreate(handler, scriptPlayer, profile, newSlotId, false))
return ProfileOperation.error(MSG_CANCELLED);
}
Slot newSlot = new Slot(newSlotId, "Slot " + newSlotId);
newSlot.setLastLoaded(System.currentTimeMillis());
profile.getSlots().put(newSlotId, newSlot);
if (profile.player != null) {
verifySlotQuests(profile.player);
save(profile.player, profile);
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
EventHooks.onProfileCreate(handler, scriptPlayer, profile, newSlotId, true);
}
return ProfileOperation.success(MSG_NEW_SLOT_CREATED);
}
private ProfileOperation changeSlotInternal(Profile profile, int newSlotId) {
if (profile.isLocked()) {
return ProfileOperation.locked(MSG_PROFILE_LOCKED_CHANGE);
}
if (profile.getCurrentSlotId() == newSlotId) {
return ProfileOperation.error(MSG_SLOT_ALREADY_ACTIVE);
}
if (!profile.getSlots().containsKey(newSlotId)) {
return ProfileOperation.error(MSG_SLOT_NOT_EXIST);
}
if (profile.player != null) {
if (ConfigMain.RegionProfileSwitching) {
boolean allowed = hasPermission(profile.player, PROFILE_REGION_BYPASS);
if (!allowed) {
int playerDim = profile.player.dimension;
int playerX = (int) profile.player.posX;
int playerY = (int) profile.player.posY;
int playerZ = (int) profile.player.posZ;
for (List<Integer> region : ConfigMain.RestrictedProfileRegions) {
if (region.size() == 7) {
int dim = region.get(0);
int x1 = Math.min(region.get(1), region.get(4));
int y1 = Math.min(region.get(2), region.get(5));
int z1 = Math.min(region.get(3), region.get(6));
int x2 = Math.max(region.get(1), region.get(4));
int y2 = Math.max(region.get(2), region.get(5));
int z2 = Math.max(region.get(3), region.get(6));
if (playerDim == dim &&
playerX >= x1 && playerX <= x2 &&
playerY >= y1 && playerY <= y2 &&
playerZ >= z1 && playerZ <= z2) {
allowed = true;
break;
}
}
}
}
if (!allowed) {
return ProfileOperation.error(MSG_REGION_NOT_ALLOWED);
}
}
List<IProfileData> dataList = new ArrayList<>(profileTypes.values());
dataList.sort(Comparator.comparingInt(IProfileData::getSwitchPriority));
for (IProfileData pd : dataList) {
if (pd.verifySwitch(profile.player).getResult() != EnumProfileOperation.SUCCESS) {
return pd.verifySwitch(profile.player);
}
}
int prevSlot = profile.getCurrentSlotId();
PlayerDataScript handler = ScriptController.Instance.playerScripts;
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
if (EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, false))
return ProfileOperation.error(MSG_CANCELLED);
saveSlotData(profile.player);
profile.currentSlotId = newSlotId;
loadSlotData(profile.player);
EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true);
} else {
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
}
return ProfileOperation.success(MSG_CHANGE_SUCCESS);
}
public ProfileOperation cloneSlot(EntityPlayer player, int sourceSlotId, int destinationSlotId, boolean temporary) {
Profile profile = getProfile(player);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = cloneSlotInternal(profile, sourceSlotId, destinationSlotId, temporary);
if (result.getResult() == EnumProfileOperation.SUCCESS && player != null) {
save(player, profile);
}
return result;
}
public ProfileOperation cloneSlot(UUID uuid, int sourceSlotId, int destinationSlotId, boolean temporary) {
Profile profile = getProfile(uuid);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = cloneSlotInternal(profile, sourceSlotId, destinationSlotId, temporary);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
if (profile.player != null)
save(profile.player, profile);
else
saveOffline(profile, uuid);
}
return result;
}
public ProfileOperation cloneSlot(String username, int sourceSlotId, int destinationSlotId, boolean temporary) {
Profile profile = getProfile(username);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = cloneSlotInternal(profile, sourceSlotId, destinationSlotId, temporary);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
if (profile.player != null)
save(profile.player, profile);
else {
UUID uuid = getUUIDFromUsername(username);
if (uuid != null)
saveOffline(profile, uuid);
}
}
return result;
}
public ProfileOperation removeSlot(EntityPlayer player, int slotId) {
Profile profile = getProfile(player);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = removeSlotInternal(profile, slotId);
if (result.getResult() == EnumProfileOperation.SUCCESS && player != null) {
save(player, profile);
}
return result;
}
public ProfileOperation removeSlot(String username, int slotId) {
Profile profile = getProfile(username);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = removeSlotInternal(profile, slotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
if (profile.player != null)
save(profile.player, profile);
else {
UUID uuid = getUUIDFromUsername(username);
if (uuid != null)
saveOffline(profile, uuid);
}
}
return result;
}
public ProfileOperation changeSlot(EntityPlayer player, int newSlotId) {
Profile profile = getProfile(player);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = changeSlotInternal(profile, newSlotId);
if (result.getResult() == EnumProfileOperation.SUCCESS && player != null)
save(player, profile);
return result;
}
public ProfileOperation changeSlot(String username, int newSlotId) {
Profile profile = getProfile(username);
if (profile == null)
return ProfileOperation.error(MSG_PLAYER_NOT_FOUND);
ProfileOperation result = changeSlotInternal(profile, newSlotId);
if (result.getResult() == EnumProfileOperation.SUCCESS) {
if (profile.player != null)
save(profile.player, profile);
else {
UUID uuid = getUUIDFromUsername(username);
if (uuid != null)
saveOffline(profile, uuid);
}
}
return result;
}
public void saveSlotData(EntityPlayer player) {
if (player == null || !activeProfiles.containsKey(player.getUniqueID()))
return;
Profile profile = activeProfiles.get(player.getUniqueID());
if (profile.isLocked()) {
return;
}
ISlot slot = profile.getSlots().get(profile.getCurrentSlotId());
if (slot == null) {
slot = new Slot(profile.getCurrentSlotId(), "Slot " + profile.getCurrentSlotId());
profile.getSlots().put(profile.getCurrentSlotId(), slot);
}
for (IProfileData profileData : profileTypes.values()) {
NBTTagCompound cloned = (NBTTagCompound) profileData.getCurrentNBT(player).copy();
slot.setComponentData(profileData.getTagName(), cloned);
}
slot.setLastLoaded(System.currentTimeMillis());
}
public void loadSlotData(EntityPlayer player) {
if (player == null || !activeProfiles.containsKey(player.getUniqueID()))
return;
Profile profile = activeProfiles.get(player.getUniqueID());
ISlot slot = profile.getSlots().get(profile.getCurrentSlotId());
if (slot == null)
return;
for (IProfileData profileData : profileTypes.values()) {
NBTTagCompound data;
if (slot.getComponents().containsKey(profileData.getTagName()))
data = slot.getComponentData(profileData.getTagName());
else
data = new NBTTagCompound();
profileData.setNBT(player, data);
}
for (IProfileData profileData : profileTypes.values()) {
profileData.save(player);
}
PlayerData pdata = PlayerData.get(player);
pdata.profileSlot = profile.getCurrentSlotId();
pdata.save();
if (ConfigMain.AttributesEnabled)
AttributeController.getTracker(player).recalcAttributes(player);
}
public List<ProfileInfoEntry> getProfileInfo(EntityPlayer player, int slotId) {
List<ProfileInfoEntry> infoList = new ArrayList<>();
Profile profile = getProfile(player);
if (profile == null)
return infoList;
List<IProfileData> dataList = new ArrayList<>(profileTypes.values());
dataList.sort(Comparator.comparingInt(IProfileData::getSwitchPriority));
if (slotId == profile.getCurrentSlotId()) {
for (IProfileData pd : dataList) {
NBTTagCompound currentNBT = pd.getCurrentNBT(player);
List<ProfileInfoEntry> subInfo = pd.getInfo(player, currentNBT);
infoList.addAll(subInfo);
}
} else {
if (!profile.getSlots().containsKey(slotId))
return infoList;
ISlot slot = profile.getSlots().get(slotId);
for (IProfileData pd : dataList) {
if (slot.getComponents().containsKey(pd.getTagName())) {
NBTTagCompound sub = slot.getComponentData(pd.getTagName());
List<ProfileInfoEntry> subInfo = pd.getInfo(player, sub);
infoList.addAll(subInfo);
}
}
}
return infoList;
}
public boolean allowSlotPermission(EntityPlayer player) {
Profile profile = getProfile(player);
int currentSlots = profile.getSlots().size();
if (CustomNpcsPermissions.hasCustomPermission(player, PROFILE_MAX.name)) {
return true;
}
int highestAllowed = 0;
for (int i = 1; i <= 50; i++) {
String perm = "customnpcs.profile.max." + i;
if (CustomNpcsPermissions.hasCustomPermission(player, perm)) {
highestAllowed = i;
}
}
if (highestAllowed == 0) {
highestAllowed = 1;
}
return currentSlots < highestAllowed;
}
@Override
public IProfile getProfile(IPlayer player) {
if (player == null || player.getMCEntity() == null)
return null;
return getProfile((EntityPlayer) player.getMCEntity());
}
@Override
public boolean changeSlot(IPlayer player, int slotID) {
if (player == null || player.getMCEntity() == null)
return false;
EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity();
ProfileOperation profileOperation = changeSlot(entityPlayer, slotID);
return profileOperation.getResult() == EnumProfileOperation.SUCCESS;
}
@Override
public boolean hasSlot(IPlayer player, int slotID) {
if (player == null || player.getMCEntity() == null)
return false;
EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity();
Profile profile = getProfile(entityPlayer);
if (profile == null)
return false;
return profile.getSlots().containsKey(slotID);
}
@Override
public boolean removeSlot(IPlayer player, int slotID) {
if (player == null || player.getMCEntity() == null)
return false;
EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity();
ProfileOperation profileOperation = removeSlot(entityPlayer, slotID);
return profileOperation.getResult() == EnumProfileOperation.SUCCESS;
}
@Override
public IPlayerData getSlotPlayerData(IPlayer player, int slotID) {
PlayerData playerData;
if (player == null || player.getMCEntity() == null)
return null;
EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity();
Profile profile = getProfile(entityPlayer);
if (profile == null)
return null;
return getSlotPlayerData(entityPlayer, slotID);
}
@Override
public void saveSlotData(IPlayer player) {
if (player == null || player.getMCEntity() == null)
return;
EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity();
saveSlotData(entityPlayer);
}
public IPlayerData getSlotPlayerData(EntityPlayer player, int slotID) {
PlayerData playerData;
Profile profile = getProfile(player);
if (profile == null)
return null;
if (profile.currentSlotId == slotID) {
playerData = PlayerData.get(player);
} else {
Slot slot = (Slot) profile.getSlots().get(slotID);
playerData = getSlotPlayerData(player, slot);
}
return playerData;
}
public PlayerData getSlotPlayerData(EntityPlayer player, Slot slot) {
if (slot == null)
return null;
PlayerData playerData = new PlayerData();
playerData.player = player;
NBTTagCompound compound = slot.getComponentData(new CNPCData().getTagName());
if (compound == null)
compound = new NBTTagCompound();
playerData.setNBT(compound);
return playerData;
}
public void verifySlotQuests(EntityPlayer player) {
Profile profile = getProfile(player);
if (profile == null) {
return;
}
Map<Integer, Long> universalFinished = new HashMap<>();
for (Integer questId : QuestController.Instance.sharedQuests.keySet()) {
long maxTime = 0;
for (ISlot slot : profile.getSlots().values()) {
IPlayerData data = getSlotPlayerData(player, slot.getId());
if (data == null) {
continue;
}
PlayerQuestData questData = (PlayerQuestData) data.getQuestData();
Long t = questData.finishedQuests.get(questId);
if (t != null && t > maxTime) {
maxTime = t;
}
}
if (maxTime > 0) {
universalFinished.put(questId, maxTime);
}
}
// Push the universal shared completion times into every slot.
for (ISlot slot : profile.getSlots().values()) {
IPlayerData data = getSlotPlayerData(player, slot.getId());
if (data != null) {
PlayerData playerData = (PlayerData) data;
PlayerQuestData questData = (PlayerQuestData) data.getQuestData();
questData.finishedQuests.putAll(universalFinished);
slot.setComponentData(new CNPCData().getTagName(), playerData.getNBT());
}
}
}
public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) {
Profile profile = getProfile(player);
if (profile == null) {
return;
}
for (ISlot slot : profile.getSlots().values()) {
IPlayerData playerData = getSlotPlayerData(player, slot.getId());
if (playerData != null) {
PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData();
Long existing = questData.finishedQuests.get(questId);
if (existing == null || completeTime > existing) {
questData.finishedQuests.put(questId, completeTime);
}
playerData.save();
}
}
save(player, profile);
}
}
@@ -0,0 +1,670 @@
package kamkeel.npcs.controllers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSyncAction;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.packets.data.LoginPacket;
import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
import kamkeel.npcs.network.packets.data.large.SyncPacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.controllers.*;
import noppes.npcs.controllers.data.*;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class SyncController {
public static void syncPlayer(EntityPlayerMP player) {
// Login Packet
PacketHandler.Instance.sendToPlayer(new LoginPacket(), player);
// 1) Factions
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.FACTION,
EnumSyncAction.RELOAD,
-1,
factionsNBT()
), player);
// 2) Dialog Categories
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.DIALOG_CATEGORY,
EnumSyncAction.RELOAD,
-1,
dialogCategoriesNBT()
), player);
// 3) Quest Categories
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.QUEST_CATEGORY,
EnumSyncAction.RELOAD,
-1,
questCategoriesNBT()
), player);
// 4) Workbench Recipes
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.WORKBENCH_RECIPES,
EnumSyncAction.RELOAD,
-1,
workbenchNBT()
), player);
// 5) Carpentry Recipes
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.CARPENTRY_RECIPES,
EnumSyncAction.RELOAD,
-1,
carpentryNBT()
), player);
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.ANVIL_RECIPES,
EnumSyncAction.RELOAD,
-1,
anvilNBT()
), player);
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.CUSTOM_EFFECTS,
EnumSyncAction.RELOAD,
-1,
customEffectsNBT()
), player);
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.MAGIC,
EnumSyncAction.RELOAD,
-1,
magicsNBT()
), player);
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.MAGIC_CYCLE,
EnumSyncAction.RELOAD,
-1,
magicCyclesNBT()
), player);
DBCAddon.instance.syncPlayer(player);
syncPlayerData(player, false);
}
public static NBTTagCompound workbenchNBT() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeCarpentry recipe : controller.globalRecipes.values()) {
list.appendTag(recipe.writeNBT());
}
compound.setTag("recipes", list);
return compound;
}
public static NBTTagCompound carpentryNBT() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) {
list.appendTag(recipe.writeNBT());
}
compound.setTag("recipes", list);
return compound;
}
public static NBTTagCompound anvilNBT() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeAnvil recipe : controller.anvilRecipes.values()) {
list.appendTag(recipe.writeNBT());
}
compound.setTag("recipes", list);
return compound;
}
public static NBTTagCompound factionsNBT() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Faction faction : FactionController.getInstance().factions.values()) {
NBTTagCompound factioNBT = new NBTTagCompound();
faction.writeNBT(factioNBT);
list.appendTag(factioNBT);
}
compound.setTag("Factions", list);
return compound;
}
public static NBTTagCompound dialogCategoriesNBT() {
NBTTagCompound compound = new NBTTagCompound();
NBTTagList categoryList = new NBTTagList();
for (DialogCategory category : DialogController.Instance.categories.values()) {
NBTTagCompound questCompound = new NBTTagCompound();
NBTTagList dialogList = new NBTTagList();
for (int dialogID : category.dialogs.keySet()) {
Dialog quest = category.dialogs.get(dialogID);
dialogList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", dialogList);
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
categoryList.appendTag(questCompound);
}
compound.setTag("DialogCategories", categoryList);
return compound;
}
public static NBTTagCompound questCategoriesNBT() {
NBTTagCompound compound = new NBTTagCompound();
NBTTagList categoryList = new NBTTagList();
for (QuestCategory category : QuestController.Instance.categories.values()) {
NBTTagCompound questCompound = new NBTTagCompound();
;
NBTTagList questList = new NBTTagList();
for (int questID : category.quests.keySet()) {
Quest quest = category.quests.get(questID);
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", questList);
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
categoryList.appendTag(questCompound);
}
compound.setTag("QuestCategories", categoryList);
return compound;
}
public static NBTTagCompound customEffectsNBT() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) {
list.appendTag(effect.writeToNBT(false));
}
compound.setTag("Data", list);
return compound;
}
public static NBTTagCompound magicsNBT() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Magic magic : MagicController.getInstance().magics.values()) {
NBTTagCompound magicCompound = new NBTTagCompound();
magic.writeNBT(magicCompound);
list.appendTag(magicCompound);
}
compound.setTag("Data", list);
return compound;
}
public static NBTTagCompound magicCyclesNBT() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
NBTTagCompound cycleCompound = new NBTTagCompound();
cycle.writeNBT(cycleCompound);
list.appendTag(cycleCompound);
}
compound.setTag("Data", list);
return compound;
}
public static void syncPlayerData(EntityPlayerMP player, boolean update) {
PlayerData data = PlayerData.get(player);
if (data != null) {
if (update) {
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.PLAYERDATA,
EnumSyncAction.UPDATE,
-1,
data.getSyncNBT())
, player);
} else {
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.PLAYERDATA,
EnumSyncAction.RELOAD,
-1,
data.getSyncNBTFull()), player);
}
}
}
public static void syncRemove(EnumSyncType enumSyncType, int id) {
PacketHandler.Instance.sendToAll(new SyncPacket(
enumSyncType,
EnumSyncAction.REMOVE,
id,
new NBTTagCompound()
));
}
public static void syncAllDialogs() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.DIALOG_CATEGORY,
EnumSyncAction.RELOAD,
-1,
dialogCategoriesNBT()
));
}
public static void syncAllQuests() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.QUEST_CATEGORY,
EnumSyncAction.RELOAD,
-1,
questCategoriesNBT()
));
}
public static void syncAllWorkbenchRecipes() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.WORKBENCH_RECIPES,
EnumSyncAction.RELOAD,
-1,
workbenchNBT()
));
}
public static void syncAllCarpentryRecipes() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.CARPENTRY_RECIPES,
EnumSyncAction.RELOAD,
-1,
carpentryNBT()
));
}
public static void syncAllAnvilRecipes() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.ANVIL_RECIPES,
EnumSyncAction.RELOAD,
-1,
anvilNBT()
));
}
public static void syncAllCustomEffects() {
PacketHandler.Instance.sendToAll(new SyncPacket(
EnumSyncType.CUSTOM_EFFECTS,
EnumSyncAction.RELOAD,
-1,
customEffectsNBT()
));
}
@SideOnly(Side.CLIENT)
public static void clientSync(EnumSyncType enumSyncType, NBTTagCompound fullCompound) {
switch (enumSyncType) {
case FACTION: {
NBTTagList list = fullCompound.getTagList("Factions", 10);
for (int i = 0; i < list.tagCount(); i++) {
Faction faction = new Faction();
faction.readNBT(list.getCompoundTagAt(i));
FactionController.getInstance().factionsSync.put(faction.id, faction);
}
FactionController.getInstance().factions = FactionController.getInstance().factionsSync;
FactionController.getInstance().factionsSync = new HashMap<Integer, Faction>();
break;
}
case DIALOG_CATEGORY: {
if (!fullCompound.hasNoTags()) {
NBTTagList categories = fullCompound.getTagList("DialogCategories", 10);
for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) {
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
if (categoryCompound.hasNoTags())
continue;
DialogCategory category = new DialogCategory();
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
NBTTagList dialogList = categoryCompound.getTagList("Data", 10);
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
category = DialogController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < dialogList.tagCount(); i++) {
Dialog dialog = new Dialog();
dialog.readNBT(dialogList.getCompoundTagAt(i));
dialog.category = category;
category.dialogs.put(dialog.id, dialog);
}
DialogController.Instance.categoriesSync.put(category.id, category);
}
}
HashMap<Integer, Dialog> dialogs = new HashMap<Integer, Dialog>();
for (DialogCategory category : DialogController.Instance.categoriesSync.values()) {
for (Dialog dialog : category.dialogs.values()) {
dialogs.put(dialog.id, dialog);
}
}
DialogController.Instance.categories = DialogController.Instance.categoriesSync;
DialogController.Instance.dialogs = dialogs;
DialogController.Instance.categoriesSync = new HashMap<Integer, DialogCategory>();
break;
}
case QUEST_CATEGORY: {
if (!fullCompound.hasNoTags()) {
NBTTagList categories = fullCompound.getTagList("QuestCategories", 10);
for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) {
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
if (categoryCompound.hasNoTags())
continue;
QuestCategory category = new QuestCategory();
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
NBTTagList questList = categoryCompound.getTagList("Data", 10);
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
category = QuestController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < questList.tagCount(); i++) {
Quest quest = new Quest();
quest.readNBT(questList.getCompoundTagAt(i));
quest.category = category;
category.quests.put(quest.id, quest);
}
QuestController.Instance.categoriesSync.put(category.id, category);
}
}
HashMap<Integer, Quest> quests = new HashMap<Integer, Quest>();
for (QuestCategory category : QuestController.Instance.categoriesSync.values()) {
for (Quest quest : category.quests.values()) {
quests.put(quest.id, quest);
}
}
QuestController.Instance.categories = QuestController.Instance.categoriesSync;
QuestController.Instance.quests = quests;
QuestController.Instance.categoriesSync = new HashMap<Integer, QuestCategory>();
break;
}
case PLAYERDATA: {
ClientCacheHandler.playerData.setSyncNBTFull(fullCompound);
break;
}
case MAGIC: {
NBTTagList list = fullCompound.getTagList("Data", 10);
MagicController mc = MagicController.getInstance();
mc.magicSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
Magic magic = new Magic();
magic.readNBT(list.getCompoundTagAt(i));
mc.magicSync.put(magic.id, magic);
}
mc.magics.clear();
mc.magics.putAll(mc.magicSync);
mc.magicSync.clear();
break;
}
case MAGIC_CYCLE: {
NBTTagList list = fullCompound.getTagList("Data", 10);
MagicController mc = MagicController.getInstance();
mc.cyclesSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
MagicCycle cycle = new MagicCycle();
cycle.readNBT(list.getCompoundTagAt(i));
mc.cyclesSync.put(cycle.id, cycle);
}
mc.cycles.clear();
mc.cycles.putAll(mc.cyclesSync);
mc.cyclesSync.clear();
break;
}
case WORKBENCH_RECIPES: {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
RecipeCarpentry recipe = RecipeCarpentry.read(list.getCompoundTagAt(i));
RecipeController.syncRecipes.put(recipe.id, recipe);
}
RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes);
RecipeController.syncRecipes = new HashMap<Integer, RecipeCarpentry>();
break;
}
case CARPENTRY_RECIPES: {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
RecipeCarpentry recipe = RecipeCarpentry.read(list.getCompoundTagAt(i));
RecipeController.syncRecipes.put(recipe.id, recipe);
}
RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes;
RecipeController.syncRecipes = new HashMap<Integer, RecipeCarpentry>();
break;
}
case ANVIL_RECIPES: {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
RecipeAnvil recipe = RecipeAnvil.read(list.getCompoundTagAt(i));
RecipeController.syncAnvilRecipes.put(recipe.id, recipe);
}
RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes;
RecipeController.syncAnvilRecipes = new HashMap<Integer, RecipeAnvil>();
break;
}
case CUSTOM_EFFECTS: {
NBTTagList list = fullCompound.getTagList("Data", 10);
CustomEffectController ce = CustomEffectController.getInstance();
ce.customEffectsSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
CustomEffect effect = new CustomEffect();
effect.readFromNBT(list.getCompoundTagAt(i));
ClientCacheHandler.getImageData(effect.icon);
ce.customEffectsSync.put(effect.id, effect);
}
ce.getCustomEffects().clear();
ce.getCustomEffects().putAll(ce.customEffectsSync);
ce.customEffectsSync.clear();
break;
}
}
}
/**
* Update Related Tasks
*/
@SideOnly(Side.CLIENT)
public static void clientUpdate(EnumSyncType enumSyncType, int category_id, NBTTagCompound compound) {
switch (enumSyncType) {
case FACTION: {
Faction faction = new Faction();
faction.readNBT(compound);
FactionController.getInstance().factions.put(faction.id, faction);
break;
}
case DIALOG: {
DialogCategory category = DialogController.Instance.categories.get(category_id);
Dialog dialog = new Dialog();
dialog.category = category;
dialog.readNBT(compound);
DialogController.Instance.dialogs.put(dialog.id, dialog);
category.dialogs.put(dialog.id, dialog);
break;
}
case QUEST: {
QuestCategory category = QuestController.Instance.categories.get(category_id);
Quest quest = new Quest();
quest.category = category;
quest.readNBT(compound);
QuestController.Instance.quests.put(quest.id, quest);
category.quests.put(quest.id, quest);
break;
}
case QUEST_CATEGORY: {
QuestCategory category = new QuestCategory();
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
NBTTagList list = compound.getTagList("Data", 10);
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
category = QuestController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < list.tagCount(); i++) {
Quest quest = new Quest();
quest.readNBT(list.getCompoundTagAt(i));
quest.category = category;
category.quests.put(quest.id, quest);
}
QuestController.Instance.categories.put(category.id, category);
break;
}
case DIALOG_CATEGORY: {
DialogCategory category = new DialogCategory();
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
NBTTagList list = compound.getTagList("Data", 10);
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
category = DialogController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < list.tagCount(); i++) {
Dialog dialog = new Dialog();
dialog.readNBT(list.getCompoundTagAt(i));
dialog.category = category;
category.dialogs.put(dialog.id, dialog);
}
DialogController.Instance.categories.put(category.id, category);
break;
}
case MAGIC_CYCLE: {
MagicCycle cycle = new MagicCycle();
cycle.readNBT(compound);
MagicController.getInstance().cycles.put(cycle.id, cycle);
break;
}
case MAGIC: {
Magic magic = new Magic();
magic.readNBT(compound);
MagicController.getInstance().magics.put(magic.id, magic);
break;
}
case PLAYERDATA: {
ClientCacheHandler.playerData.setSyncNBT(compound);
break;
}
case CUSTOM_EFFECTS: {
CustomEffect effect = new CustomEffect();
effect.readFromNBT(compound);
ClientCacheHandler.getImageData(effect.icon);
CustomEffectController.Instance.getCustomEffects().put(effect.id, effect);
break;
}
}
}
public static void syncUpdate(EnumSyncType type, int cat, NBTTagCompound compound) {
PacketHandler.Instance.sendToAll(new SyncPacket(
type,
EnumSyncAction.UPDATE,
cat,
compound
));
}
public static NBTTagCompound updateQuestCat(QuestCategory questCategory) {
NBTTagCompound questCompound = new NBTTagCompound();
NBTTagList questList = new NBTTagList();
for (int questID : questCategory.quests.keySet()) {
Quest quest = questCategory.quests.get(questID);
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", questList);
questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound()));
return questCompound;
}
public static NBTTagCompound updateDialogCat(DialogCategory dialogCategory) {
NBTTagCompound dialogCompound = new NBTTagCompound();
NBTTagList dialogList = new NBTTagList();
for (int questID : dialogCategory.dialogs.keySet()) {
Dialog dialog = dialogCategory.dialogs.get(questID);
dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound()));
}
dialogCompound.setTag("Data", dialogList);
dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound()));
return dialogCompound;
}
@SideOnly(Side.CLIENT)
public static void clientSyncRemove(EnumSyncType enumSyncType, int id) {
switch (enumSyncType) {
case FACTION:
FactionController.getInstance().factions.remove(id);
break;
case DIALOG:
Dialog dialog = DialogController.Instance.dialogs.remove(id);
if (dialog != null) {
dialog.category.dialogs.remove(id);
}
break;
case DIALOG_CATEGORY:
DialogCategory dialogCategory = DialogController.Instance.categories.remove(id);
if (dialogCategory != null) {
DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet());
}
break;
case QUEST:
Quest quest = QuestController.Instance.quests.remove(id);
if (quest != null) {
quest.category.quests.remove(id);
}
break;
case QUEST_CATEGORY:
QuestCategory questCategory = QuestController.Instance.categories.remove(id);
if (questCategory != null) {
QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet());
}
break;
case MAGIC:
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
cycle.associations.remove(id);
}
MagicController.getInstance().cycles.remove(id);
break;
case MAGIC_CYCLE:
MagicController.getInstance().cycles.remove(id);
break;
case CUSTOM_EFFECTS:
CustomEffectController.Instance.getCustomEffects().remove(id);
break;
}
}
public static void syncEffects(EntityPlayerMP playerMP) {
ConcurrentHashMap<EffectKey, PlayerEffect> playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP);
PlayerData playerData = PlayerData.get(playerMP);
playerData.effectData.setEffects(playerEffects);
NBTTagCompound compound = playerData.getPlayerEffects();
PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP);
}
@SideOnly(Side.CLIENT)
public static void clientSyncEffects(NBTTagCompound compound) {
PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
if (playerData != null) {
playerData.setPlayerEffects(compound);
}
}
}
@@ -0,0 +1,55 @@
package kamkeel.npcs.controllers.data.attribute;
public class AttributeDefinition {
private final String key;
private String translationKey;// e.g., "main_attack_flat"
private final String displayName; // Human‑readable name
private final char colorCode;
private final AttributeValueType attributeValueType;
private final AttributeSection section;
public AttributeDefinition(String key, String displayName, char colorCode, AttributeValueType attributeValueType, AttributeSection section) {
this.key = key;
this.translationKey = "rpgcore:attribute." + key;
this.displayName = displayName;
this.attributeValueType = attributeValueType;
this.section = section;
this.colorCode = colorCode;
}
public String getKey() {
return key;
}
public String getDisplayName() {
return displayName;
}
public String getTranslationKey() {
return translationKey;
}
public void setTranslationKey(String translationKey) {
this.translationKey = translationKey;
}
public AttributeValueType getValueType() {
return attributeValueType;
}
public AttributeSection getSection() {
return section;
}
public char getColorCode() {
return colorCode;
}
public enum AttributeSection {
BASE,
MODIFIER,
STATS,
INFO,
EXTRA;
}
}
@@ -0,0 +1,7 @@
package kamkeel.npcs.controllers.data.attribute;
public enum AttributeValueType {
FLAT, // e.g., +10 Health or +3 Damage
PERCENT, // e.g., +0.25 means +25% bonus
MAGIC // Represents a container of magic–based values (summed up as a float)
}
@@ -0,0 +1,12 @@
package kamkeel.npcs.controllers.data.attribute;
/**
* IAttributeInstance represents an instance of an attribute (with a base value and applied modifiers).
*/
public interface ICustomAttribute {
AttributeDefinition getAttribute();
float getValue();
void setValue(float value);
}
@@ -0,0 +1,27 @@
package kamkeel.npcs.controllers.data.attribute;
public class PlayerAttribute implements ICustomAttribute {
private final AttributeDefinition attribute;
private float baseValue;
public PlayerAttribute(AttributeDefinition attribute, float baseValue) {
this.attribute = attribute;
this.baseValue = baseValue;
}
@Override
public AttributeDefinition getAttribute() {
return attribute;
}
@Override
public float getValue() {
return baseValue;
}
@Override
public void setValue(float value) {
this.baseValue = value;
}
}
@@ -0,0 +1,29 @@
package kamkeel.npcs.controllers.data.attribute;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* CustomAttributeMap holds a set of attribute instances for an entity (or item).
*/
public class PlayerAttributeMap {
private final Map<AttributeDefinition, ICustomAttribute> map = new HashMap<>();
public ICustomAttribute registerAttribute(AttributeDefinition attribute, float baseValue) {
if (map.containsKey(attribute)) {
throw new IllegalArgumentException("Attribute already registered: " + attribute.getKey());
}
ICustomAttribute instance = new PlayerAttribute(attribute, baseValue);
map.put(attribute, instance);
return instance;
}
public ICustomAttribute getAttributeInstance(AttributeDefinition attribute) {
return map.get(attribute);
}
public Collection<ICustomAttribute> getAllAttributes() {
return map.values();
}
}
@@ -0,0 +1,21 @@
package kamkeel.npcs.controllers.data.attribute.requirement;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
public interface IRequirementChecker {
public String getKey();
public String getTranslation();
String getTooltipValue(NBTTagCompound nbt);
void apply(NBTTagCompound nbt, Object value);
/**
* Checks the requirement in the provided NBT.
* Return false if the requirement isn’t met.
*/
boolean check(EntityPlayer player, NBTTagCompound nbt);
}
@@ -0,0 +1,42 @@
package kamkeel.npcs.controllers.data.attribute.requirement;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class RequirementCheckerRegistry {
private static final Map<String, IRequirementChecker> checkers = new HashMap<>();
public static void registerChecker(IRequirementChecker checker) {
if (!checkers.containsKey(checker.getKey())) {
checkers.put(checker.getKey(), checker);
}
}
/**
* Loops over all registered requirement keys.
* For each key present in the NBT, its checker must return true.
*/
public static boolean checkRequirements(EntityPlayer player, NBTTagCompound nbt) {
for (Map.Entry<String, IRequirementChecker> entry : checkers.entrySet()) {
String reqKey = entry.getKey();
if (nbt.hasKey(reqKey)) {
if (!entry.getValue().check(player, nbt)) {
return false;
}
}
}
return true;
}
public static Set<String> getAllKeys() {
return checkers.keySet();
}
public static IRequirementChecker getChecker(String key) {
return checkers.get(key);
}
}
@@ -0,0 +1,47 @@
package kamkeel.npcs.controllers.data.attribute.requirement.types;
import kamkeel.npcs.controllers.data.attribute.requirement.IRequirementChecker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.data.PlayerData;
public class QuestActiveRequirement implements IRequirementChecker {
@Override
public String getKey() {
return "cnpc_quest_active";
}
@Override
public String getTranslation() {
return "quest.active";
}
@Override
public String getTooltipValue(NBTTagCompound nbt) {
if (nbt.hasKey(getKey())) {
int questID = nbt.getInteger(getKey());
if (QuestController.Instance.get(questID) != null) {
return QuestController.Instance.get(questID).getName();
}
}
return "null";
}
@Override
public void apply(NBTTagCompound nbt, Object value) {
if (value instanceof Integer) {
nbt.setInteger(getKey(), (Integer) value);
}
}
@Override
public boolean check(EntityPlayer player, NBTTagCompound nbt) {
if (nbt.hasKey(getKey())) {
int questID = nbt.getInteger(getKey());
return PlayerData.get(player).questData.hasActiveQuest(questID);
}
return true;
}
}
@@ -0,0 +1,47 @@
package kamkeel.npcs.controllers.data.attribute.requirement.types;
import kamkeel.npcs.controllers.data.attribute.requirement.IRequirementChecker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.data.PlayerData;
public class QuestCompletedRequirement implements IRequirementChecker {
@Override
public String getKey() {
return "cnpc_quest_completed";
}
@Override
public String getTranslation() {
return "quest.quest";
}
@Override
public String getTooltipValue(NBTTagCompound nbt) {
if (nbt.hasKey(getKey())) {
int questID = nbt.getInteger(getKey());
if (QuestController.Instance.get(questID) != null) {
return QuestController.Instance.get(questID).getName();
}
}
return "null";
}
@Override
public void apply(NBTTagCompound nbt, Object value) {
if (value instanceof Integer) {
nbt.setInteger(getKey(), (Integer) value);
}
}
@Override
public boolean check(EntityPlayer player, NBTTagCompound nbt) {
if (nbt.hasKey(getKey())) {
int questID = nbt.getInteger(getKey());
return PlayerData.get(player).questData.hasFinishedQuest(questID);
}
return true;
}
}
@@ -0,0 +1,28 @@
package kamkeel.npcs.controllers.data.attribute.tracker;
import net.minecraft.entity.player.EntityPlayer;
import java.util.ArrayList;
import java.util.List;
public class AttributeRecalcEvent {
private static final List<IAttributeRecalcListener> listeners = new ArrayList<>();
/**
* Allows other mods to register a listener that is called after attribute recalculation.
*/
public static void registerListener(IAttributeRecalcListener listener) {
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
/**
* Posts an event to all registered listeners.
*/
public static void post(EntityPlayer player, PlayerAttributeTracker tracker) {
for (IAttributeRecalcListener listener : listeners) {
listener.onAttributesRecalculated(player, tracker);
}
}
}
@@ -0,0 +1,10 @@
package kamkeel.npcs.controllers.data.attribute.tracker;
import net.minecraft.entity.player.EntityPlayer;
/**
* Implement this interface to receive a callback after a player's attributes have been recalculated.
*/
public interface IAttributeRecalcListener {
void onAttributesRecalculated(EntityPlayer player, PlayerAttributeTracker tracker);
}
@@ -0,0 +1,170 @@
package kamkeel.npcs.controllers.data.attribute.tracker;
import kamkeel.npcs.CustomAttributes;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.ICustomAttribute;
import kamkeel.npcs.controllers.data.attribute.PlayerAttributeMap;
import kamkeel.npcs.controllers.data.attribute.requirement.RequirementCheckerRegistry;
import kamkeel.npcs.util.AttributeAttackUtil;
import kamkeel.npcs.util.AttributeItemUtil;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
public class PlayerAttributeTracker {
public static UUID healthUUID = UUID.fromString("48a0ad75-2cf8-4838-ad2f-9a0aadc57dfe");
private final UUID playerId;
private PlayerAttributeMap playerAttributes = new PlayerAttributeMap();
public float extraHealth = 0;
public float gearOutput = 0.0f;
public final Map<Integer, Float> magicDamage = new HashMap<>();
public final Map<Integer, Float> magicBoost = new HashMap<>();
public final Map<Integer, Float> magicDefense = new HashMap<>();
public final Map<Integer, Float> magicResistance = new HashMap<>();
private PlayerEquipmentTracker equipmentTracker = new PlayerEquipmentTracker();
public PlayerAttributeTracker(UUID playerId) {
this.playerId = playerId;
// Initial recalc with base damage 0.
recalcAttributes(null);
}
public PlayerAttributeMap getPlayerAttributes() {
return playerAttributes;
}
public void recalcAttributes(EntityPlayer player) {
// Reset aggregated attributes and magic maps.
playerAttributes = new PlayerAttributeMap();
magicDamage.clear();
magicBoost.clear();
magicDefense.clear();
magicResistance.clear();
if (player != null) {
// Update equipment tracker.
PlayerEquipmentTracker currentEquip = new PlayerEquipmentTracker();
currentEquip.updateFrom(player);
ItemStack[] equipment = new ItemStack[]{currentEquip.heldItem, currentEquip.boots, currentEquip.leggings, currentEquip.chestplate, currentEquip.helmet};
for (ItemStack piece : equipment) {
if (piece != null) {
if (piece.stackTagCompound != null && piece.stackTagCompound.hasKey(AttributeItemUtil.TAG_RPGCORE)) {
NBTTagCompound rpgCore = piece.stackTagCompound.getCompoundTag(AttributeItemUtil.TAG_RPGCORE);
if (rpgCore.hasKey(AttributeItemUtil.TAG_REQUIREMENTS)) {
NBTTagCompound reqTag = rpgCore.getCompoundTag(AttributeItemUtil.TAG_REQUIREMENTS);
if (!RequirementCheckerRegistry.checkRequirements(player, reqTag)) {
continue;
}
}
}
for (Entry<String, Float> entry : AttributeItemUtil.readAttributes(piece).entrySet()) {
String key = entry.getKey();
float value = entry.getValue();
AttributeDefinition def = AttributeController.getAttribute(key);
if (def != null) {
ICustomAttribute inst = playerAttributes.getAttributeInstance(def);
if (inst == null) {
inst = playerAttributes.registerAttribute(def, 0.0f);
}
inst.setValue(inst.getValue() + value);
}
}
// Process Magic
// OFFENSIVE MAGIC
Map<Integer, Float> magicFlat = AttributeItemUtil.readMagicAttributeMap(piece, CustomAttributes.MAGIC_DAMAGE_KEY);
for (Entry<Integer, Float> entry : magicFlat.entrySet()) {
int magicId = entry.getKey();
float value = entry.getValue();
magicDamage.put(magicId, magicDamage.getOrDefault(magicId, 0.0f) + value);
}
Map<Integer, Float> magicPercent = AttributeItemUtil.readMagicAttributeMap(piece, CustomAttributes.MAGIC_BOOST_KEY);
for (Entry<Integer, Float> entry : magicPercent.entrySet()) {
int magicId = entry.getKey();
float value = entry.getValue();
magicBoost.put(magicId, magicBoost.getOrDefault(magicId, 0.0f) + value);
}
// DEFENSIVE MAGIC
Map<Integer, Float> magicDefFlat = AttributeItemUtil.readMagicAttributeMap(piece, CustomAttributes.MAGIC_DEFENSE_KEY);
for (Entry<Integer, Float> entry : magicDefFlat.entrySet()) {
int magicId = entry.getKey();
float value = entry.getValue();
magicDefense.put(magicId, magicDefense.getOrDefault(magicId, 0.0f) + value);
}
Map<Integer, Float> magicResist = AttributeItemUtil.readMagicAttributeMap(piece, CustomAttributes.MAGIC_RESISTANCE_KEY);
for (Entry<Integer, Float> entry : magicResist.entrySet()) {
int magicId = entry.getKey();
float value = entry.getValue();
magicResistance.put(magicId, magicResistance.getOrDefault(magicId, 0.0f) + value);
}
}
}
equipmentTracker = currentEquip;
gearOutput = AttributeAttackUtil.calculateGearOutput(this);
extraHealth = getAttributeValue(CustomAttributes.HEALTH);
updatePlayerMaxHealth(player);
// Post Recalculation Event to Listeners
AttributeRecalcEvent.post(player, this);
}
}
/**
* Updates the player's maximum health attribute by applying a custom attribute modifier.
* In this system, the aggregated HEALTH attribute is treated as bonus health on top of a base of 20.
*
* @param player The EntityPlayer whose max health should be updated.
*/
public void updatePlayerMaxHealth(EntityPlayer player) {
float bonusHealth = extraHealth;
IAttributeInstance maxHealthAttr = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.maxHealth);
try {
AttributeModifier old = maxHealthAttr.getModifier(healthUUID);
if (old != null) {
maxHealthAttr.removeModifier(old);
}
} catch (Exception ignored) {
}
if (bonusHealth != 0) {
maxHealthAttr.applyModifier(new AttributeModifier(healthUUID, "RPGCoreHealthBonus", bonusHealth, 0));
}
// Ensure the player's current health does not exceed the new maximum.
float currentHealth = player.getHealth();
if (currentHealth > maxHealthAttr.getAttributeValue()) {
player.setHealth((float) maxHealthAttr.getAttributeValue());
}
}
/**
* Checks if the player's equipment has changed and recalculates attributes if needed.
*/
public void updateIfChanged(EntityPlayer player) {
PlayerEquipmentTracker currentEquip = new PlayerEquipmentTracker();
currentEquip.updateFrom(player);
if (!equipmentTracker.equals(player)) {
recalcAttributes(player);
}
}
public float getAttributeValue(AttributeDefinition def) {
ICustomAttribute inst = playerAttributes.getAttributeInstance(def);
return inst != null ? inst.getValue() : 0.0f;
}
}
@@ -0,0 +1,66 @@
package kamkeel.npcs.controllers.data.attribute.tracker;
import kamkeel.npcs.util.AttributeItemUtil;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class PlayerEquipmentTracker {
public ItemStack heldItem;
public ItemStack helmet;
public ItemStack chestplate;
public ItemStack leggings;
public ItemStack boots;
/**
* Updates the stored equipment based on the player's current held item and armor.
*/
public void updateFrom(EntityPlayer player) {
heldItem = copyIfNotNull(player.getHeldItem());
ItemStack[] armor = player.inventory.armorInventory;
// Armor inventory order: 0=boots, 1=leggings, 2=chestplate, 3=helmet.
boots = copyIfNotNull(armor[0]);
leggings = copyIfNotNull(armor[1]);
chestplate = copyIfNotNull(armor[2]);
helmet = copyIfNotNull(armor[3]);
}
/**
* Compares the stored equipment with the player's current equipment.
* Ignores changes like durability by comparing the item and the CNPCAttributes NBT only.
*/
public boolean equals(EntityPlayer player) {
if (player == null) return false;
if (!areItemStacksEquivalent(heldItem, player.getHeldItem())) return false;
ItemStack[] armor = player.inventory.armorInventory;
if (!areItemStacksEquivalent(boots, armor[0])) return false;
if (!areItemStacksEquivalent(leggings, armor[1])) return false;
if (!areItemStacksEquivalent(chestplate, armor[2])) return false;
if (!areItemStacksEquivalent(helmet, armor[3])) return false;
return true;
}
/**
* Returns a copy of the given ItemStack, or null if it is null.
*/
private ItemStack copyIfNotNull(ItemStack stack) {
return (stack == null) ? null : stack.copy();
}
/**
* Compares two ItemStacks for equivalence, ignoring durability differences.
* It checks if the items are the same and if the "CNPCAttributes" NBT compound is equal.
*/
private boolean areItemStacksEquivalent(ItemStack a, ItemStack b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (a.getItem() != b.getItem()) return false;
NBTTagCompound tagA = a.stackTagCompound;
NBTTagCompound tagB = b.stackTagCompound;
String attrA = (tagA != null && tagA.hasKey(AttributeItemUtil.TAG_RPGCORE))
? tagA.getCompoundTag(AttributeItemUtil.TAG_RPGCORE).toString() : "";
String attrB = (tagB != null && tagB.hasKey(AttributeItemUtil.TAG_RPGCORE))
? tagB.getCompoundTag(AttributeItemUtil.TAG_RPGCORE).toString() : "";
return attrA.equals(attrB);
}
}
@@ -0,0 +1,71 @@
package kamkeel.npcs.controllers.data.profile;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
import java.util.List;
public class CNPCData implements IProfileData {
@Override
public String getTagName() {
return "CNPC+";
}
@Override
public NBTTagCompound getCurrentNBT(EntityPlayer player) {
PlayerData customNPCData = PlayerData.get(player);
return customNPCData.getNBT();
}
@Override
public void save(EntityPlayer player) {
PlayerData customNPCData = PlayerData.get(player);
customNPCData.save();
SyncController.syncPlayerData((EntityPlayerMP) player, false);
}
@Override
public void setNBT(EntityPlayer player, NBTTagCompound replace) {
PlayerData customNPCData = PlayerData.get(player);
if (replace.hasNoTags()) {
PlayerData newData = new PlayerData();
newData.player = player;
customNPCData.setNBT((NBTTagCompound) newData.getNBT().copy());
} else {
customNPCData.setNBT(replace);
}
customNPCData.updateClient = true;
}
@Override
public int getSwitchPriority() {
return 0;
}
@Override
public ProfileOperation verifySwitch(EntityPlayer player) {
PlayerData playerData = PlayerData.get(player);
if (playerData.partyUUID != null)
return ProfileOperation.error("Cannot switch while in Party");
return ProfileOperation.success("");
}
@Override
public List<ProfileInfoEntry> getInfo(EntityPlayer player, NBTTagCompound compound) {
PlayerData playerData = new PlayerData();
playerData.player = player;
playerData.setNBT(compound);
List<ProfileInfoEntry> info = new ArrayList<>();
info.add(new ProfileInfoEntry("profile.info.quest.finished", 0x60fa57, playerData.questData.finishedQuests.size(), 0xFFFFFF));
info.add(new ProfileInfoEntry("profile.info.quest.active", 0xf75336, playerData.questData.activeQuests.size(), 0xFFFFFF));
info.add(new ProfileInfoEntry("profile.info.dialog.read", 0x47acf5, playerData.dialogData.dialogsRead.size(), 0xFFFFFF));
return info;
}
}
@@ -0,0 +1,7 @@
package kamkeel.npcs.controllers.data.profile;
public enum EnumProfileOperation {
SUCCESS,
ERROR,
LOCKED
}
@@ -0,0 +1,55 @@
package kamkeel.npcs.controllers.data.profile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
public interface IProfileData {
/**
* Do not use the tags: Name, lastLoaded, ID.
*
* @return The save tag utilized in the Profile.
*/
public String getTagName();
/**
* @return NBTTagCompound of the current data for a given EntityPlayer.
*/
public NBTTagCompound getCurrentNBT(EntityPlayer player);
/**
* Called immediately after setNBT() to replace existing NBT.
*/
public void save(EntityPlayer player);
/**
* Replaces the current data operation when changing profiles.
*/
public void setNBT(EntityPlayer player, NBTTagCompound replace);
/**
* Returns the priority for this ProfileData's verification check.
* Lower numbers run first.
*/
public int getSwitchPriority();
/**
* Called before a profile switch occurs.
*
* @param player The player switching profiles.
* @return true if allowed, false if not.
*/
public ProfileOperation verifySwitch(EntityPlayer player);
/**
* NEW: Builds and returns a list of informational strings about this profile data,
* based on the provided NBTTagCompound from the slot.
*
* @param player The player in question.
* @param compound The NBT data from the slot under this profile data's tag.
* @return A list of InfoEntry with information
*/
public List<ProfileInfoEntry> getInfo(EntityPlayer player, NBTTagCompound compound);
}
@@ -0,0 +1,92 @@
package kamkeel.npcs.controllers.data.profile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.api.handler.data.IProfile;
import noppes.npcs.api.handler.data.ISlot;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Profile implements IProfile {
public EntityPlayer player;
public int currentSlotId;
private Map<Integer, ISlot> slots = new HashMap<>();
private boolean locked = false;
public Profile(EntityPlayer player, NBTTagCompound compound) {
this.player = player;
if (compound.hasKey("CurrentSlotId")) {
this.currentSlotId = compound.getInteger("CurrentSlotId");
} else {
this.currentSlotId = 0;
}
if (compound.hasKey("Slots")) {
NBTTagCompound slotsCompound = compound.getCompoundTag("Slots");
Set<String> keys = slotsCompound.func_150296_c();
for (String key : keys) {
try {
int slotId = Integer.parseInt(key);
NBTTagCompound slotNBT = slotsCompound.getCompoundTag(key);
ISlot slot = Slot.fromNBT(slotId, slotNBT);
slots.put(slotId, slot);
} catch (NumberFormatException e) {
// Skip keys that are not valid slot IDs.
}
}
}
}
public Profile(EntityPlayer player) {
this.player = player;
this.currentSlotId = 0;
// Create a default slot.
Slot defaultSlot = new Slot(0, "Default Slot");
defaultSlot.setLastLoaded(System.currentTimeMillis());
slots.put(0, defaultSlot);
}
@Override
public IPlayer getPlayer() {
return NoppesUtilServer.getIPlayer(player);
}
@Override
public int getCurrentSlotId() {
return currentSlotId;
}
@Override
public Map<Integer, ISlot> getSlots() {
return slots;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Override
public NBTTagCompound writeToNBT() {
NBTTagCompound compound = new NBTTagCompound();
if (player != null)
compound.setString("Name", player.getCommandSenderName());
compound.setInteger("CurrentSlotId", currentSlotId);
NBTTagCompound slotsCompound = new NBTTagCompound();
for (Map.Entry<Integer, ISlot> entry : slots.entrySet()) {
// Save only non-temporary slots.
if (entry.getValue().isTemporary())
continue;
slotsCompound.setTag(String.valueOf(entry.getKey()), entry.getValue().toNBT());
}
compound.setTag("Slots", slotsCompound);
return compound;
}
}
@@ -0,0 +1,62 @@
package kamkeel.npcs.controllers.data.profile;
import net.minecraft.nbt.NBTTagCompound;
public class ProfileInfoEntry {
private String label;
private String result;
private int labelColor;
private int resultColor;
public ProfileInfoEntry() {
}
public ProfileInfoEntry(String label, int labelColor, String result, int resultColor) {
this.label = label;
this.result = result;
this.labelColor = labelColor;
this.resultColor = resultColor;
}
public ProfileInfoEntry(String label, int labelColor, int result, int resultColor) {
this(label, labelColor, String.valueOf(result), resultColor);
}
public ProfileInfoEntry(String label, String result) {
this(label, 0xFFFFFF, result, 0xFFFFFF);
}
public NBTTagCompound writeToNBT() {
NBTTagCompound tag = new NBTTagCompound();
tag.setString("Label", label);
tag.setInteger("LabelColor", labelColor);
tag.setString("Result", result);
tag.setInteger("ResultColor", resultColor);
return tag;
}
public static ProfileInfoEntry readFromNBT(NBTTagCompound tag) {
return new ProfileInfoEntry(
tag.getString("Label"),
tag.getInteger("LabelColor"),
tag.getString("Result"),
tag.getInteger("ResultColor")
);
}
public String getLabel() {
return label;
}
public String getResult() {
return result;
}
public int getLabelColor() {
return labelColor;
}
public int getResultColor() {
return resultColor;
}
}
@@ -0,0 +1,31 @@
package kamkeel.npcs.controllers.data.profile;
public class ProfileOperation {
private final EnumProfileOperation result;
private final String message;
public ProfileOperation(EnumProfileOperation result, String message) {
this.result = result;
this.message = message;
}
public EnumProfileOperation getResult() {
return result;
}
public String getMessage() {
return message;
}
public static ProfileOperation success(String message) {
return new ProfileOperation(EnumProfileOperation.SUCCESS, message);
}
public static ProfileOperation error(String message) {
return new ProfileOperation(EnumProfileOperation.ERROR, message);
}
public static ProfileOperation locked(String message) {
return new ProfileOperation(EnumProfileOperation.LOCKED, message);
}
}
@@ -0,0 +1,114 @@
package kamkeel.npcs.controllers.data.profile;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.handler.data.ISlot;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Slot implements ISlot {
private int id;
private String name;
private long lastLoaded;
private boolean temporary;
private Map<String, NBTTagCompound> components = new HashMap<>();
public Slot(int id, String name) {
this.id = id;
this.name = name;
}
public Slot(int id, String name, long lastLoaded, boolean temporary, Map<String, NBTTagCompound> components) {
this.id = id;
this.name = name;
this.lastLoaded = lastLoaded;
this.temporary = temporary;
this.components = components;
}
@Override
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public long getLastLoaded() {
return lastLoaded;
}
@Override
public void setLastLoaded(long time) {
this.lastLoaded = time;
}
@Override
public boolean isTemporary() {
return temporary;
}
@Override
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
@Override
public Map<String, NBTTagCompound> getComponents() {
return components;
}
@Override
public void setComponentData(String key, NBTTagCompound data) {
components.put(key, data);
}
@Override
public NBTTagCompound getComponentData(String key) {
return components.get(key);
}
@Override
public NBTTagCompound toNBT() {
NBTTagCompound slotNBT = new NBTTagCompound();
slotNBT.setString("Name", name);
slotNBT.setLong("LastLoaded", lastLoaded);
slotNBT.setBoolean("Temporary", temporary);
NBTTagCompound compCompound = new NBTTagCompound();
for (Map.Entry<String, NBTTagCompound> entry : components.entrySet()) {
compCompound.setTag(entry.getKey(), entry.getValue());
}
slotNBT.setTag("Components", compCompound);
return slotNBT;
}
public static Slot fromNBT(int id, NBTTagCompound slotNBT) {
String name = slotNBT.getString("Name");
long lastLoaded = slotNBT.getLong("LastLoaded");
boolean temporary = slotNBT.getBoolean("Temporary");
Slot slot = new Slot(id, name);
slot.setLastLoaded(lastLoaded);
slot.setTemporary(temporary);
if (slotNBT.hasKey("Components")) {
NBTTagCompound compCompound = slotNBT.getCompoundTag("Components");
Set<String> keys = compCompound.func_150296_c();
for (String key : keys) {
slot.setComponentData(key, compCompound.getCompoundTag(key));
}
}
return slot;
}
}
@@ -1,4 +1,4 @@
package kamkeel.developer; package kamkeel.npcs.developer;
import java.util.HashSet; import java.util.HashSet;
import java.util.UUID; import java.util.UUID;
@@ -0,0 +1,62 @@
package kamkeel.npcs.network;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.entity.EntityNPCInterface;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public abstract class AbstractPacket {
public EntityNPCInterface npc;
public FMLProxyPacket generatePacket() {
PacketChannel packetChannel = getChannel();
ByteBuf buf = Unpooled.buffer();
try {
buf.writeInt(packetChannel.getChannelType().ordinal());
buf.writeInt(getType().ordinal());
sendData(buf);
return new FMLProxyPacket(buf, packetChannel.getChannelName());
} catch (Exception e) {
// For debugging, you might want to log it
e.printStackTrace();
}
return null;
}
public List<FMLProxyPacket> generatePackets() {
FMLProxyPacket single = generatePacket();
if (single == null) {
return Collections.emptyList();
}
return Collections.singletonList(single);
}
public abstract Enum getType();
public abstract PacketChannel getChannel();
public CustomNpcsPermissions.Permission getPermission() {
return null;
}
public boolean needsNPC() {
return false;
}
public void setNPC(EntityNPCInterface npc) {
this.npc = npc;
}
public abstract void sendData(ByteBuf out) throws IOException;
//"player" on the server side is the client who sent this packet
//"player" on the client side is the client player
public abstract void receiveData(ByteBuf in, EntityPlayer player) throws IOException;
}
@@ -0,0 +1,164 @@
package kamkeel.npcs.network;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.LogWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public abstract class LargeAbstractPacket extends AbstractPacket {
private static final Map<UUID, PacketStorage> packetChunks = new ConcurrentHashMap<>();
private static final int CHUNK_SIZE = 10000;
/**
* Create multiple FMLProxyPacket objects, each containing up to CHUNK_SIZE bytes.
*/
@Override
public List<FMLProxyPacket> generatePackets() {
List<FMLProxyPacket> packets = new ArrayList<>();
PacketChannel packetChannel = getChannel();
byte[] fullData;
try {
fullData = getData();
} catch (IOException e) {
e.printStackTrace();
return packets;
}
int totalSize = fullData.length;
UUID packetId = UUID.randomUUID();
// Break data into CHUNK_SIZE chunks
for (int offset = 0; offset < totalSize; offset += CHUNK_SIZE) {
int chunkSize = Math.min(CHUNK_SIZE, totalSize - offset);
ByteBuf chunkBuf = Unpooled.buffer();
chunkBuf.writeInt(packetChannel.getChannelType().ordinal());
chunkBuf.writeInt(getType().ordinal());
chunkBuf.writeLong(packetId.getMostSignificantBits());
chunkBuf.writeLong(packetId.getLeastSignificantBits());
chunkBuf.writeInt(totalSize);
chunkBuf.writeInt(offset);
chunkBuf.writeInt((totalSize + CHUNK_SIZE - 1) / CHUNK_SIZE);
chunkBuf.writeBytes(fullData, offset, chunkSize);
FMLProxyPacket proxyPacket = new FMLProxyPacket(chunkBuf, packetChannel.getChannelName());
packets.add(proxyPacket);
}
return packets;
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
UUID packetId = null;
PacketStorage storage = null;
ByteBuf chunk = null;
ByteBuf completeData = null;
try {
// Read UUID from the buffer
long mostSigBits = in.readLong();
long leastSigBits = in.readLong();
packetId = new UUID(mostSigBits, leastSigBits);
// Read packet metadata
int totalSize = in.readInt();
int offset = in.readInt();
int totalChunks = in.readInt(); // Debugging info
int chunkSize = Math.min(CHUNK_SIZE, totalSize - offset);
// Basic validation to ensure the chunk won't overwrite out of bounds
if (chunkSize <= 0 || offset < 0 || (offset + chunkSize) > totalSize) {
throw new IndexOutOfBoundsException("Invalid chunk size/offset: chunkSize="
+ chunkSize + ", offset=" + offset + ", totalSize=" + totalSize);
}
// Read the exact chunk data
chunk = in.readBytes(chunkSize);
// Store the received chunk in a PacketStorage
storage = packetChunks.computeIfAbsent(packetId, k -> new PacketStorage(Unpooled.buffer(totalSize), 0, totalSize));
// Write this chunk into the buffer at the correct offset
storage.data.setBytes(offset, chunk);
storage.receivedSoFar += chunkSize;
// If we've received all bytes, finalize
if (storage.receivedSoFar >= totalSize) {
packetChunks.remove(packetId);
completeData = storage.data.copy(0, totalSize);
try {
handleCompleteData(completeData, player);
} finally {
completeData.release();
}
storage.data.release();
}
} catch (Exception e) {
// Log the exception with contextual information
LogWriter.error("Error in receiveData for packetId " + (packetId != null ? packetId.toString() : "null") + ": " + e.getMessage());
e.printStackTrace();
// If storage was created but the packet is incomplete, release storage.data
if (storage != null && storage.receivedSoFar < storage.totalSize) {
storage.data.release();
if (packetId != null) {
packetChunks.remove(packetId);
}
}
throw e; // Rethrow the exception after logging
} finally {
// Ensure that 'chunk' is released if it was allocated
if (chunk != null && chunk.refCnt() > 0) {
chunk.release();
}
// Ensure that 'completeData' is released if it was created and not yet released
if (completeData != null && completeData.refCnt() > 0) {
completeData.release();
}
}
}
protected abstract byte[] getData() throws IOException;
protected abstract void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException;
@Override
public final FMLProxyPacket generatePacket() {
return null;
}
@Override
public void sendData(ByteBuf out) throws IOException {
}
/**
* Simple storage class to keep track of partial data and how many bytes we've received so far.
*/
private static class PacketStorage {
final ByteBuf data;
int receivedSoFar;
final int totalSize;
PacketStorage(ByteBuf data, int receivedSoFar, int totalSize) {
this.data = data;
this.receivedSoFar = receivedSoFar;
this.totalSize = totalSize;
}
}
}
@@ -0,0 +1,43 @@
package kamkeel.npcs.network;
import kamkeel.npcs.network.enums.EnumChannelType;
import java.util.Hashtable;
import java.util.Map;
public class PacketChannel {
private String channelName;
private EnumChannelType channelType;
public Map<Integer, AbstractPacket> packets = new Hashtable<>();
public PacketChannel(String channelName, EnumChannelType channelType) {
this.channelName = channelName;
this.channelType = channelType;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public EnumChannelType getChannelType() {
return channelType;
}
public void setChannelType(EnumChannelType channelType) {
this.channelType = channelType;
}
public void registerPacket(AbstractPacket packet) {
if (packets.containsKey(packet.getType().ordinal())) {
System.out.println("Packet ID: " + packet.getType().ordinal() + " is already registered in " + this.channelName);
return;
}
this.packets.put(packet.getType().ordinal(), packet);
}
}
@@ -0,0 +1,8 @@
package kamkeel.npcs.network;
public class PacketClient extends PacketHandler {
public static void sendClient(AbstractPacket packet) {
PacketHandler.Instance.sendToServer(packet);
}
}
@@ -0,0 +1,594 @@
package kamkeel.npcs.network;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLEventChannel;
import cpw.mods.fml.common.network.FMLNetworkEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.enums.EnumChannelType;
import kamkeel.npcs.network.packets.data.*;
import kamkeel.npcs.network.packets.data.gui.*;
import kamkeel.npcs.network.packets.data.large.*;
import kamkeel.npcs.network.packets.data.npc.*;
import kamkeel.npcs.network.packets.data.script.ScriptOverlayClosePacket;
import kamkeel.npcs.network.packets.data.script.ScriptOverlayDataPacket;
import kamkeel.npcs.network.packets.data.script.ScriptedParticlePacket;
import kamkeel.npcs.network.packets.player.*;
import kamkeel.npcs.network.packets.player.customgui.CustomGuiButtonPacket;
import kamkeel.npcs.network.packets.player.customgui.CustomGuiClosePacket;
import kamkeel.npcs.network.packets.player.customgui.CustomGuiUnfocusedPacket;
import kamkeel.npcs.network.packets.player.customgui.CustomScrollClickPacket;
import kamkeel.npcs.network.packets.player.profile.*;
import kamkeel.npcs.network.packets.request.*;
import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket;
import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
import kamkeel.npcs.network.packets.request.bank.BankGetPacket;
import kamkeel.npcs.network.packets.request.bank.BankRemovePacket;
import kamkeel.npcs.network.packets.request.bank.BankSavePacket;
import kamkeel.npcs.network.packets.request.bank.BanksGetPacket;
import kamkeel.npcs.network.packets.request.clone.*;
import kamkeel.npcs.network.packets.request.dialog.*;
import kamkeel.npcs.network.packets.request.effects.EffectGetPacket;
import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket;
import kamkeel.npcs.network.packets.request.effects.EffectSavePacket;
import kamkeel.npcs.network.packets.request.effects.EffectsGetPacket;
import kamkeel.npcs.network.packets.request.faction.*;
import kamkeel.npcs.network.packets.request.feather.DimensionTeleportPacket;
import kamkeel.npcs.network.packets.request.item.ColorBrushPacket;
import kamkeel.npcs.network.packets.request.item.ColorSetPacket;
import kamkeel.npcs.network.packets.request.item.HammerPacket;
import kamkeel.npcs.network.packets.request.jobs.JobGetPacket;
import kamkeel.npcs.network.packets.request.jobs.JobSavePacket;
import kamkeel.npcs.network.packets.request.jobs.JobSpawnerAddPacket;
import kamkeel.npcs.network.packets.request.jobs.JobSpawnerRemovePacket;
import kamkeel.npcs.network.packets.request.linked.*;
import kamkeel.npcs.network.packets.request.magic.*;
import kamkeel.npcs.network.packets.request.mainmenu.*;
import kamkeel.npcs.network.packets.request.naturalspawns.NaturalSpawnGetAllPacket;
import kamkeel.npcs.network.packets.request.naturalspawns.NaturalSpawnGetPacket;
import kamkeel.npcs.network.packets.request.naturalspawns.NaturalSpawnRemovePacket;
import kamkeel.npcs.network.packets.request.naturalspawns.NaturalSpawnSavePacket;
import kamkeel.npcs.network.packets.request.npc.*;
import kamkeel.npcs.network.packets.request.party.*;
import kamkeel.npcs.network.packets.request.pather.MovingPathGetPacket;
import kamkeel.npcs.network.packets.request.pather.MovingPathSavePacket;
import kamkeel.npcs.network.packets.request.playerdata.*;
import kamkeel.npcs.network.packets.request.quest.*;
import kamkeel.npcs.network.packets.request.recipe.RecipeGetPacket;
import kamkeel.npcs.network.packets.request.recipe.RecipeRemovePacket;
import kamkeel.npcs.network.packets.request.recipe.RecipeSavePacket;
import kamkeel.npcs.network.packets.request.recipe.RecipesGetPacket;
import kamkeel.npcs.network.packets.request.role.RoleCompanionUpdatePacket;
import kamkeel.npcs.network.packets.request.role.RoleGetPacket;
import kamkeel.npcs.network.packets.request.role.RoleSavePacket;
import kamkeel.npcs.network.packets.request.script.*;
import kamkeel.npcs.network.packets.request.script.item.ItemScriptErrorPacket;
import kamkeel.npcs.network.packets.request.script.item.ItemScriptPacket;
import kamkeel.npcs.network.packets.request.script.item.LinkedItemScriptPacket;
import kamkeel.npcs.network.packets.request.tags.*;
import kamkeel.npcs.network.packets.request.transform.TransformGetPacket;
import kamkeel.npcs.network.packets.request.transform.TransformLoadPacket;
import kamkeel.npcs.network.packets.request.transform.TransformSavePacket;
import kamkeel.npcs.network.packets.request.transport.*;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import noppes.npcs.CustomNpcs;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.LogWriter;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class PacketHandler {
public static PacketHandler Instance;
// Channels
public Map<EnumChannelType, FMLEventChannel> channels = new Hashtable<>();
// Client to Server
public static final PacketChannel REQUEST_PACKET = new PacketChannel("CNPC+|Req", EnumChannelType.REQUEST);
// Client to Server - Typically information
public static final PacketChannel PLAYER_PACKET = new PacketChannel("CNPC+|Player", EnumChannelType.PLAYER);
// Server to Client
public static final PacketChannel DATA_PACKET = new PacketChannel("CNPC+|Data", EnumChannelType.DATA);
public static final List<PacketChannel> packetChannels = new ArrayList<>();
public PacketHandler() {
// Register Channels
packetChannels.add(REQUEST_PACKET);
packetChannels.add(PLAYER_PACKET);
packetChannels.add(DATA_PACKET);
this.registerDataPackets();
this.registerRequestPackets();
this.registerPlayerPackets();
}
public void registerRequestPackets() {
// NPC Packets
REQUEST_PACKET.registerPacket(new NpcClosePacket());
REQUEST_PACKET.registerPacket(new NpcDeletePacket());
// Script Packets
REQUEST_PACKET.registerPacket(new BlockScriptPacket());
REQUEST_PACKET.registerPacket(new EventScriptPacket());
REQUEST_PACKET.registerPacket(new ForgeScriptPacket());
REQUEST_PACKET.registerPacket(new GlobalNPCScriptPacket());
REQUEST_PACKET.registerPacket(new ItemScriptPacket());
REQUEST_PACKET.registerPacket(new ItemScriptErrorPacket());
REQUEST_PACKET.registerPacket(new LinkedItemScriptPacket());
REQUEST_PACKET.registerPacket(new NPCScriptPacket());
REQUEST_PACKET.registerPacket(new PlayerScriptPacket());
REQUEST_PACKET.registerPacket(new ScriptInfoPacket());
REQUEST_PACKET.registerPacket(new EffectScriptPacket());
// Cloner Packets
REQUEST_PACKET.registerPacket(new CloneListPacket());
REQUEST_PACKET.registerPacket(new SpawnMobPacket());
REQUEST_PACKET.registerPacket(new MobSpawnerPacket());
REQUEST_PACKET.registerPacket(new ClonePreSavePacket());
REQUEST_PACKET.registerPacket(new CloneSavePacket());
REQUEST_PACKET.registerPacket(new CloneRemovePacket());
REQUEST_PACKET.registerPacket(new CloneTagListPacket());
REQUEST_PACKET.registerPacket(new CloneAllTagsPacket());
REQUEST_PACKET.registerPacket(new CloneAllTagsShortPacket());
// Linked Packets
REQUEST_PACKET.registerPacket(new LinkedGetAllPacket());
REQUEST_PACKET.registerPacket(new LinkedGetPacket());
REQUEST_PACKET.registerPacket(new LinkedNPCRemovePacket());
REQUEST_PACKET.registerPacket(new LinkedSetPacket());
REQUEST_PACKET.registerPacket(new LinkedNPCAddPacket());
REQUEST_PACKET.registerPacket(new LinkedItemSavePacket());
REQUEST_PACKET.registerPacket(new LinkedItemRemovePacket());
REQUEST_PACKET.registerPacket(new LinkedItemBuildPacket());
// Bank Packets
REQUEST_PACKET.registerPacket(new BanksGetPacket());
REQUEST_PACKET.registerPacket(new BankGetPacket());
REQUEST_PACKET.registerPacket(new BankRemovePacket());
REQUEST_PACKET.registerPacket(new BankSavePacket());
// Recipe Packets
REQUEST_PACKET.registerPacket(new RecipesGetPacket());
REQUEST_PACKET.registerPacket(new RecipeGetPacket());
REQUEST_PACKET.registerPacket(new RecipeRemovePacket());
REQUEST_PACKET.registerPacket(new RecipeSavePacket());
// Natural Spawn Packets
REQUEST_PACKET.registerPacket(new NaturalSpawnGetAllPacket());
REQUEST_PACKET.registerPacket(new NaturalSpawnGetPacket());
REQUEST_PACKET.registerPacket(new NaturalSpawnSavePacket());
REQUEST_PACKET.registerPacket(new NaturalSpawnRemovePacket());
// Dialog Category Packets
REQUEST_PACKET.registerPacket(new DialogCategorySavePacket());
REQUEST_PACKET.registerPacket(new DialogCategoryRemovePacket());
REQUEST_PACKET.registerPacket(new DialogCategoryGetPacket());
REQUEST_PACKET.registerPacket(new DialogCategoriesGetPacket());
// Dialog Packets
REQUEST_PACKET.registerPacket(new DialogSavePacket());
REQUEST_PACKET.registerPacket(new DialogRemovePacket());
REQUEST_PACKET.registerPacket(new DialogsGetPacket());
REQUEST_PACKET.registerPacket(new DialogGetPacket());
REQUEST_PACKET.registerPacket(new DialogNpcGetPacket());
REQUEST_PACKET.registerPacket(new DialogNpcSetPacket());
REQUEST_PACKET.registerPacket(new DialogNpcRemovePacket());
// Quest Category Packets
REQUEST_PACKET.registerPacket(new QuestCategorySavePacket());
REQUEST_PACKET.registerPacket(new QuestCategoryRemovePacket());
REQUEST_PACKET.registerPacket(new QuestCategoryGetPacket());
REQUEST_PACKET.registerPacket(new QuestCategoriesGetPacket());
// Quest Packets
REQUEST_PACKET.registerPacket(new QuestOpenGuiPacket());
REQUEST_PACKET.registerPacket(new QuestSavePacket());
REQUEST_PACKET.registerPacket(new QuestRemovePacket());
REQUEST_PACKET.registerPacket(new QuestDialogGetTitlePacket());
REQUEST_PACKET.registerPacket(new QuestLogToServerPacket());
REQUEST_PACKET.registerPacket(new QuestUntrackPacket());
REQUEST_PACKET.registerPacket(new QuestGetPacket());
REQUEST_PACKET.registerPacket(new QuestsGetPacket());
// Faction Packets
REQUEST_PACKET.registerPacket(new FactionSavePacket());
REQUEST_PACKET.registerPacket(new FactionRemovePacket());
REQUEST_PACKET.registerPacket(new FactionSetPacket());
REQUEST_PACKET.registerPacket(new FactionGetPacket());
REQUEST_PACKET.registerPacket(new FactionsGetPacket());
// Tag Packets
REQUEST_PACKET.registerPacket(new TagsGetPacket());
REQUEST_PACKET.registerPacket(new TagGetPacket());
REQUEST_PACKET.registerPacket(new TagsNpcGetPacket());
REQUEST_PACKET.registerPacket(new TagSetPacket());
REQUEST_PACKET.registerPacket(new TagSavePacket());
REQUEST_PACKET.registerPacket(new TagRemovePacket());
// PlayerData Packets
REQUEST_PACKET.registerPacket(new PlayerDataGetNamesPacket());
REQUEST_PACKET.registerPacket(new PlayerDataRemovePacket());
REQUEST_PACKET.registerPacket(new PlayerDataGetInfoPacket());
REQUEST_PACKET.registerPacket(new PlayerDataDeleteInfoPacket());
REQUEST_PACKET.registerPacket(new PlayerDataSaveInfoPacket());
REQUEST_PACKET.registerPacket(new PlayerDataMapRegenPacket());
// Main Menu Packets
REQUEST_PACKET.registerPacket(new MainmenuDisplayGetPacket());
REQUEST_PACKET.registerPacket(new MainmenuDisplaySavePacket());
REQUEST_PACKET.registerPacket(new MainmenuStatsGetPacket());
REQUEST_PACKET.registerPacket(new MainmenuStatsSavePacket());
REQUEST_PACKET.registerPacket(new MainmenuAIGetPacket());
REQUEST_PACKET.registerPacket(new MainmenuAISavePacket());
REQUEST_PACKET.registerPacket(new MainmenuAdvancedGetPacket());
REQUEST_PACKET.registerPacket(new MainmenuAdvancedSavePacket());
REQUEST_PACKET.registerPacket(new MainmenuAdvancedMarkDataPacket());
REQUEST_PACKET.registerPacket(new MainmenuInvGetPacket());
REQUEST_PACKET.registerPacket(new MainmenuInvSavePacket());
// Transport Packets
REQUEST_PACKET.registerPacket(new TransportCategoriesGetPacket());
REQUEST_PACKET.registerPacket(new TransportCategorySavePacket());
REQUEST_PACKET.registerPacket(new TransportCategoryRemovePacket());
REQUEST_PACKET.registerPacket(new TransportRemovePacket());
REQUEST_PACKET.registerPacket(new TransportsGetPacket());
REQUEST_PACKET.registerPacket(new TransportSavePacket());
REQUEST_PACKET.registerPacket(new TransportGetLocationPacket());
// Remote Packets Packets
REQUEST_PACKET.registerPacket(new RemoteMainMenuPacket());
REQUEST_PACKET.registerPacket(new RemoteGlobalMenuPacket());
REQUEST_PACKET.registerPacket(new RemoteDeletePacket());
REQUEST_PACKET.registerPacket(new RemoteNpcsGetPacket());
REQUEST_PACKET.registerPacket(new RemoteFreezeGetPacket());
REQUEST_PACKET.registerPacket(new RemoteFreezePacket());
REQUEST_PACKET.registerPacket(new RemoteResetPacket());
REQUEST_PACKET.registerPacket(new RemoteTpToNpcPacket());
// Job Packets
REQUEST_PACKET.registerPacket(new JobGetPacket());
REQUEST_PACKET.registerPacket(new JobSavePacket());
REQUEST_PACKET.registerPacket(new JobSpawnerAddPacket());
REQUEST_PACKET.registerPacket(new JobSpawnerRemovePacket());
// Role Packets
REQUEST_PACKET.registerPacket(new RoleCompanionUpdatePacket());
REQUEST_PACKET.registerPacket(new RoleSavePacket());
REQUEST_PACKET.registerPacket(new RoleGetPacket());
// Transform Packets
REQUEST_PACKET.registerPacket(new TransformSavePacket());
REQUEST_PACKET.registerPacket(new TransformGetPacket());
REQUEST_PACKET.registerPacket(new TransformLoadPacket());
// Trader Packets
REQUEST_PACKET.registerPacket(new TraderMarketSavePacket());
// Party Packets
REQUEST_PACKET.registerPacket(new PartySavePacket());
REQUEST_PACKET.registerPacket(new PartyInfoPacket());
REQUEST_PACKET.registerPacket(new PartyDisbandPacket());
REQUEST_PACKET.registerPacket(new PartySetLeaderPacket());
REQUEST_PACKET.registerPacket(new PartyKickPacket());
REQUEST_PACKET.registerPacket(new PartyLeavePacket());
REQUEST_PACKET.registerPacket(new PartySetQuestPacket());
REQUEST_PACKET.registerPacket(new PartyInvitePacket());
REQUEST_PACKET.registerPacket(new PartyAcceptInvitePacket());
REQUEST_PACKET.registerPacket(new PartyIgnoreInvitePacket());
REQUEST_PACKET.registerPacket(new PartyLogToServerPacket());
// Animation Packets
REQUEST_PACKET.registerPacket(new AnimationsGetPacket());
REQUEST_PACKET.registerPacket(new AnimationGetPacket());
REQUEST_PACKET.registerPacket(new AnimationRemovePacket());
REQUEST_PACKET.registerPacket(new AnimationSavePacket());
// Moving Path
REQUEST_PACKET.registerPacket(new MovingPathSavePacket());
REQUEST_PACKET.registerPacket(new MovingPathGetPacket());
// Tool Packets
REQUEST_PACKET.registerPacket(new ColorBrushPacket());
REQUEST_PACKET.registerPacket(new ColorSetPacket());
REQUEST_PACKET.registerPacket(new HammerPacket());
// Custom Effect Packets
REQUEST_PACKET.registerPacket(new EffectGetPacket());
REQUEST_PACKET.registerPacket(new EffectsGetPacket());
REQUEST_PACKET.registerPacket(new EffectSavePacket());
REQUEST_PACKET.registerPacket(new EffectRemovePacket());
// Magic Packets
REQUEST_PACKET.registerPacket(new MagicCycleRemovePacket());
REQUEST_PACKET.registerPacket(new MagicCycleSavePacket());
REQUEST_PACKET.registerPacket(new MagicGetAllPacket());
REQUEST_PACKET.registerPacket(new MagicSavePacket());
REQUEST_PACKET.registerPacket(new MagicRemovePacket());
REQUEST_PACKET.registerPacket(new MagicGetPacket());
REQUEST_PACKET.registerPacket(new MagicNpcGetPacket());
REQUEST_PACKET.registerPacket(new MagicNpcSavePacket());
// Other Packets
REQUEST_PACKET.registerPacket(new IsGuiOpenInform());
REQUEST_PACKET.registerPacket(new GuiRequestPacket());
REQUEST_PACKET.registerPacket(new DimensionsGetPacket());
REQUEST_PACKET.registerPacket(new MerchantUpdatePacket());
REQUEST_PACKET.registerPacket(new ModelDataSavePacket());
REQUEST_PACKET.registerPacket(new MailOpenSetupPacket());
REQUEST_PACKET.registerPacket(new TileEntityGetPacket());
REQUEST_PACKET.registerPacket(new TileEntitySavePacket());
REQUEST_PACKET.registerPacket(new MountPacket());
REQUEST_PACKET.registerPacket(new DimensionTeleportPacket());
}
public void registerDataPackets() {
// Data Packets
DATA_PACKET.registerPacket(new LoginPacket());
DATA_PACKET.registerPacket(new AchievementPacket());
DATA_PACKET.registerPacket(new ChatAlertPacket());
DATA_PACKET.registerPacket(new ChatBubblePacket());
DATA_PACKET.registerPacket(new ConfigCommandPacket());
DATA_PACKET.registerPacket(new DisableMouseInputPacket());
DATA_PACKET.registerPacket(new MarkDataPacket());
DATA_PACKET.registerPacket(new OverlayQuestTrackingPacket());
DATA_PACKET.registerPacket(new ParticlePacket());
DATA_PACKET.registerPacket(new PlayerUpdateSkinOverlaysPacket());
DATA_PACKET.registerPacket(new QuestCompletionPacket());
DATA_PACKET.registerPacket(new ScrollSelectedPacket());
DATA_PACKET.registerPacket(new SoundManagementPacket());
DATA_PACKET.registerPacket(new SwingPlayerArmPacket());
DATA_PACKET.registerPacket(new UpdateAnimationsPacket());
DATA_PACKET.registerPacket(new VillagerListPacket());
DATA_PACKET.registerPacket(new PlayerDataInfoPacket());
// Data | GUI Packets
DATA_PACKET.registerPacket(new GuiClosePacket());
DATA_PACKET.registerPacket(new GuiOpenPacket());
DATA_PACKET.registerPacket(new GuiErrorPacket());
DATA_PACKET.registerPacket(new GuiRedstonePacket());
DATA_PACKET.registerPacket(new GuiTeleporterPacket());
DATA_PACKET.registerPacket(new GuiWaypointPacket());
DATA_PACKET.registerPacket(new IsGuiOpenPacket());
DATA_PACKET.registerPacket(new GuiOpenBookPacket());
// Data | NPC Packets
DATA_PACKET.registerPacket(new DeleteNpcPacket());
DATA_PACKET.registerPacket(new EditNpcPacket());
DATA_PACKET.registerPacket(new UpdateNpcPacket());
DATA_PACKET.registerPacket(new DialogPacket());
DATA_PACKET.registerPacket(new RolePacket());
DATA_PACKET.registerPacket(new WeaponNpcPacket());
// Data | Script Packets
DATA_PACKET.registerPacket(new ScriptedParticlePacket());
DATA_PACKET.registerPacket(new ScriptOverlayClosePacket());
DATA_PACKET.registerPacket(new ScriptOverlayDataPacket());
// Data | Large Packets
DATA_PACKET.registerPacket(new ClonerPacket());
DATA_PACKET.registerPacket(new ScrollDataPacket());
DATA_PACKET.registerPacket(new ScrollListPacket());
DATA_PACKET.registerPacket(new SyncPacket());
DATA_PACKET.registerPacket(new SyncEffectPacket());
DATA_PACKET.registerPacket(new GuiDataPacket());
DATA_PACKET.registerPacket(new PartyDataPacket());
}
public void registerPlayerPackets() {
PLAYER_PACKET.registerPacket(new FollowerPacket());
PLAYER_PACKET.registerPacket(new TransportPacket());
PLAYER_PACKET.registerPacket(new BankActionPacket());
PLAYER_PACKET.registerPacket(new DialogSelectPacket());
PLAYER_PACKET.registerPacket(new CheckPlayerValue());
PLAYER_PACKET.registerPacket(new MailActionPacket());
PLAYER_PACKET.registerPacket(new MailActionPacket.MailSendPacket());
PLAYER_PACKET.registerPacket(new SaveSignPacket());
PLAYER_PACKET.registerPacket(new SaveBookPacket());
PLAYER_PACKET.registerPacket(new CompanionActionPacket());
PLAYER_PACKET.registerPacket(new GetNPCRole());
PLAYER_PACKET.registerPacket(new InputDevicePacket());
PLAYER_PACKET.registerPacket(new ScreenSizePacket());
// CustomGUI Packets
PLAYER_PACKET.registerPacket(new CustomGuiButtonPacket());
PLAYER_PACKET.registerPacket(new CustomGuiClosePacket());
PLAYER_PACKET.registerPacket(new CustomGuiUnfocusedPacket());
PLAYER_PACKET.registerPacket(new CustomScrollClickPacket());
// Profile Packets
PLAYER_PACKET.registerPacket(new ProfileCreatePacket());
PLAYER_PACKET.registerPacket(new ProfileRemovePacket());
PLAYER_PACKET.registerPacket(new ProfileRenamePacket());
PLAYER_PACKET.registerPacket(new ProfileChangePacket());
PLAYER_PACKET.registerPacket(new ProfileGetPacket());
PLAYER_PACKET.registerPacket(new ProfileGetInfoPacket());
}
public void registerChannels() {
for (PacketChannel channel : packetChannels) {
FMLEventChannel eventChannel =
NetworkRegistry.INSTANCE.newEventDrivenChannel(channel.getChannelName());
eventChannel.register(this);
channels.put(channel.getChannelType(), eventChannel);
}
}
public PacketChannel getPacketChannel(EnumChannelType type) {
return packetChannels.stream()
.filter(channel -> channel.getChannelType() == type)
.findFirst()
.orElse(null);
}
public FMLEventChannel getEventChannel(AbstractPacket abstractPacket) {
PacketChannel packetChannel = getPacketChannel(abstractPacket.getChannel().getChannelType());
if (packetChannel == null) {
return null;
}
return channels.get(packetChannel.getChannelType());
}
@SubscribeEvent
public void onServerPacket(FMLNetworkEvent.ServerCustomPacketEvent event) {
handlePacket(event.packet, ((NetHandlerPlayServer) event.handler).playerEntity, Side.SERVER);
}
@SubscribeEvent
public void onClientPacket(FMLNetworkEvent.ClientCustomPacketEvent event) {
handlePacket(event.packet, CustomNpcs.proxy.getPlayer(), Side.CLIENT);
}
private void handlePacket(FMLProxyPacket packet, EntityPlayer player, Side side) {
ByteBuf buf = packet.payload();
try {
int packetTypeOrdinal = buf.readInt();
EnumChannelType packetType = EnumChannelType.values()[packetTypeOrdinal];
PacketChannel packetChannel = getPacketChannel(packetType);
if (packetChannel == null) {
LogWriter.error("Error: Packet channel is null for packet type: " + packetType);
return;
}
int packetId = buf.readInt();
AbstractPacket abstractPacket = packetChannel.packets.get(packetId);
if (abstractPacket == null) {
LogWriter.error("Error: Abstract packet is null for packet ID: " + packetId);
return;
}
if (side == Side.SERVER) {
if (abstractPacket.getChannel() == REQUEST_PACKET && ConfigMain.OpsOnly && !NoppesUtilServer.isOp(player)) {
LogWriter.error(String.format("%s tried to use CNPC+ without being an op", player.getCommandSenderName()));
return;
}
// Check if permission is allowed
if (abstractPacket.getPermission() != null && !CustomNpcsPermissions.hasPermission(player, abstractPacket.getPermission())) {
return;
}
// Check for required NPC
EntityNPCInterface npc = NoppesUtilServer.getEditingNpc(player);
if (abstractPacket.needsNPC() && npc == null) {
return;
}
abstractPacket.setNPC(npc);
}
// Let the packet parse the rest
abstractPacket.receiveData(buf, player);
} catch (IndexOutOfBoundsException e) {
LogWriter.error("Error: IndexOutOfBoundsException in handlePacket: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
LogWriter.error("Error: Exception in handlePacket: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Sends every FMLProxyPacket produced by packet.generatePackets()
*/
private void sendAllPackets(AbstractPacket packet, SendAction action) {
// get all generated FMLProxyPacket objects (could be 1 for normal, or many for large)
List<FMLProxyPacket> proxyPackets = packet.generatePackets();
if (proxyPackets.isEmpty()) {
LogWriter.error("Warning: No packets generated for " + packet.getClass().getName());
}
for (FMLProxyPacket proxy : proxyPackets) {
action.send(proxy);
}
}
// ------------------------------------------------------------------------
// Public API methods for sending
public void sendToPlayer(AbstractPacket packet, EntityPlayerMP player) {
FMLEventChannel eventChannel = getEventChannel(packet);
if (eventChannel == null) {
LogWriter.error("Error: Event channel is null for packet: " + packet.getClass().getName());
return;
}
sendAllPackets(packet, p -> eventChannel.sendTo(p, player));
}
public void sendToServer(AbstractPacket packet) {
FMLEventChannel eventChannel = getEventChannel(packet);
if (eventChannel == null) {
LogWriter.error("Error: Event channel is null for packet: " + packet.getClass().getName());
return;
}
sendAllPackets(packet, eventChannel::sendToServer);
}
public void sendToAll(AbstractPacket packet) {
FMLEventChannel eventChannel = getEventChannel(packet);
if (eventChannel == null) {
LogWriter.error("Error: Event channel is null for packet: " + packet.getClass().getName());
return;
}
sendAllPackets(packet, eventChannel::sendToAll);
}
public void sendToDimension(AbstractPacket packet, final int dimensionId) {
FMLEventChannel eventChannel = getEventChannel(packet);
if (eventChannel == null) {
LogWriter.error("Error: Event channel is null for packet: " + packet.getClass().getName());
return;
}
sendAllPackets(packet, p -> eventChannel.sendToDimension(p, dimensionId));
}
public void sendTracking(AbstractPacket packet, final Entity entity) {
FMLEventChannel eventChannel = getEventChannel(packet);
if (eventChannel == null) {
LogWriter.error("Error: Event channel is null for packet: " + packet.getClass().getName());
return;
}
final NetworkRegistry.TargetPoint point = new NetworkRegistry.TargetPoint(entity.dimension, entity.posX, entity.posY, entity.posZ, 60);
sendAllPackets(packet, p -> eventChannel.sendToAllAround(p, point));
}
// Simple functional interface to unify the "send" action
private interface SendAction {
void send(FMLProxyPacket proxy);
}
}
@@ -0,0 +1,253 @@
package kamkeel.npcs.network;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomItems;
import noppes.npcs.LogWriter;
import noppes.npcs.NBTTags;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.IScriptHandler;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class PacketUtil {
public static boolean verifyItemPacket(EnumItemPacketType type, EntityPlayer player) {
if (player == null)
return false;
ItemStack item = player.inventory.getCurrentItem();
if (item == null) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without an item, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
switch (type) {
case WAND:
if (item.getItem() != CustomItems.wand) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Wand, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case MOUNTER:
if (item.getItem() != CustomItems.mount) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Mounter, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case CLONER:
if (item.getItem() != CustomItems.cloner) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Cloner, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case TELEPORTER:
if (item.getItem() != CustomItems.teleporter) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Teleporter, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case SCRIPTER:
if (item.getItem() != CustomItems.scripter) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Scripter, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case PATHER:
if (item.getItem() != CustomItems.moving) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Pather, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case BLOCK:
if (item.getItem() == Item.getItemFromBlock(CustomItems.waypoint)
|| item.getItem() == Item.getItemFromBlock(CustomItems.border)
|| item.getItem() == Item.getItemFromBlock(CustomItems.redstoneBlock)) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a valid Block, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case BRUSH:
if (item.getItem() != CustomItems.tool || item.getItemDamage() != 1) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Pather, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
case HAMMER:
if (item.getItem() != CustomItems.tool || item.getItemDamage() != 0) {
LogWriter.error(String.format("%s attempted to utilize a %s Packet without a Pather, they could be a hacker",
player.getCommandSenderName(), type));
return false;
}
break;
}
return true;
}
/**
* New method that accepts multiple EnumItemPacketTypes.
* It returns true if any one of the provided types is valid.
* If none are valid, a merged error message is logged.
*/
public static boolean verifyItemPacket(EntityPlayer player, EnumItemPacketType... types) {
if (player == null)
return false;
ItemStack item = player.inventory.getCurrentItem();
if (item == null) {
LogWriter.error(String.format("%s attempted to utilize a Packet without an item. Expected one of: %s, they could be a hacker",
player.getCommandSenderName(), getExpectedItemNames(types)));
return false;
}
for (EnumItemPacketType type : types) {
if (isValidItemForType(item, type)) {
return true;
}
}
// None passed; log one merged error message listing all expected items.
LogWriter.error(String.format("%s attempted to utilize a Packet without a valid item. Expected one of: %s, they could be a hacker",
player.getCommandSenderName(), getExpectedItemNames(types)));
return false;
}
private static boolean isValidItemForType(ItemStack item, EnumItemPacketType type) {
if (item == null || item.getItem() == null)
return false;
switch (type) {
case WAND:
return item.getItem() == CustomItems.wand;
case MOUNTER:
return item.getItem() == CustomItems.mount;
case CLONER:
return item.getItem() == CustomItems.cloner;
case TELEPORTER:
return item.getItem() == CustomItems.teleporter;
case SCRIPTER:
return item.getItem() == CustomItems.scripter;
case PATHER:
return item.getItem() == CustomItems.moving;
case BLOCK:
// For BLOCK, the item is valid as long as it is NOT one of these blocks.
return !(item.getItem() == Item.getItemFromBlock(CustomItems.waypoint)
|| item.getItem() == Item.getItemFromBlock(CustomItems.border)
|| item.getItem() == Item.getItemFromBlock(CustomItems.redstoneBlock));
case BRUSH:
return item.getItem() == CustomItems.tool && item.getItemDamage() == 1;
case HAMMER:
return item.getItem() == CustomItems.tool && item.getItemDamage() == 0;
default:
return false;
}
}
/**
* Builds a comma‐separated list of expected item names for the given types.
*/
private static String getExpectedItemNames(EnumItemPacketType... types) {
Set<String> expectedNames = new LinkedHashSet<>();
for (EnumItemPacketType type : types) {
expectedNames.add(getExpectedItemName(type));
}
return String.join(", ", expectedNames);
}
/**
* Returns the expected item name for the given EnumItemPacketType.
*/
private static String getExpectedItemName(EnumItemPacketType type) {
switch (type) {
case WAND:
return "Wand";
case MOUNTER:
return "Mounter";
case CLONER:
return "Cloner";
case TELEPORTER:
return "Teleporter";
case SCRIPTER:
return "Scripter";
case PATHER:
return "Pather";
case BLOCK:
return "valid Block";
case BRUSH:
return "Paintbrush";
case HAMMER:
return "Hammer";
default:
return type.toString();
}
}
public static void getScripts(IScriptHandler data, EntityPlayerMP player) {
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("ScriptEnabled", data.getEnabled());
compound.setString("ScriptLanguage", data.getLanguage());
compound.setTag("Languages", ScriptController.Instance.nbtLanguages());
compound.setTag("ScriptConsole", NBTTags.NBTLongStringMap(data.getConsoleText()));
GuiDataPacket.sendGuiData(player, compound);
List<ScriptContainer> containers = data.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
NBTTagCompound tabCompound = new NBTTagCompound();
tabCompound.setInteger("Tab", i);
tabCompound.setTag("Script", container.writeToNBT(new NBTTagCompound()));
tabCompound.setInteger("TotalScripts", containers.size());
GuiDataPacket.sendGuiData(player, tabCompound);
}
}
public static void saveScripts(IScriptHandler data, ByteBuf buffer) throws IOException {
int tab = buffer.readInt();
int totalScripts = buffer.readInt();
if (totalScripts == 0) {
data.getScripts().clear();
}
if (tab >= 0) {
if (data.getScripts().size() > totalScripts) {
data.setScripts(data.getScripts().subList(0, totalScripts));
} else while (data.getScripts().size() < totalScripts) {
data.getScripts().add(new ScriptContainer(data));
}
NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer);
ScriptContainer script = new ScriptContainer(data);
script.readFromNBT(tabCompound);
data.getScripts().set(tab, script);
} else {
NBTTagCompound compound = ByteBufUtils.readNBT(buffer);
data.setLanguage(compound.getString("ScriptLanguage"));
if (!ScriptController.Instance.languages.containsKey(data.getLanguage())) {
if (!ScriptController.Instance.languages.isEmpty()) {
data.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]);
} else {
data.setLanguage("ECMAScript");
}
}
data.setEnabled(compound.getBoolean("ScriptEnabled"));
}
}
}
@@ -0,0 +1,8 @@
package kamkeel.npcs.network.enums;
public enum EnumChannelType {
REQUEST,
PLAYER,
DATA,
INFO
}
@@ -0,0 +1,5 @@
package kamkeel.npcs.network.enums;
public enum EnumConfigOperation {
FONT,
}
@@ -0,0 +1,61 @@
package kamkeel.npcs.network.enums;
// Packets to the Client
public enum EnumDataPacket {
// Synchronization
SYNC,
SYNC_EFFECTS,
CONFIG_COMMAND,
// Messages
CHAT_ALERT,
ACHIEVEMENT,
CHATBUBBLE,
SOUND,
DIALOG,
QUEST_COMPLETION,
// NPC
EDIT_NPC,
UPDATE_NPC,
ROLE_NPC,
DELETE_NPC,
CLONE_NPC,
WEAPON_NPC,
// Data
SCROLL_LIST,
SCROLL_DATA,
SCROLL_GROUP,
SCROLL_SELECTED,
PARTY_DATA,
// GUI
GUI_OPEN,
GUI_REDSTONE,
GUI_WAYPOINT,
GUI_TELEPORTER,
GUI_BOOK,
GUI_DATA,
PLAYER_DATA,
GUI_ERROR,
GUI_CLOSE,
ISGUIOPEN,
// Visual
SCRIPTED_PARTICLE,
PARTICLE,
PLAYER_UPDATE_SKIN_OVERLAYS,
UPDATE_ANIMATIONS,
SCRIPT_OVERLAY_DATA,
SCRIPT_OVERLAY_CLOSE,
OVERLAY_QUEST_TRACKING,
MARK_DATA,
// Other
VILLAGER_LIST,
SWING_PLAYER_ARM,
DISABLE_MOUSE_INPUT,
LOGIN,
}
@@ -0,0 +1,13 @@
package kamkeel.npcs.network.enums;
public enum EnumItemPacketType {
WAND,
MOUNTER,
CLONER,
TELEPORTER,
SCRIPTER,
PATHER,
BLOCK,
BRUSH,
HAMMER
}
@@ -0,0 +1,27 @@
package kamkeel.npcs.network.enums;
public enum EnumPlayerPacket {
FollowerAction,
Transport,
BankAction,
DialogSelect,
GetPlayerValue,
MailBoxAction,
MailSend,
SaveSign,
SaveBook,
CompanionAction,
GetRole,
InputDevice,
ScreenSize,
CustomGuiButton,
CustomGuiScrollClick,
CustomGuiClose,
CustomGuiUnfocused,
ProfileCreate,
ProfileRemove,
ProfileRename,
ProfileChange, ProfileGet, ProfileGetInfo,
}
@@ -0,0 +1,196 @@
package kamkeel.npcs.network.enums;
public enum EnumRequestPacket {
NPCDelete,
RemoteMainMenu,
RemoteGlobalMenu,
NpcClose,
RemoteDelete,
RemoteFreeze,
RemoteFreezeGet,
RemoteReset,
SpawnMob,
MobSpawner,
DimensionsGet,
MainmenuAISave,
MainmenuAIGet,
MainmenuInvSave,
MainmenuInvGet,
MainmenuStatsSave,
MainmenuStatsGet,
MainmenuDisplaySave,
MainmenuDisplayGet,
ModelDataSave,
MainmenuAdvancedSave,
MainmenuAdvancedGet,
MainmenuAdvancedMarkData,
DialogNpcSet,
DialogNpcRemove,
DialogNpcGet,
DialogCategorySave,
DialogCategoriesGet,
DialogCategoryRemove,
DialogCategoryGet,
DialogSave,
DialogsGet,
DialogGet,
DialogRemove,
TransportSave,
TransportCategoriesGet,
TransportCategorySave,
TransportCategoryRemove,
TransportRemove,
TransportGetLocation,
TransportsGet,
FactionSet,
FactionSave,
FactionsGet,
FactionGet,
FactionRemove,
TagSet,
TagSave,
TagsGet,
TagGet,
NpcTagsGet,
TagRemove,
QuestUntrack,
QuestLogToServer,
QuestCategorySave,
QuestCategoriesGet,
QuestRemove,
QuestCategoryRemove,
QuestRewardSave,
QuestSave,
QuestsGetFromQuest,
QuestsGet,
QuestDialogGetTitle,
QuestOpenGui,
QuestGet,
RecipeSave,
RecipeRemove,
RecipesGet,
RecipeGet,
NaturalSpawnSave,
NaturalSpawnGet,
NaturalSpawnRemove,
NaturalSpawnGetAll,
MerchantUpdate,
MountPacket,
MovingPathSave,
MovingPathGet,
AnimationsGet,
AnimationGet,
AnimationRemove,
AnimationSave,
RemoteNpcsGet,
RemoteTpToNpc,
TileEntitySave,
TileEntityGet,
Gui,
IsGuiOpen,
CacheAnimation,
PartyLogToServer,
PartySave,
PartyInfo,
PartyDisband,
PartyKick,
PartyLeave,
PartyInvite,
PartyAcceptInvite,
PartyIgnoreInvite,
PartySetLeader,
PartySetQuest,
LinkedNPCRemove,
LinkedNPCAdd,
LinkedGetAll,
LinkedSet,
LinkedGet,
LinkedItemSave,
LinkedItemRemove,
LinkedItemBuild,
LinkedItemScript,
BankGet,
BanksGet,
BankSave,
BankRemove,
QuestCategoryGet,
PlayerDataInfo,
PlayerDataGetNames,
PlayerDataDeleteInfo,
PlayerDataRemove,
PlayerDataMapRegen,
PlayerDataSave,
JobSave,
JobGet,
JobSpawnerAdd,
JobSpawnerRemove,
RoleCompanionUpdate,
RoleSave,
RoleGet,
MailOpenSetup,
TransformSave,
TransformGet,
TransformLoad,
TraderMarketSave,
CloneList,
CloneSave,
CloneRemove,
CloneTagList,
CloneAllTags,
CloneAllTagsShort,
ClonePreSave,
EventScript,
PlayerScript,
ForgeScript,
GlobalNPCScript,
ItemScript,
ItemScriptError,
BlockScript,
NPCScript,
ScriptInfo,
EffectScript,
DimensionTeleport,
EffectList,
EffectGet,
EffectScriptGet,
EffectRemove,
EffectSave,
ColorSet,
ColorBrush,
MagicCycleRemove,
MagicCycleSave,
MagicGetAll,
MagicRemove,
MagicGet,
MagicSave,
NpcMagicGet,
NpcMagicSave, Hammer,
}
@@ -0,0 +1,12 @@
package kamkeel.npcs.network.enums;
public enum EnumSoundOperation {
CONTINUE_SOUNDS,
PAUSE_SOUNDS,
PLAY_MUSIC,
PLAY_SOUND,
PLAY_SOUND_TO,
PLAY_SOUND_TO_NO_ID,
STOP_SOUND_FOR,
STOP_SOUNDS
}
@@ -0,0 +1,7 @@
package kamkeel.npcs.network.enums;
public enum EnumSyncAction {
RELOAD,
UPDATE,
REMOVE
}
@@ -0,0 +1,16 @@
package kamkeel.npcs.network.enums;
public enum EnumSyncType {
FACTION,
DIALOG,
DIALOG_CATEGORY,
QUEST,
QUEST_CATEGORY,
PLAYERDATA,
MAGIC,
MAGIC_CYCLE,
WORKBENCH_RECIPES,
CARPENTRY_RECIPES,
ANVIL_RECIPES,
CUSTOM_EFFECTS
}
@@ -0,0 +1,76 @@
package kamkeel.npcs.network.packets.data;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.achievement.GuiAchievement;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.stats.Achievement;
import net.minecraft.util.StatCollector;
import noppes.npcs.CustomItems;
import noppes.npcs.client.MessageAchievement;
import noppes.npcs.config.ConfigClient;
import java.io.IOException;
public final class AchievementPacket extends AbstractPacket {
public static final String packetName = "Data|Achievement";
private boolean isParty;
private String description;
private String message;
public AchievementPacket() {
}
public AchievementPacket(boolean isParty, String description, String message) {
this.isParty = isParty;
this.description = description;
this.message = message;
}
public static void sendAchievement(EntityPlayerMP playerMP, boolean isParty, String description, String message) {
AchievementPacket packet = new AchievementPacket(isParty, description, message);
PacketHandler.Instance.sendToPlayer(packet, playerMP);
}
@Override
public Enum getType() {
return EnumDataPacket.ACHIEVEMENT;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.DATA_PACKET;
}
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeBoolean(this.isParty);
ByteBufUtils.writeString(out, this.description);
ByteBufUtils.writeString(out, this.message);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!ConfigClient.BannerAlerts)
return;
boolean isNotParty = !in.readBoolean();
String description = StatCollector.translateToLocal(ByteBufUtils.readString(in));
String message = ByteBufUtils.readString(in);
Achievement ach = isNotParty ? new MessageAchievement(message, description) : new MessageAchievement(CustomItems.bag == null ? Items.paper : CustomItems.bag, message, description);
Minecraft.getMinecraft().guiAchievement.func_146256_a(ach);
ObfuscationReflectionHelper.setPrivateValue(GuiAchievement.class, Minecraft.getMinecraft().guiAchievement, ach.getDescription(), 4);
}
}
@@ -0,0 +1,76 @@
package kamkeel.npcs.network.packets.data;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import kamkeel.npcs.util.ColorUtil;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.StatCollector;
import noppes.npcs.config.ConfigClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class ChatAlertPacket extends AbstractPacket {
public static final String packetName = "Data|ChatAlert";
private Object[] objects;
public ChatAlertPacket() {
}
public ChatAlertPacket(final Object... obs) {
this.objects = obs;
}
public static void sendChatAlert(EntityPlayerMP playerMP, final Object... obs) {
ChatAlertPacket packet = new ChatAlertPacket(obs);
PacketHandler.Instance.sendToPlayer(packet, playerMP);
}
@Override
public Enum getType() {
return EnumDataPacket.CHAT_ALERT;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.DATA_PACKET;
}
@Override
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.fillBuffer(out, this.objects);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!ConfigClient.ChatAlerts)
return;
// Read all objects (sent as strings) from the buffer.
List<String> parts = new ArrayList<>();
String part;
while ((part = ByteBufUtils.readString(in)) != null && !part.isEmpty()) {
parts.add(part);
}
StringBuilder finalMessage = new StringBuilder();
for (String s : parts) {
finalMessage.append(StatCollector.translateToLocal(s));
}
String text = finalMessage.toString();
IChatComponent comp = ColorUtil.assembleComponent(text);
player.addChatMessage(comp);
}
}
@@ -0,0 +1,70 @@
package kamkeel.npcs.network.packets.data;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.RenderChatMessages;
import noppes.npcs.entity.EntityNPCInterface;
import java.io.IOException;
public final class ChatBubblePacket extends AbstractPacket {
public static final String packetName = "Data|ChatBubble";
private int entityId;
private String text;
private boolean hideText;
public ChatBubblePacket() {
}
public ChatBubblePacket(int entityId, String text, boolean hideText) {
this.entityId = entityId;
this.text = text;
this.hideText = hideText;
}
@Override
public Enum getType() {
return EnumDataPacket.CHATBUBBLE;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.DATA_PACKET;
}
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(this.entityId);
ByteBufUtils.writeString(out, this.text);
out.writeBoolean(this.hideText);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(in.readInt());
if (!(entity instanceof EntityNPCInterface))
return;
EntityNPCInterface npc = (EntityNPCInterface) entity;
if (npc.messages == null)
npc.messages = new RenderChatMessages();
String text = NoppesStringUtils.formatText(ByteBufUtils.readString(in), player, npc);
npc.messages.addMessage(text, npc);
if (in.readBoolean())
player.addChatMessage(new ChatComponentTranslation(npc.getCommandSenderName() + ": " + text));
}
}
Loaded 100 of 1287 files, more files were not shown because too many files have changed in this diff. Show more