├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java └── com │ └── github │ └── yona168 │ └── multiblockapi │ ├── API.java │ ├── MoveMultiblockCancellers.java │ ├── MultiblockAPI.java │ ├── StateLoaderListeners.java │ ├── pattern │ ├── Pattern.java │ └── PatternCreator.java │ ├── registry │ ├── MultiblockRegistry.java │ └── SimpleMultiblockRegistry.java │ ├── state │ ├── AbstractTickableState.java │ ├── Backup.java │ ├── CountingState.java │ ├── IntState.java │ ├── MultiblockState.java │ ├── SimpleMultiblockState.java │ └── Tickable.java │ ├── storage │ ├── AbstractDataTunnel.java │ ├── DataTunnelRegistry.java │ ├── KryoDataTunnel.java │ ├── SimpleDataTunnelRegistry.java │ ├── SimpleStateCache.java │ ├── StateCache.java │ ├── StateDataTunnel.java │ ├── StateDataTunnels.java │ └── kryo │ │ ├── BukkitKryogenics.java │ │ ├── BukkitSerializers.java │ │ └── Kryogenic.java │ ├── structure │ ├── LocationInfo.java │ ├── Multiblock.java │ ├── SimpleMultiblock.java │ └── StateCreator.java │ └── util │ ├── AvelynUtils.java │ ├── ChunkCoords.java │ ├── NamespacedKey.java │ ├── SimpleChunkCoords.java │ ├── Stacktrace.java │ ├── ThreeDimensionalArrayCoords.java │ └── ToggleableTasks.java └── resources └── plugin.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 2 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 3 | 4 | .idea/ 5 | .gradle/ 6 | 7 | # IntelliJ 8 | out/ 9 | build/ 10 | 11 | #Server 12 | Server/ 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MultiblockAPI 2 | *Created in 2019 3 | ## Important Notes 4 | 1. This plugin has since been [archived](https://www.spigotmc.org/resources/multiblockapi-archived.70697/) and is no 5 | longer undergoing active development. The jar is still available at that link, though. The last tested spigot version remains 1.8 6 | 2. Since its 1.0.0 release, a dependency gave the build trouble, causing builds to fail. This has been 7 | fixed in version 1.0.1. The actual code did not change, so the 1.0.0 jar from the link above should work fine, 8 | or you can build it yourself. You also need to add the following to your build.gradle: 9 | 10 | `implementation 'com.gitlab.Avelyn:Architecture:1.0.0'` 11 | 12 | 13 | ## What is it? 14 | MultiblockAPI is a spigot API to allow the creation of multiblocks. 15 | Multiblocks are structures made from multiple blocks that, when together, make up their own special function. 16 | This can be used to create, for example, machines, guard towers, and magical altars. 17 | 18 | ## Installation 19 | 20 | Get the plugin from the spigot page: https://www.spigotmc.org/resources/multiblockapi.70697/ 21 | 22 | See https://jitpack.io/#com.github.ygins/MultiblockAPI for adding it to your project. Just make sure you are not compiling the plugin in- 23 | this is a standalone plugin. If you are using gradle, for example, do NOT use implementation-compileOnly works fine. 24 | 25 | ## Usage 26 | ### Types of Multiblocks 27 | There are two kinds of multiblocks-normal, and tickable. 28 | Normal multiblocks do something on click, and tickable blocks are 29 | enabled on tick and then do something continuously. First, 30 | let's create a simple multiblock. 31 | 32 | ###Creating a Normal Multiblock 33 | In creating a normal multiblock, there are five steps: 34 | 1. Define the structure 35 | 2. ID the structure 36 | 3. Define how state is created and stored 37 | 4. Define the multiblock function 38 | 5. Register multiblock with the API 39 | 40 | Let's try to make a multiblock that simply sends the message "Hi" when clicked. 41 | #### 1. Defining the structure 42 | To define the structure, we use the `Pattern` class. Our structure needs structure blocks, 43 | as well as a trigger block (the block that will trigger the action). 44 | Let's say we just want a simple multiblock, with a diamond block on top of a gold one, and the trigger 45 | to be the diamond block: 46 | 47 | ```java 48 | Pattern myPattern=new PatternCreator(2,1,1).//Size Levels, Rows, Columns. 49 | level(0). 50 | set(0,0, Material.GOLD_BLOCK). //set the gold block 51 | level(1).set(0,0, Material.DIAMOND_BLOCK). //Set the diamond block 52 | triggerCoords(1,0,0); //Tell the PatternCreator that the diamond block is our trigger 53 | ``` 54 | 55 | #### 2. ID'ing the structure. 56 | For 1.8 compatibility, MultiblockAPI provides its own ```NamespacedKey``` class for identification. 57 | ```java 58 | NamespacedKey saysHiKey=new NamespacedKey(this, "HiBlock"); 59 | ``` 60 | 61 | #### 3. Define how state is created and stored 62 | As of now, we have defined the structure of our multiblock. What we have not done is give 63 | it some way to instantiate that structure in the world. This is what ```MultiblockState``` is for. 64 | Each instance of ```MultiblockState``` represents one instance of the Multiblock in the world. 65 | Anything within a ```MultiblockState``` gets stored away, and only data specific to each instance should be stored in it. 66 | For this example, we don't have specific data being stored in multiblocks, as each instance does the same thing 67 | (says "Hi") on click. Therefore, we can simply use a provided implementation of ```MultiblockState```: ```SimpleMultiblockState``` 68 | What we have to do now is define a ```StateCreator``` that provides us with new states on demand. 69 | 70 | ```java 71 | StateCreator myStateCreator=(multiblock, locationInfo, event)->new SimpleMultiblockState(multiblock, locationInfo); 72 | ``` 73 | Now, we have to decide how our state is going to be stored away in a database. The objects that handle these 74 | are ```StateDataTunnels```-that is, they transport data from server to DB and back again. 75 | As of now, MultiblockAPI 76 | supports the use of Kryo-a fast serialization library-to store states in files. To reference the default ```KryoDataTunnel```, 77 | we simply do 78 | ```java 79 | StateDataTunnel kryoDataTUnnel=StateDataTunnels.kryo(); 80 | ``` 81 | #### 4. Define Multiblock Function 82 | Now, what we are going to is take these and join them into one-a ```Multiblock``` object. 83 | Just like with ```MultiblockState```, you could have your own implementation. However, using 84 | ```SimpleMultiblock``` is easy here: 85 | ```java 86 | Multiblock saysHiMultiblock=new SimpleMultiblock(myPattern, saysHiId, kryoDataTunnel,myStateCreator); 87 | saysHiMultiblock.onClick((event, state)->{ //Event is a PlayerInteractEvent 88 | event.getPlayer().sendMessage("Hi!"); 89 | }) 90 | ``` 91 | #### 5. Registering our Multiblock 92 | Easy peasy! 93 | ```java 94 | MultiblockAPI.getAPI().getMultiblockRegistry().register(saysHiMultiblock, plugin); 95 | ``` 96 | And we're done! 97 | 98 | ### How States are Stored 99 | ```MultiblockStates``` are cached when their chunk is loaded, and offloaded when not. 100 | This provides enable/disable functionality (see below) 101 | 102 | ### Custom states/multiblocks 103 | 104 | When it comes to creating more complicated structures, you may want something besides the ```Simple``` 105 | implementations for ```MultiblockState``` and ```Multiblock```. If so, you can easily make your own implementations. 106 | The recommended way is to simply extend the ```Simple``` implementations and add your own data. 107 | When deciding which to extend, ask yourself this simple question: "Is my data specific to each multiblock instance?". 108 | If yes, your data should be inside your state, and if not, inside your multiblock 109 | 110 | What's also useful about extending states is that you can add things that happen: 111 | 1. On enable (clicked for the first time or reloaded back into the world) 112 | 2. On disable (when being offloaded or destroyed) 113 | 3. On destroy (when being destroyed) 114 | 115 | So lets see how a custom state might work: 116 | 117 | ```java 118 | class CounterState extends SimpleMultiblockState{ 119 | private final LocationInfo locationInfo; 120 | private int timesClicked=0; 121 | private CounterState(UUID uuid, Multiblock multiblock, LocationInfo locationInfo, int timesClicked){ 122 | super(uuid, multiblock, locationInfo); 123 | this.locationInfo=locationInfo; 124 | this.timesClicked=timesClicked; 125 | } 126 | public CounterState(Multiblock multiblock, LocationInfo locationInfo){ 127 | this(UUID.randomUUID(), multiblock, locationInfo, 0); 128 | } 129 | public void increment(){ 130 | this.timesClicked++; 131 | } 132 | public int getTimesClicked(){ 133 | return this.timesClicked; 134 | } 135 | @Override 136 | public void onEnable(){ 137 | //You dont have to override me, but you could! 138 | } 139 | @Override 140 | public void onDisable(){ 141 | //You dont have to override me, but you could! 142 | } 143 | @Override 144 | public void onDestroy(){ 145 | //You dont have to override me, but you could! 146 | } 147 | 148 | @Override 149 | public MultiblockState snapshot(){ //Note: MUST override this method 150 | return new CounterState(this.getUniqueId(), getMultiblock(), locationInfo, timesClicked); 151 | } 152 | } 153 | ``` 154 | Then, when registering our multiblock: 155 | ```java 156 | myMultiblock.onClick((event, state)->{ 157 | event.getPlayer().sendMessage("You have clicked me "+state.getTimesClicked()+" times!"); 158 | }); 159 | ``` 160 | #### What's with this snapshot() thing? 161 | When our multiblock is enabled, it cannot be stored. To avoid disabling multiblocks, storing, then re-enabling mid-game, 162 | this method exists to provide disabled state snapshots. Snapshot should return a new state representing 163 | how the state looks when disabled, which is why this ALWAYS has to be overridden. 164 | 165 | The snapshot method is declared by the ```Backup``` interface, which is not automatically a part of 166 | ```MultiblockState```. If you have your own implementation of ```MultiblockState``` that does not implement ```Backup```, 167 | it still works fine-the only difference being that your multiblocks will NOT be backed up while still in use-they 168 | will only be stored when the chunk they are in unloads, or the server stops. It is highly reccomended to implement it. 169 | 170 | #### Tickable states. 171 | So, using this concept, you can easily create tickable states. There's just a few extra methods you 172 | have to implement. Here's a fully working example of a tower that, when clicked, shoots arrows at nearby hostiles. 173 | 174 | ```java 175 | public class GuardTowerState extends AbstractTickableState implements Backup { 176 | private transient Monster currentTarget; 177 | private final Multiblock multiblock; 178 | private final LocationInfo locationInfo; 179 | private final Plugin pLugin; 180 | public GuardTowerState(Multiblock multiblock, LocationInfo locInfo, Plugin plugin) { 181 | this(UUID.randomUUID(), multiblock, locInfo, plugin); 182 | } 183 | 184 | private GuardTowerState(UUID uuid, Multiblock multiblock, LocationInfo locationInfo, Plugin plugin){ 185 | super(uuid,multiblock,locationInfo,plugin); 186 | this.multiblock=multiblock; 187 | this.locationInfo=locationInfo; 188 | this.pLugin=plugin; 189 | } 190 | 191 | @Override 192 | public int getPeriod() { //how often the run() method is called (in ticks) 193 | return 5; 194 | } 195 | 196 | @Override 197 | public boolean isAsync() { //Whether run() runs asynchronously or synchronously. 198 | return false; 199 | } 200 | 201 | @Override 202 | public void run() { 203 | if(currentTarget==null||currentTarget.isDead()){ 204 | Optional target=this.getTriggerBlockLoc().getBlock().getWorld().getNearbyEntities(getTriggerBlockLoc(),5,5,5) 205 | .stream().filter(entity->entity instanceof Monster).map(it->(Monster)it).findFirst(); 206 | target.ifPresent(monster->this.currentTarget=monster); 207 | }else{ 208 | Vector targetVec = currentTarget.getLocation().toVector(); 209 | Location aboveTowerLocation=getBlockByPattern(4,0,0).getLocation(); 210 | aboveTowerLocation.setX(aboveTowerLocation.getX()+.5); 211 | aboveTowerLocation.setZ(aboveTowerLocation.getZ()+.5); 212 | Vector subtractedVec=aboveTowerLocation.toVector().subtract(targetVec); 213 | aboveTowerLocation.getWorld().spawnArrow(aboveTowerLocation, 214 | subtractedVec.setX(subtractedVec.getX()*-1).setZ(subtractedVec.getZ()*-1) , (float)(currentTarget.getLocation().distanceSquared(aboveTowerLocation)/135), 1); 215 | } 216 | } 217 | 218 | @Override 219 | public MultiblockState snapshot() { 220 | return new GuardTowerState(getUniqueid(),multiblock,locationInfo,pLugin); 221 | } 222 | 223 | @Override 224 | public void postTaskEnable() { 225 | Bukkit.broadcastMessage("Guard tower enabled!"); 226 | } 227 | 228 | @Override 229 | public void postTaskDisable(){ 230 | Bukkit.broadcastMessage("Guard tower disabled!"); 231 | } 232 | /* The above two methods replace onEnable and onDisable-they are triggered after Bukkit schedules and unschedules the timer task.*/ 233 | } 234 | ``` 235 | 236 | And to register: 237 | ```java 238 | class MyPlugin extends JavaPlugin{ 239 | public void onEnable(){ 240 | API multiblockAPI = MultiblockAPI.getAPI(); 241 | //Create what structure of the guard tower looks like 242 | Pattern guardTowerPattern = new PatternCreator(3, 1, 1) //Dimensions 243 | .level(0).set(0, 0, Material.COBBLESTONE) //y level=0. Material[0][0][0]=Cobble 244 | .level(1).set(0, 0, Material.DIAMOND_BLOCK)//y level=1 Mateerial[1][0][0]=diamond 245 | .level(2).set(0, 0, Material.GOLD_BLOCK) 246 | .triggerCoords(2, 0, 0);//Index in array where clicking enables it (gold block) 247 | NamespacedKey guardTowerId = new NamespacedKey(this, "Guard Tower");//note-own namespacedkey for backwards capability 248 | //A way for us to make states 249 | StateCreator guardTowerStateStateCreator = (multiblock, locInfo, event) -> new GuardTowerState(multiblock, locInfo, this); 250 | //Multiblock object creation. DataTunnels.kryo() tells us to use the default kryo storer to store the states for this multiblock 251 | Multiblock guardTowerMultiblock = new SimpleMultiblock<>(guardTowerPattern, guardTowerId, kryo(), guardTowerStateStateCreator); 252 | //pop multiblock in registry 253 | multiblockAPI.getMultiblockRegistry().register(guardTowerMultiblock, this); 254 | } 255 | } 256 | ``` 257 | Note how we implement Backup here-Backup is what defines our snapshot() method. There is no ```Simple``` 258 | implementation of ```TickableState```, so Backup is optional. Again, though, highly reccomended to use it. 259 | 260 | ## Default Kryo Data Tunnel and why you should implement your own: 261 | The default kryo data tunnel is easy to use, and is an option. The only issue with it is that it works outside of your plugin. 262 | If a server owner suddenly decides to remove a plugin using this API, that could mess up kryo files due to class registration. 263 | Creating your own ```KryoDataTunnel``` as an alternative is easy: 264 | ```java 265 | Path folderToStoreIn=plugin.getDataFolder().resolve("multiblockchunks"); 266 | StateDataTunnel myKryoDataTunnel=new KryoDataTunnel(Kryogenic.getNewPool(MultiblockAPI.getAPI()), folderToStoreIn, plugin); 267 | ``` 268 | # Commands 269 | 1. /mbapi -> backs up all multiblocks that can be backed up. 270 | 271 | # TODO 272 | Abstract SimpleMultiblockState further to allow optional implementation of Backup w/ easy extendability. 273 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'java-library' 4 | id 'com.github.johnrengelman.shadow' version '8.1.1' 5 | } 6 | 7 | group 'com.github.yona168' 8 | version '1.0.1' 9 | 10 | repositories { 11 | mavenCentral() 12 | maven { 13 | url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' 14 | } 15 | maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' } 16 | maven { url 'https://jitpack.io' } 17 | } 18 | 19 | dependencies { 20 | implementation 'com.esotericsoftware:kryo:5.0.0-RC4' 21 | implementation "de.javakaffee:kryo-serializers:0.45" 22 | compileOnly 'org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT' 23 | api 'com.gitlab.Avelyn:Core:0.0.16' 24 | implementation 'com.gitlab.Avelyn:Architecture:1.0.0' 25 | } 26 | 27 | shadowJar { 28 | archiveBaseName = "${project.name}.jar" 29 | destinationDirectory = file('Server/plugins') 30 | minimize() 31 | manifest { 32 | attributes("Main-Class": "com.github.yona168.multiblockapi.MultiblockAPI") 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ygins/MultiblockAPI/2f823942254bc1846b94837324b72f6952171b4d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'MultiblockAPI' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/API.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi; 2 | 3 | import com.github.yona168.multiblockapi.registry.MultiblockRegistry; 4 | import com.github.yona168.multiblockapi.storage.DataTunnelRegistry; 5 | 6 | public interface API { 7 | DataTunnelRegistry getDataTunnelRegistry(); 8 | MultiblockRegistry getMultiblockRegistry(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/MoveMultiblockCancellers.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi; 2 | 3 | import com.github.yona168.multiblockapi.storage.StateCache; 4 | import com.github.yona168.multiblockapi.util.AvelynUtils; 5 | import com.gitlab.avelyn.architecture.base.Component; 6 | import com.gitlab.avelyn.core.base.Events; 7 | import org.bukkit.Location; 8 | import org.bukkit.block.Block; 9 | import org.bukkit.entity.FallingBlock; 10 | import org.bukkit.event.Cancellable; 11 | import org.bukkit.event.Event; 12 | import org.bukkit.event.block.BlockPistonExtendEvent; 13 | import org.bukkit.event.block.BlockPistonRetractEvent; 14 | import org.bukkit.event.entity.EntityChangeBlockEvent; 15 | import org.bukkit.inventory.ItemStack; 16 | 17 | import java.util.HashSet; 18 | import java.util.Set; 19 | import java.util.function.Consumer; 20 | import java.util.function.Predicate; 21 | 22 | class MoveMultiblockCancellers extends Component { 23 | private final StateCache stateCache; 24 | 25 | private MoveMultiblockCancellers(StateCache stateCache) { 26 | this.stateCache = stateCache; 27 | addChild(cancel(BlockPistonExtendEvent.class) 28 | .iff(event -> event.getBlocks().stream().anyMatch(block -> 29 | isMultiblock(block) || isMultiblock(block.getRelative(event.getDirection())) 30 | ))); 31 | addChild(cancel(BlockPistonRetractEvent.class).iff(event -> event.getBlocks().stream().anyMatch(block -> 32 | isMultiblock(block) || isMultiblock(block.getRelative(event.getDirection())) 33 | ))); 34 | addChild(cancel(EntityChangeBlockEvent.class).iff(event -> event.getEntity() instanceof FallingBlock 35 | && isMultiblock(event.getBlock())).andThen(event -> { 36 | FallingBlock fallingBlock = (FallingBlock) event.getBlock(); 37 | if (fallingBlock.getDropItem()) { 38 | fallingBlock.getWorld().dropItemNaturally(fallingBlock.getLocation(), new ItemStack(fallingBlock.getMaterial())); 39 | } 40 | })); 41 | } 42 | 43 | private static Cancel cancel(Class inClazz) { 44 | return new Cancel<>(inClazz); 45 | } 46 | 47 | private static class Cancel extends Component { 48 | private final Class clazz; 49 | private final Set> andThens; 50 | 51 | private Cancel(Class clazz) { 52 | this.clazz = clazz; 53 | andThens = new HashSet<>(); 54 | } 55 | 56 | private Cancel iff(Predicate test) { 57 | addChild(AvelynUtils.listen(clazz, event -> { 58 | if (test.test(event)) { 59 | event.setCancelled(true); 60 | andThens.forEach(handler -> handler.accept(event)); 61 | } 62 | })); 63 | return this; 64 | } 65 | 66 | private Cancel andThen(Consumer handler) { 67 | andThens.add(handler); 68 | return this; 69 | } 70 | } 71 | 72 | private boolean isMultiblock(Location location) { 73 | return stateCache.getAt(location) != null; 74 | } 75 | 76 | private boolean isMultiblock(Block block) { 77 | return isMultiblock(block.getLocation()); 78 | } 79 | 80 | static MoveMultiblockCancellers cancelAttemptsToMoveMultiblocks(StateCache stateCache) { 81 | return new MoveMultiblockCancellers(stateCache); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/MultiblockAPI.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi; 2 | 3 | import com.github.yona168.multiblockapi.registry.MultiblockRegistry; 4 | import com.github.yona168.multiblockapi.registry.SimpleMultiblockRegistry; 5 | import com.github.yona168.multiblockapi.storage.DataTunnelRegistry; 6 | import com.github.yona168.multiblockapi.storage.SimpleDataTunnelRegistry; 7 | import com.github.yona168.multiblockapi.storage.SimpleStateCache; 8 | import com.github.yona168.multiblockapi.storage.StateCache; 9 | import com.gitlab.avelyn.core.components.ComponentPlugin; 10 | import org.bukkit.ChatColor; 11 | import org.bukkit.command.Command; 12 | import org.bukkit.command.CommandExecutor; 13 | import org.bukkit.command.CommandSender; 14 | import org.jetbrains.annotations.NotNull; 15 | 16 | import java.util.function.Function; 17 | import java.util.function.Supplier; 18 | 19 | 20 | public class MultiblockAPI extends ComponentPlugin implements API { 21 | private final MultiblockRegistry multiblockRegistry; 22 | private final DataTunnelRegistry dataTunnelRegistry; 23 | private static API api; 24 | 25 | public MultiblockAPI() { 26 | multiblockRegistry = new SimpleMultiblockRegistry(); 27 | final StateCache stateCache = new SimpleStateCache(); 28 | dataTunnelRegistry = new SimpleDataTunnelRegistry(); 29 | final MultiblockAPI ref = this; 30 | onEnable(() -> api = new API() { 31 | @Override 32 | public DataTunnelRegistry getDataTunnelRegistry() { 33 | return ref.getDataTunnelRegistry(); 34 | } 35 | 36 | @Override 37 | public MultiblockRegistry getMultiblockRegistry() { 38 | return ref.getMultiblockRegistry(); 39 | } 40 | }); 41 | onDisable(() -> api = null); 42 | 43 | addChild(new StateLoaderListeners(stateCache, multiblockRegistry, dataTunnelRegistry, this, null)); 44 | onEnable(()->{ 45 | getCommand("mbapi").setExecutor(new CommandExecutor() { 46 | private final ChatColor MAIN_COLOR=ChatColor.GRAY; 47 | private final ChatColor SECONDARY_COLOR=ChatColor.LIGHT_PURPLE; 48 | private final Supplier tag=()->SECONDARY_COLOR+"["+MAIN_COLOR+"MBAPI"+SECONDARY_COLOR+"]"; 49 | private final Function msg=(msg)->tag.get()+ChatColor.RESET+" "+msg; 50 | private final Function err=(msg)->tag.get()+ChatColor.RED+" "+msg; 51 | @Override 52 | public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { 53 | if(sender.hasPermission("mbapi.backup")){ 54 | sender.sendMessage(msg.apply("Backup starting...")); 55 | stateCache.backup().thenAccept($->sender.sendMessage(msg.apply("Backup complete!"))); 56 | }else{ 57 | sender.sendMessage(err.apply("You do not have permission to use this command!")); 58 | } 59 | return true; 60 | } 61 | }); 62 | }); 63 | 64 | } 65 | 66 | @Override 67 | public DataTunnelRegistry getDataTunnelRegistry() { 68 | return dataTunnelRegistry; 69 | } 70 | 71 | @Override 72 | public MultiblockRegistry getMultiblockRegistry() { 73 | return multiblockRegistry; 74 | } 75 | 76 | public static API getAPI() { 77 | return api; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/StateLoaderListeners.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi; 2 | 3 | import com.github.yona168.multiblockapi.registry.MultiblockRegistry; 4 | import com.github.yona168.multiblockapi.storage.StateCache; 5 | import com.github.yona168.multiblockapi.state.MultiblockState; 6 | import com.github.yona168.multiblockapi.storage.DataTunnelRegistry; 7 | import com.github.yona168.multiblockapi.storage.StateDataTunnel; 8 | import com.github.yona168.multiblockapi.storage.StateDataTunnels; 9 | import com.github.yona168.multiblockapi.util.NamespacedKey; 10 | import com.gitlab.avelyn.architecture.base.Component; 11 | import com.gitlab.avelyn.architecture.base.Toggleable; 12 | import com.gitlab.avelyn.core.base.Events; 13 | import org.bukkit.Bukkit; 14 | import org.bukkit.World; 15 | import org.bukkit.block.Block; 16 | import org.bukkit.*; 17 | import org.bukkit.command.CommandSender; 18 | import org.bukkit.event.EventPriority; 19 | import org.bukkit.event.block.Action; 20 | import org.bukkit.event.block.BlockBreakEvent; 21 | import org.bukkit.event.entity.EntityExplodeEvent; 22 | import org.bukkit.event.player.PlayerInteractEvent; 23 | import org.bukkit.event.world.ChunkLoadEvent; 24 | import org.bukkit.event.world.ChunkUnloadEvent; 25 | import org.bukkit.event.world.WorldUnloadEvent; 26 | import org.bukkit.inventory.EquipmentSlot; 27 | import org.bukkit.plugin.Plugin; 28 | 29 | import java.util.*; 30 | import java.util.function.BiConsumer; 31 | import java.util.stream.Collectors; 32 | 33 | import static com.github.yona168.multiblockapi.MoveMultiblockCancellers.cancelAttemptsToMoveMultiblocks; 34 | import static com.github.yona168.multiblockapi.util.AvelynUtils.listen; 35 | import static com.github.yona168.multiblockapi.util.ToggleableTasks.syncLater; 36 | import static java.lang.System.currentTimeMillis; 37 | import static org.bukkit.Bukkit.*; 38 | 39 | public class StateLoaderListeners extends Component { 40 | private final BiConsumer debug; 41 | private final StateCache stateCache; 42 | private final DataTunnelRegistry dataTunnelRegistry; 43 | private final MultiblockRegistry multiblockRegistry; 44 | private final Plugin plugin; 45 | 46 | public StateLoaderListeners(StateCache stateCache, MultiblockRegistry multiblockRegistry, DataTunnelRegistry storageMethodRegistry, Plugin plugin, BiConsumer debug) { 47 | this.plugin = plugin; 48 | this.debug = debug; 49 | this.stateCache = stateCache; 50 | this.dataTunnelRegistry = storageMethodRegistry; 51 | this.multiblockRegistry = multiblockRegistry; 52 | addChild(multiblockRegistry); 53 | addChild(StateDataTunnels.enabler(plugin, multiblockRegistry)); 54 | addChild(cancelAttemptsToMoveMultiblocks(stateCache)); 55 | addChild(listen(PlayerInteractEvent.class, this::handleInteract)); 56 | addChild(Events.listen(BlockBreakEvent.class, EventPriority.MONITOR, this::handleBlockBreak)); 57 | addChild(Events.listen(EntityExplodeEvent.class, EventPriority.MONITOR, this::handleEntityExplode)); 58 | addChild(listen(ChunkUnloadEvent.class, this::handleChunkUnload)); 59 | addChild(listen(WorldUnloadEvent.class, this::handleWorldUnload)); 60 | addChild(listen(ChunkLoadEvent.class, this::handleChunkLoad)); 61 | onEnable(() -> dataTunnelRegistry.register(new NamespacedKey(plugin, "KRYO"), StateDataTunnels.kryo())); 62 | onEnable(() -> 63 | getScheduler().runTask(plugin, () -> Bukkit.getWorlds().stream().map(World::getLoadedChunks) 64 | .flatMap(Arrays::stream).forEach(chunk -> proccessLoadingChunk(chunk, false))) 65 | ); 66 | onDisable(() -> { 67 | Bukkit.getWorlds().forEach(world -> processUnloadingWorld(world, false)); 68 | storageMethodRegistry.waitForAllAsyncsDone(); 69 | stateCache.clear(); 70 | }); 71 | } 72 | 73 | public StateLoaderListeners(StateCache stateCache, MultiblockRegistry registry, DataTunnelRegistry storageMethodRegistry, Plugin plugin) { 74 | this(stateCache, registry, storageMethodRegistry, plugin, null); 75 | } 76 | 77 | 78 | private void handleInteract(PlayerInteractEvent event) { 79 | if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { 80 | return; 81 | } 82 | final Location clickedLoc = event.getClickedBlock().getLocation(); 83 | if (dataTunnelRegistry.isProcessing(clickedLoc.getChunk())) { 84 | return; 85 | } 86 | MultiblockState existingState = stateCache.getAt(clickedLoc); 87 | long before = currentTimeMillis(); 88 | if (existingState == null) { 89 | multiblockRegistry.getAllMultiblocks().stream().map(multiblock -> multiblock.generateStateFrom(event)).filter(Optional::isPresent).map(Optional::get).findFirst().ifPresent(multiblockState -> { 90 | boolean wouldOverwriteExistingState = multiblockState.getAllBlocksLocs().stream().anyMatch(loc -> stateCache.getAt(loc) != null); 91 | if (wouldOverwriteExistingState) { 92 | return; 93 | } 94 | stateCache.store(multiblockState); 95 | (multiblockState).enable(); 96 | multiblockState.getMultiblock().doClickActions(event, multiblockState); 97 | if (debug != null) { 98 | long difference = currentTimeMillis() - before; 99 | debug.accept(event.getPlayer(), "Multiblock has been registered, and the whole process took " + ChatColor.LIGHT_PURPLE + difference + ChatColor.RESET + " millis"); 100 | } 101 | }); 102 | } else { 103 | existingState.getMultiblock().doClickActions(event, existingState); 104 | if (debug != null) { 105 | long difference = currentTimeMillis() - before; 106 | debug.accept(event.getPlayer(), "Multiblock was detected as registered, and the whole process took " + ChatColor.LIGHT_PURPLE + difference + ChatColor.RESET + " millis"); 107 | } 108 | } 109 | } 110 | 111 | private void handleBlockBreak(BlockBreakEvent event) { 112 | if (event.isCancelled()) { 113 | return; 114 | } 115 | if (dataTunnelRegistry.isProcessing(event.getBlock().getLocation().getChunk())) { 116 | event.getPlayer().sendMessage("Multiblocks are being updated for this chunk, please wait..."); 117 | event.setCancelled(true); 118 | } else { 119 | processBrokenBlock(event.getBlock()); 120 | } 121 | } 122 | 123 | private void handleEntityExplode(EntityExplodeEvent event) { 124 | if (event.isCancelled()) { 125 | } else { 126 | event.blockList().forEach(this::processBrokenBlock); 127 | } 128 | } 129 | 130 | private void processBrokenBlock(Block block) { 131 | long removeTime = 0; 132 | if (debug != null) { 133 | removeTime = currentTimeMillis(); 134 | } 135 | final Location broken = block.getLocation(); 136 | final MultiblockState brokenState = stateCache.getAt(broken); 137 | if (brokenState != null) { 138 | brokenState.disable(); 139 | brokenState.destroy(); 140 | stateCache.remove(brokenState); 141 | brokenState.getMultiblock().getDataTunnel().removeFromAfarAsync(brokenState); 142 | if (debug != null) { 143 | debug.accept(getConsoleSender(), removeTimeMsg(removeTime)); 144 | } 145 | } 146 | } 147 | 148 | private void handleChunkUnload(ChunkUnloadEvent event) { 149 | final Chunk chunk = event.getChunk(); 150 | long removeTimeU = 0; 151 | if (debug != null) { 152 | removeTimeU = currentTimeMillis(); 153 | } 154 | final long removeTime = removeTimeU; 155 | final Collection statesInChunk = new HashSet<>(stateCache.getAt(chunk)); 156 | if (!statesInChunk.isEmpty()) { 157 | Toggleable unloadTask = syncLater(plugin, 100L, () -> { 158 | if (chunk.isLoaded()) { 159 | return; 160 | } 161 | int size = statesInChunk.size(); 162 | statesInChunk.forEach(state -> { 163 | state.disable(); 164 | stateCache.remove(state); 165 | state.getMultiblock().getDataTunnel().storeAwayAsync(state); 166 | }); 167 | if (debug != null) { 168 | debug.accept(getConsoleSender(), size + "states were removed from chunk " + ChatColor.RED + chunk.getX() + ", " + chunk.getZ() + " in " + ChatColor.LIGHT_PURPLE + (currentTimeMillis() - removeTime) + ChatColor.RESET + " ms."); 169 | } 170 | }); 171 | unloadTask.enable(); 172 | } 173 | } 174 | 175 | private void handleChunkLoad(ChunkLoadEvent event) { 176 | proccessLoadingChunk(event.getChunk(), true); 177 | } 178 | 179 | private void proccessLoadingChunk(Chunk chunk, boolean async) { 180 | Collection alreadyLoadedStates = stateCache.getAt(chunk); 181 | if (alreadyLoadedStates == null || (alreadyLoadedStates.size() != 0) || dataTunnelRegistry.isProcessing(chunk)) { 182 | return; 183 | } 184 | long removeTime = currentTimeMillis(); 185 | if (async) { 186 | dataTunnelRegistry.getAllStorageMethods().forEach(dataTunnel -> { 187 | dataTunnel.getFromAfarAsync(chunk).thenAccept(multiblockStates -> { 188 | int size = multiblockStates.size(); 189 | multiblockStates.forEach(state -> { 190 | sync(() -> stateCache.store(state)); 191 | sync(state::enable); 192 | }); 193 | if (debug != null && multiblockStates.size() != 0) { 194 | debug.accept(getConsoleSender(), size + " states were pulled from afar into chunk " + ChatColor.RED + chunk.getX() + ", " + chunk.getZ() + " in " + ChatColor.LIGHT_PURPLE + (currentTimeMillis() - removeTime) + ChatColor.RESET + " ms."); 195 | } 196 | }); 197 | }); 198 | } else { 199 | List multiblockStates = dataTunnelRegistry.getAllStorageMethods() 200 | .stream().map(dataTunnel -> dataTunnel.getFromAfar(chunk)) 201 | .flatMap(Collection::stream).collect(Collectors.toList()); 202 | int size = multiblockStates.size(); 203 | multiblockStates.forEach(state -> { 204 | stateCache.store(state); 205 | state.enable(); 206 | }); 207 | if (debug != null && multiblockStates.size() != 0) { 208 | debug.accept(getConsoleSender(), size + " states were pulled from afar into chunk " + ChatColor.RED + chunk.getX() + ", " + chunk.getZ() + " in " + ChatColor.LIGHT_PURPLE + (currentTimeMillis() - removeTime) + ChatColor.RESET + " ms."); 209 | } 210 | } 211 | } 212 | 213 | private void handleWorldUnload(WorldUnloadEvent event) { 214 | processUnloadingWorld(event.getWorld(), true); 215 | } 216 | 217 | private void processUnloadingWorld(World world, boolean async) { 218 | long removeTime = 0; 219 | if (debug != null) { 220 | removeTime = currentTimeMillis(); 221 | } 222 | final Collection unloadedStates = new HashSet<>(stateCache.getAt(world)); 223 | if (unloadedStates.isEmpty()) { 224 | return; 225 | } 226 | int size = unloadedStates.size(); 227 | unloadedStates.forEach(state -> { 228 | stateCache.remove(state); 229 | state.disable(); 230 | final StateDataTunnel dataTunnel = state.getMultiblock().getDataTunnel(); 231 | if (async) dataTunnel.storeAwayAsync(state); 232 | else dataTunnel.storeAway(state); 233 | }); 234 | if (debug != null) { 235 | debug.accept(getConsoleSender(), size + " states were removed from world " + ChatColor.RED + world + " in " + (currentTimeMillis() - removeTime) + " ms."); 236 | } 237 | } 238 | 239 | private static String removeTimeMsg(long removeTime) { 240 | return "Multiblock removed in " + ChatColor.LIGHT_PURPLE + (currentTimeMillis() - removeTime) + ChatColor.RESET + " ms"; 241 | } 242 | 243 | private void sync(Runnable runnable) { 244 | getScheduler().runTask(this.plugin, runnable); 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/pattern/Pattern.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.pattern; 2 | 3 | 4 | import com.github.yona168.multiblockapi.util.ThreeDimensionalArrayCoords; 5 | import org.bukkit.Material; 6 | 7 | public interface Pattern { 8 | Material[][][] asArray(); 9 | 10 | ThreeDimensionalArrayCoords getTriggerCoords(); 11 | 12 | static Pattern of(Material[][][] pattern, ThreeDimensionalArrayCoords coords) { 13 | return new Pattern() { 14 | @Override 15 | public Material[][][] asArray() { 16 | return pattern; 17 | } 18 | 19 | @Override 20 | public ThreeDimensionalArrayCoords getTriggerCoords() { 21 | return coords; 22 | } 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/pattern/PatternCreator.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.pattern; 2 | 3 | import com.github.yona168.multiblockapi.util.ThreeDimensionalArrayCoords; 4 | import org.bukkit.Material; 5 | 6 | public class PatternCreator { 7 | private final Material[][][] pattern; 8 | 9 | public PatternCreator(int height, int depth, int length) { 10 | this(new Material[height][depth][length]); 11 | } 12 | 13 | private PatternCreator(Material[][][] arr) { 14 | this.pattern = arr; 15 | } 16 | 17 | public static PatternCreator wrap(Material[][][] arr) { 18 | return new PatternCreator(arr); 19 | } 20 | 21 | public PatternCreator set(int level, int row, int column, Material material) { 22 | this.pattern[level][row][column] = material; 23 | return this; 24 | } 25 | 26 | public PatternCreator fillRow(int level, int row, Material material) { 27 | for (int c = 0; c < pattern[0][0].length; c++) { 28 | set(level, row, c, material); 29 | } 30 | return this; 31 | } 32 | 33 | public PatternCreator fillColumn(int level, int column, Material material) { 34 | for (int r = 0; r < pattern[0].length; r++) { 35 | set(level, r, column, material); 36 | } 37 | return this; 38 | } 39 | 40 | public PatternCreator fillLevel(int level, Material material) { 41 | for (int r = 0; r < pattern[0].length; r++) { 42 | for (int c = 0; c < pattern[0][0].length; c++) { 43 | set(level, r, c, material); 44 | } 45 | } 46 | return this; 47 | } 48 | 49 | 50 | public SetYPatternCreator level(int y) { 51 | if (y < 0) { 52 | throw new IllegalArgumentException("You cannot set the working level to a negative value! you entered: " + y); 53 | } 54 | return new SetYPatternCreator(pattern, y); 55 | } 56 | 57 | public Pattern triggerCoords(int y, int x, int z) { 58 | return Pattern.of(this.pattern,new ThreeDimensionalArrayCoords(y,x,z)); 59 | } 60 | 61 | public static class SetYPatternCreator extends PatternCreator { 62 | private final int workingLevel; 63 | 64 | private SetYPatternCreator(Material[][][] arr, int workingLevel) { 65 | super(arr); 66 | this.workingLevel = workingLevel; 67 | } 68 | 69 | public SetYPatternCreator set(int row, int column, Material material) { 70 | super.set(workingLevel, row, column, material); 71 | return this; 72 | } 73 | 74 | public SetYPatternCreator fillLevel(Material material) { 75 | super.fillLevel(workingLevel, material); 76 | return this; 77 | } 78 | 79 | public SetYPatternCreator fillRow(int row, Material material){ 80 | super.fillRow(workingLevel,row,material); 81 | return this; 82 | } 83 | 84 | public SetYPatternCreator fillColumn(int column, Material material){ 85 | super.fillColumn(workingLevel, column, material); 86 | return this; 87 | } 88 | } 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/registry/MultiblockRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.registry; 2 | 3 | import com.github.yona168.multiblockapi.structure.Multiblock; 4 | import com.github.yona168.multiblockapi.util.NamespacedKey; 5 | import com.gitlab.avelyn.architecture.base.Toggleable; 6 | import org.bukkit.plugin.Plugin; 7 | 8 | import java.util.Collection; 9 | 10 | public interface MultiblockRegistry extends Toggleable { 11 | void register(Multiblock item, Plugin plugin); 12 | 13 | Collection> getForPlugin(Plugin plugin); 14 | 15 | Multiblock get(NamespacedKey name); 16 | 17 | Collection> getAllMultiblocks(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/registry/SimpleMultiblockRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.registry; 2 | 3 | import com.github.yona168.multiblockapi.structure.Multiblock; 4 | import com.github.yona168.multiblockapi.util.NamespacedKey; 5 | import com.gitlab.avelyn.architecture.base.Component; 6 | import com.google.common.collect.HashMultimap; 7 | import com.google.common.collect.Multimap; 8 | import org.bukkit.plugin.Plugin; 9 | 10 | import java.util.*; 11 | 12 | public class SimpleMultiblockRegistry extends Component implements MultiblockRegistry { 13 | private final Map> registryMapById; 14 | private final Multimap> registryMapByPlugin; 15 | private final List> allMultiblocks; 16 | 17 | public SimpleMultiblockRegistry() { 18 | registryMapById = new HashMap<>(); 19 | registryMapByPlugin = HashMultimap.create(); 20 | allMultiblocks = new ArrayList<>(); 21 | onDisable(() -> { 22 | registryMapById.clear(); 23 | registryMapByPlugin.clear(); 24 | allMultiblocks.clear(); 25 | }); 26 | } 27 | 28 | @Override 29 | public void register(Multiblock multiblock, Plugin plugin) { 30 | registryMapById.put(multiblock.getId(), multiblock); 31 | allMultiblocks.add(multiblock); 32 | registryMapByPlugin.put(plugin, multiblock); 33 | } 34 | 35 | @Override 36 | public Collection> getForPlugin(Plugin plugin) { 37 | Collection> multiblocks = registryMapByPlugin.get(plugin); 38 | if (multiblocks == null) { 39 | return null; 40 | } 41 | return multiblocks; 42 | } 43 | 44 | @Override 45 | public Multiblock get(NamespacedKey id) { 46 | return registryMapById.get(id); 47 | } 48 | 49 | @Override 50 | public Collection> getAllMultiblocks() { 51 | return allMultiblocks; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/AbstractTickableState.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | import com.github.yona168.multiblockapi.structure.LocationInfo; 4 | import com.github.yona168.multiblockapi.structure.Multiblock; 5 | import org.bukkit.plugin.Plugin; 6 | import org.bukkit.scheduler.BukkitScheduler; 7 | 8 | import java.util.UUID; 9 | 10 | import static org.bukkit.Bukkit.getScheduler; 11 | 12 | public abstract class AbstractTickableState extends SimpleMultiblockState implements Tickable { 13 | private final Plugin plugin; 14 | private int taskId; 15 | 16 | public AbstractTickableState(Multiblock multiblock, LocationInfo locInfo, Plugin plugin) { 17 | this(UUID.randomUUID(), multiblock, locInfo, plugin); 18 | } 19 | 20 | protected AbstractTickableState(UUID uuid, Multiblock multiblock, LocationInfo locationInfo, Plugin plugin) { 21 | super(uuid, multiblock, locationInfo); 22 | this.plugin = plugin; 23 | } 24 | 25 | @Override 26 | public final void onEnable() { 27 | BukkitScheduler scheduler = getScheduler(); 28 | taskId = isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, getPeriod()).getTaskId() : 29 | scheduler.runTaskTimer(plugin, this, 0, getPeriod()).getTaskId(); 30 | postTaskEnable(); 31 | } 32 | 33 | @Override 34 | public final void onDisable() { 35 | getScheduler().cancelTask(taskId); 36 | postTaskDisable(); 37 | } 38 | 39 | public void postTaskEnable() { 40 | 41 | } 42 | 43 | public void postTaskDisable() { 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/Backup.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | public interface Backup { 4 | MultiblockState snapshot(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/CountingState.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | import com.github.yona168.multiblockapi.structure.LocationInfo; 4 | import com.github.yona168.multiblockapi.structure.Multiblock; 5 | import org.bukkit.plugin.Plugin; 6 | 7 | import static org.bukkit.Bukkit.broadcastMessage; 8 | 9 | public class CountingState extends AbstractTickableState { 10 | private final int interval; 11 | private int num=0; 12 | public CountingState(Multiblock multiblock, LocationInfo locInfo, Plugin plugin, int interval) { 13 | super(multiblock, locInfo, plugin); 14 | this.interval=interval; 15 | } 16 | 17 | @Override 18 | public int getPeriod() { 19 | return interval; 20 | } 21 | 22 | @Override 23 | public boolean isAsync() { 24 | return false; 25 | } 26 | 27 | @Override 28 | public void postTaskEnable(){ 29 | broadcastMessage("Tickable enabled!"); 30 | } 31 | @Override 32 | public void postTaskDisable(){ 33 | broadcastMessage("Tickable disabled!"); 34 | } 35 | @Override 36 | public void onDestroy(){ 37 | broadcastMessage("Tickable destroyed!"); 38 | } 39 | @Override 40 | public void run() { 41 | num++; 42 | } 43 | public int getNum(){ 44 | return this.num; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/IntState.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | import com.github.yona168.multiblockapi.structure.LocationInfo; 4 | import com.github.yona168.multiblockapi.structure.Multiblock; 5 | 6 | import static org.bukkit.Bukkit.broadcastMessage; 7 | 8 | public class IntState extends SimpleMultiblockState { 9 | private int x = 0; 10 | 11 | public IntState(Multiblock multiblock, LocationInfo locInfo) { 12 | super(multiblock, locInfo); 13 | } 14 | 15 | public void toggle() { 16 | x++; 17 | } 18 | 19 | public int getInt() { 20 | return x; 21 | } 22 | 23 | @Override 24 | public void onEnable() { 25 | broadcastMessage("This state is enabled!"); 26 | } 27 | 28 | @Override 29 | public void onDisable() { 30 | broadcastMessage("This state is disabled!"); 31 | } 32 | 33 | @Override 34 | public void onDestroy() { 35 | broadcastMessage("This state is destroyed!"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/MultiblockState.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | import com.github.yona168.multiblockapi.structure.Multiblock; 4 | import com.github.yona168.multiblockapi.util.ChunkCoords; 5 | import com.github.yona168.multiblockapi.util.ThreeDimensionalArrayCoords; 6 | import com.gitlab.avelyn.architecture.base.Toggleable; 7 | import org.bukkit.Chunk; 8 | import org.bukkit.Location; 9 | import org.bukkit.World; 10 | import org.bukkit.block.Block; 11 | 12 | import java.util.*; 13 | 14 | public interface MultiblockState extends Toggleable { 15 | 16 | Block getBlockByPattern(int level, int row, int column); 17 | 18 | Location getTriggerBlockLoc(); 19 | 20 | Set getStructureBlocksLocs(); 21 | 22 | Multiblock getMultiblock(); 23 | 24 | Set getAllBlocksLocs(); 25 | 26 | Set getOccupiedChunks(); 27 | 28 | Chunk getTriggerChunk(); 29 | 30 | Orientation getOrientation(); 31 | 32 | UUID getUniqueid(); 33 | 34 | default World getWorld() { 35 | return getTriggerBlockLoc().getWorld(); 36 | } 37 | 38 | void onEnable(); 39 | void onDisable(); 40 | 41 | void destroy(); 42 | void onDestroy(); 43 | 44 | boolean isDestroyed(); 45 | 46 | enum Orientation { 47 | NORTH { 48 | @Override 49 | Block getBlock(int level, int row, int column, Block bottomLeftCorner) { 50 | return bottomLeftCorner.getRelative(column, level, row); 51 | } 52 | }, 53 | SOUTH { 54 | @Override 55 | Block getBlock(int level, int row, int column, Block bottomLeftCorner) { 56 | return bottomLeftCorner.getRelative(-column, level, -row); 57 | } 58 | }, 59 | EAST { 60 | @Override 61 | Block getBlock(int level, int row, int column, Block bottomLeftCorner) { 62 | return bottomLeftCorner.getRelative(-row, level, column); 63 | } 64 | }, 65 | WEST { 66 | @Override 67 | Block getBlock(int level, int row, int column, Block bottomLeftCorner) { 68 | return bottomLeftCorner.getRelative(row, level, -column); 69 | } 70 | }; 71 | 72 | abstract Block getBlock(int level, int row, int column, Block bottomLeftCorner); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/SimpleMultiblockState.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | import com.github.yona168.multiblockapi.structure.LocationInfo; 4 | import com.github.yona168.multiblockapi.structure.Multiblock; 5 | import com.github.yona168.multiblockapi.util.ChunkCoords; 6 | import com.github.yona168.multiblockapi.util.ThreeDimensionalArrayCoords; 7 | import org.bukkit.Chunk; 8 | import org.bukkit.Location; 9 | import org.bukkit.block.Block; 10 | 11 | import java.util.HashSet; 12 | import java.util.Objects; 13 | import java.util.Set; 14 | import java.util.UUID; 15 | import java.util.stream.Collectors; 16 | 17 | import static java.util.UUID.randomUUID; 18 | 19 | public class SimpleMultiblockState implements MultiblockState, Backup { 20 | private final Orientation orientation; 21 | private final Block bottomLeftBlock; 22 | private final Location triggerLoc; 23 | private final Set structureBlocks; 24 | private final Set allBlocks; 25 | private final Set occupiedChunks; 26 | private final Chunk triggerChunk; 27 | private final Multiblock multiblock; 28 | private final UUID uuid; 29 | private final LocationInfo locationInfo; 30 | //Whether or not the state exists within the world at the moment (not offloaded) 31 | private boolean enabled; 32 | //Whether or not the state is destroyed (Multiblock is destroyed) 33 | private boolean destroyed; 34 | 35 | protected SimpleMultiblockState(UUID uuid, Multiblock multiblock, LocationInfo locationInfo) { 36 | this.uuid = uuid; 37 | this.enabled = false; 38 | this.destroyed = false; 39 | this.multiblock = multiblock; 40 | this.locationInfo=locationInfo; 41 | this.orientation = locationInfo.getOrientation(); 42 | this.bottomLeftBlock = locationInfo.getBottomLeftCorner(); 43 | ThreeDimensionalArrayCoords triggerCoords = multiblock.getPattern().getTriggerCoords(); 44 | this.triggerLoc = orientation.getBlock(triggerCoords.getY(), triggerCoords.getRow(), triggerCoords.getColumn(), bottomLeftBlock).getLocation(); 45 | this.allBlocks = locationInfo.getAllBlockLocations(); 46 | Set allBlocksCopy = new HashSet<>(allBlocks); 47 | allBlocksCopy.remove(triggerLoc); 48 | this.structureBlocks = allBlocksCopy; 49 | occupiedChunks = allBlocks.stream().map(Location::getChunk).map(ChunkCoords::fromChunk).collect(Collectors.toSet()); 50 | this.triggerChunk = triggerLoc.getChunk(); 51 | } 52 | 53 | public SimpleMultiblockState(Multiblock multiblock, LocationInfo locInfo) { 54 | this(randomUUID(), multiblock, locInfo); 55 | } 56 | 57 | @Override 58 | public Location getTriggerBlockLoc() { 59 | return triggerLoc; 60 | } 61 | 62 | @Override 63 | public Set getStructureBlocksLocs() { 64 | return structureBlocks; 65 | } 66 | 67 | @Override 68 | public Block getBlockByPattern(int level, int row, int column) { 69 | return orientation.getBlock(level, row, column, bottomLeftBlock); 70 | } 71 | 72 | @Override 73 | public Multiblock getMultiblock() { 74 | return multiblock; 75 | } 76 | 77 | @Override 78 | public Set getAllBlocksLocs() { 79 | return allBlocks; 80 | } 81 | 82 | @Override 83 | public Set getOccupiedChunks() { 84 | return this.occupiedChunks; 85 | } 86 | 87 | @Override 88 | public Chunk getTriggerChunk() { 89 | return triggerChunk; 90 | } 91 | 92 | @Override 93 | public Orientation getOrientation() { 94 | return orientation; 95 | } 96 | 97 | @Override 98 | public UUID getUniqueid() { 99 | return uuid; 100 | } 101 | 102 | @Override 103 | public boolean isDestroyed() { 104 | return destroyed; 105 | } 106 | 107 | @Override 108 | public void destroy() { 109 | if (destroyed) { 110 | throw new IllegalStateException("This State is already destroyed!"); 111 | } else { 112 | onDestroy(); 113 | destroyed = true; 114 | } 115 | } 116 | 117 | @Override 118 | public void onDestroy() { 119 | 120 | } 121 | 122 | @Override 123 | public MultiblockState enable() { 124 | if (isEnabled()) { 125 | throw new IllegalStateException("This state is already enabled!"); 126 | } else { 127 | onEnable(); 128 | enabled = true; 129 | return this; 130 | } 131 | } 132 | 133 | @Override 134 | public MultiblockState disable() { 135 | if (!isEnabled()) { 136 | throw new IllegalStateException("This state is already disabled!"); 137 | } else { 138 | onDisable(); 139 | enabled = false; 140 | return this; 141 | } 142 | } 143 | 144 | @Override 145 | public void onEnable() { 146 | 147 | } 148 | 149 | @Override 150 | public void onDisable() { 151 | 152 | } 153 | 154 | @Override 155 | public boolean isEnabled() { 156 | return enabled; 157 | } 158 | 159 | @Override 160 | public int hashCode() { 161 | return Objects.hash(orientation, triggerLoc, bottomLeftBlock, allBlocks, multiblock); 162 | } 163 | 164 | @Override 165 | public boolean equals(Object obj) { 166 | if (!(obj instanceof SimpleMultiblockState)) { 167 | return false; 168 | } 169 | SimpleMultiblockState other = (SimpleMultiblockState) obj; 170 | if (orientation != other.orientation || this.multiblock != other.multiblock || (!(this.allBlocks.equals(other.allBlocks)))) { 171 | return false; 172 | } 173 | return true; 174 | } 175 | 176 | 177 | @Override 178 | public MultiblockState snapshot() { 179 | return new SimpleMultiblockState(this.uuid, this.multiblock, this.locationInfo); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/state/Tickable.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.state; 2 | 3 | public interface Tickable extends Runnable { 4 | int getPeriod(); 5 | boolean isAsync(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/AbstractDataTunnel.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.state.MultiblockState; 4 | import com.gitlab.avelyn.architecture.base.Component; 5 | import org.bukkit.Chunk; 6 | import org.bukkit.World; 7 | import org.bukkit.plugin.Plugin; 8 | import org.bukkit.scheduler.BukkitRunnable; 9 | 10 | import java.util.Collection; 11 | import java.util.Map; 12 | import java.util.Set; 13 | import java.util.concurrent.CompletableFuture; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | import java.util.concurrent.locks.Lock; 16 | import java.util.concurrent.locks.ReadWriteLock; 17 | import java.util.concurrent.locks.ReentrantReadWriteLock; 18 | import java.util.function.Function; 19 | 20 | import static java.util.Collections.newSetFromMap; 21 | 22 | public abstract class AbstractDataTunnel extends Component implements StateDataTunnel { 23 | private final Plugin plugin; 24 | private final Map processingChunks; 25 | private final Map lockMap; 26 | private final Set runningAsyncTasks; 27 | 28 | public AbstractDataTunnel(Plugin plugin) { 29 | this.plugin = plugin; 30 | lockMap = new ConcurrentHashMap<>(); 31 | processingChunks = new ConcurrentHashMap<>(); 32 | runningAsyncTasks = newSetFromMap(new ConcurrentHashMap<>()); 33 | onDisable(() -> { 34 | lockMap.clear(); 35 | processingChunks.clear(); 36 | runningAsyncTasks.clear(); 37 | }); 38 | } 39 | 40 | 41 | abstract Collection initGetFromAfar(Chunk chunk); 42 | 43 | abstract void initRemoveFromAfar(MultiblockState state); 44 | 45 | abstract void initStoreAway(MultiblockState state); 46 | 47 | @Override 48 | public void storeAway(MultiblockState state) { 49 | withWriteLockFor(state.getTriggerChunk(), () -> initStoreAway(state)); 50 | } 51 | 52 | @Override 53 | public CompletableFuture storeAwayAsync(MultiblockState state) { 54 | CompletableFuture returning = new CompletableFuture<>(); 55 | asyncProccess(() -> { 56 | withWriteLockFor(state.getTriggerChunk(), () -> { 57 | initStoreAway(state); 58 | returning.complete(null); 59 | }); 60 | }); 61 | return returning; 62 | } 63 | 64 | @Override 65 | public boolean isProcessingInDB(Chunk chunk) { 66 | return processingChunks.containsKey(chunk); 67 | } 68 | 69 | @Override 70 | public Collection getFromAfar(Chunk chunk) { 71 | return withReadLockFor(chunk, $ -> initGetFromAfar(chunk)); 72 | } 73 | 74 | @Override 75 | public CompletableFuture> getFromAfarAsync(Chunk chunk) { 76 | CompletableFuture> returning = new CompletableFuture<>(); 77 | asyncProccess(() -> 78 | returning.complete(withReadLockFor(chunk, $ -> initGetFromAfar(chunk)))); 79 | return returning; 80 | } 81 | 82 | @Override 83 | public void removeFromAfar(MultiblockState state) { 84 | withWriteLockFor(state.getTriggerChunk(), () -> initRemoveFromAfar(state)); 85 | } 86 | 87 | @Override 88 | public CompletableFuture removeFromAfarAsync(MultiblockState state) { 89 | CompletableFuture returning = new CompletableFuture<>(); 90 | asyncProccess(() -> { 91 | withWriteLockFor(state.getTriggerChunk(), () -> { 92 | initRemoveFromAfar(state); 93 | returning.complete(null); 94 | }); 95 | }); 96 | return returning; 97 | } 98 | 99 | @Override 100 | public void blockUntilAsyncsDone() { 101 | while (!runningAsyncTasks.isEmpty()) { 102 | 103 | } 104 | } 105 | 106 | private ReadWriteLock lockFor(Chunk chunk) { 107 | return lockMap.compute(chunk, ($, lock) -> lock == null ? new ReentrantReadWriteLock(true) : lock); 108 | } 109 | 110 | private void withWriteLockFor(Chunk chunk, Runnable runnable) { 111 | withLockAndChunk(lockFor(chunk).writeLock(), chunk, runnable); 112 | } 113 | 114 | private T withReadLockFor(Chunk chunk, Function function) { 115 | return withLockAndChunk(lockFor(chunk).readLock(), chunk, function); 116 | } 117 | 118 | private T withLockAndChunk(Lock lock, Chunk chunk, Function function) { 119 | lock.lock(); 120 | processingChunks.put(chunk, chunk.getWorld()); 121 | final T result = function.apply(chunk); 122 | processingChunks.remove(chunk); 123 | lock.unlock(); 124 | return result; 125 | } 126 | 127 | private void withLockAndChunk(Lock lock, Chunk chunk, Runnable runnable) { 128 | lock.lock(); 129 | processingChunks.put(chunk, chunk.getWorld()); 130 | runnable.run(); 131 | processingChunks.remove(chunk); 132 | lock.unlock(); 133 | } 134 | 135 | private void asyncProccess(Runnable action) { 136 | new BukkitRunnable() { 137 | @Override 138 | public void run() { 139 | runningAsyncTasks.add(this.getTaskId()); 140 | action.run(); 141 | runningAsyncTasks.remove(this.getTaskId()); 142 | } 143 | }.runTaskAsynchronously(plugin); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/DataTunnelRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.util.NamespacedKey; 4 | import org.bukkit.Chunk; 5 | 6 | import java.util.Collection; 7 | 8 | public interface DataTunnelRegistry { 9 | void register(NamespacedKey namespacedKey, StateDataTunnel storageMethod); 10 | 11 | Collection getAllStorageMethods(); 12 | 13 | StateDataTunnel getStorageMethod(NamespacedKey namespacedKey); 14 | 15 | default void waitForAllAsyncsDone() { 16 | getAllStorageMethods().forEach(StateDataTunnel::blockUntilAsyncsDone); 17 | } 18 | 19 | default boolean isProcessing(Chunk chunk){ 20 | return getAllStorageMethods().stream().anyMatch(tunnel->tunnel.isProcessingInDB(chunk)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/KryoDataTunnel.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.esotericsoftware.kryo.Kryo; 4 | import com.esotericsoftware.kryo.util.Pool; 5 | import com.github.yona168.multiblockapi.state.MultiblockState; 6 | import com.github.yona168.multiblockapi.storage.kryo.Kryogenic; 7 | import org.bukkit.Chunk; 8 | import org.bukkit.World; 9 | import org.bukkit.plugin.Plugin; 10 | 11 | import java.io.IOException; 12 | import java.nio.file.Files; 13 | import java.nio.file.Path; 14 | import java.util.Collection; 15 | import java.util.HashSet; 16 | 17 | import static java.nio.file.Files.*; 18 | import static java.util.stream.Collectors.toSet; 19 | 20 | public class KryoDataTunnel extends AbstractDataTunnel { 21 | private final Path dataFolder; 22 | private final Pool kryoPool; 23 | 24 | public KryoDataTunnel(Pool kryoPool, Path dataFolder, Plugin plugin) { 25 | super(plugin); 26 | this.dataFolder = dataFolder; 27 | this.kryoPool = kryoPool; 28 | createDirIfNotExists(dataFolder); 29 | } 30 | 31 | public KryoDataTunnel(Path dataFolder, Plugin plugin){ 32 | this(Kryogenic.getKryoPool(), dataFolder,plugin); 33 | } 34 | @Override 35 | public void initStoreAway(MultiblockState state) { 36 | if (state.isEnabled()) { 37 | throw new IllegalStateException("Enabled state is tryna be stored!"); 38 | } 39 | final Chunk targetChunk = state.getTriggerChunk(); 40 | final Path targetChunkFolder = getFilePathFor(targetChunk); 41 | createDirIfNotExists(targetChunkFolder); 42 | final Path targetFile = targetChunkFolder.resolve(state.getUniqueid().toString() + "-" + state.getMultiblock().getId().getNamespacedKey()); 43 | try { 44 | Kryogenic.freeze(kryoPool.obtain(), targetFile, state); 45 | } catch (IOException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | 50 | 51 | @Override 52 | public Collection initGetFromAfar(Chunk chunk) { 53 | try { 54 | Path targetDir = getFilePathFor(chunk); 55 | if (notExists(targetDir)) { 56 | return new HashSet<>(); 57 | } 58 | return list(targetDir).map(path -> { 59 | try { 60 | MultiblockState state = Kryogenic.thaw(kryoPool.obtain(), path); 61 | return state; 62 | } catch (IOException e) { 63 | throw new RuntimeException("Error with Kryo parsing!"); 64 | } 65 | }).collect(toSet()); 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | return new HashSet<>(); 69 | } 70 | } 71 | 72 | @Override 73 | public void initRemoveFromAfar(MultiblockState state) { 74 | final Path targetFile = getFilePathFor(state.getTriggerChunk()).resolve(state.getUniqueid().toString() + "-" + state.getMultiblock().getId().getNamespacedKey()); 75 | try { 76 | Files.deleteIfExists(targetFile); 77 | } catch (IOException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | 82 | private Path getFilePathFor(Chunk chunk) { 83 | return getFilePathFor(chunk.getWorld(), chunk.getX(), chunk.getZ()); 84 | } 85 | 86 | private Path getFilePathFor(World world, int x, int z) { 87 | return dataFolder.resolve(world.getUID().toString()).resolve(x + "-" + z); 88 | } 89 | 90 | private void createDirIfNotExists(Path dir) { 91 | if (!exists(dir)) { 92 | try { 93 | createDirectories(dir); 94 | } catch (IOException e) { 95 | e.printStackTrace(); 96 | } 97 | } 98 | } 99 | 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/SimpleDataTunnelRegistry.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.util.NamespacedKey; 4 | import com.gitlab.avelyn.architecture.base.Component; 5 | 6 | import java.util.Collection; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | public class SimpleDataTunnelRegistry extends Component implements DataTunnelRegistry { 11 | private final Map storageMethodMap = new HashMap<>(); 12 | 13 | public SimpleDataTunnelRegistry() { 14 | onDisable(storageMethodMap::clear); 15 | } 16 | 17 | @Override 18 | public void register(NamespacedKey namespacedKey, StateDataTunnel storageMethod) { 19 | storageMethodMap.put(namespacedKey, storageMethod); 20 | } 21 | 22 | @Override 23 | public Collection getAllStorageMethods() { 24 | return storageMethodMap.values(); 25 | } 26 | 27 | @Override 28 | public StateDataTunnel getStorageMethod(NamespacedKey namespacedKey) { 29 | return storageMethodMap.get(namespacedKey); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/SimpleStateCache.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.state.MultiblockState; 4 | import com.github.yona168.multiblockapi.util.ChunkCoords; 5 | import com.google.common.collect.HashMultimap; 6 | import com.google.common.collect.Multimap; 7 | import org.bukkit.Chunk; 8 | import org.bukkit.Location; 9 | import org.bukkit.World; 10 | 11 | import java.util.Collection; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | public class SimpleStateCache implements StateCache { 16 | 17 | private final Map stateByLocation; 18 | private final Multimap stateByChunk; 19 | private final Multimap stateByWorld; 20 | 21 | public SimpleStateCache() { 22 | stateByWorld = HashMultimap.create(); 23 | stateByChunk = HashMultimap.create(); 24 | stateByLocation = new HashMap<>(); 25 | } 26 | 27 | @Override 28 | public void store(MultiblockState state) { 29 | state.getAllBlocksLocs().stream().map(SimpleStateCache::normalize).forEach(loc -> stateByLocation.put(loc, state)); 30 | state.getOccupiedChunks().forEach(loc -> stateByChunk.put(loc, state)); 31 | stateByWorld.put(state.getWorld(), state); 32 | } 33 | 34 | @Override 35 | public MultiblockState getAt(Location location) { 36 | return stateByLocation.get(location); 37 | } 38 | 39 | @Override 40 | public Collection getAt(Chunk chunk) { 41 | return stateByChunk.get(ChunkCoords.fromChunk(chunk)); 42 | } 43 | 44 | @Override 45 | public Collection getAt(World world) { 46 | return stateByWorld.get(world); 47 | } 48 | 49 | @Override 50 | public Collection getAll() { 51 | return stateByWorld.values(); 52 | } 53 | 54 | @Override 55 | public void remove(MultiblockState state) { 56 | state.getAllBlocksLocs().forEach(stateByLocation::remove); 57 | state.getOccupiedChunks().forEach(chunk -> stateByChunk.remove(chunk, state)); 58 | stateByWorld.remove(state.getWorld(), state); 59 | } 60 | 61 | @Override 62 | public void clear() { 63 | stateByChunk.clear(); 64 | stateByLocation.clear(); 65 | stateByWorld.clear(); 66 | } 67 | 68 | private static Location normalize(Location loc) { 69 | loc.setYaw(0); 70 | loc.setPitch(0); 71 | return loc; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/StateCache.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.state.Backup; 4 | import com.github.yona168.multiblockapi.state.MultiblockState; 5 | import com.github.yona168.multiblockapi.structure.Multiblock; 6 | import org.bukkit.Chunk; 7 | import org.bukkit.Location; 8 | import org.bukkit.World; 9 | 10 | import java.util.Collection; 11 | import java.util.concurrent.CompletableFuture; 12 | 13 | public interface StateCache { 14 | 15 | void store(MultiblockState multiblockState); 16 | 17 | MultiblockState getAt(Location location); 18 | 19 | Collection getAt(Chunk chunk); 20 | 21 | Collection getAt(World world); 22 | 23 | Collection getAll(); 24 | 25 | void remove(MultiblockState state); 26 | 27 | void clear(); 28 | 29 | default CompletableFuture backup(){ 30 | return CompletableFuture.allOf( 31 | getAll().stream().filter(it->it instanceof Backup) 32 | .map(backupable->backupable.getMultiblock().getDataTunnel().storeAwayAsync(((Backup) backupable).snapshot())) 33 | .toArray(CompletableFuture[]::new)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/StateDataTunnel.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.state.MultiblockState; 4 | import com.github.yona168.multiblockapi.structure.Multiblock; 5 | import org.bukkit.Chunk; 6 | 7 | import java.util.Collection; 8 | import java.util.concurrent.CompletableFuture; 9 | 10 | public interface StateDataTunnel { 11 | 12 | void storeAway(MultiblockState state); 13 | 14 | CompletableFuture storeAwayAsync(MultiblockState t); 15 | 16 | Collection getFromAfar(Chunk chunk); 17 | 18 | CompletableFuture> getFromAfarAsync(Chunk chunk); 19 | 20 | boolean isProcessingInDB(Chunk chunk); 21 | 22 | void removeFromAfar(MultiblockState state); 23 | 24 | CompletableFuture removeFromAfarAsync(MultiblockState state); 25 | 26 | void blockUntilAsyncsDone(); 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/StateDataTunnels.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.storage; 2 | 3 | import com.github.yona168.multiblockapi.registry.MultiblockRegistry; 4 | import com.github.yona168.multiblockapi.storage.kryo.Kryogenic; 5 | import com.gitlab.avelyn.architecture.base.Component; 6 | import com.gitlab.avelyn.architecture.base.Toggleable; 7 | import org.bukkit.plugin.Plugin; 8 | 9 | public class StateDataTunnels { 10 | private static StateDataTunnel kryo; 11 | 12 | public static Toggleable enabler(Plugin plugin, MultiblockRegistry multiblockRegistry) { 13 | Component component = new Component() 14 | .onEnable(() -> kryo = new KryoDataTunnel(plugin.getDataFolder().toPath().resolve("chunks"), plugin)) 15 | .onDisable(() -> kryo = null); 16 | component.addChild(Kryogenic.enabler(multiblockRegistry)); 17 | return component; 18 | } 19 | 20 | public static StateDataTunnel kryo(){ 21 | return kryo; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/kryo/BukkitKryogenics.java: -------------------------------------------------------------------------------- 1 | //Created by https://github.com/Exerosis with personal alterations. Used with permission. 2 | package com.github.yona168.multiblockapi.storage.kryo; 3 | 4 | import com.esotericsoftware.kryo.Kryo; 5 | import com.esotericsoftware.kryo.Serializer; 6 | import com.esotericsoftware.kryo.io.Input; 7 | import com.esotericsoftware.kryo.io.Output; 8 | import com.github.yona168.multiblockapi.util.ChunkCoords; 9 | import org.bukkit.Bukkit; 10 | import org.bukkit.Chunk; 11 | import org.bukkit.Location; 12 | import org.bukkit.World; 13 | import org.bukkit.block.Block; 14 | import org.bukkit.inventory.ItemStack; 15 | import org.bukkit.plugin.Plugin; 16 | 17 | import java.lang.Class; 18 | import java.util.UUID; 19 | 20 | import static com.github.yona168.multiblockapi.storage.kryo.BukkitSerializers.*; 21 | import static org.bukkit.Bukkit.getWorld; 22 | 23 | public class BukkitKryogenics { 24 | private static final String ERR_SAVE_ENTITY = "Failed to serialize NBT for an Entity."; 25 | private static final String ERR_SAVE_ITEM = "Failed to serialize NBT for an ItemStack."; 26 | private static final String ERR_LOAD_ITEM = "Failed to deserialize NBT for an ItemStack."; 27 | private static final String ERR_LOAD_ENTITY = "Failed to deserialize NBT for an Entity."; 28 | 29 | public static void registerSerializers(Kryo kryo) { 30 | /* 31 | stream(values()).map(EntityType::getEntityClass).forEach(type -> { 32 | if (type == null) { 33 | return; 34 | } 35 | 36 | kryo.register(type, new Serializer() { 37 | @Override 38 | public void write(Kryo kryo, Output out, Entity entity) { 39 | try { 40 | saveEntity(entity, out); 41 | } catch (Exception reason) { 42 | throw new IllegalStateException(ERR_SAVE_ENTITY, reason); 43 | } 44 | } 45 | 46 | @Override 47 | public Entity read(Kryo kryo, Input in, Class type) { 48 | try { 49 | return loadEntity(Bukkit.getWorlds().get(0), in); 50 | } catch (Exception e) { 51 | throw new IllegalStateException(ERR_LOAD_ENTITY, e); 52 | } 53 | } 54 | }); 55 | }); 56 | */ 57 | new Serializer() { 58 | { 59 | kryo.register(ItemStack.class, this); 60 | kryo.register(CLASS_CRAFT_ITEM, this); 61 | } 62 | 63 | @Override 64 | public void write(Kryo kryo, Output out, ItemStack item) { 65 | try { 66 | saveItem(item, out); 67 | } catch (Exception e) { 68 | throw new IllegalStateException(ERR_SAVE_ITEM, e); 69 | } 70 | } 71 | 72 | @Override 73 | public ItemStack read(Kryo kryo, Input in, Class type) { 74 | try { 75 | return BukkitSerializers.loadItem(in); 76 | } catch (Exception e) { 77 | throw new IllegalStateException(ERR_LOAD_ITEM, e); 78 | } 79 | } 80 | }; 81 | 82 | Serializer uuidSerializer = new Serializer() { 83 | @Override 84 | public void write(Kryo kryo, Output out, UUID uuid) { 85 | out.writeLong(uuid.getMostSignificantBits()); 86 | out.writeLong(uuid.getLeastSignificantBits()); 87 | } 88 | 89 | @Override 90 | public UUID read(Kryo kryo, Input in, Class type) { 91 | return new UUID(in.readLong(), in.readLong()); 92 | } 93 | }; 94 | kryo.register(UUID.class, uuidSerializer); 95 | 96 | kryo.register(Location.class, new Serializer() { 97 | @Override 98 | public void write(Kryo kryo, Output output, Location location) { 99 | kryo.writeObject(output, location.getWorld()); 100 | output.writeDouble(location.getX()); 101 | output.writeDouble(location.getY()); 102 | output.writeDouble(location.getZ()); 103 | output.writeFloat(location.getYaw()); 104 | output.writeFloat(location.getPitch()); 105 | 106 | } 107 | 108 | @Override 109 | public Location read(Kryo kryo, Input input, Class type) { 110 | return new Location( 111 | kryo.readObject(input, World.class), 112 | input.readDouble(), 113 | input.readDouble(), 114 | input.readDouble(), 115 | input.readFloat(), 116 | input.readFloat() 117 | ); 118 | } 119 | }); 120 | 121 | final Serializer blockSerializer = new Serializer() { 122 | @Override 123 | public void write(Kryo kryo, Output output, Block object) { 124 | kryo.writeClassAndObject(output, object.getLocation()); 125 | } 126 | 127 | @Override 128 | public Block read(Kryo kryo, Input input, Class type) { 129 | return ((Location)kryo.readClassAndObject(input)).getBlock(); 130 | } 131 | }; 132 | kryo.register(Block.class, blockSerializer); 133 | kryo.register(CLASS_CRAFT_BLOCK, blockSerializer); 134 | 135 | Serializer worldSerializer = new Serializer() { 136 | @Override 137 | public void write(Kryo kryo, Output output, World object) { 138 | uuidSerializer.write(kryo, output, object.getUID()); 139 | } 140 | 141 | @Override 142 | public World read(Kryo kryo, Input input, Class type) { 143 | return getWorld(uuidSerializer.read(kryo, input, UUID.class)); 144 | } 145 | }; 146 | kryo.register(World.class, worldSerializer); 147 | kryo.register(CLASS_CRAFT_WORLD, worldSerializer); 148 | 149 | Serializer chunkSerializer = new Serializer() { 150 | @Override 151 | public void write(Kryo kryo, Output output, Chunk object) { 152 | kryo.writeClassAndObject(output, ChunkCoords.fromChunk(object)); 153 | } 154 | 155 | @Override 156 | public Chunk read(Kryo kryo, Input input, Class type) { 157 | return ((ChunkCoords) kryo.readClassAndObject(input)).toChunk(); 158 | } 159 | }; 160 | 161 | kryo.addDefaultSerializer(Chunk.class, chunkSerializer); 162 | kryo.register(Chunk.class); 163 | 164 | kryo.addDefaultSerializer(Plugin.class,new Serializer(){ 165 | 166 | @Override 167 | public void write(Kryo kryo, Output output, Plugin object) { 168 | output.writeString(object.getName()); 169 | } 170 | 171 | @Override 172 | public Plugin read(Kryo kryo, Input input, Class type) { 173 | return Bukkit.getPluginManager().getPlugin(input.readString()); 174 | } 175 | }); 176 | } 177 | 178 | 179 | } 180 | 181 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/kryo/BukkitSerializers.java: -------------------------------------------------------------------------------- 1 | //Created by https://github.com/Exerosis with personal alterations. Used with permission. 2 | package com.github.yona168.multiblockapi.storage.kryo; 3 | 4 | import org.bukkit.World; 5 | import org.bukkit.entity.Entity; 6 | import org.bukkit.inventory.ItemStack; 7 | 8 | import java.io.*; 9 | import java.lang.reflect.Constructor; 10 | import java.lang.reflect.Method; 11 | import java.nio.ByteBuffer; 12 | 13 | import static java.lang.Class.forName; 14 | import static java.lang.String.format; 15 | import static org.bukkit.Bukkit.getServer; 16 | 17 | public class BukkitSerializers { 18 | private static final String 19 | ERR_NBT_LOAD = "Failed to find a load method in NBTCompressedStreamTools", 20 | ERR_NBT_SAVE = "Failed to find a save method in NBTCompressedStreamTools", 21 | ERR_ENTITY_LOAD = "Failed to find a load method in EntityTypes."; 22 | 23 | private static final Constructor CONSTRUCTOR_NBT; 24 | private static final Method 25 | METHOD_NBT_SAVE, 26 | METHOD_NBT_LOAD, 27 | METHOD_NBT_SET_STRING; 28 | 29 | private static final Class CLASS_ITEM; 30 | protected static final Class CLASS_CRAFT_ITEM; 31 | protected static final Class CLASS_CRAFT_BLOCK; 32 | protected static final Class CLASS_CRAFT_WORLD; 33 | private static final Constructor CONSTRUCTOR_ITEM; 34 | private static final Method 35 | METHOD_ITEM_CREATE, 36 | METHOD_ITEM_TO, 37 | METHOD_ITEM_FROM, 38 | METHOD_ITEM_SAVE; 39 | 40 | private static final Method 41 | METHOD_ENTITY_HANDLE, 42 | METHOD_ENTITY_GET, 43 | METHOD_ENTITY_SAVE, 44 | METHOD_ENTITY_LOAD, 45 | METHOD_WORLD_HANDLE; 46 | 47 | 48 | static { 49 | try { 50 | final String version = getServer().getClass().getName().split("\\.")[3]; 51 | final String nms = "net.minecraft.server.%s.%s"; 52 | final String cb = "org.bukkit.craftbukkit.%s.%s"; 53 | 54 | final Class nbt = Class(nms, version, "NBTTagCompound"); 55 | CONSTRUCTOR_NBT = nbt.getConstructor(); 56 | CONSTRUCTOR_NBT.setAccessible(true); 57 | METHOD_NBT_SET_STRING = nbt.getDeclaredMethod("setString", String.class, String.class); 58 | Method nbtSave = null, nbtLoad = null; 59 | for (Method method : Class(nms, version, "NBTCompressedStreamTools").getDeclaredMethods()) { 60 | final Class[] params = method.getParameterTypes(); 61 | if (params.length == 2 && params[1] == DataOutput.class) 62 | nbtSave = method; 63 | else if (params.length == 1 && params[0] == DataInputStream.class) 64 | nbtLoad = method; 65 | } 66 | if ((METHOD_NBT_SAVE = nbtSave) == null) 67 | throw new IllegalStateException(ERR_NBT_SAVE); 68 | if ((METHOD_NBT_LOAD = nbtLoad) == null) 69 | throw new IllegalStateException(ERR_NBT_LOAD); 70 | METHOD_NBT_SAVE.setAccessible(true); 71 | METHOD_NBT_LOAD.setAccessible(true); 72 | 73 | CLASS_ITEM = Class(nms, version, "ItemStack"); 74 | CLASS_CRAFT_ITEM = Class(cb, version, "inventory.CraftItemStack"); 75 | CLASS_CRAFT_BLOCK=Class(cb, version, "block.CraftBlock"); 76 | CLASS_CRAFT_WORLD=Class(cb,version,"CraftWorld"); 77 | METHOD_ITEM_FROM = CLASS_CRAFT_ITEM.getDeclaredMethod("asBukkitCopy", CLASS_ITEM); 78 | METHOD_ITEM_TO = CLASS_CRAFT_ITEM.getDeclaredMethod("asNMSCopy", ItemStack.class); 79 | Method methodItemCreate; 80 | Constructor itemConstructor; 81 | try { 82 | itemConstructor = CLASS_ITEM.getConstructor(nbt); 83 | itemConstructor.setAccessible(true); 84 | methodItemCreate = null; 85 | } catch (Throwable ignored) { 86 | itemConstructor = null; 87 | try { 88 | methodItemCreate = CLASS_ITEM.getDeclaredMethod("a", nbt); 89 | }catch(NoSuchMethodException ex){ 90 | methodItemCreate=CLASS_ITEM.getDeclaredMethod("createStack", nbt); 91 | } 92 | methodItemCreate.setAccessible(true); 93 | } 94 | CONSTRUCTOR_ITEM = itemConstructor; 95 | METHOD_ITEM_CREATE = methodItemCreate; 96 | METHOD_ITEM_SAVE = CLASS_ITEM.getDeclaredMethod("save", nbt); 97 | METHOD_ITEM_SAVE.setAccessible(true); 98 | 99 | final Class entity = Class(nms, version, "Entity"); 100 | final Class craftEntity = Class(cb, version, "entity.CraftEntity"); 101 | final Class craftServer = Class(cb, version, "CraftServer"); 102 | METHOD_ENTITY_HANDLE = craftEntity.getDeclaredMethod("getHandle"); 103 | METHOD_ENTITY_GET = craftEntity.getDeclaredMethod("getEntity", craftServer, entity); 104 | METHOD_ENTITY_SAVE = entity.getDeclaredMethod("save", nbt); 105 | final Class entityTypes = Class(nms, version, "EntityTypes"); 106 | Method entityLoad = null; 107 | for (Method method : entityTypes.getDeclaredMethods()) { 108 | final Class[] params = method.getParameterTypes(); 109 | if (params.length == 2 && params[0] == nbt) 110 | entityLoad = method; 111 | } 112 | if ((METHOD_ENTITY_LOAD = entityLoad) == null) 113 | throw new IllegalStateException(ERR_ENTITY_LOAD); 114 | 115 | final Class craftWorld = Class(cb, version, "CraftWorld"); 116 | METHOD_WORLD_HANDLE = craftWorld.getDeclaredMethod("getHandle"); 117 | } catch (Exception e) { 118 | throw new IllegalStateException("Could not initialize reflection!", e); 119 | } 120 | 121 | 122 | } 123 | 124 | private static Class Class(String format, String version, String name) throws ClassNotFoundException { 125 | return forName(format(format, version, name)); 126 | } 127 | 128 | public static Object createNBTTagCompound() throws Exception { 129 | return CONSTRUCTOR_NBT.newInstance(); 130 | } 131 | 132 | public static void saveNBT(OutputStream out, Object nbt) throws Exception { 133 | METHOD_NBT_SAVE.invoke(null, nbt, new DataOutputStream(out)); 134 | } 135 | 136 | public static Object loadNBT(InputStream in) throws Exception { 137 | return METHOD_NBT_LOAD.invoke(null, new DataInputStream(in)); 138 | } 139 | 140 | public static void setString(Object nbt, String key, String value) throws Exception { 141 | METHOD_NBT_SET_STRING.invoke(nbt, key, value); 142 | } 143 | 144 | public static Object getHandle(Entity entity) throws Exception { 145 | return METHOD_ENTITY_HANDLE.invoke(entity); 146 | } 147 | 148 | public static Object getHandle(World world) throws Exception { 149 | return METHOD_WORLD_HANDLE.invoke(world); 150 | } 151 | 152 | public static Object itemFromBukkit(ItemStack item) throws Exception { 153 | return METHOD_ITEM_TO.invoke(null, item); 154 | } 155 | 156 | public static ItemStack itemToBukkit(Object item) throws Exception { 157 | return (ItemStack) METHOD_ITEM_FROM.invoke(null, item); 158 | } 159 | 160 | public static void saveItems(ItemStack[] contents, OutputStream out) throws Exception { 161 | final ByteBuffer length = ByteBuffer.allocate(4); 162 | length.putInt(contents.length); 163 | out.write(length.array()); 164 | for (ItemStack item : contents) 165 | saveItem(item, out); 166 | } 167 | 168 | public static ItemStack[] loadItems(InputStream in) throws Exception { 169 | final ByteBuffer length = ByteBuffer.allocate(4); 170 | in.read(length.array()); 171 | final ItemStack[] contents = new ItemStack[length.getInt()]; 172 | for (int i = 0; i < contents.length; i++) 173 | contents[i] = loadItem(in); 174 | return contents; 175 | } 176 | 177 | public static void saveEntity(Entity entity, OutputStream out) throws Exception { 178 | final String id = entity.getType().getName(); 179 | if (entity.isDead() || id == null) 180 | throw new IllegalStateException("Cannot save dead entity."); 181 | final Object nbt = createNBTTagCompound(); 182 | setString(nbt, "id", id); 183 | METHOD_ENTITY_SAVE.invoke(getHandle(entity), nbt); 184 | saveNBT(out, nbt); 185 | } 186 | 187 | public static Entity loadEntity(World world, InputStream in) throws Exception { 188 | final Object entity = METHOD_ENTITY_LOAD.invoke(null, loadNBT(in), getHandle(world)); 189 | if (entity == null) 190 | return null; 191 | return (Entity) METHOD_ENTITY_GET.invoke(null, getServer(), entity); 192 | } 193 | 194 | public static void saveItem(ItemStack item, OutputStream out) throws Exception { 195 | saveNBT(out, METHOD_ITEM_SAVE.invoke(itemFromBukkit(item), createNBTTagCompound())); 196 | } 197 | 198 | public static ItemStack loadItem(InputStream in) throws Exception { 199 | return itemToBukkit(CONSTRUCTOR_ITEM == null ? 200 | METHOD_ITEM_CREATE.invoke(null, loadNBT(in)) : 201 | CONSTRUCTOR_ITEM.newInstance(loadNBT(in)) 202 | ); 203 | } 204 | } -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/storage/kryo/Kryogenic.java: -------------------------------------------------------------------------------- 1 | //Created by https://github.com/Exerosis with personal alterations. Used with permission. 2 | package com.github.yona168.multiblockapi.storage.kryo; 3 | 4 | import com.esotericsoftware.kryo.Kryo; 5 | import com.esotericsoftware.kryo.Serializer; 6 | import com.esotericsoftware.kryo.io.Input; 7 | import com.esotericsoftware.kryo.io.Output; 8 | import com.esotericsoftware.kryo.serializers.DefaultSerializers; 9 | import com.esotericsoftware.kryo.unsafe.UnsafeInput; 10 | import com.esotericsoftware.kryo.unsafe.UnsafeOutput; 11 | import com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy; 12 | import com.esotericsoftware.kryo.util.Pool; 13 | import com.github.yona168.multiblockapi.MultiblockAPI; 14 | import com.github.yona168.multiblockapi.registry.MultiblockRegistry; 15 | import com.github.yona168.multiblockapi.state.MultiblockState; 16 | import com.github.yona168.multiblockapi.structure.Multiblock; 17 | import com.github.yona168.multiblockapi.util.ChunkCoords; 18 | import com.github.yona168.multiblockapi.util.NamespacedKey; 19 | import com.github.yona168.multiblockapi.util.SimpleChunkCoords; 20 | import com.gitlab.avelyn.architecture.base.Component; 21 | import com.gitlab.avelyn.architecture.base.Toggleable; 22 | import de.javakaffee.kryoserializers.GregorianCalendarSerializer; 23 | import de.javakaffee.kryoserializers.JdkProxySerializer; 24 | import de.javakaffee.kryoserializers.SynchronizedCollectionsSerializer; 25 | import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer; 26 | import de.javakaffee.kryoserializers.cglib.CGLibProxySerializer; 27 | import de.javakaffee.kryoserializers.guava.*; 28 | import org.objenesis.strategy.StdInstantiatorStrategy; 29 | 30 | import java.io.IOException; 31 | import java.io.InputStream; 32 | import java.io.OutputStream; 33 | import java.lang.reflect.InvocationHandler; 34 | import java.nio.file.Path; 35 | import java.util.*; 36 | import java.util.function.Consumer; 37 | import java.util.function.Supplier; 38 | 39 | import static java.nio.file.Files.*; 40 | import static org.bukkit.Bukkit.getWorld; 41 | 42 | @SuppressWarnings("unchecked") 43 | public class Kryogenic { 44 | 45 | 46 | private static Pool kryoPool=null; 47 | 48 | public static Pool getKryoPool() { 49 | return kryoPool; 50 | } 51 | public static Kryo getNextKryo(){return getKryoPool().obtain();} 52 | private static final Set> actions=new HashSet<>(); 53 | 54 | public static Toggleable enabler(MultiblockRegistry multiblockRegistry) { 55 | Component component = new Component(); 56 | component.onEnable(() ->kryoPool=new Pool(true,false, 32) { 57 | @Override 58 | protected Kryo create() { 59 | final Kryo kryo=new Kryo(); 60 | init(multiblockRegistry,kryo); 61 | actions.forEach(action->action.accept(kryo)); 62 | return kryo; 63 | } 64 | }); 65 | component.onDisable(()->kryoPool=null); 66 | component.onDisable(actions::clear); 67 | return component; 68 | } 69 | 70 | public static void kryoAction(Consumer action){ 71 | if(kryoPool!=null){ 72 | throw new IllegalStateException("kryoAction can only be called on plugin load!"); 73 | } 74 | actions.add(action); 75 | } 76 | 77 | public static Pool getNewPool(MultiblockAPI api){ 78 | return new Pool(true, false, 32){ 79 | @Override 80 | protected Kryo create() { 81 | final Kryo kryo=new Kryo(); 82 | init(api.getMultiblockRegistry(), kryo); 83 | return kryo; 84 | } 85 | }; 86 | } 87 | private static void init(MultiblockRegistry multiblockRegistry, Kryo KRYO) { 88 | KRYO.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); 89 | KRYO.setRegistrationRequired(false); 90 | BukkitKryogenics.registerSerializers(KRYO); 91 | KRYO.register(Arrays.asList("").getClass(), new DefaultSerializers.ArraysAsListSerializer()); 92 | KRYO.register(Collections.EMPTY_LIST.getClass(), new DefaultSerializers.CollectionsEmptyListSerializer()); 93 | KRYO.register(Collections.EMPTY_MAP.getClass(), new DefaultSerializers.CollectionsEmptyMapSerializer()); 94 | KRYO.register(Collections.EMPTY_SET.getClass(), new DefaultSerializers.CollectionsEmptySetSerializer()); 95 | KRYO.register(Collections.singletonList("").getClass(), new DefaultSerializers.CollectionsSingletonListSerializer()); 96 | KRYO.register(Collections.singleton("").getClass(), new DefaultSerializers.CollectionsSingletonSetSerializer()); 97 | KRYO.register(Collections.singletonMap("", "").getClass(), new DefaultSerializers.CollectionsSingletonMapSerializer()); 98 | KRYO.register(GregorianCalendar.class, new GregorianCalendarSerializer()); 99 | KRYO.register(InvocationHandler.class, new JdkProxySerializer()); 100 | UnmodifiableCollectionsSerializer.registerSerializers(KRYO); 101 | SynchronizedCollectionsSerializer.registerSerializers(KRYO); 102 | 103 | // register CGLibProxySerializer, works in combination with the appropriate action in handleUnregisteredClass (see below) 104 | KRYO.register(CGLibProxySerializer.CGLibProxyMarker.class, new CGLibProxySerializer()); 105 | // guava ImmutableList, ImmutableSet, ImmutableMap, ImmutableMultimap, ImmutableTable, ReverseList, UnmodifiableNavigableSet 106 | ImmutableListSerializer.registerSerializers(KRYO); 107 | ImmutableSetSerializer.registerSerializers(KRYO); 108 | ImmutableMapSerializer.registerSerializers(KRYO); 109 | ImmutableMultimapSerializer.registerSerializers(KRYO); 110 | ImmutableTableSerializer.registerSerializers(KRYO); 111 | ReverseListSerializer.registerSerializers(KRYO); 112 | UnmodifiableNavigableSetSerializer.registerSerializers(KRYO); 113 | // guava ArrayListMultimap, HashMultimap, LinkedHashMultimap, LinkedListMultimap, TreeMultimap, ArrayTable, HashBasedTable, TreeBasedTable 114 | ArrayListMultimapSerializer.registerSerializers(KRYO); 115 | HashMultimapSerializer.registerSerializers(KRYO); 116 | LinkedHashMultimapSerializer.registerSerializers(KRYO); 117 | LinkedListMultimapSerializer.registerSerializers(KRYO); 118 | TreeMultimapSerializer.registerSerializers(KRYO); 119 | ArrayTableSerializer.registerSerializers(KRYO); 120 | HashBasedTableSerializer.registerSerializers(KRYO); 121 | TreeBasedTableSerializer.registerSerializers(KRYO); 122 | KRYO.addDefaultSerializer(Multiblock.class, new Serializer() { 123 | @Override 124 | public void write(Kryo kryo, Output output, Multiblock object) { 125 | kryo.writeClassAndObject(output, object.getId()); 126 | } 127 | 128 | @Override 129 | public Multiblock read(Kryo kryo, Input input, Class type) { 130 | return multiblockRegistry.get((NamespacedKey) kryo.readClassAndObject(input)); 131 | } 132 | }); 133 | KRYO.addDefaultSerializer(ChunkCoords.class, new Serializer() { 134 | 135 | @Override 136 | public void write(Kryo kryo, Output output, ChunkCoords object) { 137 | kryo.writeClassAndObject(output, object.getWorld().getUID()); 138 | output.writeInt(object.getX()); 139 | output.writeInt(object.getZ()); 140 | } 141 | 142 | @Override 143 | public ChunkCoords read(Kryo kryo, Input input, Class type) { 144 | return ChunkCoords.fromData( 145 | getWorld((UUID) kryo.readClassAndObject(input)), 146 | input.readInt(), 147 | input.readInt() 148 | ); 149 | } 150 | }); 151 | KRYO.register(SimpleChunkCoords.class); 152 | KRYO.register(MultiblockState.Orientation.class, new Serializer() { 153 | 154 | @Override 155 | public void write(Kryo kryo, Output output, MultiblockState.Orientation object) { 156 | output.writeString(object.name()); 157 | } 158 | 159 | @Override 160 | public MultiblockState.Orientation read(Kryo kryo, Input input, Class type) { 161 | return MultiblockState.Orientation.valueOf(input.readString()); 162 | } 163 | }); 164 | 165 | KRYO.register(NamespacedKey.class, new Serializer(){ 166 | 167 | @Override 168 | public void write(Kryo kryo, Output output, NamespacedKey object) { 169 | output.writeString(object.getNamespace()); 170 | output.writeString(object.getKey()); 171 | } 172 | 173 | @Override 174 | public NamespacedKey read(Kryo kryo, Input input, Class type) { 175 | return new NamespacedKey(input.readString(), input.readString()); 176 | } 177 | }); 178 | } 179 | 180 | //--Path-- 181 | public static void freeze(Kryo kryo,Path file, Object value) throws IOException { 182 | if (file.getParent() != null) 183 | createDirectories(file.getParent()); 184 | freeze(kryo,newOutputStream(file), value); 185 | } 186 | 187 | public static Type thaw(Kryo kryo,Path file) throws IOException { 188 | return thaw(kryo,file, () -> null); 189 | } 190 | 191 | public static Type thaw(Kryo kryo,Path file, Type defaultValue) throws IOException { 192 | return thaw(kryo,file, () -> defaultValue); 193 | } 194 | 195 | public static Type thaw(Kryo kryo,Path file, Supplier defaultSupplier) throws IOException { 196 | return isRegularFile(file) ? thaw(kryo,newInputStream(file), defaultSupplier) : defaultSupplier.get(); 197 | } 198 | 199 | //--IO-- 200 | public static void freeze(Kryo kryo,OutputStream output, Object value) { 201 | try (final Output out = new UnsafeOutput(output)) { 202 | kryo.writeClassAndObject(out, value); 203 | } 204 | } 205 | 206 | public static Type thaw(Kryo kryo,InputStream input) { 207 | return thaw(kryo,input, () -> null); 208 | } 209 | 210 | public static Type thaw(Kryo kryo,InputStream input, Type defaultValue) { 211 | return thaw(kryo,input, () -> defaultValue); 212 | } 213 | 214 | public static Type thaw(Kryo kryo,InputStream input, Supplier defaultSupplier) { 215 | try (final Input in = new UnsafeInput(input)) { 216 | final Type value = (Type) kryo.readClassAndObject(in); 217 | return value == null ? defaultSupplier.get() : value; 218 | } 219 | } 220 | } -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/structure/LocationInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.structure; 2 | 3 | import com.github.yona168.multiblockapi.state.MultiblockState; 4 | import org.bukkit.Location; 5 | import org.bukkit.block.Block; 6 | 7 | import java.util.Set; 8 | 9 | public class LocationInfo { 10 | private final Block bottomLeftCorner; 11 | private final MultiblockState.Orientation orientation; 12 | private final Set allBlockLocations; 13 | 14 | public LocationInfo(Block bottomLeftCorner, Set allBlockLocations, MultiblockState.Orientation orientation) { 15 | this.bottomLeftCorner = bottomLeftCorner; 16 | this.orientation = orientation; 17 | this.allBlockLocations=allBlockLocations; 18 | } 19 | 20 | public Block getBottomLeftCorner() { 21 | return bottomLeftCorner; 22 | } 23 | 24 | public MultiblockState.Orientation getOrientation() { 25 | return orientation; 26 | } 27 | 28 | public Set getAllBlockLocations(){ 29 | return allBlockLocations; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/structure/Multiblock.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.structure; 2 | 3 | import com.github.yona168.multiblockapi.pattern.Pattern; 4 | import com.github.yona168.multiblockapi.state.MultiblockState; 5 | import com.github.yona168.multiblockapi.storage.StateDataTunnel; 6 | import com.github.yona168.multiblockapi.util.NamespacedKey; 7 | import org.bukkit.event.player.PlayerInteractEvent; 8 | 9 | import java.util.Optional; 10 | import java.util.function.BiConsumer; 11 | import java.util.function.BiPredicate; 12 | 13 | public interface Multiblock { 14 | Optional generateStateFrom(PlayerInteractEvent event); 15 | 16 | void onClick(BiConsumer eventConsumer); 17 | 18 | void preStateGenCheck(BiPredicate> check); 19 | 20 | void postStateGenCheck(BiPredicate check); 21 | 22 | void doClickActions(PlayerInteractEvent event, T state); 23 | 24 | Pattern getPattern(); 25 | 26 | NamespacedKey getId(); 27 | 28 | StateDataTunnel getDataTunnel(); 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/structure/SimpleMultiblock.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.structure; 2 | 3 | import com.github.yona168.multiblockapi.pattern.Pattern; 4 | import com.github.yona168.multiblockapi.state.MultiblockState; 5 | import com.github.yona168.multiblockapi.state.SimpleMultiblockState; 6 | import com.github.yona168.multiblockapi.storage.StateDataTunnel; 7 | import com.github.yona168.multiblockapi.util.NamespacedKey; 8 | import com.github.yona168.multiblockapi.util.ThreeDimensionalArrayCoords; 9 | import org.bukkit.Location; 10 | import org.bukkit.Material; 11 | import org.bukkit.block.Block; 12 | import org.bukkit.event.player.PlayerInteractEvent; 13 | 14 | import java.util.HashSet; 15 | import java.util.Optional; 16 | import java.util.Set; 17 | import java.util.function.BiConsumer; 18 | import java.util.function.BiPredicate; 19 | 20 | import static java.util.Optional.empty; 21 | 22 | public class SimpleMultiblock implements Multiblock { 23 | private final Material trigger; 24 | private final Pattern pattern; 25 | private final Set> eventConsumers; 26 | private final StateCreator stateCreator; 27 | private final NamespacedKey id; 28 | private final StateDataTunnel dataTunnel; 29 | private final Set>> preStateGenChecks; 30 | private final Set> postStateGenChecks; 31 | 32 | 33 | public SimpleMultiblock(Pattern pattern, NamespacedKey id, StateDataTunnel dataTunnel, StateCreator stateCreator) { 34 | this.eventConsumers = new HashSet<>(); 35 | this.pattern = pattern; 36 | this.trigger = ThreeDimensionalArrayCoords.get(pattern, pattern.getTriggerCoords()); 37 | this.stateCreator = stateCreator; 38 | this.id = id; 39 | this.dataTunnel = dataTunnel; 40 | this.preStateGenChecks = new HashSet<>(); 41 | this.postStateGenChecks = new HashSet<>(); 42 | } 43 | 44 | @Override 45 | public Optional generateStateFrom(PlayerInteractEvent event) { 46 | if (event.getClickedBlock() == null || event.getClickedBlock().getType() != trigger) { 47 | return empty(); 48 | } else { 49 | final Material[][][] pattern = getPattern().asArray(); 50 | final Location clickedLoc = event.getClickedBlock().getLocation(); 51 | final ThreeDimensionalArrayCoords triggerCoords = this.pattern.getTriggerCoords(); 52 | final Block facingSouthBottomLeft = clickedLoc.clone().add(triggerCoords.getColumn(), -triggerCoords.getY(), triggerCoords.getRow()).getBlock(); 53 | boolean southValid = true; 54 | boolean northValid = true; 55 | boolean westValid = true; 56 | boolean eastValid = true; 57 | Set allBlockLocations = new HashSet<>(); 58 | south: 59 | for (int y = 0; y < pattern.length; y++) { 60 | for (int r = 0; r < pattern[0].length; r++) { 61 | for (int c = 0; c < pattern[0][0].length; c++) { 62 | final Material targetMaterial = pattern[y][r][c]; 63 | if (targetMaterial != null) { 64 | final Block relativeBlock = facingSouthBottomLeft.getRelative(-c, y, -r); 65 | if (targetMaterial != relativeBlock.getType()) { 66 | southValid = false; 67 | allBlockLocations.clear(); 68 | break south; 69 | } 70 | allBlockLocations.add(relativeBlock.getLocation()); 71 | } 72 | } 73 | } 74 | } 75 | if (southValid) { 76 | if(!checkPreState(event)){ 77 | return Optional.empty(); 78 | } 79 | T state = stateCreator.createFrom(this, new LocationInfo(facingSouthBottomLeft, allBlockLocations, SimpleMultiblockState.Orientation.SOUTH), event); 80 | if (checkPostState(event, state)) { 81 | return Optional.of(state); 82 | } else { 83 | return Optional.empty(); 84 | } 85 | } 86 | final Block facingNorthBottomLeft = clickedLoc.clone().add(-triggerCoords.getColumn(), -triggerCoords.getY(), -triggerCoords.getRow()).getBlock(); 87 | north: 88 | for (int y = 0; y < pattern.length; y++) { 89 | for (int r = 0; r < pattern[0].length; r++) { 90 | for (int c = 0; c < pattern[0][0].length; c++) { 91 | final Material targetMaterial = pattern[y][r][c]; 92 | if (targetMaterial != null) { 93 | Block relativeBlock = facingNorthBottomLeft.getRelative(c, y, r); 94 | if (targetMaterial != relativeBlock.getType()) { 95 | northValid = false; 96 | allBlockLocations.clear(); 97 | break north; 98 | } 99 | allBlockLocations.add(relativeBlock.getLocation()); 100 | } 101 | } 102 | } 103 | } 104 | if (northValid) { 105 | if(!checkPreState(event)){ 106 | return Optional.empty(); 107 | } 108 | T state = stateCreator.createFrom(this, new LocationInfo(facingNorthBottomLeft, allBlockLocations, SimpleMultiblockState.Orientation.NORTH), event); 109 | if(checkPostState(event,state)){ 110 | return Optional.of(state); 111 | }else{ 112 | return Optional.empty(); 113 | } 114 | } 115 | 116 | 117 | final Block facingEastBottomLeft = clickedLoc.clone().add(triggerCoords.getRow(), -triggerCoords.getY(), -triggerCoords.getColumn()).getBlock(); 118 | east: 119 | for (int y = 0; y < pattern.length; y++) { 120 | for (int r = 0; r < pattern[0].length; r++) { 121 | for (int c = 0; c < pattern[0][0].length; c++) { 122 | final Material targetMaterial = pattern[y][r][c]; 123 | if (targetMaterial != null) { 124 | Block relativeBlock = facingEastBottomLeft.getRelative(-r, y, c); 125 | if (targetMaterial != relativeBlock.getType()) { 126 | eastValid = false; 127 | allBlockLocations.clear(); 128 | break east; 129 | } 130 | allBlockLocations.add(relativeBlock.getLocation()); 131 | } 132 | } 133 | } 134 | } 135 | if (eastValid){ 136 | if(!checkPreState(event)){ 137 | return Optional.empty(); 138 | } 139 | T state=stateCreator.createFrom(this, new LocationInfo(facingEastBottomLeft, allBlockLocations, MultiblockState.Orientation.EAST), event); 140 | if(checkPostState(event,state)){ 141 | return Optional.of(state); 142 | }else{ 143 | return Optional.empty(); 144 | } 145 | } 146 | 147 | 148 | final Block facingWestBottomLeft = clickedLoc.clone().add(-triggerCoords.getRow(), -triggerCoords.getY(), triggerCoords.getColumn()).getBlock(); 149 | west: 150 | for (int y = 0; y < pattern.length; y++) { 151 | for (int r = 0; r < pattern[0].length; r++) { 152 | for (int c = 0; c < pattern[0][0].length; c++) { 153 | final Material targetMaterial = pattern[y][r][c]; 154 | if (targetMaterial != null) { 155 | Block relativeBlock = facingWestBottomLeft.getRelative(r, y, -c); 156 | if (targetMaterial != relativeBlock.getType()) { 157 | westValid = false; 158 | allBlockLocations.clear(); 159 | break west; 160 | } 161 | allBlockLocations.add(relativeBlock.getLocation()); 162 | } 163 | } 164 | } 165 | } 166 | if (westValid){ 167 | if(!checkPreState(event)){ 168 | return Optional.empty(); 169 | } 170 | T state=stateCreator.createFrom(this, new LocationInfo(facingWestBottomLeft, allBlockLocations, SimpleMultiblockState.Orientation.WEST), event); 171 | if(checkPostState(event, state)){ 172 | return Optional.of(state); 173 | }else{ 174 | return Optional.empty(); 175 | } 176 | } 177 | } 178 | return empty(); 179 | } 180 | 181 | @Override 182 | public void onClick(BiConsumer eventConsumer) { 183 | this.eventConsumers.add(eventConsumer); 184 | } 185 | 186 | @Override 187 | public void preStateGenCheck(BiPredicate> check) { 188 | this.preStateGenChecks.add(check); 189 | } 190 | 191 | @Override 192 | public void postStateGenCheck(BiPredicate check) { 193 | this.postStateGenChecks.add(check); 194 | } 195 | 196 | private boolean checkPreState(PlayerInteractEvent event) { 197 | return this.preStateGenChecks.stream().allMatch(predicate -> predicate.test(event, this)); 198 | } 199 | 200 | private boolean checkPostState(PlayerInteractEvent event, T state) { 201 | return this.postStateGenChecks.stream().allMatch(predicate -> predicate.test(event, state)); 202 | } 203 | 204 | @Override 205 | public void doClickActions(PlayerInteractEvent event, T multiblockState) { 206 | event.setCancelled(true); 207 | this.eventConsumers.forEach(cons -> cons.accept(event, multiblockState)); 208 | } 209 | 210 | @Override 211 | public Pattern getPattern() { 212 | return pattern; 213 | } 214 | 215 | @Override 216 | public NamespacedKey getId() { 217 | return this.id; 218 | } 219 | 220 | @Override 221 | public StateDataTunnel getDataTunnel() { 222 | return dataTunnel; 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/structure/StateCreator.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.structure; 2 | 3 | import com.github.yona168.multiblockapi.state.MultiblockState; 4 | import org.bukkit.event.player.PlayerInteractEvent; 5 | 6 | public interface StateCreator { 7 | T createFrom(Multiblock multiblock, LocationInfo locationInfo, PlayerInteractEvent event); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/AvelynUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import com.gitlab.avelyn.architecture.base.Toggleable; 4 | import com.gitlab.avelyn.core.base.Events; 5 | import org.bukkit.event.Event; 6 | import org.bukkit.event.EventPriority; 7 | 8 | import java.util.function.Consumer; 9 | 10 | public interface AvelynUtils { 11 | static Toggleable listen(Class clazz, Consumer handler){ 12 | return Events.listen(clazz, EventPriority.NORMAL, handler); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/ChunkCoords.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import org.bukkit.Chunk; 4 | import org.bukkit.World; 5 | 6 | public interface ChunkCoords { 7 | 8 | int getX(); 9 | 10 | int getZ(); 11 | 12 | World getWorld(); 13 | 14 | default Chunk toChunk() { 15 | return getWorld().getChunkAt(getX(), getZ()); 16 | } 17 | 18 | static ChunkCoords fromData(World world, int x, int z) { 19 | return new SimpleChunkCoords(x, z, world); 20 | } 21 | 22 | static ChunkCoords fromChunk(Chunk chunk) { 23 | return new SimpleChunkCoords(chunk); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/NamespacedKey.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import org.bukkit.plugin.Plugin; 4 | 5 | import java.util.Objects; 6 | 7 | public class NamespacedKey { 8 | private final String namespacedKey; 9 | private final String namespace; 10 | private final String key; 11 | 12 | public NamespacedKey(Plugin plugin, String key) { 13 | this(plugin.getName(), key); 14 | } 15 | 16 | public NamespacedKey(String namespace, String key) { 17 | this.namespace = namespace; 18 | this.key = key; 19 | this.namespacedKey = namespace + "-" + key; 20 | } 21 | 22 | public String getNamespacedKey() { 23 | return namespacedKey; 24 | } 25 | 26 | public String getKey() { 27 | return key; 28 | } 29 | 30 | public String getNamespace() { 31 | return namespace; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return getNamespacedKey(); 37 | } 38 | 39 | @Override 40 | public int hashCode() { 41 | return Objects.hash(namespacedKey); 42 | } 43 | 44 | @Override 45 | public boolean equals(Object o) { 46 | if (o instanceof NamespacedKey) { 47 | NamespacedKey other = (NamespacedKey) o; 48 | return namespacedKey.equals(other.namespacedKey) && 49 | namespace.equals(other.namespace) && 50 | key.equals(other.key); 51 | } 52 | return false; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/SimpleChunkCoords.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import org.bukkit.Chunk; 4 | import org.bukkit.World; 5 | 6 | import java.util.Objects; 7 | 8 | public class SimpleChunkCoords implements ChunkCoords { 9 | private final int x; 10 | private final int z; 11 | private final World world; 12 | 13 | public SimpleChunkCoords(int x, int z, World world) { 14 | this.x = x; 15 | this.z = z; 16 | this.world = world; 17 | } 18 | 19 | public SimpleChunkCoords(Chunk chunk) { 20 | this(chunk.getX(), chunk.getZ(), chunk.getWorld()); 21 | } 22 | 23 | @Override 24 | public int getX() { 25 | return x; 26 | } 27 | 28 | @Override 29 | public int getZ() { 30 | return z; 31 | } 32 | 33 | @Override 34 | public World getWorld() { 35 | return world; 36 | } 37 | 38 | @Override 39 | public boolean equals(Object o) { 40 | { 41 | if (!(o instanceof ChunkCoords)) { 42 | return false; 43 | } 44 | ChunkCoords other = (ChunkCoords) o; 45 | return other.getX() == getX() && other.getZ() == getZ() && getWorld().equals(other.getWorld()); 46 | } 47 | } 48 | 49 | @Override 50 | public int hashCode(){ 51 | return Objects.hash(world,x,z); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/Stacktrace.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | public class Stacktrace { 4 | public static void printStackTrace(){ 5 | StackTraceElement[] elements = Thread.currentThread().getStackTrace(); 6 | for (int i = 1; i < elements.length; i++) { 7 | StackTraceElement s = elements[i]; 8 | System.out.println("\tat " + s.getClassName() + "." + s.getMethodName() 9 | + "(" + s.getFileName() + ":" + s.getLineNumber() + ")"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/ThreeDimensionalArrayCoords.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import com.github.yona168.multiblockapi.pattern.Pattern; 4 | import org.bukkit.Material; 5 | 6 | public class ThreeDimensionalArrayCoords { 7 | private final int x; 8 | private final int y; 9 | private final int z; 10 | 11 | public ThreeDimensionalArrayCoords(int level, int row, int column) { 12 | this.x = row; 13 | this.y = level; 14 | this.z = column; 15 | } 16 | 17 | public int getRow() { 18 | return x; 19 | } 20 | 21 | public int getY() { 22 | return y; 23 | } 24 | 25 | public int getColumn() { 26 | return z; 27 | } 28 | 29 | public static T get(T[][][] arr, ThreeDimensionalArrayCoords coords) { 30 | return arr[coords.y][coords.x][coords.z]; 31 | } 32 | 33 | public static Material get(Pattern pattern, ThreeDimensionalArrayCoords coords) { 34 | return get(pattern.asArray(), coords); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/github/yona168/multiblockapi/util/ToggleableTasks.java: -------------------------------------------------------------------------------- 1 | package com.github.yona168.multiblockapi.util; 2 | 3 | import com.gitlab.avelyn.architecture.base.Toggleable; 4 | import org.bukkit.plugin.Plugin; 5 | import org.bukkit.scheduler.BukkitTask; 6 | 7 | import java.util.function.Function; 8 | 9 | import static org.bukkit.Bukkit.getScheduler; 10 | 11 | public class ToggleableTasks { 12 | private static Toggleable toggleableTask(Runnable runnable, Function function) { 13 | return new Toggleable() { 14 | private BukkitTask task; 15 | private boolean isEnabled = false; 16 | 17 | @Override 18 | public Toggleable enable() { 19 | if (!isEnabled()) { 20 | this.task = function.apply(runnable); 21 | isEnabled = true; 22 | } 23 | return this; 24 | } 25 | 26 | @Override 27 | public Toggleable disable() { 28 | if (isEnabled()) { 29 | task.cancel(); 30 | isEnabled = false; 31 | } 32 | return this; 33 | } 34 | 35 | @Override 36 | public boolean isEnabled() { 37 | return isEnabled; 38 | } 39 | }; 40 | } 41 | 42 | public static Toggleable syncRepeating(Plugin plugin, long interval, Runnable runnable) { 43 | return toggleableTask(runnable, run -> getScheduler().runTaskTimer(plugin, run, 0, interval)); 44 | } 45 | 46 | public static Toggleable asyncRepeating(Plugin plugin, long interval, Runnable runnable) { 47 | return toggleableTask(runnable, run -> getScheduler().runTaskTimerAsynchronously(plugin, run, 0, interval)); 48 | } 49 | 50 | public static Toggleable syncLater(Plugin plugin, long delay, Runnable runnable){ 51 | return toggleableTask(runnable, run->getScheduler().runTaskLater(plugin, run, delay)); 52 | } 53 | 54 | public static Toggleable asyncLater(Plugin plugin, long delay, Runnable runnable){ 55 | return toggleableTask(runnable, run->getScheduler().runTaskLater(plugin, run, delay)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | main: com.github.yona168.multiblockapi.MultiblockAPI 2 | name: MultiblockAPI 3 | version: "1.0.0" 4 | 5 | commands: 6 | mbapi: 7 | description: "Multiblock API core command" 8 | usage: "/mbapi" --------------------------------------------------------------------------------