Update formatting

This commit is contained in:
Jakob K
2021-05-15 21:26:10 +02:00
parent ddc576a394
commit fa8fa9ae96
71 changed files with 203 additions and 249 deletions

View File

@@ -28,4 +28,4 @@ annotation class NMS_1_16_1
* which is more likely to stay the same
* over a long period of time.
*/
annotation class NMS_General
annotation class NMS_General

View File

@@ -7,6 +7,7 @@ import net.md_5.bungee.api.chat.*
import net.md_5.bungee.api.chat.hover.content.Entity
import net.md_5.bungee.api.chat.hover.content.Item
import net.md_5.bungee.api.chat.hover.content.Text
import java.awt.Color
inline fun chatComponent(builder: KSpigotComponentBuilder.() -> Unit): Array<out BaseComponent> {
return KSpigotComponentBuilder().apply(builder).create()
@@ -14,7 +15,7 @@ inline fun chatComponent(builder: KSpigotComponentBuilder.() -> Unit): Array<out
class KSpigotComponentBuilder {
private val components = ArrayList<BaseComponent>()
// COMPONENTS
inline fun text(text: String, builder: TextComponent.() -> Unit = { }) {
this += TextComponent(text).apply(builder)
}
@@ -41,7 +42,7 @@ class KSpigotComponentBuilder {
) {
this += TranslatableComponent(translatable, with).apply(builder)
}
// SPECIAL
fun legacyText(text: String, color: ChatColor = ChatColor.WHITE, builder: BaseComponent.() -> Unit = { }) {
this += TextComponent.fromLegacyText(text, color).onEach { it.apply(builder) }
}
@@ -56,10 +57,7 @@ class KSpigotComponentBuilder {
fun create() = components.toTypedArray()
}
/*
* BASE COMPONENT
*/
// extensions
inline fun BaseComponent.hoverEventText(builder: KSpigotComponentBuilder.() -> Unit) {
hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(KSpigotComponentBuilder().apply(builder).create()))
}
@@ -75,8 +73,7 @@ fun BaseComponent.hoverEventEntity(type: String, id: String, baseComponent: Base
fun BaseComponent.clickEvent(action: ClickEvent.Action, value: String) {
clickEvent = ClickEvent(action, value)
}
/*
* GLOBAL SHORTCUTS
*/
fun col(hex: String): ChatColor = ChatColor.of(hex)
fun col(hex: String): ChatColor = ChatColor.of(hex)
fun col(rgb: Int): ChatColor = ChatColor.of(Color(rgb))

View File

@@ -11,4 +11,4 @@ fun CommandSender.sendMessage(vararg components: BaseComponent) {
fun CommandSender.sendMessage(builder: KSpigotComponentBuilder.() -> Unit) {
this.spigot().sendMessage(*KSpigotComponentBuilder().apply(builder).create())
}
}

View File

@@ -76,7 +76,9 @@ internal abstract class PlayerInput<T>(
timeoutSeconds: Int,
) {
private var received = false
protected abstract val inputListeners: List<Listener>
protected fun onReceive(input: T?) {
if (!received) {
inputListeners.forEach { it.unregister() }
@@ -95,4 +97,4 @@ internal abstract class PlayerInput<T>(
onReceive(null)
}
}
}
}

View File

@@ -41,6 +41,7 @@ internal class PlayerInputAnvilInv(
)
.text("${KColors.ORANGERED}$startText")
.open(player)
override val inputListeners = listOf(
listen<InventoryClickEvent> {
if (it.clickedInventory == anvilInv.inventory)
@@ -51,4 +52,4 @@ internal class PlayerInputAnvilInv(
override fun onTimeout() {
anvilInv.inventory.closeForViewers()
}
}
}

View File

@@ -46,6 +46,7 @@ internal abstract class PlayerInputBook<T>(
}
abstract fun loadBookContent(bookMeta: BookMeta): T
override val inputListeners = listOf(
listen<PlayerEditBookEvent> {
val meta = it.newBookMeta
@@ -63,11 +64,13 @@ internal abstract class PlayerInputBook<T>(
companion object {
val idKey = NamespacedKey(KSpigotMainInstance, "kspigot_bookinput_id")
internal val usedIDs = ArrayList<Int>()
fun getID(): Int {
var returnID = (0..Int.MAX_VALUE).random()
while (usedIDs.contains(returnID)) returnID = (0..Int.MAX_VALUE).random()
return returnID
}
}
}
}

View File

@@ -14,7 +14,6 @@ internal class PlayerInputChat(
timeoutSeconds: Int,
question: String,
) : PlayerInput<String>(player, callback, timeoutSeconds) {
init {
player.sendMessage("${KColors.ORANGERED}$question")
}
@@ -27,4 +26,4 @@ internal class PlayerInputChat(
}
}
)
}
}

View File

@@ -8,4 +8,4 @@ class PluginFile(path: String, child: String? = null) : File(
run {
if (child == null) path else File(path, child).path
}
)
)

View File

@@ -61,4 +61,4 @@ class NBTData {
companion object {
fun deserialize(nbtString: String) = NBTData(nbtString)
}
}
}

View File

@@ -24,4 +24,4 @@ val ItemStack.nbtData: NBTData
CraftItemStack.asNMSCopy(this).let {
return if (it.hasTag()) NBTData(it.tag) else NBTData()
}
}
}

View File

@@ -9,27 +9,50 @@ interface NBTDataType<T> {
fun writeToCompound(key: String, data: T, compound: NBTTagCompound)
companion object {
val COMPOUND = nbtDataType<NBTData, NBTTagCompound>({ NBTData(it) },
{ key, data, compound -> compound.set(key, data.nbtTagCompound) })
val BYTE =
nbtDataType<Byte, NBTTagByte>({ it.asByte() }, { key, data, compound -> compound.setByte(key, data) })
val BYTE_ARRAY = nbtDataType<ByteArray, NBTTagByteArray>({ it.bytes },
{ key, data, compound -> compound.setByteArray(key, data) })
val DOUBLE = nbtDataType<Double, NBTTagDouble>({ it.asDouble() },
{ key, data, compound -> compound.setDouble(key, data) })
val FLOAT =
nbtDataType<Float, NBTTagFloat>({ it.asFloat() }, { key, data, compound -> compound.setFloat(key, data) })
val INT = nbtDataType<Int, NBTTagInt>({ it.asInt() }, { key, data, compound -> compound.setInt(key, data) })
val INT_ARRAY = nbtDataType<IntArray, NBTTagIntArray>({ it.ints },
{ key, data, compound -> compound.setIntArray(key, data) })
val LONG =
nbtDataType<Long, NBTTagLong>({ it.asLong() }, { key, data, compound -> compound.setLong(key, data) })
val LONG_ARRAY = nbtDataType<LongArray, NBTTagLongArray>({ it.longs },
{ key, data, compound -> compound.set(key, NBTTagLongArray(data)) })
val SHORT =
nbtDataType<Short, NBTTagShort>({ it.asShort() }, { key, data, compound -> compound.setShort(key, data) })
val STRING = nbtDataType<String, NBTTagString>({ it.asString() },
{ key, data, compound -> compound.setString(key, data) })
val COMPOUND = nbtDataType<NBTData, NBTTagCompound>(
{ NBTData(it) },
{ key, data, compound -> compound.set(key, data.nbtTagCompound) }
)
val BYTE = nbtDataType<Byte, NBTTagByte>(
{ it.asByte() },
{ key, data, compound -> compound.setByte(key, data) }
)
val BYTE_ARRAY = nbtDataType<ByteArray, NBTTagByteArray>(
{ it.bytes },
{ key, data, compound -> compound.setByteArray(key, data) }
)
val DOUBLE = nbtDataType<Double, NBTTagDouble>(
{ it.asDouble() },
{ key, data, compound -> compound.setDouble(key, data) }
)
val FLOAT = nbtDataType<Float, NBTTagFloat>(
{ it.asFloat() },
{ key, data, compound -> compound.setFloat(key, data) }
)
val INT = nbtDataType<Int, NBTTagInt>(
{ it.asInt() },
{ key, data, compound -> compound.setInt(key, data) }
)
val INT_ARRAY = nbtDataType<IntArray, NBTTagIntArray>(
{ it.ints },
{ key, data, compound -> compound.setIntArray(key, data) }
)
val LONG = nbtDataType<Long, NBTTagLong>(
{ it.asLong() },
{ key, data, compound -> compound.setLong(key, data) }
)
val LONG_ARRAY = nbtDataType<LongArray, NBTTagLongArray>(
{ it.longs },
{ key, data, compound -> compound.set(key, NBTTagLongArray(data)) }
)
val SHORT = nbtDataType<Short, NBTTagShort>(
{ it.asShort() },
{ key, data, compound -> compound.setShort(key, data) }
)
val STRING = nbtDataType<String, NBTTagString>(
{ it.asString() },
{ key, data, compound -> compound.setString(key, data) }
)
}
}
@@ -46,4 +69,4 @@ private inline fun <T, reified E> nbtDataType(
override fun writeToCompound(key: String, data: T, compound: NBTTagCompound) =
writeToCompound.invoke(key, data, compound)
}
}
}

View File

@@ -75,4 +75,4 @@ inline fun <reified T : Event> listen(
}
if (register) listener.register(priority, ignoreCancelled)
return listener
}
}

View File

@@ -46,4 +46,4 @@ val console get() = Bukkit.getConsoleSender()
/**
* Shortcut for creating a new [NamespacedKey]
*/
fun pluginKey(key: String) = NamespacedKey(KSpigotMainInstance, key)
fun pluginKey(key: String) = NamespacedKey(KSpigotMainInstance, key)

View File

@@ -1,5 +1,7 @@
package net.axay.kspigot.extensions.bukkit
// FROM BUNGEE COLOR
/**
* Returns the corresponding Bukkit Color object.
*/
@@ -12,7 +14,9 @@ val net.md_5.bungee.api.ChatColor.bukkitColor
*/
val net.md_5.bungee.api.ChatColor.javaAwtColor: java.awt.Color
get() = color
// FROM BUKKIT COLOR
/**
* Returns the corresponding Bungee Color object.
*/
@@ -24,7 +28,9 @@ val org.bukkit.Color.bungeeColor: net.md_5.bungee.api.ChatColor
*/
val org.bukkit.Color.javaAwtColor: java.awt.Color
get() = java.awt.Color(asRGB())
// FROM JAVA AWT COLOR
/**
* Returns the corresponding Bukkit Color object.
*/
@@ -36,7 +42,9 @@ val java.awt.Color.bukkitColor
*/
val java.awt.Color.bungeeColor: net.md_5.bungee.api.ChatColor
get() = net.md_5.bungee.api.ChatColor.of(this)
// FROM BUKKIT CHAT COLOR
/**
* Returns the corresponding Bukkit Color object.
*/
@@ -53,4 +61,4 @@ val org.bukkit.ChatColor.bungeeColor: net.md_5.bungee.api.ChatColor
* Returns the corresponding Java Color object.
*/
val org.bukkit.ChatColor.javaAwtColor: java.awt.Color
get() = bungeeColor.javaAwtColor
get() = bungeeColor.javaAwtColor

View File

@@ -17,4 +17,4 @@ fun CommandExecutor.register(commandName: String): Boolean {
return true
}
return false
}
}

View File

@@ -29,4 +29,4 @@ fun CommandSender.error(text: String, plugin: Plugin? = KSpigotMainInstance) =
* Sends the given message and adds the given prefix with the given color to it.
*/
fun CommandSender.printColoredPrefix(text: String, textColor: ChatColor, prefix: String, prefixColor: ChatColor) =
sendMessage("${prefixColor}[${prefix}]${textColor} $text")
sendMessage("${prefixColor}[${prefix}]${textColor} $text")

View File

@@ -14,11 +14,6 @@ import org.bukkit.entity.*
import org.bukkit.inventory.EquipmentSlot
import org.bukkit.inventory.ItemStack
/**
* Checks if the entity is completely in water.
*/
val LivingEntity.isInWater: Boolean get() = isFeetInWater && isHeadInWater
/**
* Checks if the entities' head is in water.
*/
@@ -167,4 +162,4 @@ fun Player.sendToServer(servername: String) {
* Adds the given ItemStacks to the player's inventory.
* @return The items that did not fit into the player's inventory.
*/
fun Player.give(vararg itemStacks: ItemStack) = inventory.addItem(*itemStacks)
fun Player.give(vararg itemStacks: ItemStack) = inventory.addItem(*itemStacks)

View File

@@ -9,4 +9,4 @@ val GameMode.isDamageable: Boolean
get() = when (this) {
GameMode.SURVIVAL, GameMode.ADVENTURE -> true
GameMode.SPECTATOR, GameMode.CREATIVE -> false
}
}

View File

@@ -23,4 +23,4 @@ val Chunk.allBlocks
for (z in 0 until 16)
add(getBlock(x, y, z))
}
}
}

View File

@@ -10,4 +10,4 @@ val BookMeta.content
append('\n')
append(it)
}
}.toString()
}.toString()

View File

@@ -18,4 +18,4 @@ val PrepareItemCraftEvent.isCancelled: Boolean
*/
fun PrepareItemCraftEvent.cancel() {
this.inventory.result = ItemStack(Material.AIR)
}
}

View File

@@ -32,10 +32,11 @@ data class SimpleChunkLocation(
val x: Int,
val z: Int,
)
// CONVERTER
fun Location.toSimple() = SimpleLocation3D(x, y, z)
fun Chunk.toSimple() = SimpleChunkLocation(x, z)
fun SimpleLocation3D.withWorld(world: World) = Location(world, x, y, z).apply { direction = this@withWorld.direction }
fun SimpleChunkLocation.withWorld(world: World) = world.getChunkAt(x, z)
fun Vector.toSimpleLoc() = SimpleLocation3D(x, y, z)
fun SimpleLocation3D.toVector() = Vector(x, y, z)
fun SimpleLocation3D.toVector() = Vector(x, y, z)

View File

@@ -14,8 +14,10 @@ class SimpleLocationPair(loc1: Location, loc2: Location) {
if (it == loc2.worldOrException) it
else throw IllegalArgumentException("The given locations worlds are not the same!")
}
val minSimpleLoc = SimpleLocation3D(min(loc1.x, loc2.x), min(loc1.y, loc2.y), min(loc1.z, loc2.z))
val maxSimpleLoc = SimpleLocation3D(max(loc1.x, loc2.x), max(loc1.y, loc2.y), max(loc1.z, loc2.z))
fun isInArea(
loc: Location,
check3d: Boolean = true,
@@ -59,14 +61,19 @@ class LocationArea(loc1: Location, loc2: Location) {
field = value
simpleLocationPair = SimpleLocationPair(loc1, value)
}
var simpleLocationPair = SimpleLocationPair(loc1, loc2); private set
val world: World get() = simpleLocationPair.world
val minLoc: Location get() = simpleLocationPair.minSimpleLoc.withWorld(simpleLocationPair.world)
val maxLoc: Location get() = simpleLocationPair.maxSimpleLoc.withWorld(simpleLocationPair.world)
val touchedChunks: Set<Chunk> get() = simpleLocationPair.touchedSimpleChunks.mapTo(HashSet()) { it.withWorld(world) }
fun isInArea(
loc: Location,
check3d: Boolean = true,
tolerance: Int = 0,
) = simpleLocationPair.isInArea(loc, check3d, tolerance)
}
}

View File

@@ -36,6 +36,7 @@ infix fun Location.reduceZ(distance: Number) = subtract(0.0, 0.0, distance)
infix fun Location.reduceXY(distance: Number) = subtract(distance, distance, 0.0)
infix fun Location.reduceYZ(distance: Number) = subtract(0.0, distance, distance)
infix fun Location.reduceXZ(distance: Number) = subtract(distance, 0.0, distance)
// extensions
fun Location.add(x: Number, y: Number, z: Number) = add(x.toDouble(), y.toDouble(), z.toDouble())
fun Location.subtract(x: Number, y: Number, z: Number) = subtract(x.toDouble(), y.toDouble(), z.toDouble())
@@ -83,9 +84,11 @@ infix fun Location.increase(loc: Location) = add(loc)
infix fun Location.reduce(loc: Location) = subtract(loc)
infix fun Location.increase(loc: SimpleLocation3D) = add(loc.x, loc.y, loc.z)
infix fun Location.reduce(loc: SimpleLocation3D) = subtract(loc.x, loc.y, loc.z)
/*
* VECTOR
*/
val Vector.isFinite: Boolean get() = x.isFinite() && y.isFinite() && z.isFinite()
// fast construct
@@ -125,4 +128,4 @@ operator fun Vector.timesAssign(num: Number) {
infix fun Vector.increase(vec: Vector) = add(vec)
infix fun Vector.reduce(vec: Vector) = subtract(vec)
infix fun Vector.multiply(vec: Vector) = multiply(vec)
infix fun Vector.multiply(num: Number) = multiply(num.toDouble())
infix fun Vector.multiply(num: Number) = multiply(num.toDouble())

View File

@@ -23,6 +23,7 @@ fun buildCounterMessageCallback(
StringBuilder().apply {
if (beforeTime != null)
append(beforeTime)
val hourTime = (curSeconds / 3600)
val minuteTime = ((curSeconds % 3600) / 60)
val secondsTime = (curSeconds % 60)
@@ -78,4 +79,4 @@ private val Long.isCounterValue: Boolean
1L, 2L, 3L, 4L, 5L, 10L, 15L, 20L, 30L -> true
0L -> false
else -> this % 60 == 0L
}
}

View File

@@ -39,4 +39,4 @@ class GamePhaseBuilder(val length: Long) {
fun build() = GamePhase(length, start, end, counterMessage)
}
fun buildGame(builder: GamePhaseSystemBuilder.() -> Unit) = GamePhaseSystemBuilder().apply(builder).build()
fun buildGame(builder: GamePhaseSystemBuilder.() -> Unit) = GamePhaseSystemBuilder().apply(builder).build()

View File

@@ -39,6 +39,7 @@ abstract class GUI<T : ForInventory>(
* all instances.
*/
abstract fun closeGUI()
protected fun unregisterAndClose() {
getAllInstances().forEach {
it.bukkitInventory.closeForViewers()
@@ -58,7 +59,9 @@ class GUIShared<T : ForInventory>(
}
override fun getInstance(player: Player) = singleInstance
override fun getAllInstances() = _singleInstance?.let { listOf(it) } ?: emptyList()
override fun closeGUI() {
unregisterAndClose()
_singleInstance = null
@@ -71,10 +74,12 @@ class GUIIndividual<T : ForInventory>(
resetOnQuit: Boolean,
) : GUI<T>(guiData) {
private val playerInstances = HashMap<Player, GUIInstance<T>>()
override fun getInstance(player: Player) =
playerInstances[player] ?: createInstance(player)
override fun getAllInstances() = playerInstances.values
private fun createInstance(player: Player) =
GUIInstance(this, player).apply {
playerInstances[player] = this
@@ -82,6 +87,7 @@ class GUIIndividual<T : ForInventory>(
}
fun deleteInstance(player: Player) = playerInstances.remove(player)?.unregister()
override fun closeGUI() {
unregisterAndClose()
playerInstances.clear()
@@ -107,8 +113,11 @@ class GUIInstance<T : ForInventory>(
holder: Player?,
) {
internal val bukkitInventory = gui.data.guiType.createBukkitInv(holder, gui.data.title)
private val currentElements = HashSet<GUIElement<*>>()
internal var isInMove: Boolean = false
var currentPageInt: Int = gui.data.defaultPage; private set
val currentPage
get() = getPage(currentPageInt)
@@ -222,4 +231,4 @@ class GUIInstance<T : ForInventory>(
if (!isInMove)
loadPage(currentPage)
}
}
}

View File

@@ -7,4 +7,4 @@ class GUIClickEvent<T : ForInventory>(
val bukkitEvent: InventoryClickEvent,
val guiInstance: GUIInstance<T>,
val player: Player,
)
)

View File

@@ -13,4 +13,4 @@ class IndividualGUICreator<T : ForInventory>(
private val resetOnQuit: Boolean = true,
) : GUICreator<T>() {
override fun createInstance(guiData: GUIData<T>) = GUIIndividual(guiData, resetOnClose, resetOnQuit)
}
}

View File

@@ -5,15 +5,17 @@ import org.bukkit.inventory.ItemStack
abstract class GUISlot<T : ForInventory> {
abstract fun onClick(clickEvent: GUIClickEvent<T>)
}
// ELEMENT
abstract class GUIElement<T : ForInventory> : GUISlot<T>() {
abstract fun getItemStack(slot: Int): ItemStack
final override fun onClick(clickEvent: GUIClickEvent<T>) {
clickEvent.guiInstance.gui.data.generalOnClick?.invoke(clickEvent)
onClickElement(clickEvent)
}
protected abstract fun onClickElement(clickEvent: GUIClickEvent<T>)
internal open fun startUsing(gui: GUIInstance<*>) {}
internal open fun stopUsing(gui: GUIInstance<*>) {}
}
}

View File

@@ -13,4 +13,4 @@ internal fun Player.openGUIInstance(guiInstance: GUIInstance<*>, page: Int? = nu
guiInstance.loadPageUnsafe(page)
return openInventory(guiInstance.bukkitInventory)
}
}

View File

@@ -8,6 +8,7 @@ import org.bukkit.inventory.Inventory
object GUIHolder : AutoCloseable {
private val registered = HashMap<Inventory, GUIInstance<ForInventory>>()
fun register(guiInstance: GUIInstance<ForInventory>) {
registered[guiInstance.bukkitInventory] = guiInstance
}
@@ -39,6 +40,7 @@ object GUIHolder : AutoCloseable {
val inv = it.inventory
val gui = registered[inv] ?: return@listen
val player = it.playerOrCancel ?: return@listen
var ifCancel = false
for (slotIndex in it.inventorySlots) {
@@ -80,4 +82,4 @@ private val InventoryInteractEvent.playerOrCancel: Player?
get() = (whoClicked as? Player) ?: kotlin.run {
isCancelled = true
return null
}
}

View File

@@ -5,4 +5,4 @@ class GUIPage<T : ForInventory>(
internal val slots: Map<Int, GUISlot<T>>,
val transitionTo: PageChangeEffect?,
val transitionFrom: PageChangeEffect?,
)
)

View File

@@ -7,6 +7,7 @@ import net.axay.kspigot.languageextensions.kotlinextensions.MinMaxPair
// INVENTORY
data class InventoryDimensions(val width: Int, val height: Int) {
val slotAmount = width * height
val invSlots by lazy {
ArrayList<InventorySlot>().apply {
(1..height).forEach { row ->
@@ -60,6 +61,7 @@ data class InventorySlot(val row: Int, val slotInRow: Int) : Comparable<Inventor
interface InventorySlotCompound<out T : ForInventory> {
fun withInvType(invType: GUIType<T>): Collection<InventorySlot>
fun realSlotsWithInvType(invType: GUIType<T>) =
withInvType(invType).mapNotNull { it.realSlotIn(invType.dimensions) }
}
@@ -70,6 +72,7 @@ open class SingleInventorySlot<T : ForInventory> internal constructor(
constructor(row: Int, slotInRow: Int) : this(InventorySlot(row, slotInRow))
private val slotAsList = listOf(inventorySlot)
override fun withInvType(invType: GUIType<T>) = slotAsList
}
@@ -194,8 +197,10 @@ class InventoryCornerSlots<T : ForInventory> internal constructor(
class InventoryAllSlots<T : ForInventory> : InventorySlotCompound<T> {
override fun withInvType(invType: GUIType<T>) = invType.dimensions.invSlots
}
// SLOT TYPE SAFETY
// COLUMNS
// columns
interface ForColumnOne : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
interface ForColumnTwo : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
interface ForColumnThree : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
@@ -205,7 +210,7 @@ interface ForColumnSix : ForInventoryWidthNine
interface ForColumnSeven : ForInventoryWidthNine
interface ForColumnEight : ForInventoryWidthNine
interface ForColumnNine : ForInventoryWidthNine
// ROWS
// rows
interface ForRowOne : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine, ForInventoryFourByNine,
ForInventoryFiveByNine, ForInventorySixByNine
@@ -216,22 +221,19 @@ interface ForRowThree : ForInventoryThreeByNine, ForInventoryFourByNine, ForInve
interface ForRowFour : ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine
interface ForRowFive : ForInventoryFiveByNine, ForInventorySixByNine
interface ForRowSix : ForInventorySixByNine
// EDGE CASES:
// ROW ONE
// edge cases:
// row one
interface ForRowOneSlotOneToThree : ForRowOne, ForInventoryOneByFive, ForInventoryThreeByThree
interface ForRowOneSlotFourToFive : ForRowOne, ForInventoryOneByFive
// ROW TWO
// row two
interface ForRowTwoSlotOneToThree : ForRowTwo, ForInventoryThreeByThree
// ROW THREE
// row three
interface ForRowThreeSlotOneToThree : ForRowThree, ForInventoryThreeByThree
// COMPLETE ROWS (including the edge cases)
// complete rows (including the edge cases)
interface ForCompleteRowOne : ForRowOne, ForRowOneSlotOneToThree, ForRowOneSlotFourToFive
interface ForCompleteRowTwo : ForRowTwo, ForRowTwoSlotOneToThree
interface ForCompleteRowThree : ForRowThree, ForRowThreeSlotOneToThree
object Slots {
// ROW ONE
val RowOneSlotOne = SingleInventorySlot<ForRowOneSlotOneToThree>(1, 1)
@@ -337,4 +339,4 @@ object Slots {
// ALL
val All = InventoryAllSlots<ForEveryInventory>()
}
}

View File

@@ -32,6 +32,7 @@ class GUIType<in T : ForInventory>(
}
}
}
// INVENTORY TYPE SAFETY
interface ForInventory
interface ForInventoryThreeByThree : ForInventoryThreeByNine
@@ -42,12 +43,11 @@ interface ForInventoryThreeByNine : ForInventoryFourByNine
interface ForInventoryFourByNine : ForInventoryFiveByNine
interface ForInventoryFiveByNine : ForInventorySixByNine
interface ForInventorySixByNine : ForInventory
interface ForEveryInventory
: ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
interface ForEveryInventory : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine,
ForInventoryThreeByThree, ForInventoryOneByFive
interface ForInventoryWidthThree : ForInventoryThreeByThree
interface ForInventoryWidthFive : ForInventoryOneByFive
interface ForInventoryWidthNine : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine

View File

@@ -14,4 +14,4 @@ open class GUIButton<T : ForInventory>(
clickEvent.bukkitEvent.isCancelled = true
action(clickEvent)
}
}
}

View File

@@ -19,4 +19,4 @@ class GUIButtonInventoryChange<T : ForInventory>(
it.player.openGUIInstance(changeToGUI)
onChange?.invoke(it)
})
})

View File

@@ -8,4 +8,4 @@ class GUIFreeSlot<T : ForInventory> : GUISlot<T>() {
override fun onClick(clickEvent: GUIClickEvent<T>) {
/* do nothing */
}
}
}

View File

@@ -12,4 +12,4 @@ class GUIPlaceholder<T : ForInventory>(
override fun onClickElement(clickEvent: GUIClickEvent<T>) {
clickEvent.bukkitEvent.isCancelled = true
}
}
}

View File

@@ -10,9 +10,11 @@ class GUISpaceCompoundElement<T : ForInventory, E> internal constructor(
private val compound: AbstractGUISpaceCompound<T, E>,
) : GUIElement<T>() {
override fun getItemStack(slot: Int) = compound.getItemStack(slot)
override fun onClickElement(clickEvent: GUIClickEvent<T>) {
compound.onClickElement(clickEvent)
}
// the following two methods register and unregister the instance
// for each compound element, but that is ok because it gets
// added/removed to/from a HashSet
@@ -44,12 +46,19 @@ abstract class AbstractGUISpaceCompound<T : ForInventory, E> internal constructo
private val onClick: ((GUIClickEvent<T>, E) -> Unit)?,
) {
private val content = ArrayList<E>()
private var currentContent: List<E> = emptyList()
private val internalSlots: MutableList<Int> = ArrayList()
private var scrollProgress: Int = 0
private var contentSort: () -> Unit = { }
private val registeredGUIs = HashSet<GUIInstance<*>>()
private fun contentAtSlot(slot: Int) = currentContent.getOrNull(internalSlots.indexOf(slot))
private fun recalculateCurrentContent() {
if (scrollProgress > content.size)
throw IllegalStateException("The scrollProgress is greater than the content size.")
@@ -83,6 +92,7 @@ abstract class AbstractGUISpaceCompound<T : ForInventory, E> internal constructo
}
internal abstract fun handleScrollEndReached(newProgress: Int, internalSlotsSize: Int, contentSize: Int): Boolean
internal fun getItemStack(slot: Int): ItemStack {
return contentAtSlot(slot)?.let { return@let iconGenerator.invoke(it) }
?: ItemStack(Material.AIR)
@@ -180,4 +190,4 @@ abstract class AbstractGUISpaceCompound<T : ForInventory, E> internal constructo
open class GUICompoundElement<T : ForInventory>(
internal val icon: ItemStack,
internal val onClick: ((GUIClickEvent<T>) -> Unit)? = null,
)
)

View File

@@ -37,4 +37,4 @@ data class CustomItemIdentifier(val customModelData: Int, val placeHolderMateria
itemStack
} else null
}
}
}

View File

@@ -61,4 +61,4 @@ val CharSequence.lengthWithoutMinecraftColour: Int
}
return count
}
}

View File

@@ -6,15 +6,11 @@ import org.bukkit.inventory.ItemFlag
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
/*
ITEM STACK
*/
// creation
/**
* Creates a new [ItemStack] and opens a builder for it.
*/
inline fun itemStack(material: Material, builder: ItemStack.() -> Unit) = ItemStack(material).apply(builder)
// extensions
/**
* Opens a builder with the current meta.
* @param T the specific type of the meta
@@ -44,10 +40,7 @@ inline fun <reified T : ItemMeta> ItemStack.setMeta(builder: T.() -> Unit) {
/** @see setMeta */
@JvmName("simpleSetMeta")
inline fun ItemStack.setMeta(builder: ItemMeta.() -> Unit) = setMeta<ItemMeta>(builder)
/*
ITEM META
*/
// creation
/**
* Creates new a [ItemMeta] instance of the given material and opens a builder for it.
* @param T the specific type of the meta
@@ -60,7 +53,7 @@ inline fun <reified T : ItemMeta> itemMeta(material: Material, builder: T.() ->
/** @see itemMeta */
@JvmName("simpleItemMeta")
inline fun itemMeta(material: Material, builder: ItemMeta.() -> Unit) = itemMeta<ItemMeta>(material, builder)
// extensions
/**
* Sets the lore (description) of the item.
*/
@@ -127,4 +120,4 @@ var ItemMeta.customModel: Int?
*/
var ItemMeta.localName: String
get() = localizedName
set(value) = setLocalizedName(value)
set(value) = setLocalizedName(value)

View File

@@ -2,10 +2,12 @@ package net.axay.kspigot.languageextensions.kotlinextensions
import java.io.File
internal fun File.createIfNotExists(): Boolean {
fun File.createIfNotExists(): Boolean {
return if (!exists()) {
if (!parentFile.exists())
parentFile.mkdirs()
createNewFile()
if (isDirectory)
mkdir()
else createNewFile()
} else true
}

View File

@@ -4,4 +4,4 @@ internal fun <T> T.applyIfNotNull(block: (T.() -> Unit)?): T {
if (block != null)
apply(block)
return this
}
}

View File

@@ -1,5 +1,7 @@
package net.axay.kspigot.languageextensions.kotlinextensions
internal inline fun <T, R> Lazy<T>.ifInitialized(block: (T) -> R) = if (isInitialized()) block(value) else null
internal val <T> Lazy<T>.valueIfInitialized get() = ifInitialized { value }
internal fun Lazy<AutoCloseable>.closeIfInitialized() = ifInitialized { value.close() }
internal fun Lazy<AutoCloseable>.closeIfInitialized() = ifInitialized { value.close() }

View File

@@ -13,4 +13,4 @@ internal class MinMaxPair<T : Comparable<T>>(a: T, b: T) {
min = a; max = b
}
}
}
}

View File

@@ -1,12 +0,0 @@
package net.axay.kspigot.languageextensions.kotlinextensions
internal fun stringBuilder(builder: StringBuilder.() -> Unit) = StringBuilder().apply(builder).toString()
inline fun multiLine(builder: MultiLineBuilder.() -> Unit) = MultiLineBuilder().apply(builder).build()
class MultiLineBuilder {
private val stringBuilder = StringBuilder()
operator fun String.unaryPlus() {
stringBuilder.appendLine(this)
}
fun build() = stringBuilder.toString()
}

View File

@@ -73,4 +73,4 @@ fun Player.localize(key: String) =
* @see Localization.get
*/
fun Player.localize(key: String, vararg args: Pair<String, Any?>) =
Localization.get(Localization.localeProvider(this), key, *args)
Localization.get(Localization.localeProvider(this), key, *args)

View File

@@ -56,4 +56,4 @@ abstract class KSpigot : JavaPlugin() {
}
}
lateinit var KSpigotMainInstance: KSpigot private set
lateinit var KSpigotMainInstance: KSpigot private set

View File

@@ -1,13 +0,0 @@
package net.axay.kspigot.main
import com.google.gson.Gson
import com.google.gson.GsonBuilder
object ValueHolder {
private val gsonBuilder by lazy {
GsonBuilder()
}
private val gson: Gson by lazy { gsonBuilder.create() }
private val gsonPretty: Gson by lazy { gsonBuilder.setPrettyPrinting().create() }
fun getGson(pretty: Boolean = false) = if (pretty) gsonPretty else gson
}

View File

@@ -79,4 +79,4 @@ fun Location.particle(particle: Particle, builder: (KSpigotParticle.() -> Unit)?
* @see KSpigotParticle
*/
fun Player.particle(particle: Particle, builder: (KSpigotParticle.() -> Unit)? = null) =
KSpigotParticle(particle).applyIfNotNull(builder).spawnFor(this)
KSpigotParticle(particle).applyIfNotNull(builder).spawnFor(this)

View File

@@ -11,4 +11,4 @@ interface BungeePluginMessageRandomPlayer {
interface BungeePluginMessagePlayerSpecific {
fun sendWithPlayer(player: Player)
}
}

View File

@@ -34,4 +34,4 @@ private object BungeePluginMessageReceiver : PluginMessageListener {
callback.onResponse.invoke(msgin)
}
}
}
}

View File

@@ -86,4 +86,4 @@ class PluginMessageGetServers(
) {
response.invoke(it.readUTF().split(", "))
}
}
}

View File

@@ -62,4 +62,4 @@ fun sendPluginMessageToBungeeCord(
BungeePluginMessageResponseCallback(subChannel, responseTimeout, onResponse)
player.sendPluginMessage(KSpigotMainInstance, "BungeeCord", msgbytes.toByteArray())
}
}

View File

@@ -8,6 +8,7 @@ abstract class ChainedRunnablePart<T, R>(
val sync: Boolean,
) {
var next: ChainedRunnablePart<R, *>? = null
protected abstract fun invoke(data: T): R
/**
@@ -79,6 +80,7 @@ class ChainedRunnablePartFirst<R>(
sync: Boolean,
) : ChainedRunnablePart<Unit, R>(sync) {
override fun execute() = start(Unit)
override fun <E : Exception> executeCatchingImpl(
exceptionClass: KClass<E>,
exceptionSync: Boolean,
@@ -94,6 +96,7 @@ class ChainedRunnablePartThen<T, R>(
val previous: ChainedRunnablePart<*, T>,
) : ChainedRunnablePart<T, R>(sync) {
override fun execute() = previous.execute()
override fun <E : Exception> executeCatchingImpl(
exceptionClass: KClass<E>,
exceptionSync: Boolean,
@@ -113,4 +116,4 @@ fun <T, R, U> ChainedRunnablePart<T, R>.thenDo(sync: Boolean, runnable: (R) -> U
ChainedRunnablePartThen(runnable, sync, this).apply { previous.next = this }
fun <T, R, U> ChainedRunnablePart<T, R>.thenSync(runnable: (R) -> U) = thenDo(true, runnable)
fun <T, R, U> ChainedRunnablePart<T, R>.thenAsync(runnable: (R) -> U) = thenDo(false, runnable)
fun <T, R, U> ChainedRunnablePart<T, R>.thenAsync(runnable: (R) -> U) = thenDo(false, runnable)

View File

@@ -127,4 +127,4 @@ fun sync(runnable: () -> Unit) = Bukkit.getScheduler().runTask(KSpigotMainInstan
/**
* Starts an asynchronous task.
*/
fun async(runnable: () -> Unit) = Bukkit.getScheduler().runTaskAsynchronously(KSpigotMainInstance, runnable)
fun async(runnable: () -> Unit) = Bukkit.getScheduler().runTaskAsynchronously(KSpigotMainInstance, runnable)

View File

@@ -24,10 +24,12 @@ object ItemMetaSerializer : KSerializerForBukkit<ItemMeta>(ItemMeta::class)
object ItemStackSerializer : KSerializerForBukkit<ItemStack>(ItemStack::class)
object LocationSerializer : KSerializerForBukkit<Location>(Location::class)
object VectorSerializer : KSerializerForBukkit<Vector>(Vector::class)
open class KSerializerForBukkit<T : ConfigurationSerializable>(
private val kClass: KClass<T>,
) : KSerializer<T> {
override val descriptor = ByteArraySerializer().descriptor
override fun serialize(encoder: Encoder, value: T) {
val bytes = ByteArrayOutputStream()
BukkitObjectOutputStream(bytes).use {
@@ -45,4 +47,4 @@ open class KSerializerForBukkit<T : ConfigurationSerializable>(
?: throw IllegalStateException("The object can not be deserialized to an object of the type ${kClass.simpleName}")
}
}
}
}

View File

@@ -1,26 +0,0 @@
package net.axay.kspigot.serialization
import net.axay.kspigot.main.ValueHolder
interface SpigotSerializable<T> {
/**
* Converts this serializable object
* into the corresponding spigot object.
*/
fun toSpigot(): T
}
interface SpigotSerializableCompanion<T>
/**
* @return A json string.
*/
fun SpigotSerializable<*>.serialize(pretty: Boolean = true): String = ValueHolder.getGson(pretty).toJson(this)
/**
* Deserializes the given json string and
* returns the deserialized object.
*/
@Suppress("unused")
inline fun <reified T> SpigotSerializableCompanion<T>.deserialize(json: String): T =
ValueHolder.getGson().fromJson(json, T::class.java)

View File

@@ -1,26 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.Location
data class SerializableLocation(
val world: SerializableWorld?,
val x: Double,
val y: Double,
val z: Double,
val direction: SerializableVector,
) : SpigotSerializable<Location> {
companion object : SpigotSerializableCompanion<SerializableLocation>
constructor(loc: Location) : this(loc.world?.let { SerializableWorld(it) },
loc.x,
loc.y,
loc.z,
SerializableVector(loc.direction))
override fun toSpigot() = Location(world?.toSpigot(), x, y, z)
.apply { direction = this@SerializableLocation.direction.toSpigot() }
}

View File

@@ -1,19 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.util.Vector
data class SerializableVector(
val x: Double,
val y: Double,
val z: Double,
) : SpigotSerializable<Vector> {
companion object : SpigotSerializableCompanion<SerializableVector>
constructor(vec: Vector) : this(vec.x, vec.y, vec.z)
override fun toSpigot() = Vector(x, y, z)
}

View File

@@ -1,19 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.Bukkit
import org.bukkit.World
class SerializableWorld(
val name: String,
) : SpigotSerializable<World> {
companion object : SpigotSerializableCompanion<World>
constructor(world: World) : this(world.name)
override fun toSpigot() = Bukkit.getWorld(name)
?: throw NullPointerException("The world \"$name\" does not exist")
}

View File

@@ -10,6 +10,7 @@ import org.bukkit.entity.EntityType
private fun circleEdgeLocations(radius: Number) = HashSet<SimpleLocation2D>().apply {
val currentRadius = radius.toDouble()
var d = -currentRadius
var x = currentRadius
var y = 0
@@ -40,6 +41,7 @@ private fun MutableSet<SimpleLocation2D>.addSimpleLoc2D(first: Number, second: N
abstract class Circle(val radius: Number) {
protected abstract val data: StructureData
val fillLocations by lazy {
var currentRadius = radius.toDouble()
@@ -66,8 +68,10 @@ abstract class Circle(val radius: Number) {
val edgeLocations by lazy {
circleEdgeLocations(radius)
}
val filledStructure by lazy { structure(true) }
val edgeStructure by lazy { structure(false) }
fun structure(filled: Boolean) = Structure(
HashSet<SingleStructureData>().apply {
val locations = if (filled) fillLocations else edgeLocations
@@ -87,4 +91,4 @@ class ParticleCircle(radius: Number, particle: KSpigotParticle) : Circle(radius)
class EntityCircle(radius: Number, entityType: EntityType) : Circle(radius) {
override val data = StructureDataEntity(entityType)
}
}

View File

@@ -28,9 +28,6 @@ data class Structure(
constructor(vararg structureDataSets: Set<SingleStructureData>)
: this(structureDataSets.flatMapTo(HashSet()) { it })
}
/*
* Structure data implementations.
*/
data class StructureDataMaterial(
val material: Material,
@@ -73,4 +70,4 @@ data class StructureDataParticle(
override fun createAt(loc: Location) {
particle.spawnAt(loc)
}
}
}

View File

@@ -33,4 +33,4 @@ inline fun Structure.rotate(angle: Number, vectorRotation: (Vector, Double) -> V
)
}
}
)
)

View File

@@ -30,8 +30,7 @@ fun LocationArea.loadStructure(includeBlocks: Boolean = true, includeEntities: B
* Sorted by their coordinates.
*/
val LocationArea.fillBlocks: Set<Block>
get()
= LinkedHashSet<Block>().apply {
get() = LinkedHashSet<Block>().apply {
(minLoc.blockX until maxLoc.blockX + 1).forEach { x ->
(minLoc.blockY until maxLoc.blockY + 1).forEach { y ->
(minLoc.blockZ until maxLoc.blockZ + 1).forEach { z ->
@@ -45,12 +44,11 @@ val LocationArea.fillBlocks: Set<Block>
* @return All entities in the given [LocationArea].
*/
val LocationArea.entities: Set<Entity>
get()
= HashSet<Entity>().apply {
get() = HashSet<Entity>().apply {
touchedChunks.forEach {
it.entities.forEach { en ->
if (simpleLocationPair.isInArea(en.location))
this += en
}
}
}
}

View File

@@ -49,4 +49,4 @@ enum class CardinalDirection {
}
}
}
}
}

View File

@@ -31,4 +31,4 @@ fun FireworkMeta.addEffect(builder: FireworkEffect.Builder.() -> Unit) =
*/
fun Firework.editMeta(builder: FireworkMeta.() -> Unit) {
fireworkMeta = fireworkMeta.apply(builder)
}
}

View File

@@ -17,6 +17,7 @@ object KSpigotFirework {
class KSpigotFireworkBuilder {
val effects = ArrayList<FireworkEffect>()
var power: Int? = null
inline fun effect(builder: FireworkEffectBuilder.() -> Unit) {
effects += FireworkEffectBuilder().apply(builder).fireworkEffect
}
@@ -32,9 +33,11 @@ class KSpigotFireworkBuilder {
class FireworkEffectBuilder {
private val fireworkBuilder = FireworkEffect.builder()
var type: FireworkEffect.Type? = null
var trail: Boolean? = null
var flicker: Boolean? = null
fun fade(vararg colors: Color) {
fireworkBuilder.withFade(*colors)
}
@@ -51,4 +54,4 @@ class FireworkEffectBuilder {
return fireworkBuilder.build()
}
}
}

View File

@@ -33,7 +33,7 @@ fun PersistentDataHolder.unmark(key: String) {
* this objects' markings.
*/
fun PersistentDataHolder.hasMark(key: String) = persistentDataContainer.has(markerKey(key), PersistentDataType.BYTE)
// quick access for ItemStacks
/** @see PersistentDataHolder.mark */
fun ItemStack.mark(key: String) = meta { mark(key) }
@@ -45,4 +45,4 @@ fun ItemStack.hasMark(key: String): Boolean {
var result: Boolean = false
meta { result = hasMark(key) }
return result
}
}